1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PPCISelLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "PPCISelLowering.h"
14 #include "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCCState.h"
17 #include "PPCCallingConv.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCMachineFunctionInfo.h"
21 #include "PPCPerfectShuffle.h"
22 #include "PPCRegisterInfo.h"
23 #include "PPCSubtarget.h"
24 #include "PPCTargetMachine.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/APInt.h"
27 #include "llvm/ADT/ArrayRef.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/None.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/CodeGen/CallingConvLower.h"
38 #include "llvm/CodeGen/ISDOpcodes.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineJumpTableInfo.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/RuntimeLibcalls.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetLowering.h"
55 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/IntrinsicsPowerPC.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSectionXCOFF.h"
78 #include "llvm/MC/MCSymbolXCOFF.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/BranchProbability.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/CodeGen.h"
83 #include "llvm/Support/CommandLine.h"
84 #include "llvm/Support/Compiler.h"
85 #include "llvm/Support/Debug.h"
86 #include "llvm/Support/ErrorHandling.h"
87 #include "llvm/Support/Format.h"
88 #include "llvm/Support/KnownBits.h"
89 #include "llvm/Support/MachineValueType.h"
90 #include "llvm/Support/MathExtras.h"
91 #include "llvm/Support/raw_ostream.h"
92 #include "llvm/Target/TargetMachine.h"
93 #include "llvm/Target/TargetOptions.h"
94 #include <algorithm>
95 #include <cassert>
96 #include <cstdint>
97 #include <iterator>
98 #include <list>
99 #include <utility>
100 #include <vector>
101 
102 using namespace llvm;
103 
104 #define DEBUG_TYPE "ppc-lowering"
105 
106 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
107 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
108 
109 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
110 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
111 
112 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
113 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
114 
115 static cl::opt<bool> DisableSCO("disable-ppc-sco",
116 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
117 
118 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
119 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
120 
121 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
122 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
123 
124 STATISTIC(NumTailCalls, "Number of tail calls");
125 STATISTIC(NumSiblingCalls, "Number of sibling calls");
126 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
127 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 // FIXME: Remove this once the bug has been fixed!
134 extern cl::opt<bool> ANDIGlueBug;
135 
136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
137                                      const PPCSubtarget &STI)
138     : TargetLowering(TM), Subtarget(STI) {
139   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
140   // arguments are at least 4/8 bytes aligned.
141   bool isPPC64 = Subtarget.isPPC64();
142   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
143 
144   // Set up the register classes.
145   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
146   if (!useSoftFloat()) {
147     if (hasSPE()) {
148       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
149       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
150     } else {
151       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
152       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
153     }
154   }
155 
156   // Match BITREVERSE to customized fast code sequence in the td file.
157   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
158   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
159 
160   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
161   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
162 
163   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
164   for (MVT VT : MVT::integer_valuetypes()) {
165     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
167   }
168 
169   if (Subtarget.isISA3_0()) {
170     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
171     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
172     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
173     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
174   } else {
175     // No extending loads from f16 or HW conversions back and forth.
176     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
177     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
178     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
179     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
180     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
181     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
182     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
183     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
184   }
185 
186   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
187 
188   // PowerPC has pre-inc load and store's.
189   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
190   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
191   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
192   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
193   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
194   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
199   if (!Subtarget.hasSPE()) {
200     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
201     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
202     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
203     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
204   }
205 
206   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
207   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
208   for (MVT VT : ScalarIntVTs) {
209     setOperationAction(ISD::ADDC, VT, Legal);
210     setOperationAction(ISD::ADDE, VT, Legal);
211     setOperationAction(ISD::SUBC, VT, Legal);
212     setOperationAction(ISD::SUBE, VT, Legal);
213   }
214 
215   if (Subtarget.useCRBits()) {
216     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
217 
218     if (isPPC64 || Subtarget.hasFPCVT()) {
219       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
220       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
221                          isPPC64 ? MVT::i64 : MVT::i32);
222       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
223       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
224                         isPPC64 ? MVT::i64 : MVT::i32);
225     } else {
226       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
228     }
229 
230     // PowerPC does not support direct load/store of condition registers.
231     setOperationAction(ISD::LOAD, MVT::i1, Custom);
232     setOperationAction(ISD::STORE, MVT::i1, Custom);
233 
234     // FIXME: Remove this once the ANDI glue bug is fixed:
235     if (ANDIGlueBug)
236       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
237 
238     for (MVT VT : MVT::integer_valuetypes()) {
239       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
240       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241       setTruncStoreAction(VT, MVT::i1, Expand);
242     }
243 
244     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
245   }
246 
247   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
248   // PPC (the libcall is not available).
249   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
250   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
251 
252   // We do not currently implement these libm ops for PowerPC.
253   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
254   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
255   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
256   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
257   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
258   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
259 
260   // PowerPC has no SREM/UREM instructions unless we are on P9
261   // On P9 we may use a hardware instruction to compute the remainder.
262   // When the result of both the remainder and the division is required it is
263   // more efficient to compute the remainder from the result of the division
264   // rather than use the remainder instruction. The instructions are legalized
265   // directly because the DivRemPairsPass performs the transformation at the IR
266   // level.
267   if (Subtarget.isISA3_0()) {
268     setOperationAction(ISD::SREM, MVT::i32, Legal);
269     setOperationAction(ISD::UREM, MVT::i32, Legal);
270     setOperationAction(ISD::SREM, MVT::i64, Legal);
271     setOperationAction(ISD::UREM, MVT::i64, Legal);
272   } else {
273     setOperationAction(ISD::SREM, MVT::i32, Expand);
274     setOperationAction(ISD::UREM, MVT::i32, Expand);
275     setOperationAction(ISD::SREM, MVT::i64, Expand);
276     setOperationAction(ISD::UREM, MVT::i64, Expand);
277   }
278 
279   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
280   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
281   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
282   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
283   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
284   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
285   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
288 
289   // Handle constrained floating-point operations of scalar.
290   // TODO: Handle SPE specific operation.
291   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
292   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
293   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
294   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
295   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
296   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
297 
298   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
299   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
300   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
301   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
302   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
303   if (Subtarget.hasVSX())
304     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
305 
306   if (Subtarget.hasFSQRT()) {
307     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
308     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
309   }
310 
311   if (Subtarget.hasFPRND()) {
312     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
314     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
315     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
316 
317     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
318     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
319     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
320     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
321   }
322 
323   // We don't support sin/cos/sqrt/fmod/pow
324   setOperationAction(ISD::FSIN , MVT::f64, Expand);
325   setOperationAction(ISD::FCOS , MVT::f64, Expand);
326   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
327   setOperationAction(ISD::FREM , MVT::f64, Expand);
328   setOperationAction(ISD::FPOW , MVT::f64, Expand);
329   setOperationAction(ISD::FSIN , MVT::f32, Expand);
330   setOperationAction(ISD::FCOS , MVT::f32, Expand);
331   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
332   setOperationAction(ISD::FREM , MVT::f32, Expand);
333   setOperationAction(ISD::FPOW , MVT::f32, Expand);
334   if (Subtarget.hasSPE()) {
335     setOperationAction(ISD::FMA  , MVT::f64, Expand);
336     setOperationAction(ISD::FMA  , MVT::f32, Expand);
337   } else {
338     setOperationAction(ISD::FMA  , MVT::f64, Legal);
339     setOperationAction(ISD::FMA  , MVT::f32, Legal);
340   }
341 
342   if (Subtarget.hasSPE())
343     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
344 
345   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
346 
347   // If we're enabling GP optimizations, use hardware square root
348   if (!Subtarget.hasFSQRT() &&
349       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
350         Subtarget.hasFRE()))
351     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
352 
353   if (!Subtarget.hasFSQRT() &&
354       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
355         Subtarget.hasFRES()))
356     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
357 
358   if (Subtarget.hasFCPSGN()) {
359     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
360     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
361   } else {
362     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
363     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
364   }
365 
366   if (Subtarget.hasFPRND()) {
367     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
368     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
369     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
370     setOperationAction(ISD::FROUND, MVT::f64, Legal);
371 
372     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
373     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
374     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
375     setOperationAction(ISD::FROUND, MVT::f32, Legal);
376   }
377 
378   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
379   // to speed up scalar BSWAP64.
380   // CTPOP or CTTZ were introduced in P8/P9 respectively
381   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
382   if (Subtarget.hasP9Vector())
383     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
384   else
385     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
386   if (Subtarget.isISA3_0()) {
387     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
388     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
389   } else {
390     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
391     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
392   }
393 
394   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
395     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
396     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
397   } else {
398     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
399     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
400   }
401 
402   // PowerPC does not have ROTR
403   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
404   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
405 
406   if (!Subtarget.useCRBits()) {
407     // PowerPC does not have Select
408     setOperationAction(ISD::SELECT, MVT::i32, Expand);
409     setOperationAction(ISD::SELECT, MVT::i64, Expand);
410     setOperationAction(ISD::SELECT, MVT::f32, Expand);
411     setOperationAction(ISD::SELECT, MVT::f64, Expand);
412   }
413 
414   // PowerPC wants to turn select_cc of FP into fsel when possible.
415   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
416   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
417 
418   // PowerPC wants to optimize integer setcc a bit
419   if (!Subtarget.useCRBits())
420     setOperationAction(ISD::SETCC, MVT::i32, Custom);
421 
422   // PowerPC does not have BRCOND which requires SetCC
423   if (!Subtarget.useCRBits())
424     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
425 
426   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
427 
428   if (Subtarget.hasSPE()) {
429     // SPE has built-in conversions
430     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
431     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
432     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
433     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
434     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
435     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
436   } else {
437     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
438     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
439 
440     // PowerPC does not have [U|S]INT_TO_FP
441     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
442     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
443   }
444 
445   if (Subtarget.hasDirectMove() && isPPC64) {
446     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
447     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
448     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
449     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
450     if (TM.Options.UnsafeFPMath) {
451       setOperationAction(ISD::LRINT, MVT::f64, Legal);
452       setOperationAction(ISD::LRINT, MVT::f32, Legal);
453       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
454       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
455       setOperationAction(ISD::LROUND, MVT::f64, Legal);
456       setOperationAction(ISD::LROUND, MVT::f32, Legal);
457       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
458       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
459     }
460   } else {
461     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
462     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
463     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
464     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
465   }
466 
467   // We cannot sextinreg(i1).  Expand to shifts.
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
469 
470   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
471   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
472   // support continuation, user-level threading, and etc.. As a result, no
473   // other SjLj exception interfaces are implemented and please don't build
474   // your own exception handling based on them.
475   // LLVM/Clang supports zero-cost DWARF exception handling.
476   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
477   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
478 
479   // We want to legalize GlobalAddress and ConstantPool nodes into the
480   // appropriate instructions to materialize the address.
481   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
482   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
483   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
484   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
485   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
486   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
487   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
488   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
489   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
490   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
491 
492   // TRAP is legal.
493   setOperationAction(ISD::TRAP, MVT::Other, Legal);
494 
495   // TRAMPOLINE is custom lowered.
496   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
497   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
498 
499   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
500   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
501 
502   if (Subtarget.is64BitELFABI()) {
503     // VAARG always uses double-word chunks, so promote anything smaller.
504     setOperationAction(ISD::VAARG, MVT::i1, Promote);
505     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
506     setOperationAction(ISD::VAARG, MVT::i8, Promote);
507     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
508     setOperationAction(ISD::VAARG, MVT::i16, Promote);
509     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
510     setOperationAction(ISD::VAARG, MVT::i32, Promote);
511     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
512     setOperationAction(ISD::VAARG, MVT::Other, Expand);
513   } else if (Subtarget.is32BitELFABI()) {
514     // VAARG is custom lowered with the 32-bit SVR4 ABI.
515     setOperationAction(ISD::VAARG, MVT::Other, Custom);
516     setOperationAction(ISD::VAARG, MVT::i64, Custom);
517   } else
518     setOperationAction(ISD::VAARG, MVT::Other, Expand);
519 
520   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
521   if (Subtarget.is32BitELFABI())
522     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
523   else
524     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
525 
526   // Use the default implementation.
527   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
528   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
529   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
530   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
531   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
532   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
533   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
534   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
535   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
536 
537   // We want to custom lower some of our intrinsics.
538   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
539 
540   // To handle counter-based loop conditions.
541   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
542 
543   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
544   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
545   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
547 
548   // Comparisons that require checking two conditions.
549   if (Subtarget.hasSPE()) {
550     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
551     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
552     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
553     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
554   }
555   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
556   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
557   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
558   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
559   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
560   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
561   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
562   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
563   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
564   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
565   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
566   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
567 
568   if (Subtarget.has64BitSupport()) {
569     // They also have instructions for converting between i64 and fp.
570     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
571     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
572     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
573     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
574     // This is just the low 32 bits of a (signed) fp->i64 conversion.
575     // We cannot do this with Promote because i64 is not a legal type.
576     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
577 
578     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
579       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
580   } else {
581     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
582     if (Subtarget.hasSPE()) {
583       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
584       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
585     } else
586       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
587   }
588 
589   // With the instructions enabled under FPCVT, we can do everything.
590   if (Subtarget.hasFPCVT()) {
591     if (Subtarget.has64BitSupport()) {
592       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
593       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
594       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
595       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
596     }
597 
598     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
599     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
600     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
601     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
602   }
603 
604   if (Subtarget.use64BitRegs()) {
605     // 64-bit PowerPC implementations can support i64 types directly
606     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
607     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
608     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
609     // 64-bit PowerPC wants to expand i128 shifts itself.
610     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
611     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
612     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
613   } else {
614     // 32-bit PowerPC wants to expand i64 shifts itself.
615     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
616     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
617     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
618   }
619 
620   // PowerPC has better expansions for funnel shifts than the generic
621   // TargetLowering::expandFunnelShift.
622   if (Subtarget.has64BitSupport()) {
623     setOperationAction(ISD::FSHL, MVT::i64, Custom);
624     setOperationAction(ISD::FSHR, MVT::i64, Custom);
625   }
626   setOperationAction(ISD::FSHL, MVT::i32, Custom);
627   setOperationAction(ISD::FSHR, MVT::i32, Custom);
628 
629   if (Subtarget.hasVSX()) {
630     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
631     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
632     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
633     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
634   }
635 
636   if (Subtarget.hasAltivec()) {
637     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
638       setOperationAction(ISD::SADDSAT, VT, Legal);
639       setOperationAction(ISD::SSUBSAT, VT, Legal);
640       setOperationAction(ISD::UADDSAT, VT, Legal);
641       setOperationAction(ISD::USUBSAT, VT, Legal);
642     }
643     // First set operation action for all vector types to expand. Then we
644     // will selectively turn on ones that can be effectively codegen'd.
645     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
646       // add/sub are legal for all supported vector VT's.
647       setOperationAction(ISD::ADD, VT, Legal);
648       setOperationAction(ISD::SUB, VT, Legal);
649 
650       // For v2i64, these are only valid with P8Vector. This is corrected after
651       // the loop.
652       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
653         setOperationAction(ISD::SMAX, VT, Legal);
654         setOperationAction(ISD::SMIN, VT, Legal);
655         setOperationAction(ISD::UMAX, VT, Legal);
656         setOperationAction(ISD::UMIN, VT, Legal);
657       }
658       else {
659         setOperationAction(ISD::SMAX, VT, Expand);
660         setOperationAction(ISD::SMIN, VT, Expand);
661         setOperationAction(ISD::UMAX, VT, Expand);
662         setOperationAction(ISD::UMIN, VT, Expand);
663       }
664 
665       if (Subtarget.hasVSX()) {
666         setOperationAction(ISD::FMAXNUM, VT, Legal);
667         setOperationAction(ISD::FMINNUM, VT, Legal);
668       }
669 
670       // Vector instructions introduced in P8
671       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
672         setOperationAction(ISD::CTPOP, VT, Legal);
673         setOperationAction(ISD::CTLZ, VT, Legal);
674       }
675       else {
676         setOperationAction(ISD::CTPOP, VT, Expand);
677         setOperationAction(ISD::CTLZ, VT, Expand);
678       }
679 
680       // Vector instructions introduced in P9
681       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
682         setOperationAction(ISD::CTTZ, VT, Legal);
683       else
684         setOperationAction(ISD::CTTZ, VT, Expand);
685 
686       // We promote all shuffles to v16i8.
687       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
688       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
689 
690       // We promote all non-typed operations to v4i32.
691       setOperationAction(ISD::AND   , VT, Promote);
692       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
693       setOperationAction(ISD::OR    , VT, Promote);
694       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
695       setOperationAction(ISD::XOR   , VT, Promote);
696       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
697       setOperationAction(ISD::LOAD  , VT, Promote);
698       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
699       setOperationAction(ISD::SELECT, VT, Promote);
700       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
701       setOperationAction(ISD::VSELECT, VT, Legal);
702       setOperationAction(ISD::SELECT_CC, VT, Promote);
703       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
704       setOperationAction(ISD::STORE, VT, Promote);
705       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
706 
707       // No other operations are legal.
708       setOperationAction(ISD::MUL , VT, Expand);
709       setOperationAction(ISD::SDIV, VT, Expand);
710       setOperationAction(ISD::SREM, VT, Expand);
711       setOperationAction(ISD::UDIV, VT, Expand);
712       setOperationAction(ISD::UREM, VT, Expand);
713       setOperationAction(ISD::FDIV, VT, Expand);
714       setOperationAction(ISD::FREM, VT, Expand);
715       setOperationAction(ISD::FNEG, VT, Expand);
716       setOperationAction(ISD::FSQRT, VT, Expand);
717       setOperationAction(ISD::FLOG, VT, Expand);
718       setOperationAction(ISD::FLOG10, VT, Expand);
719       setOperationAction(ISD::FLOG2, VT, Expand);
720       setOperationAction(ISD::FEXP, VT, Expand);
721       setOperationAction(ISD::FEXP2, VT, Expand);
722       setOperationAction(ISD::FSIN, VT, Expand);
723       setOperationAction(ISD::FCOS, VT, Expand);
724       setOperationAction(ISD::FABS, VT, Expand);
725       setOperationAction(ISD::FFLOOR, VT, Expand);
726       setOperationAction(ISD::FCEIL,  VT, Expand);
727       setOperationAction(ISD::FTRUNC, VT, Expand);
728       setOperationAction(ISD::FRINT,  VT, Expand);
729       setOperationAction(ISD::FNEARBYINT, VT, Expand);
730       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
731       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
732       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
733       setOperationAction(ISD::MULHU, VT, Expand);
734       setOperationAction(ISD::MULHS, VT, Expand);
735       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
736       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
737       setOperationAction(ISD::UDIVREM, VT, Expand);
738       setOperationAction(ISD::SDIVREM, VT, Expand);
739       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
740       setOperationAction(ISD::FPOW, VT, Expand);
741       setOperationAction(ISD::BSWAP, VT, Expand);
742       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
743       setOperationAction(ISD::ROTL, VT, Expand);
744       setOperationAction(ISD::ROTR, VT, Expand);
745 
746       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
747         setTruncStoreAction(VT, InnerVT, Expand);
748         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
749         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
750         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
751       }
752     }
753     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
754     if (!Subtarget.hasP8Vector()) {
755       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
756       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
757       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
758       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
759     }
760 
761     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
762       setOperationAction(ISD::ABS, VT, Custom);
763 
764     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
765     // with merges, splats, etc.
766     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
767 
768     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
769     // are cheap, so handle them before they get expanded to scalar.
770     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
771     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
772     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
773     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
774     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
775 
776     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
777     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
778     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
779     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
780     setOperationAction(ISD::SELECT, MVT::v4i32,
781                        Subtarget.useCRBits() ? Legal : Expand);
782     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
783     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
784     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
785     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
786     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
787     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
788     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
789     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
790     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
791 
792     // Without hasP8Altivec set, v2i64 SMAX isn't available.
793     // But ABS custom lowering requires SMAX support.
794     if (!Subtarget.hasP8Altivec())
795       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
796 
797     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
798     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
799     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
800     if (Subtarget.hasAltivec())
801       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
802         setOperationAction(ISD::ROTL, VT, Legal);
803     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
804     if (Subtarget.hasP8Altivec())
805       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
806 
807     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
808     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
809     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
810     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
811 
812     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
813     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
814 
815     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
816       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
817       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
818     }
819 
820     if (Subtarget.hasP8Altivec())
821       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
822     else
823       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
824 
825     if (Subtarget.isISA3_1()) {
826       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
827       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
828       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
829       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
830       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
831       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
832       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
833       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
834       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
835       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
836       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
837       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
838       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
839     }
840 
841     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
842     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
843 
844     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
845     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
846 
847     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
848     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
849     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
850     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
851 
852     // Altivec does not contain unordered floating-point compare instructions
853     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
854     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
855     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
856     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
857 
858     if (Subtarget.hasVSX()) {
859       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
860       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
861       if (Subtarget.hasP8Vector()) {
862         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
863         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
864       }
865       if (Subtarget.hasDirectMove() && isPPC64) {
866         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
867         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
868         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
869         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
870         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
871         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
872         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
873         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
874       }
875       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
876 
877       // The nearbyint variants are not allowed to raise the inexact exception
878       // so we can only code-gen them with unsafe math.
879       if (TM.Options.UnsafeFPMath) {
880         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
881         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
882       }
883 
884       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
885       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
886       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
887       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
888       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
889       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
890       setOperationAction(ISD::FROUND, MVT::f64, Legal);
891       setOperationAction(ISD::FRINT, MVT::f64, Legal);
892 
893       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
894       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
895       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
896       setOperationAction(ISD::FROUND, MVT::f32, Legal);
897       setOperationAction(ISD::FRINT, MVT::f32, Legal);
898 
899       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
900       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
901 
902       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
903       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
904 
905       // Share the Altivec comparison restrictions.
906       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
907       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
908       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
909       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
910 
911       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
912       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
913 
914       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
915 
916       if (Subtarget.hasP8Vector())
917         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
918 
919       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
920 
921       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
922       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
923       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
924 
925       if (Subtarget.hasP8Altivec()) {
926         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
927         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
928         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
929 
930         // 128 bit shifts can be accomplished via 3 instructions for SHL and
931         // SRL, but not for SRA because of the instructions available:
932         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
933         // doing
934         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
935         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
936         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
937 
938         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
939       }
940       else {
941         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
942         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
943         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
944 
945         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
946 
947         // VSX v2i64 only supports non-arithmetic operations.
948         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
949         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
950       }
951 
952       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
953 
954       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
955       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
956       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
957       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
958 
959       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
960 
961       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
962       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
963       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
964       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
965 
966       // Custom handling for partial vectors of integers converted to
967       // floating point. We already have optimal handling for v2i32 through
968       // the DAG combine, so those aren't necessary.
969       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
970       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
971       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
972       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
973       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
974       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
975       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
976       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
977 
978       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
979       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
980       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
981       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
982       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
983       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
984 
985       if (Subtarget.hasDirectMove())
986         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
987       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
988 
989       // Handle constrained floating-point operations of vector.
990       // The predictor is `hasVSX` because altivec instruction has
991       // no exception but VSX vector instruction has.
992       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
993       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
994       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
995       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
996       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
997       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
998       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
999       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1000       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
1001       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1002       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1003       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1004       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1005 
1006       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1007       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1008       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1009       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1010       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1011       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1012       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1013       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1014       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1015       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1016       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1017       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1018       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1019 
1020       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1021     }
1022 
1023     if (Subtarget.hasP8Altivec()) {
1024       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1025       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1026     }
1027 
1028     if (Subtarget.hasP9Vector()) {
1029       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1030       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1031 
1032       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1033       // SRL, but not for SRA because of the instructions available:
1034       // VS{RL} and VS{RL}O.
1035       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1036       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1037       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1038 
1039       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1040       setOperationAction(ISD::FADD, MVT::f128, Legal);
1041       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1042       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1043       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1044       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1045       // No extending loads to f128 on PPC.
1046       for (MVT FPT : MVT::fp_valuetypes())
1047         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1048       setOperationAction(ISD::FMA, MVT::f128, Legal);
1049       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1050       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1051       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1052       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1053       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1054       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1055 
1056       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1057       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1058       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1059       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1060       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1061       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1062 
1063       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1064       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1065       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1066       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1067       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1068       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1069       // No implementation for these ops for PowerPC.
1070       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1071       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1072       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1073       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1074       setOperationAction(ISD::FREM, MVT::f128, Expand);
1075 
1076       // Handle constrained floating-point operations of fp128
1077       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1078       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1079       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1080       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1081       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1082       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1083       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1084       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1085       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1086       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1087       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1088       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1089       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1090       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1091       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1092       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1093       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1094       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1095       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1096       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1097     }
1098 
1099     if (Subtarget.hasP9Altivec()) {
1100       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1101       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1102 
1103       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1104       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1105       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1106       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1107       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1108       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1109       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1110     }
1111   }
1112 
1113   if (Subtarget.has64BitSupport())
1114     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1115 
1116   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1117 
1118   if (!isPPC64) {
1119     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1120     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1121   }
1122 
1123   setBooleanContents(ZeroOrOneBooleanContent);
1124 
1125   if (Subtarget.hasAltivec()) {
1126     // Altivec instructions set fields to all zeros or all ones.
1127     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1128   }
1129 
1130   if (!isPPC64) {
1131     // These libcalls are not available in 32-bit.
1132     setLibcallName(RTLIB::SHL_I128, nullptr);
1133     setLibcallName(RTLIB::SRL_I128, nullptr);
1134     setLibcallName(RTLIB::SRA_I128, nullptr);
1135   }
1136 
1137   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1138 
1139   // We have target-specific dag combine patterns for the following nodes:
1140   setTargetDAGCombine(ISD::ADD);
1141   setTargetDAGCombine(ISD::SHL);
1142   setTargetDAGCombine(ISD::SRA);
1143   setTargetDAGCombine(ISD::SRL);
1144   setTargetDAGCombine(ISD::MUL);
1145   setTargetDAGCombine(ISD::FMA);
1146   setTargetDAGCombine(ISD::SINT_TO_FP);
1147   setTargetDAGCombine(ISD::BUILD_VECTOR);
1148   if (Subtarget.hasFPCVT())
1149     setTargetDAGCombine(ISD::UINT_TO_FP);
1150   setTargetDAGCombine(ISD::LOAD);
1151   setTargetDAGCombine(ISD::STORE);
1152   setTargetDAGCombine(ISD::BR_CC);
1153   if (Subtarget.useCRBits())
1154     setTargetDAGCombine(ISD::BRCOND);
1155   setTargetDAGCombine(ISD::BSWAP);
1156   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1157   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1158   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1159 
1160   setTargetDAGCombine(ISD::SIGN_EXTEND);
1161   setTargetDAGCombine(ISD::ZERO_EXTEND);
1162   setTargetDAGCombine(ISD::ANY_EXTEND);
1163 
1164   setTargetDAGCombine(ISD::TRUNCATE);
1165   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1166 
1167 
1168   if (Subtarget.useCRBits()) {
1169     setTargetDAGCombine(ISD::TRUNCATE);
1170     setTargetDAGCombine(ISD::SETCC);
1171     setTargetDAGCombine(ISD::SELECT_CC);
1172   }
1173 
1174   // Use reciprocal estimates.
1175   if (TM.Options.UnsafeFPMath) {
1176     setTargetDAGCombine(ISD::FDIV);
1177     setTargetDAGCombine(ISD::FSQRT);
1178   }
1179 
1180   if (Subtarget.hasP9Altivec()) {
1181     setTargetDAGCombine(ISD::ABS);
1182     setTargetDAGCombine(ISD::VSELECT);
1183   }
1184 
1185   setLibcallName(RTLIB::LOG_F128, "logf128");
1186   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1187   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1188   setLibcallName(RTLIB::EXP_F128, "expf128");
1189   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1190   setLibcallName(RTLIB::SIN_F128, "sinf128");
1191   setLibcallName(RTLIB::COS_F128, "cosf128");
1192   setLibcallName(RTLIB::POW_F128, "powf128");
1193   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1194   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1195   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1196   setLibcallName(RTLIB::REM_F128, "fmodf128");
1197 
1198   // With 32 condition bits, we don't need to sink (and duplicate) compares
1199   // aggressively in CodeGenPrep.
1200   if (Subtarget.useCRBits()) {
1201     setHasMultipleConditionRegisters();
1202     setJumpIsExpensive();
1203   }
1204 
1205   setMinFunctionAlignment(Align(4));
1206 
1207   switch (Subtarget.getCPUDirective()) {
1208   default: break;
1209   case PPC::DIR_970:
1210   case PPC::DIR_A2:
1211   case PPC::DIR_E500:
1212   case PPC::DIR_E500mc:
1213   case PPC::DIR_E5500:
1214   case PPC::DIR_PWR4:
1215   case PPC::DIR_PWR5:
1216   case PPC::DIR_PWR5X:
1217   case PPC::DIR_PWR6:
1218   case PPC::DIR_PWR6X:
1219   case PPC::DIR_PWR7:
1220   case PPC::DIR_PWR8:
1221   case PPC::DIR_PWR9:
1222   case PPC::DIR_PWR10:
1223   case PPC::DIR_PWR_FUTURE:
1224     setPrefLoopAlignment(Align(16));
1225     setPrefFunctionAlignment(Align(16));
1226     break;
1227   }
1228 
1229   if (Subtarget.enableMachineScheduler())
1230     setSchedulingPreference(Sched::Source);
1231   else
1232     setSchedulingPreference(Sched::Hybrid);
1233 
1234   computeRegisterProperties(STI.getRegisterInfo());
1235 
1236   // The Freescale cores do better with aggressive inlining of memcpy and
1237   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1238   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1239       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1240     MaxStoresPerMemset = 32;
1241     MaxStoresPerMemsetOptSize = 16;
1242     MaxStoresPerMemcpy = 32;
1243     MaxStoresPerMemcpyOptSize = 8;
1244     MaxStoresPerMemmove = 32;
1245     MaxStoresPerMemmoveOptSize = 8;
1246   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1247     // The A2 also benefits from (very) aggressive inlining of memcpy and
1248     // friends. The overhead of a the function call, even when warm, can be
1249     // over one hundred cycles.
1250     MaxStoresPerMemset = 128;
1251     MaxStoresPerMemcpy = 128;
1252     MaxStoresPerMemmove = 128;
1253     MaxLoadsPerMemcmp = 128;
1254   } else {
1255     MaxLoadsPerMemcmp = 8;
1256     MaxLoadsPerMemcmpOptSize = 4;
1257   }
1258 
1259   // Let the subtarget (CPU) decide if a predictable select is more expensive
1260   // than the corresponding branch. This information is used in CGP to decide
1261   // when to convert selects into branches.
1262   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1263 }
1264 
1265 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1266 /// the desired ByVal argument alignment.
1267 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1268   if (MaxAlign == MaxMaxAlign)
1269     return;
1270   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1271     if (MaxMaxAlign >= 32 &&
1272         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1273       MaxAlign = Align(32);
1274     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1275              MaxAlign < 16)
1276       MaxAlign = Align(16);
1277   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1278     Align EltAlign;
1279     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1280     if (EltAlign > MaxAlign)
1281       MaxAlign = EltAlign;
1282   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1283     for (auto *EltTy : STy->elements()) {
1284       Align EltAlign;
1285       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1286       if (EltAlign > MaxAlign)
1287         MaxAlign = EltAlign;
1288       if (MaxAlign == MaxMaxAlign)
1289         break;
1290     }
1291   }
1292 }
1293 
1294 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1295 /// function arguments in the caller parameter area.
1296 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1297                                                   const DataLayout &DL) const {
1298   // 16byte and wider vectors are passed on 16byte boundary.
1299   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1300   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1301   if (Subtarget.hasAltivec())
1302     getMaxByValAlign(Ty, Alignment, Align(16));
1303   return Alignment.value();
1304 }
1305 
1306 bool PPCTargetLowering::useSoftFloat() const {
1307   return Subtarget.useSoftFloat();
1308 }
1309 
1310 bool PPCTargetLowering::hasSPE() const {
1311   return Subtarget.hasSPE();
1312 }
1313 
1314 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1315   return VT.isScalarInteger();
1316 }
1317 
1318 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1319 /// type is cheaper than a multiply followed by a shift.
1320 /// This is true for words and doublewords on 64-bit PowerPC.
1321 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1322   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1323                               isOperationLegal(ISD::MULHU, Type)))
1324     return true;
1325   return TargetLowering::isMulhCheaperThanMulShift(Type);
1326 }
1327 
1328 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1329   switch ((PPCISD::NodeType)Opcode) {
1330   case PPCISD::FIRST_NUMBER:    break;
1331   case PPCISD::FSEL:            return "PPCISD::FSEL";
1332   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1333   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1334   case PPCISD::FCFID:           return "PPCISD::FCFID";
1335   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1336   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1337   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1338   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1339   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1340   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1341   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1342   case PPCISD::FP_TO_UINT_IN_VSR:
1343                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1344   case PPCISD::FP_TO_SINT_IN_VSR:
1345                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1346   case PPCISD::FRE:             return "PPCISD::FRE";
1347   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1348   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1349   case PPCISD::VPERM:           return "PPCISD::VPERM";
1350   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1351   case PPCISD::XXSPLTI_SP_TO_DP:
1352     return "PPCISD::XXSPLTI_SP_TO_DP";
1353   case PPCISD::XXSPLTI32DX:
1354     return "PPCISD::XXSPLTI32DX";
1355   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1356   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1357   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1358   case PPCISD::CMPB:            return "PPCISD::CMPB";
1359   case PPCISD::Hi:              return "PPCISD::Hi";
1360   case PPCISD::Lo:              return "PPCISD::Lo";
1361   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1362   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1363   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1364   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1365   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1366   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1367   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1368   case PPCISD::SRL:             return "PPCISD::SRL";
1369   case PPCISD::SRA:             return "PPCISD::SRA";
1370   case PPCISD::SHL:             return "PPCISD::SHL";
1371   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1372   case PPCISD::CALL:            return "PPCISD::CALL";
1373   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1374   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1375   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1376   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1377   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1378   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1379   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1380   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1381   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1382   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1383   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1384   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1385   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1386   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1387   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1388   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1389     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1390   case PPCISD::ANDI_rec_1_EQ_BIT:
1391     return "PPCISD::ANDI_rec_1_EQ_BIT";
1392   case PPCISD::ANDI_rec_1_GT_BIT:
1393     return "PPCISD::ANDI_rec_1_GT_BIT";
1394   case PPCISD::VCMP:            return "PPCISD::VCMP";
1395   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1396   case PPCISD::LBRX:            return "PPCISD::LBRX";
1397   case PPCISD::STBRX:           return "PPCISD::STBRX";
1398   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1399   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1400   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1401   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1402   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1403   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1404   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1405   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1406   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1407   case PPCISD::ST_VSR_SCAL_INT:
1408                                 return "PPCISD::ST_VSR_SCAL_INT";
1409   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1410   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1411   case PPCISD::BDZ:             return "PPCISD::BDZ";
1412   case PPCISD::MFFS:            return "PPCISD::MFFS";
1413   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1414   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1415   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1416   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1417   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1418   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1419   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1420   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1421   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1422   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1423   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1424   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1425   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1426   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1427   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1428   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1429   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1430   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1431   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1432   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1433   case PPCISD::SC:              return "PPCISD::SC";
1434   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1435   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1436   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1437   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1438   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1439   case PPCISD::VABSD:           return "PPCISD::VABSD";
1440   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1441   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1442   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1443   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1444   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1445   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1446   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1447   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1448   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1449   }
1450   return nullptr;
1451 }
1452 
1453 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1454                                           EVT VT) const {
1455   if (!VT.isVector())
1456     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1457 
1458   return VT.changeVectorElementTypeToInteger();
1459 }
1460 
1461 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1462   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1463   return true;
1464 }
1465 
1466 //===----------------------------------------------------------------------===//
1467 // Node matching predicates, for use by the tblgen matching code.
1468 //===----------------------------------------------------------------------===//
1469 
1470 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1471 static bool isFloatingPointZero(SDValue Op) {
1472   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1473     return CFP->getValueAPF().isZero();
1474   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1475     // Maybe this has already been legalized into the constant pool?
1476     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1477       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1478         return CFP->getValueAPF().isZero();
1479   }
1480   return false;
1481 }
1482 
1483 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1484 /// true if Op is undef or if it matches the specified value.
1485 static bool isConstantOrUndef(int Op, int Val) {
1486   return Op < 0 || Op == Val;
1487 }
1488 
1489 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1490 /// VPKUHUM instruction.
1491 /// The ShuffleKind distinguishes between big-endian operations with
1492 /// two different inputs (0), either-endian operations with two identical
1493 /// inputs (1), and little-endian operations with two different inputs (2).
1494 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1495 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1496                                SelectionDAG &DAG) {
1497   bool IsLE = DAG.getDataLayout().isLittleEndian();
1498   if (ShuffleKind == 0) {
1499     if (IsLE)
1500       return false;
1501     for (unsigned i = 0; i != 16; ++i)
1502       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1503         return false;
1504   } else if (ShuffleKind == 2) {
1505     if (!IsLE)
1506       return false;
1507     for (unsigned i = 0; i != 16; ++i)
1508       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1509         return false;
1510   } else if (ShuffleKind == 1) {
1511     unsigned j = IsLE ? 0 : 1;
1512     for (unsigned i = 0; i != 8; ++i)
1513       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1514           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1515         return false;
1516   }
1517   return true;
1518 }
1519 
1520 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1521 /// VPKUWUM instruction.
1522 /// The ShuffleKind distinguishes between big-endian operations with
1523 /// two different inputs (0), either-endian operations with two identical
1524 /// inputs (1), and little-endian operations with two different inputs (2).
1525 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1526 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1527                                SelectionDAG &DAG) {
1528   bool IsLE = DAG.getDataLayout().isLittleEndian();
1529   if (ShuffleKind == 0) {
1530     if (IsLE)
1531       return false;
1532     for (unsigned i = 0; i != 16; i += 2)
1533       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1534           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1535         return false;
1536   } else if (ShuffleKind == 2) {
1537     if (!IsLE)
1538       return false;
1539     for (unsigned i = 0; i != 16; i += 2)
1540       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1541           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1542         return false;
1543   } else if (ShuffleKind == 1) {
1544     unsigned j = IsLE ? 0 : 2;
1545     for (unsigned i = 0; i != 8; i += 2)
1546       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1547           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1548           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1549           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1550         return false;
1551   }
1552   return true;
1553 }
1554 
1555 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1556 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1557 /// current subtarget.
1558 ///
1559 /// The ShuffleKind distinguishes between big-endian operations with
1560 /// two different inputs (0), either-endian operations with two identical
1561 /// inputs (1), and little-endian operations with two different inputs (2).
1562 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1563 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1564                                SelectionDAG &DAG) {
1565   const PPCSubtarget& Subtarget =
1566       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1567   if (!Subtarget.hasP8Vector())
1568     return false;
1569 
1570   bool IsLE = DAG.getDataLayout().isLittleEndian();
1571   if (ShuffleKind == 0) {
1572     if (IsLE)
1573       return false;
1574     for (unsigned i = 0; i != 16; i += 4)
1575       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1576           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1577           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1578           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1579         return false;
1580   } else if (ShuffleKind == 2) {
1581     if (!IsLE)
1582       return false;
1583     for (unsigned i = 0; i != 16; i += 4)
1584       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1585           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1586           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1587           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1588         return false;
1589   } else if (ShuffleKind == 1) {
1590     unsigned j = IsLE ? 0 : 4;
1591     for (unsigned i = 0; i != 8; i += 4)
1592       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1593           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1594           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1595           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1596           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1597           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1598           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1599           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1600         return false;
1601   }
1602   return true;
1603 }
1604 
1605 /// isVMerge - Common function, used to match vmrg* shuffles.
1606 ///
1607 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1608                      unsigned LHSStart, unsigned RHSStart) {
1609   if (N->getValueType(0) != MVT::v16i8)
1610     return false;
1611   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1612          "Unsupported merge size!");
1613 
1614   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1615     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1616       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1617                              LHSStart+j+i*UnitSize) ||
1618           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1619                              RHSStart+j+i*UnitSize))
1620         return false;
1621     }
1622   return true;
1623 }
1624 
1625 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1626 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1627 /// The ShuffleKind distinguishes between big-endian merges with two
1628 /// different inputs (0), either-endian merges with two identical inputs (1),
1629 /// and little-endian merges with two different inputs (2).  For the latter,
1630 /// the input operands are swapped (see PPCInstrAltivec.td).
1631 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1632                              unsigned ShuffleKind, SelectionDAG &DAG) {
1633   if (DAG.getDataLayout().isLittleEndian()) {
1634     if (ShuffleKind == 1) // unary
1635       return isVMerge(N, UnitSize, 0, 0);
1636     else if (ShuffleKind == 2) // swapped
1637       return isVMerge(N, UnitSize, 0, 16);
1638     else
1639       return false;
1640   } else {
1641     if (ShuffleKind == 1) // unary
1642       return isVMerge(N, UnitSize, 8, 8);
1643     else if (ShuffleKind == 0) // normal
1644       return isVMerge(N, UnitSize, 8, 24);
1645     else
1646       return false;
1647   }
1648 }
1649 
1650 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1651 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1652 /// The ShuffleKind distinguishes between big-endian merges with two
1653 /// different inputs (0), either-endian merges with two identical inputs (1),
1654 /// and little-endian merges with two different inputs (2).  For the latter,
1655 /// the input operands are swapped (see PPCInstrAltivec.td).
1656 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1657                              unsigned ShuffleKind, SelectionDAG &DAG) {
1658   if (DAG.getDataLayout().isLittleEndian()) {
1659     if (ShuffleKind == 1) // unary
1660       return isVMerge(N, UnitSize, 8, 8);
1661     else if (ShuffleKind == 2) // swapped
1662       return isVMerge(N, UnitSize, 8, 24);
1663     else
1664       return false;
1665   } else {
1666     if (ShuffleKind == 1) // unary
1667       return isVMerge(N, UnitSize, 0, 0);
1668     else if (ShuffleKind == 0) // normal
1669       return isVMerge(N, UnitSize, 0, 16);
1670     else
1671       return false;
1672   }
1673 }
1674 
1675 /**
1676  * Common function used to match vmrgew and vmrgow shuffles
1677  *
1678  * The indexOffset determines whether to look for even or odd words in
1679  * the shuffle mask. This is based on the of the endianness of the target
1680  * machine.
1681  *   - Little Endian:
1682  *     - Use offset of 0 to check for odd elements
1683  *     - Use offset of 4 to check for even elements
1684  *   - Big Endian:
1685  *     - Use offset of 0 to check for even elements
1686  *     - Use offset of 4 to check for odd elements
1687  * A detailed description of the vector element ordering for little endian and
1688  * big endian can be found at
1689  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1690  * Targeting your applications - what little endian and big endian IBM XL C/C++
1691  * compiler differences mean to you
1692  *
1693  * The mask to the shuffle vector instruction specifies the indices of the
1694  * elements from the two input vectors to place in the result. The elements are
1695  * numbered in array-access order, starting with the first vector. These vectors
1696  * are always of type v16i8, thus each vector will contain 16 elements of size
1697  * 8. More info on the shuffle vector can be found in the
1698  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1699  * Language Reference.
1700  *
1701  * The RHSStartValue indicates whether the same input vectors are used (unary)
1702  * or two different input vectors are used, based on the following:
1703  *   - If the instruction uses the same vector for both inputs, the range of the
1704  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1705  *     be 0.
1706  *   - If the instruction has two different vectors then the range of the
1707  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1708  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1709  *     to 31 specify elements in the second vector).
1710  *
1711  * \param[in] N The shuffle vector SD Node to analyze
1712  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1713  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1714  * vector to the shuffle_vector instruction
1715  * \return true iff this shuffle vector represents an even or odd word merge
1716  */
1717 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1718                      unsigned RHSStartValue) {
1719   if (N->getValueType(0) != MVT::v16i8)
1720     return false;
1721 
1722   for (unsigned i = 0; i < 2; ++i)
1723     for (unsigned j = 0; j < 4; ++j)
1724       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1725                              i*RHSStartValue+j+IndexOffset) ||
1726           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1727                              i*RHSStartValue+j+IndexOffset+8))
1728         return false;
1729   return true;
1730 }
1731 
1732 /**
1733  * Determine if the specified shuffle mask is suitable for the vmrgew or
1734  * vmrgow instructions.
1735  *
1736  * \param[in] N The shuffle vector SD Node to analyze
1737  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1738  * \param[in] ShuffleKind Identify the type of merge:
1739  *   - 0 = big-endian merge with two different inputs;
1740  *   - 1 = either-endian merge with two identical inputs;
1741  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1742  *     little-endian merges).
1743  * \param[in] DAG The current SelectionDAG
1744  * \return true iff this shuffle mask
1745  */
1746 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1747                               unsigned ShuffleKind, SelectionDAG &DAG) {
1748   if (DAG.getDataLayout().isLittleEndian()) {
1749     unsigned indexOffset = CheckEven ? 4 : 0;
1750     if (ShuffleKind == 1) // Unary
1751       return isVMerge(N, indexOffset, 0);
1752     else if (ShuffleKind == 2) // swapped
1753       return isVMerge(N, indexOffset, 16);
1754     else
1755       return false;
1756   }
1757   else {
1758     unsigned indexOffset = CheckEven ? 0 : 4;
1759     if (ShuffleKind == 1) // Unary
1760       return isVMerge(N, indexOffset, 0);
1761     else if (ShuffleKind == 0) // Normal
1762       return isVMerge(N, indexOffset, 16);
1763     else
1764       return false;
1765   }
1766   return false;
1767 }
1768 
1769 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1770 /// amount, otherwise return -1.
1771 /// The ShuffleKind distinguishes between big-endian operations with two
1772 /// different inputs (0), either-endian operations with two identical inputs
1773 /// (1), and little-endian operations with two different inputs (2).  For the
1774 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1775 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1776                              SelectionDAG &DAG) {
1777   if (N->getValueType(0) != MVT::v16i8)
1778     return -1;
1779 
1780   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1781 
1782   // Find the first non-undef value in the shuffle mask.
1783   unsigned i;
1784   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1785     /*search*/;
1786 
1787   if (i == 16) return -1;  // all undef.
1788 
1789   // Otherwise, check to see if the rest of the elements are consecutively
1790   // numbered from this value.
1791   unsigned ShiftAmt = SVOp->getMaskElt(i);
1792   if (ShiftAmt < i) return -1;
1793 
1794   ShiftAmt -= i;
1795   bool isLE = DAG.getDataLayout().isLittleEndian();
1796 
1797   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1798     // Check the rest of the elements to see if they are consecutive.
1799     for (++i; i != 16; ++i)
1800       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1801         return -1;
1802   } else if (ShuffleKind == 1) {
1803     // Check the rest of the elements to see if they are consecutive.
1804     for (++i; i != 16; ++i)
1805       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1806         return -1;
1807   } else
1808     return -1;
1809 
1810   if (isLE)
1811     ShiftAmt = 16 - ShiftAmt;
1812 
1813   return ShiftAmt;
1814 }
1815 
1816 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1817 /// specifies a splat of a single element that is suitable for input to
1818 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1819 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1820   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1821          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1822 
1823   // The consecutive indices need to specify an element, not part of two
1824   // different elements.  So abandon ship early if this isn't the case.
1825   if (N->getMaskElt(0) % EltSize != 0)
1826     return false;
1827 
1828   // This is a splat operation if each element of the permute is the same, and
1829   // if the value doesn't reference the second vector.
1830   unsigned ElementBase = N->getMaskElt(0);
1831 
1832   // FIXME: Handle UNDEF elements too!
1833   if (ElementBase >= 16)
1834     return false;
1835 
1836   // Check that the indices are consecutive, in the case of a multi-byte element
1837   // splatted with a v16i8 mask.
1838   for (unsigned i = 1; i != EltSize; ++i)
1839     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1840       return false;
1841 
1842   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1843     if (N->getMaskElt(i) < 0) continue;
1844     for (unsigned j = 0; j != EltSize; ++j)
1845       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1846         return false;
1847   }
1848   return true;
1849 }
1850 
1851 /// Check that the mask is shuffling N byte elements. Within each N byte
1852 /// element of the mask, the indices could be either in increasing or
1853 /// decreasing order as long as they are consecutive.
1854 /// \param[in] N the shuffle vector SD Node to analyze
1855 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1856 /// Word/DoubleWord/QuadWord).
1857 /// \param[in] StepLen the delta indices number among the N byte element, if
1858 /// the mask is in increasing/decreasing order then it is 1/-1.
1859 /// \return true iff the mask is shuffling N byte elements.
1860 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1861                                    int StepLen) {
1862   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1863          "Unexpected element width.");
1864   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1865 
1866   unsigned NumOfElem = 16 / Width;
1867   unsigned MaskVal[16]; //  Width is never greater than 16
1868   for (unsigned i = 0; i < NumOfElem; ++i) {
1869     MaskVal[0] = N->getMaskElt(i * Width);
1870     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1871       return false;
1872     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1873       return false;
1874     }
1875 
1876     for (unsigned int j = 1; j < Width; ++j) {
1877       MaskVal[j] = N->getMaskElt(i * Width + j);
1878       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1879         return false;
1880       }
1881     }
1882   }
1883 
1884   return true;
1885 }
1886 
1887 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1888                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1889   if (!isNByteElemShuffleMask(N, 4, 1))
1890     return false;
1891 
1892   // Now we look at mask elements 0,4,8,12
1893   unsigned M0 = N->getMaskElt(0) / 4;
1894   unsigned M1 = N->getMaskElt(4) / 4;
1895   unsigned M2 = N->getMaskElt(8) / 4;
1896   unsigned M3 = N->getMaskElt(12) / 4;
1897   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1898   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1899 
1900   // Below, let H and L be arbitrary elements of the shuffle mask
1901   // where H is in the range [4,7] and L is in the range [0,3].
1902   // H, 1, 2, 3 or L, 5, 6, 7
1903   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1904       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1905     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1906     InsertAtByte = IsLE ? 12 : 0;
1907     Swap = M0 < 4;
1908     return true;
1909   }
1910   // 0, H, 2, 3 or 4, L, 6, 7
1911   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1912       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1913     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1914     InsertAtByte = IsLE ? 8 : 4;
1915     Swap = M1 < 4;
1916     return true;
1917   }
1918   // 0, 1, H, 3 or 4, 5, L, 7
1919   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1920       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1921     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1922     InsertAtByte = IsLE ? 4 : 8;
1923     Swap = M2 < 4;
1924     return true;
1925   }
1926   // 0, 1, 2, H or 4, 5, 6, L
1927   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1928       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1929     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1930     InsertAtByte = IsLE ? 0 : 12;
1931     Swap = M3 < 4;
1932     return true;
1933   }
1934 
1935   // If both vector operands for the shuffle are the same vector, the mask will
1936   // contain only elements from the first one and the second one will be undef.
1937   if (N->getOperand(1).isUndef()) {
1938     ShiftElts = 0;
1939     Swap = true;
1940     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1941     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1942       InsertAtByte = IsLE ? 12 : 0;
1943       return true;
1944     }
1945     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1946       InsertAtByte = IsLE ? 8 : 4;
1947       return true;
1948     }
1949     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1950       InsertAtByte = IsLE ? 4 : 8;
1951       return true;
1952     }
1953     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1954       InsertAtByte = IsLE ? 0 : 12;
1955       return true;
1956     }
1957   }
1958 
1959   return false;
1960 }
1961 
1962 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1963                                bool &Swap, bool IsLE) {
1964   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1965   // Ensure each byte index of the word is consecutive.
1966   if (!isNByteElemShuffleMask(N, 4, 1))
1967     return false;
1968 
1969   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1970   unsigned M0 = N->getMaskElt(0) / 4;
1971   unsigned M1 = N->getMaskElt(4) / 4;
1972   unsigned M2 = N->getMaskElt(8) / 4;
1973   unsigned M3 = N->getMaskElt(12) / 4;
1974 
1975   // If both vector operands for the shuffle are the same vector, the mask will
1976   // contain only elements from the first one and the second one will be undef.
1977   if (N->getOperand(1).isUndef()) {
1978     assert(M0 < 4 && "Indexing into an undef vector?");
1979     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1980       return false;
1981 
1982     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1983     Swap = false;
1984     return true;
1985   }
1986 
1987   // Ensure each word index of the ShuffleVector Mask is consecutive.
1988   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1989     return false;
1990 
1991   if (IsLE) {
1992     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1993       // Input vectors don't need to be swapped if the leading element
1994       // of the result is one of the 3 left elements of the second vector
1995       // (or if there is no shift to be done at all).
1996       Swap = false;
1997       ShiftElts = (8 - M0) % 8;
1998     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1999       // Input vectors need to be swapped if the leading element
2000       // of the result is one of the 3 left elements of the first vector
2001       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2002       Swap = true;
2003       ShiftElts = (4 - M0) % 4;
2004     }
2005 
2006     return true;
2007   } else {                                          // BE
2008     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2009       // Input vectors don't need to be swapped if the leading element
2010       // of the result is one of the 4 elements of the first vector.
2011       Swap = false;
2012       ShiftElts = M0;
2013     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2014       // Input vectors need to be swapped if the leading element
2015       // of the result is one of the 4 elements of the right vector.
2016       Swap = true;
2017       ShiftElts = M0 - 4;
2018     }
2019 
2020     return true;
2021   }
2022 }
2023 
2024 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2025   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2026 
2027   if (!isNByteElemShuffleMask(N, Width, -1))
2028     return false;
2029 
2030   for (int i = 0; i < 16; i += Width)
2031     if (N->getMaskElt(i) != i + Width - 1)
2032       return false;
2033 
2034   return true;
2035 }
2036 
2037 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2038   return isXXBRShuffleMaskHelper(N, 2);
2039 }
2040 
2041 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2042   return isXXBRShuffleMaskHelper(N, 4);
2043 }
2044 
2045 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2046   return isXXBRShuffleMaskHelper(N, 8);
2047 }
2048 
2049 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2050   return isXXBRShuffleMaskHelper(N, 16);
2051 }
2052 
2053 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2054 /// if the inputs to the instruction should be swapped and set \p DM to the
2055 /// value for the immediate.
2056 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2057 /// AND element 0 of the result comes from the first input (LE) or second input
2058 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2059 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2060 /// mask.
2061 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2062                                bool &Swap, bool IsLE) {
2063   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2064 
2065   // Ensure each byte index of the double word is consecutive.
2066   if (!isNByteElemShuffleMask(N, 8, 1))
2067     return false;
2068 
2069   unsigned M0 = N->getMaskElt(0) / 8;
2070   unsigned M1 = N->getMaskElt(8) / 8;
2071   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2072 
2073   // If both vector operands for the shuffle are the same vector, the mask will
2074   // contain only elements from the first one and the second one will be undef.
2075   if (N->getOperand(1).isUndef()) {
2076     if ((M0 | M1) < 2) {
2077       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2078       Swap = false;
2079       return true;
2080     } else
2081       return false;
2082   }
2083 
2084   if (IsLE) {
2085     if (M0 > 1 && M1 < 2) {
2086       Swap = false;
2087     } else if (M0 < 2 && M1 > 1) {
2088       M0 = (M0 + 2) % 4;
2089       M1 = (M1 + 2) % 4;
2090       Swap = true;
2091     } else
2092       return false;
2093 
2094     // Note: if control flow comes here that means Swap is already set above
2095     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2096     return true;
2097   } else { // BE
2098     if (M0 < 2 && M1 > 1) {
2099       Swap = false;
2100     } else if (M0 > 1 && M1 < 2) {
2101       M0 = (M0 + 2) % 4;
2102       M1 = (M1 + 2) % 4;
2103       Swap = true;
2104     } else
2105       return false;
2106 
2107     // Note: if control flow comes here that means Swap is already set above
2108     DM = (M0 << 1) + (M1 & 1);
2109     return true;
2110   }
2111 }
2112 
2113 
2114 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2115 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2116 /// elements are counted from the left of the vector register).
2117 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2118                                          SelectionDAG &DAG) {
2119   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2120   assert(isSplatShuffleMask(SVOp, EltSize));
2121   if (DAG.getDataLayout().isLittleEndian())
2122     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2123   else
2124     return SVOp->getMaskElt(0) / EltSize;
2125 }
2126 
2127 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2128 /// by using a vspltis[bhw] instruction of the specified element size, return
2129 /// the constant being splatted.  The ByteSize field indicates the number of
2130 /// bytes of each element [124] -> [bhw].
2131 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2132   SDValue OpVal(nullptr, 0);
2133 
2134   // If ByteSize of the splat is bigger than the element size of the
2135   // build_vector, then we have a case where we are checking for a splat where
2136   // multiple elements of the buildvector are folded together into a single
2137   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2138   unsigned EltSize = 16/N->getNumOperands();
2139   if (EltSize < ByteSize) {
2140     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2141     SDValue UniquedVals[4];
2142     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2143 
2144     // See if all of the elements in the buildvector agree across.
2145     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2146       if (N->getOperand(i).isUndef()) continue;
2147       // If the element isn't a constant, bail fully out.
2148       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2149 
2150       if (!UniquedVals[i&(Multiple-1)].getNode())
2151         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2152       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2153         return SDValue();  // no match.
2154     }
2155 
2156     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2157     // either constant or undef values that are identical for each chunk.  See
2158     // if these chunks can form into a larger vspltis*.
2159 
2160     // Check to see if all of the leading entries are either 0 or -1.  If
2161     // neither, then this won't fit into the immediate field.
2162     bool LeadingZero = true;
2163     bool LeadingOnes = true;
2164     for (unsigned i = 0; i != Multiple-1; ++i) {
2165       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2166 
2167       LeadingZero &= isNullConstant(UniquedVals[i]);
2168       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2169     }
2170     // Finally, check the least significant entry.
2171     if (LeadingZero) {
2172       if (!UniquedVals[Multiple-1].getNode())
2173         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2174       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2175       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2176         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2177     }
2178     if (LeadingOnes) {
2179       if (!UniquedVals[Multiple-1].getNode())
2180         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2181       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2182       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2183         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2184     }
2185 
2186     return SDValue();
2187   }
2188 
2189   // Check to see if this buildvec has a single non-undef value in its elements.
2190   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2191     if (N->getOperand(i).isUndef()) continue;
2192     if (!OpVal.getNode())
2193       OpVal = N->getOperand(i);
2194     else if (OpVal != N->getOperand(i))
2195       return SDValue();
2196   }
2197 
2198   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2199 
2200   unsigned ValSizeInBytes = EltSize;
2201   uint64_t Value = 0;
2202   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2203     Value = CN->getZExtValue();
2204   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2205     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2206     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2207   }
2208 
2209   // If the splat value is larger than the element value, then we can never do
2210   // this splat.  The only case that we could fit the replicated bits into our
2211   // immediate field for would be zero, and we prefer to use vxor for it.
2212   if (ValSizeInBytes < ByteSize) return SDValue();
2213 
2214   // If the element value is larger than the splat value, check if it consists
2215   // of a repeated bit pattern of size ByteSize.
2216   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2217     return SDValue();
2218 
2219   // Properly sign extend the value.
2220   int MaskVal = SignExtend32(Value, ByteSize * 8);
2221 
2222   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2223   if (MaskVal == 0) return SDValue();
2224 
2225   // Finally, if this value fits in a 5 bit sext field, return it
2226   if (SignExtend32<5>(MaskVal) == MaskVal)
2227     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2228   return SDValue();
2229 }
2230 
2231 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2232 /// amount, otherwise return -1.
2233 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2234   EVT VT = N->getValueType(0);
2235   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2236     return -1;
2237 
2238   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2239 
2240   // Find the first non-undef value in the shuffle mask.
2241   unsigned i;
2242   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2243     /*search*/;
2244 
2245   if (i == 4) return -1;  // all undef.
2246 
2247   // Otherwise, check to see if the rest of the elements are consecutively
2248   // numbered from this value.
2249   unsigned ShiftAmt = SVOp->getMaskElt(i);
2250   if (ShiftAmt < i) return -1;
2251   ShiftAmt -= i;
2252 
2253   // Check the rest of the elements to see if they are consecutive.
2254   for (++i; i != 4; ++i)
2255     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2256       return -1;
2257 
2258   return ShiftAmt;
2259 }
2260 
2261 //===----------------------------------------------------------------------===//
2262 //  Addressing Mode Selection
2263 //===----------------------------------------------------------------------===//
2264 
2265 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2266 /// or 64-bit immediate, and if the value can be accurately represented as a
2267 /// sign extension from a 16-bit value.  If so, this returns true and the
2268 /// immediate.
2269 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2270   if (!isa<ConstantSDNode>(N))
2271     return false;
2272 
2273   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2274   if (N->getValueType(0) == MVT::i32)
2275     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2276   else
2277     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2278 }
2279 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2280   return isIntS16Immediate(Op.getNode(), Imm);
2281 }
2282 
2283 
2284 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2285 /// be represented as an indexed [r+r] operation.
2286 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2287                                                SDValue &Index,
2288                                                SelectionDAG &DAG) const {
2289   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2290       UI != E; ++UI) {
2291     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2292       if (Memop->getMemoryVT() == MVT::f64) {
2293           Base = N.getOperand(0);
2294           Index = N.getOperand(1);
2295           return true;
2296       }
2297     }
2298   }
2299   return false;
2300 }
2301 
2302 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2303 /// can be represented as an indexed [r+r] operation.  Returns false if it
2304 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2305 /// non-zero and N can be represented by a base register plus a signed 16-bit
2306 /// displacement, make a more precise judgement by checking (displacement % \p
2307 /// EncodingAlignment).
2308 bool PPCTargetLowering::SelectAddressRegReg(
2309     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2310     MaybeAlign EncodingAlignment) const {
2311   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2312   // a [pc+imm].
2313   if (SelectAddressPCRel(N, Base))
2314     return false;
2315 
2316   int16_t Imm = 0;
2317   if (N.getOpcode() == ISD::ADD) {
2318     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2319     // SPE load/store can only handle 8-bit offsets.
2320     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2321         return true;
2322     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2323         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2324       return false; // r+i
2325     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2326       return false;    // r+i
2327 
2328     Base = N.getOperand(0);
2329     Index = N.getOperand(1);
2330     return true;
2331   } else if (N.getOpcode() == ISD::OR) {
2332     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2333         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2334       return false; // r+i can fold it if we can.
2335 
2336     // If this is an or of disjoint bitfields, we can codegen this as an add
2337     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2338     // disjoint.
2339     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2340 
2341     if (LHSKnown.Zero.getBoolValue()) {
2342       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2343       // If all of the bits are known zero on the LHS or RHS, the add won't
2344       // carry.
2345       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2346         Base = N.getOperand(0);
2347         Index = N.getOperand(1);
2348         return true;
2349       }
2350     }
2351   }
2352 
2353   return false;
2354 }
2355 
2356 // If we happen to be doing an i64 load or store into a stack slot that has
2357 // less than a 4-byte alignment, then the frame-index elimination may need to
2358 // use an indexed load or store instruction (because the offset may not be a
2359 // multiple of 4). The extra register needed to hold the offset comes from the
2360 // register scavenger, and it is possible that the scavenger will need to use
2361 // an emergency spill slot. As a result, we need to make sure that a spill slot
2362 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2363 // stack slot.
2364 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2365   // FIXME: This does not handle the LWA case.
2366   if (VT != MVT::i64)
2367     return;
2368 
2369   // NOTE: We'll exclude negative FIs here, which come from argument
2370   // lowering, because there are no known test cases triggering this problem
2371   // using packed structures (or similar). We can remove this exclusion if
2372   // we find such a test case. The reason why this is so test-case driven is
2373   // because this entire 'fixup' is only to prevent crashes (from the
2374   // register scavenger) on not-really-valid inputs. For example, if we have:
2375   //   %a = alloca i1
2376   //   %b = bitcast i1* %a to i64*
2377   //   store i64* a, i64 b
2378   // then the store should really be marked as 'align 1', but is not. If it
2379   // were marked as 'align 1' then the indexed form would have been
2380   // instruction-selected initially, and the problem this 'fixup' is preventing
2381   // won't happen regardless.
2382   if (FrameIdx < 0)
2383     return;
2384 
2385   MachineFunction &MF = DAG.getMachineFunction();
2386   MachineFrameInfo &MFI = MF.getFrameInfo();
2387 
2388   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2389     return;
2390 
2391   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2392   FuncInfo->setHasNonRISpills();
2393 }
2394 
2395 /// Returns true if the address N can be represented by a base register plus
2396 /// a signed 16-bit displacement [r+imm], and if it is not better
2397 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2398 /// displacements that are multiples of that value.
2399 bool PPCTargetLowering::SelectAddressRegImm(
2400     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2401     MaybeAlign EncodingAlignment) const {
2402   // FIXME dl should come from parent load or store, not from address
2403   SDLoc dl(N);
2404 
2405   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2406   // a [pc+imm].
2407   if (SelectAddressPCRel(N, Base))
2408     return false;
2409 
2410   // If this can be more profitably realized as r+r, fail.
2411   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2412     return false;
2413 
2414   if (N.getOpcode() == ISD::ADD) {
2415     int16_t imm = 0;
2416     if (isIntS16Immediate(N.getOperand(1), imm) &&
2417         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2418       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2419       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2420         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2421         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2422       } else {
2423         Base = N.getOperand(0);
2424       }
2425       return true; // [r+i]
2426     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2427       // Match LOAD (ADD (X, Lo(G))).
2428       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2429              && "Cannot handle constant offsets yet!");
2430       Disp = N.getOperand(1).getOperand(0);  // The global address.
2431       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2432              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2433              Disp.getOpcode() == ISD::TargetConstantPool ||
2434              Disp.getOpcode() == ISD::TargetJumpTable);
2435       Base = N.getOperand(0);
2436       return true;  // [&g+r]
2437     }
2438   } else if (N.getOpcode() == ISD::OR) {
2439     int16_t imm = 0;
2440     if (isIntS16Immediate(N.getOperand(1), imm) &&
2441         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2442       // If this is an or of disjoint bitfields, we can codegen this as an add
2443       // (for better address arithmetic) if the LHS and RHS of the OR are
2444       // provably disjoint.
2445       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2446 
2447       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2448         // If all of the bits are known zero on the LHS or RHS, the add won't
2449         // carry.
2450         if (FrameIndexSDNode *FI =
2451               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2452           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2453           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2454         } else {
2455           Base = N.getOperand(0);
2456         }
2457         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2458         return true;
2459       }
2460     }
2461   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2462     // Loading from a constant address.
2463 
2464     // If this address fits entirely in a 16-bit sext immediate field, codegen
2465     // this as "d, 0"
2466     int16_t Imm;
2467     if (isIntS16Immediate(CN, Imm) &&
2468         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2469       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2470       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2471                              CN->getValueType(0));
2472       return true;
2473     }
2474 
2475     // Handle 32-bit sext immediates with LIS + addr mode.
2476     if ((CN->getValueType(0) == MVT::i32 ||
2477          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2478         (!EncodingAlignment ||
2479          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2480       int Addr = (int)CN->getZExtValue();
2481 
2482       // Otherwise, break this down into an LIS + disp.
2483       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2484 
2485       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2486                                    MVT::i32);
2487       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2488       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2489       return true;
2490     }
2491   }
2492 
2493   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2494   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2495     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2496     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2497   } else
2498     Base = N;
2499   return true;      // [r+0]
2500 }
2501 
2502 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2503 /// represented as an indexed [r+r] operation.
2504 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2505                                                 SDValue &Index,
2506                                                 SelectionDAG &DAG) const {
2507   // Check to see if we can easily represent this as an [r+r] address.  This
2508   // will fail if it thinks that the address is more profitably represented as
2509   // reg+imm, e.g. where imm = 0.
2510   if (SelectAddressRegReg(N, Base, Index, DAG))
2511     return true;
2512 
2513   // If the address is the result of an add, we will utilize the fact that the
2514   // address calculation includes an implicit add.  However, we can reduce
2515   // register pressure if we do not materialize a constant just for use as the
2516   // index register.  We only get rid of the add if it is not an add of a
2517   // value and a 16-bit signed constant and both have a single use.
2518   int16_t imm = 0;
2519   if (N.getOpcode() == ISD::ADD &&
2520       (!isIntS16Immediate(N.getOperand(1), imm) ||
2521        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2522     Base = N.getOperand(0);
2523     Index = N.getOperand(1);
2524     return true;
2525   }
2526 
2527   // Otherwise, do it the hard way, using R0 as the base register.
2528   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2529                          N.getValueType());
2530   Index = N;
2531   return true;
2532 }
2533 
2534 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2535   Ty *PCRelCand = dyn_cast<Ty>(N);
2536   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2537 }
2538 
2539 /// Returns true if this address is a PC Relative address.
2540 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2541 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2542 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2543   // This is a materialize PC Relative node. Always select this as PC Relative.
2544   Base = N;
2545   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2546     return true;
2547   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2548       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2549       isValidPCRelNode<JumpTableSDNode>(N) ||
2550       isValidPCRelNode<BlockAddressSDNode>(N))
2551     return true;
2552   return false;
2553 }
2554 
2555 /// Returns true if we should use a direct load into vector instruction
2556 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2557 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2558 
2559   // If there are any other uses other than scalar to vector, then we should
2560   // keep it as a scalar load -> direct move pattern to prevent multiple
2561   // loads.
2562   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2563   if (!LD)
2564     return false;
2565 
2566   EVT MemVT = LD->getMemoryVT();
2567   if (!MemVT.isSimple())
2568     return false;
2569   switch(MemVT.getSimpleVT().SimpleTy) {
2570   case MVT::i64:
2571     break;
2572   case MVT::i32:
2573     if (!ST.hasP8Vector())
2574       return false;
2575     break;
2576   case MVT::i16:
2577   case MVT::i8:
2578     if (!ST.hasP9Vector())
2579       return false;
2580     break;
2581   default:
2582     return false;
2583   }
2584 
2585   SDValue LoadedVal(N, 0);
2586   if (!LoadedVal.hasOneUse())
2587     return false;
2588 
2589   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2590        UI != UE; ++UI)
2591     if (UI.getUse().get().getResNo() == 0 &&
2592         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2593         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2594       return false;
2595 
2596   return true;
2597 }
2598 
2599 /// getPreIndexedAddressParts - returns true by value, base pointer and
2600 /// offset pointer and addressing mode by reference if the node's address
2601 /// can be legally represented as pre-indexed load / store address.
2602 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2603                                                   SDValue &Offset,
2604                                                   ISD::MemIndexedMode &AM,
2605                                                   SelectionDAG &DAG) const {
2606   if (DisablePPCPreinc) return false;
2607 
2608   bool isLoad = true;
2609   SDValue Ptr;
2610   EVT VT;
2611   unsigned Alignment;
2612   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2613     Ptr = LD->getBasePtr();
2614     VT = LD->getMemoryVT();
2615     Alignment = LD->getAlignment();
2616   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2617     Ptr = ST->getBasePtr();
2618     VT  = ST->getMemoryVT();
2619     Alignment = ST->getAlignment();
2620     isLoad = false;
2621   } else
2622     return false;
2623 
2624   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2625   // instructions because we can fold these into a more efficient instruction
2626   // instead, (such as LXSD).
2627   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2628     return false;
2629   }
2630 
2631   // PowerPC doesn't have preinc load/store instructions for vectors
2632   if (VT.isVector())
2633     return false;
2634 
2635   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2636     // Common code will reject creating a pre-inc form if the base pointer
2637     // is a frame index, or if N is a store and the base pointer is either
2638     // the same as or a predecessor of the value being stored.  Check for
2639     // those situations here, and try with swapped Base/Offset instead.
2640     bool Swap = false;
2641 
2642     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2643       Swap = true;
2644     else if (!isLoad) {
2645       SDValue Val = cast<StoreSDNode>(N)->getValue();
2646       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2647         Swap = true;
2648     }
2649 
2650     if (Swap)
2651       std::swap(Base, Offset);
2652 
2653     AM = ISD::PRE_INC;
2654     return true;
2655   }
2656 
2657   // LDU/STU can only handle immediates that are a multiple of 4.
2658   if (VT != MVT::i64) {
2659     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2660       return false;
2661   } else {
2662     // LDU/STU need an address with at least 4-byte alignment.
2663     if (Alignment < 4)
2664       return false;
2665 
2666     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2667       return false;
2668   }
2669 
2670   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2671     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2672     // sext i32 to i64 when addr mode is r+i.
2673     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2674         LD->getExtensionType() == ISD::SEXTLOAD &&
2675         isa<ConstantSDNode>(Offset))
2676       return false;
2677   }
2678 
2679   AM = ISD::PRE_INC;
2680   return true;
2681 }
2682 
2683 //===----------------------------------------------------------------------===//
2684 //  LowerOperation implementation
2685 //===----------------------------------------------------------------------===//
2686 
2687 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2688 /// and LoOpFlags to the target MO flags.
2689 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2690                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2691                                const GlobalValue *GV = nullptr) {
2692   HiOpFlags = PPCII::MO_HA;
2693   LoOpFlags = PPCII::MO_LO;
2694 
2695   // Don't use the pic base if not in PIC relocation model.
2696   if (IsPIC) {
2697     HiOpFlags |= PPCII::MO_PIC_FLAG;
2698     LoOpFlags |= PPCII::MO_PIC_FLAG;
2699   }
2700 }
2701 
2702 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2703                              SelectionDAG &DAG) {
2704   SDLoc DL(HiPart);
2705   EVT PtrVT = HiPart.getValueType();
2706   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2707 
2708   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2709   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2710 
2711   // With PIC, the first instruction is actually "GR+hi(&G)".
2712   if (isPIC)
2713     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2714                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2715 
2716   // Generate non-pic code that has direct accesses to the constant pool.
2717   // The address of the global is just (hi(&g)+lo(&g)).
2718   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2719 }
2720 
2721 static void setUsesTOCBasePtr(MachineFunction &MF) {
2722   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2723   FuncInfo->setUsesTOCBasePtr();
2724 }
2725 
2726 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2727   setUsesTOCBasePtr(DAG.getMachineFunction());
2728 }
2729 
2730 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2731                                        SDValue GA) const {
2732   const bool Is64Bit = Subtarget.isPPC64();
2733   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2734   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2735                         : Subtarget.isAIXABI()
2736                               ? DAG.getRegister(PPC::R2, VT)
2737                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2738   SDValue Ops[] = { GA, Reg };
2739   return DAG.getMemIntrinsicNode(
2740       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2741       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2742       MachineMemOperand::MOLoad);
2743 }
2744 
2745 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2746                                              SelectionDAG &DAG) const {
2747   EVT PtrVT = Op.getValueType();
2748   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2749   const Constant *C = CP->getConstVal();
2750 
2751   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2752   // The actual address of the GlobalValue is stored in the TOC.
2753   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2754     if (Subtarget.isUsingPCRelativeCalls()) {
2755       SDLoc DL(CP);
2756       EVT Ty = getPointerTy(DAG.getDataLayout());
2757       SDValue ConstPool = DAG.getTargetConstantPool(
2758           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2759       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2760     }
2761     setUsesTOCBasePtr(DAG);
2762     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2763     return getTOCEntry(DAG, SDLoc(CP), GA);
2764   }
2765 
2766   unsigned MOHiFlag, MOLoFlag;
2767   bool IsPIC = isPositionIndependent();
2768   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2769 
2770   if (IsPIC && Subtarget.isSVR4ABI()) {
2771     SDValue GA =
2772         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2773     return getTOCEntry(DAG, SDLoc(CP), GA);
2774   }
2775 
2776   SDValue CPIHi =
2777       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2778   SDValue CPILo =
2779       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2780   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2781 }
2782 
2783 // For 64-bit PowerPC, prefer the more compact relative encodings.
2784 // This trades 32 bits per jump table entry for one or two instructions
2785 // on the jump site.
2786 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2787   if (isJumpTableRelative())
2788     return MachineJumpTableInfo::EK_LabelDifference32;
2789 
2790   return TargetLowering::getJumpTableEncoding();
2791 }
2792 
2793 bool PPCTargetLowering::isJumpTableRelative() const {
2794   if (UseAbsoluteJumpTables)
2795     return false;
2796   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2797     return true;
2798   return TargetLowering::isJumpTableRelative();
2799 }
2800 
2801 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2802                                                     SelectionDAG &DAG) const {
2803   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2804     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2805 
2806   switch (getTargetMachine().getCodeModel()) {
2807   case CodeModel::Small:
2808   case CodeModel::Medium:
2809     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2810   default:
2811     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2812                        getPointerTy(DAG.getDataLayout()));
2813   }
2814 }
2815 
2816 const MCExpr *
2817 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2818                                                 unsigned JTI,
2819                                                 MCContext &Ctx) const {
2820   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2821     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2822 
2823   switch (getTargetMachine().getCodeModel()) {
2824   case CodeModel::Small:
2825   case CodeModel::Medium:
2826     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2827   default:
2828     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2829   }
2830 }
2831 
2832 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2833   EVT PtrVT = Op.getValueType();
2834   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2835 
2836   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2837   if (Subtarget.isUsingPCRelativeCalls()) {
2838     SDLoc DL(JT);
2839     EVT Ty = getPointerTy(DAG.getDataLayout());
2840     SDValue GA =
2841         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2842     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2843     return MatAddr;
2844   }
2845 
2846   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2847   // The actual address of the GlobalValue is stored in the TOC.
2848   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2849     setUsesTOCBasePtr(DAG);
2850     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2851     return getTOCEntry(DAG, SDLoc(JT), GA);
2852   }
2853 
2854   unsigned MOHiFlag, MOLoFlag;
2855   bool IsPIC = isPositionIndependent();
2856   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2857 
2858   if (IsPIC && Subtarget.isSVR4ABI()) {
2859     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2860                                         PPCII::MO_PIC_FLAG);
2861     return getTOCEntry(DAG, SDLoc(GA), GA);
2862   }
2863 
2864   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2865   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2866   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2867 }
2868 
2869 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2870                                              SelectionDAG &DAG) const {
2871   EVT PtrVT = Op.getValueType();
2872   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2873   const BlockAddress *BA = BASDN->getBlockAddress();
2874 
2875   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2876   if (Subtarget.isUsingPCRelativeCalls()) {
2877     SDLoc DL(BASDN);
2878     EVT Ty = getPointerTy(DAG.getDataLayout());
2879     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2880                                            PPCII::MO_PCREL_FLAG);
2881     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2882     return MatAddr;
2883   }
2884 
2885   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2886   // The actual BlockAddress is stored in the TOC.
2887   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2888     setUsesTOCBasePtr(DAG);
2889     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2890     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2891   }
2892 
2893   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2894   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2895     return getTOCEntry(
2896         DAG, SDLoc(BASDN),
2897         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2898 
2899   unsigned MOHiFlag, MOLoFlag;
2900   bool IsPIC = isPositionIndependent();
2901   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2902   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2903   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2904   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2905 }
2906 
2907 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2908                                               SelectionDAG &DAG) const {
2909   // FIXME: TLS addresses currently use medium model code sequences,
2910   // which is the most useful form.  Eventually support for small and
2911   // large models could be added if users need it, at the cost of
2912   // additional complexity.
2913   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2914   if (DAG.getTarget().useEmulatedTLS())
2915     return LowerToTLSEmulatedModel(GA, DAG);
2916 
2917   SDLoc dl(GA);
2918   const GlobalValue *GV = GA->getGlobal();
2919   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2920   bool is64bit = Subtarget.isPPC64();
2921   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2922   PICLevel::Level picLevel = M->getPICLevel();
2923 
2924   const TargetMachine &TM = getTargetMachine();
2925   TLSModel::Model Model = TM.getTLSModel(GV);
2926 
2927   if (Model == TLSModel::LocalExec) {
2928     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2929                                                PPCII::MO_TPREL_HA);
2930     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2931                                                PPCII::MO_TPREL_LO);
2932     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2933                              : DAG.getRegister(PPC::R2, MVT::i32);
2934 
2935     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2936     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2937   }
2938 
2939   if (Model == TLSModel::InitialExec) {
2940     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2941     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2942                                                 PPCII::MO_TLS);
2943     SDValue GOTPtr;
2944     if (is64bit) {
2945       setUsesTOCBasePtr(DAG);
2946       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2947       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2948                            PtrVT, GOTReg, TGA);
2949     } else {
2950       if (!TM.isPositionIndependent())
2951         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2952       else if (picLevel == PICLevel::SmallPIC)
2953         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2954       else
2955         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2956     }
2957     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2958                                    PtrVT, TGA, GOTPtr);
2959     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2960   }
2961 
2962   if (Model == TLSModel::GeneralDynamic) {
2963     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2964     SDValue GOTPtr;
2965     if (is64bit) {
2966       setUsesTOCBasePtr(DAG);
2967       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2968       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2969                                    GOTReg, TGA);
2970     } else {
2971       if (picLevel == PICLevel::SmallPIC)
2972         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2973       else
2974         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2975     }
2976     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2977                        GOTPtr, TGA, TGA);
2978   }
2979 
2980   if (Model == TLSModel::LocalDynamic) {
2981     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2982     SDValue GOTPtr;
2983     if (is64bit) {
2984       setUsesTOCBasePtr(DAG);
2985       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2986       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2987                            GOTReg, TGA);
2988     } else {
2989       if (picLevel == PICLevel::SmallPIC)
2990         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2991       else
2992         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2993     }
2994     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2995                                   PtrVT, GOTPtr, TGA, TGA);
2996     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2997                                       PtrVT, TLSAddr, TGA);
2998     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2999   }
3000 
3001   llvm_unreachable("Unknown TLS model!");
3002 }
3003 
3004 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3005                                               SelectionDAG &DAG) const {
3006   EVT PtrVT = Op.getValueType();
3007   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3008   SDLoc DL(GSDN);
3009   const GlobalValue *GV = GSDN->getGlobal();
3010 
3011   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3012   // The actual address of the GlobalValue is stored in the TOC.
3013   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3014     if (Subtarget.isUsingPCRelativeCalls()) {
3015       EVT Ty = getPointerTy(DAG.getDataLayout());
3016       if (isAccessedAsGotIndirect(Op)) {
3017         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3018                                                 PPCII::MO_PCREL_FLAG |
3019                                                     PPCII::MO_GOT_FLAG);
3020         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3021         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3022                                    MachinePointerInfo());
3023         return Load;
3024       } else {
3025         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3026                                                 PPCII::MO_PCREL_FLAG);
3027         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3028       }
3029     }
3030     setUsesTOCBasePtr(DAG);
3031     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3032     return getTOCEntry(DAG, DL, GA);
3033   }
3034 
3035   unsigned MOHiFlag, MOLoFlag;
3036   bool IsPIC = isPositionIndependent();
3037   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3038 
3039   if (IsPIC && Subtarget.isSVR4ABI()) {
3040     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3041                                             GSDN->getOffset(),
3042                                             PPCII::MO_PIC_FLAG);
3043     return getTOCEntry(DAG, DL, GA);
3044   }
3045 
3046   SDValue GAHi =
3047     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3048   SDValue GALo =
3049     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3050 
3051   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3052 }
3053 
3054 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3055   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3056   SDLoc dl(Op);
3057 
3058   if (Op.getValueType() == MVT::v2i64) {
3059     // When the operands themselves are v2i64 values, we need to do something
3060     // special because VSX has no underlying comparison operations for these.
3061     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3062       // Equality can be handled by casting to the legal type for Altivec
3063       // comparisons, everything else needs to be expanded.
3064       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3065         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3066                  DAG.getSetCC(dl, MVT::v4i32,
3067                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3068                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3069                    CC));
3070       }
3071 
3072       return SDValue();
3073     }
3074 
3075     // We handle most of these in the usual way.
3076     return Op;
3077   }
3078 
3079   // If we're comparing for equality to zero, expose the fact that this is
3080   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3081   // fold the new nodes.
3082   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3083     return V;
3084 
3085   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3086     // Leave comparisons against 0 and -1 alone for now, since they're usually
3087     // optimized.  FIXME: revisit this when we can custom lower all setcc
3088     // optimizations.
3089     if (C->isAllOnesValue() || C->isNullValue())
3090       return SDValue();
3091   }
3092 
3093   // If we have an integer seteq/setne, turn it into a compare against zero
3094   // by xor'ing the rhs with the lhs, which is faster than setting a
3095   // condition register, reading it back out, and masking the correct bit.  The
3096   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3097   // the result to other bit-twiddling opportunities.
3098   EVT LHSVT = Op.getOperand(0).getValueType();
3099   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3100     EVT VT = Op.getValueType();
3101     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3102                                 Op.getOperand(1));
3103     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3104   }
3105   return SDValue();
3106 }
3107 
3108 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3109   SDNode *Node = Op.getNode();
3110   EVT VT = Node->getValueType(0);
3111   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3112   SDValue InChain = Node->getOperand(0);
3113   SDValue VAListPtr = Node->getOperand(1);
3114   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3115   SDLoc dl(Node);
3116 
3117   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3118 
3119   // gpr_index
3120   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3121                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3122   InChain = GprIndex.getValue(1);
3123 
3124   if (VT == MVT::i64) {
3125     // Check if GprIndex is even
3126     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3127                                  DAG.getConstant(1, dl, MVT::i32));
3128     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3129                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3130     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3131                                           DAG.getConstant(1, dl, MVT::i32));
3132     // Align GprIndex to be even if it isn't
3133     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3134                            GprIndex);
3135   }
3136 
3137   // fpr index is 1 byte after gpr
3138   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3139                                DAG.getConstant(1, dl, MVT::i32));
3140 
3141   // fpr
3142   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3143                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3144   InChain = FprIndex.getValue(1);
3145 
3146   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3147                                        DAG.getConstant(8, dl, MVT::i32));
3148 
3149   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3150                                         DAG.getConstant(4, dl, MVT::i32));
3151 
3152   // areas
3153   SDValue OverflowArea =
3154       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3155   InChain = OverflowArea.getValue(1);
3156 
3157   SDValue RegSaveArea =
3158       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3159   InChain = RegSaveArea.getValue(1);
3160 
3161   // select overflow_area if index > 8
3162   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3163                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3164 
3165   // adjustment constant gpr_index * 4/8
3166   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3167                                     VT.isInteger() ? GprIndex : FprIndex,
3168                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3169                                                     MVT::i32));
3170 
3171   // OurReg = RegSaveArea + RegConstant
3172   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3173                                RegConstant);
3174 
3175   // Floating types are 32 bytes into RegSaveArea
3176   if (VT.isFloatingPoint())
3177     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3178                          DAG.getConstant(32, dl, MVT::i32));
3179 
3180   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3181   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3182                                    VT.isInteger() ? GprIndex : FprIndex,
3183                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3184                                                    MVT::i32));
3185 
3186   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3187                               VT.isInteger() ? VAListPtr : FprPtr,
3188                               MachinePointerInfo(SV), MVT::i8);
3189 
3190   // determine if we should load from reg_save_area or overflow_area
3191   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3192 
3193   // increase overflow_area by 4/8 if gpr/fpr > 8
3194   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3195                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3196                                           dl, MVT::i32));
3197 
3198   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3199                              OverflowAreaPlusN);
3200 
3201   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3202                               MachinePointerInfo(), MVT::i32);
3203 
3204   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3205 }
3206 
3207 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3208   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3209 
3210   // We have to copy the entire va_list struct:
3211   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3212   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3213                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3214                        false, true, false, MachinePointerInfo(),
3215                        MachinePointerInfo());
3216 }
3217 
3218 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3219                                                   SelectionDAG &DAG) const {
3220   if (Subtarget.isAIXABI())
3221     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3222 
3223   return Op.getOperand(0);
3224 }
3225 
3226 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3227                                                 SelectionDAG &DAG) const {
3228   if (Subtarget.isAIXABI())
3229     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3230 
3231   SDValue Chain = Op.getOperand(0);
3232   SDValue Trmp = Op.getOperand(1); // trampoline
3233   SDValue FPtr = Op.getOperand(2); // nested function
3234   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3235   SDLoc dl(Op);
3236 
3237   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3238   bool isPPC64 = (PtrVT == MVT::i64);
3239   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3240 
3241   TargetLowering::ArgListTy Args;
3242   TargetLowering::ArgListEntry Entry;
3243 
3244   Entry.Ty = IntPtrTy;
3245   Entry.Node = Trmp; Args.push_back(Entry);
3246 
3247   // TrampSize == (isPPC64 ? 48 : 40);
3248   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3249                                isPPC64 ? MVT::i64 : MVT::i32);
3250   Args.push_back(Entry);
3251 
3252   Entry.Node = FPtr; Args.push_back(Entry);
3253   Entry.Node = Nest; Args.push_back(Entry);
3254 
3255   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3256   TargetLowering::CallLoweringInfo CLI(DAG);
3257   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3258       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3259       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3260 
3261   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3262   return CallResult.second;
3263 }
3264 
3265 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3266   MachineFunction &MF = DAG.getMachineFunction();
3267   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3268   EVT PtrVT = getPointerTy(MF.getDataLayout());
3269 
3270   SDLoc dl(Op);
3271 
3272   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3273     // vastart just stores the address of the VarArgsFrameIndex slot into the
3274     // memory location argument.
3275     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3276     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3277     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3278                         MachinePointerInfo(SV));
3279   }
3280 
3281   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3282   // We suppose the given va_list is already allocated.
3283   //
3284   // typedef struct {
3285   //  char gpr;     /* index into the array of 8 GPRs
3286   //                 * stored in the register save area
3287   //                 * gpr=0 corresponds to r3,
3288   //                 * gpr=1 to r4, etc.
3289   //                 */
3290   //  char fpr;     /* index into the array of 8 FPRs
3291   //                 * stored in the register save area
3292   //                 * fpr=0 corresponds to f1,
3293   //                 * fpr=1 to f2, etc.
3294   //                 */
3295   //  char *overflow_arg_area;
3296   //                /* location on stack that holds
3297   //                 * the next overflow argument
3298   //                 */
3299   //  char *reg_save_area;
3300   //               /* where r3:r10 and f1:f8 (if saved)
3301   //                * are stored
3302   //                */
3303   // } va_list[1];
3304 
3305   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3306   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3307   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3308                                             PtrVT);
3309   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3310                                  PtrVT);
3311 
3312   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3313   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3314 
3315   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3316   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3317 
3318   uint64_t FPROffset = 1;
3319   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3320 
3321   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3322 
3323   // Store first byte : number of int regs
3324   SDValue firstStore =
3325       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3326                         MachinePointerInfo(SV), MVT::i8);
3327   uint64_t nextOffset = FPROffset;
3328   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3329                                   ConstFPROffset);
3330 
3331   // Store second byte : number of float regs
3332   SDValue secondStore =
3333       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3334                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3335   nextOffset += StackOffset;
3336   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3337 
3338   // Store second word : arguments given on stack
3339   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3340                                     MachinePointerInfo(SV, nextOffset));
3341   nextOffset += FrameOffset;
3342   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3343 
3344   // Store third word : arguments given in registers
3345   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3346                       MachinePointerInfo(SV, nextOffset));
3347 }
3348 
3349 /// FPR - The set of FP registers that should be allocated for arguments
3350 /// on Darwin and AIX.
3351 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3352                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3353                                 PPC::F11, PPC::F12, PPC::F13};
3354 
3355 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3356 /// the stack.
3357 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3358                                        unsigned PtrByteSize) {
3359   unsigned ArgSize = ArgVT.getStoreSize();
3360   if (Flags.isByVal())
3361     ArgSize = Flags.getByValSize();
3362 
3363   // Round up to multiples of the pointer size, except for array members,
3364   // which are always packed.
3365   if (!Flags.isInConsecutiveRegs())
3366     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3367 
3368   return ArgSize;
3369 }
3370 
3371 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3372 /// on the stack.
3373 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3374                                          ISD::ArgFlagsTy Flags,
3375                                          unsigned PtrByteSize) {
3376   Align Alignment(PtrByteSize);
3377 
3378   // Altivec parameters are padded to a 16 byte boundary.
3379   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3380       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3381       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3382       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3383     Alignment = Align(16);
3384 
3385   // ByVal parameters are aligned as requested.
3386   if (Flags.isByVal()) {
3387     auto BVAlign = Flags.getNonZeroByValAlign();
3388     if (BVAlign > PtrByteSize) {
3389       if (BVAlign.value() % PtrByteSize != 0)
3390         llvm_unreachable(
3391             "ByVal alignment is not a multiple of the pointer size");
3392 
3393       Alignment = BVAlign;
3394     }
3395   }
3396 
3397   // Array members are always packed to their original alignment.
3398   if (Flags.isInConsecutiveRegs()) {
3399     // If the array member was split into multiple registers, the first
3400     // needs to be aligned to the size of the full type.  (Except for
3401     // ppcf128, which is only aligned as its f64 components.)
3402     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3403       Alignment = Align(OrigVT.getStoreSize());
3404     else
3405       Alignment = Align(ArgVT.getStoreSize());
3406   }
3407 
3408   return Alignment;
3409 }
3410 
3411 /// CalculateStackSlotUsed - Return whether this argument will use its
3412 /// stack slot (instead of being passed in registers).  ArgOffset,
3413 /// AvailableFPRs, and AvailableVRs must hold the current argument
3414 /// position, and will be updated to account for this argument.
3415 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3416                                    unsigned PtrByteSize, unsigned LinkageSize,
3417                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3418                                    unsigned &AvailableFPRs,
3419                                    unsigned &AvailableVRs) {
3420   bool UseMemory = false;
3421 
3422   // Respect alignment of argument on the stack.
3423   Align Alignment =
3424       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3425   ArgOffset = alignTo(ArgOffset, Alignment);
3426   // If there's no space left in the argument save area, we must
3427   // use memory (this check also catches zero-sized arguments).
3428   if (ArgOffset >= LinkageSize + ParamAreaSize)
3429     UseMemory = true;
3430 
3431   // Allocate argument on the stack.
3432   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3433   if (Flags.isInConsecutiveRegsLast())
3434     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3435   // If we overran the argument save area, we must use memory
3436   // (this check catches arguments passed partially in memory)
3437   if (ArgOffset > LinkageSize + ParamAreaSize)
3438     UseMemory = true;
3439 
3440   // However, if the argument is actually passed in an FPR or a VR,
3441   // we don't use memory after all.
3442   if (!Flags.isByVal()) {
3443     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3444       if (AvailableFPRs > 0) {
3445         --AvailableFPRs;
3446         return false;
3447       }
3448     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3449         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3450         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3451         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3452       if (AvailableVRs > 0) {
3453         --AvailableVRs;
3454         return false;
3455       }
3456   }
3457 
3458   return UseMemory;
3459 }
3460 
3461 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3462 /// ensure minimum alignment required for target.
3463 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3464                                      unsigned NumBytes) {
3465   return alignTo(NumBytes, Lowering->getStackAlign());
3466 }
3467 
3468 SDValue PPCTargetLowering::LowerFormalArguments(
3469     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3470     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3471     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3472   if (Subtarget.isAIXABI())
3473     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3474                                     InVals);
3475   if (Subtarget.is64BitELFABI())
3476     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3477                                        InVals);
3478   if (Subtarget.is32BitELFABI())
3479     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3480                                        InVals);
3481 
3482   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3483                                      InVals);
3484 }
3485 
3486 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3487     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3488     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3489     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3490 
3491   // 32-bit SVR4 ABI Stack Frame Layout:
3492   //              +-----------------------------------+
3493   //        +-->  |            Back chain             |
3494   //        |     +-----------------------------------+
3495   //        |     | Floating-point register save area |
3496   //        |     +-----------------------------------+
3497   //        |     |    General register save area     |
3498   //        |     +-----------------------------------+
3499   //        |     |          CR save word             |
3500   //        |     +-----------------------------------+
3501   //        |     |         VRSAVE save word          |
3502   //        |     +-----------------------------------+
3503   //        |     |         Alignment padding         |
3504   //        |     +-----------------------------------+
3505   //        |     |     Vector register save area     |
3506   //        |     +-----------------------------------+
3507   //        |     |       Local variable space        |
3508   //        |     +-----------------------------------+
3509   //        |     |        Parameter list area        |
3510   //        |     +-----------------------------------+
3511   //        |     |           LR save word            |
3512   //        |     +-----------------------------------+
3513   // SP-->  +---  |            Back chain             |
3514   //              +-----------------------------------+
3515   //
3516   // Specifications:
3517   //   System V Application Binary Interface PowerPC Processor Supplement
3518   //   AltiVec Technology Programming Interface Manual
3519 
3520   MachineFunction &MF = DAG.getMachineFunction();
3521   MachineFrameInfo &MFI = MF.getFrameInfo();
3522   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3523 
3524   EVT PtrVT = getPointerTy(MF.getDataLayout());
3525   // Potential tail calls could cause overwriting of argument stack slots.
3526   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3527                        (CallConv == CallingConv::Fast));
3528   const Align PtrAlign(4);
3529 
3530   // Assign locations to all of the incoming arguments.
3531   SmallVector<CCValAssign, 16> ArgLocs;
3532   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3533                  *DAG.getContext());
3534 
3535   // Reserve space for the linkage area on the stack.
3536   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3537   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3538   if (useSoftFloat())
3539     CCInfo.PreAnalyzeFormalArguments(Ins);
3540 
3541   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3542   CCInfo.clearWasPPCF128();
3543 
3544   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3545     CCValAssign &VA = ArgLocs[i];
3546 
3547     // Arguments stored in registers.
3548     if (VA.isRegLoc()) {
3549       const TargetRegisterClass *RC;
3550       EVT ValVT = VA.getValVT();
3551 
3552       switch (ValVT.getSimpleVT().SimpleTy) {
3553         default:
3554           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3555         case MVT::i1:
3556         case MVT::i32:
3557           RC = &PPC::GPRCRegClass;
3558           break;
3559         case MVT::f32:
3560           if (Subtarget.hasP8Vector())
3561             RC = &PPC::VSSRCRegClass;
3562           else if (Subtarget.hasSPE())
3563             RC = &PPC::GPRCRegClass;
3564           else
3565             RC = &PPC::F4RCRegClass;
3566           break;
3567         case MVT::f64:
3568           if (Subtarget.hasVSX())
3569             RC = &PPC::VSFRCRegClass;
3570           else if (Subtarget.hasSPE())
3571             // SPE passes doubles in GPR pairs.
3572             RC = &PPC::GPRCRegClass;
3573           else
3574             RC = &PPC::F8RCRegClass;
3575           break;
3576         case MVT::v16i8:
3577         case MVT::v8i16:
3578         case MVT::v4i32:
3579           RC = &PPC::VRRCRegClass;
3580           break;
3581         case MVT::v4f32:
3582           RC = &PPC::VRRCRegClass;
3583           break;
3584         case MVT::v2f64:
3585         case MVT::v2i64:
3586           RC = &PPC::VRRCRegClass;
3587           break;
3588       }
3589 
3590       SDValue ArgValue;
3591       // Transform the arguments stored in physical registers into
3592       // virtual ones.
3593       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3594         assert(i + 1 < e && "No second half of double precision argument");
3595         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3596         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3597         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3598         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3599         if (!Subtarget.isLittleEndian())
3600           std::swap (ArgValueLo, ArgValueHi);
3601         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3602                                ArgValueHi);
3603       } else {
3604         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3605         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3606                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3607         if (ValVT == MVT::i1)
3608           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3609       }
3610 
3611       InVals.push_back(ArgValue);
3612     } else {
3613       // Argument stored in memory.
3614       assert(VA.isMemLoc());
3615 
3616       // Get the extended size of the argument type in stack
3617       unsigned ArgSize = VA.getLocVT().getStoreSize();
3618       // Get the actual size of the argument type
3619       unsigned ObjSize = VA.getValVT().getStoreSize();
3620       unsigned ArgOffset = VA.getLocMemOffset();
3621       // Stack objects in PPC32 are right justified.
3622       ArgOffset += ArgSize - ObjSize;
3623       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3624 
3625       // Create load nodes to retrieve arguments from the stack.
3626       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3627       InVals.push_back(
3628           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3629     }
3630   }
3631 
3632   // Assign locations to all of the incoming aggregate by value arguments.
3633   // Aggregates passed by value are stored in the local variable space of the
3634   // caller's stack frame, right above the parameter list area.
3635   SmallVector<CCValAssign, 16> ByValArgLocs;
3636   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3637                       ByValArgLocs, *DAG.getContext());
3638 
3639   // Reserve stack space for the allocations in CCInfo.
3640   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3641 
3642   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3643 
3644   // Area that is at least reserved in the caller of this function.
3645   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3646   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3647 
3648   // Set the size that is at least reserved in caller of this function.  Tail
3649   // call optimized function's reserved stack space needs to be aligned so that
3650   // taking the difference between two stack areas will result in an aligned
3651   // stack.
3652   MinReservedArea =
3653       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3654   FuncInfo->setMinReservedArea(MinReservedArea);
3655 
3656   SmallVector<SDValue, 8> MemOps;
3657 
3658   // If the function takes variable number of arguments, make a frame index for
3659   // the start of the first vararg value... for expansion of llvm.va_start.
3660   if (isVarArg) {
3661     static const MCPhysReg GPArgRegs[] = {
3662       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3663       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3664     };
3665     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3666 
3667     static const MCPhysReg FPArgRegs[] = {
3668       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3669       PPC::F8
3670     };
3671     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3672 
3673     if (useSoftFloat() || hasSPE())
3674        NumFPArgRegs = 0;
3675 
3676     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3677     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3678 
3679     // Make room for NumGPArgRegs and NumFPArgRegs.
3680     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3681                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3682 
3683     FuncInfo->setVarArgsStackOffset(
3684       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3685                             CCInfo.getNextStackOffset(), true));
3686 
3687     FuncInfo->setVarArgsFrameIndex(
3688         MFI.CreateStackObject(Depth, Align(8), false));
3689     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3690 
3691     // The fixed integer arguments of a variadic function are stored to the
3692     // VarArgsFrameIndex on the stack so that they may be loaded by
3693     // dereferencing the result of va_next.
3694     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3695       // Get an existing live-in vreg, or add a new one.
3696       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3697       if (!VReg)
3698         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3699 
3700       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3701       SDValue Store =
3702           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3703       MemOps.push_back(Store);
3704       // Increment the address by four for the next argument to store
3705       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3706       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3707     }
3708 
3709     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3710     // is set.
3711     // The double arguments are stored to the VarArgsFrameIndex
3712     // on the stack.
3713     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3714       // Get an existing live-in vreg, or add a new one.
3715       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3716       if (!VReg)
3717         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3718 
3719       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3720       SDValue Store =
3721           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3722       MemOps.push_back(Store);
3723       // Increment the address by eight for the next argument to store
3724       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3725                                          PtrVT);
3726       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3727     }
3728   }
3729 
3730   if (!MemOps.empty())
3731     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3732 
3733   return Chain;
3734 }
3735 
3736 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3737 // value to MVT::i64 and then truncate to the correct register size.
3738 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3739                                              EVT ObjectVT, SelectionDAG &DAG,
3740                                              SDValue ArgVal,
3741                                              const SDLoc &dl) const {
3742   if (Flags.isSExt())
3743     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3744                          DAG.getValueType(ObjectVT));
3745   else if (Flags.isZExt())
3746     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3747                          DAG.getValueType(ObjectVT));
3748 
3749   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3750 }
3751 
3752 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3753     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3754     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3755     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3756   // TODO: add description of PPC stack frame format, or at least some docs.
3757   //
3758   bool isELFv2ABI = Subtarget.isELFv2ABI();
3759   bool isLittleEndian = Subtarget.isLittleEndian();
3760   MachineFunction &MF = DAG.getMachineFunction();
3761   MachineFrameInfo &MFI = MF.getFrameInfo();
3762   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3763 
3764   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3765          "fastcc not supported on varargs functions");
3766 
3767   EVT PtrVT = getPointerTy(MF.getDataLayout());
3768   // Potential tail calls could cause overwriting of argument stack slots.
3769   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3770                        (CallConv == CallingConv::Fast));
3771   unsigned PtrByteSize = 8;
3772   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3773 
3774   static const MCPhysReg GPR[] = {
3775     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3776     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3777   };
3778   static const MCPhysReg VR[] = {
3779     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3780     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3781   };
3782 
3783   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3784   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3785   const unsigned Num_VR_Regs  = array_lengthof(VR);
3786 
3787   // Do a first pass over the arguments to determine whether the ABI
3788   // guarantees that our caller has allocated the parameter save area
3789   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3790   // in the ELFv2 ABI, it is true if this is a vararg function or if
3791   // any parameter is located in a stack slot.
3792 
3793   bool HasParameterArea = !isELFv2ABI || isVarArg;
3794   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3795   unsigned NumBytes = LinkageSize;
3796   unsigned AvailableFPRs = Num_FPR_Regs;
3797   unsigned AvailableVRs = Num_VR_Regs;
3798   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3799     if (Ins[i].Flags.isNest())
3800       continue;
3801 
3802     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3803                                PtrByteSize, LinkageSize, ParamAreaSize,
3804                                NumBytes, AvailableFPRs, AvailableVRs))
3805       HasParameterArea = true;
3806   }
3807 
3808   // Add DAG nodes to load the arguments or copy them out of registers.  On
3809   // entry to a function on PPC, the arguments start after the linkage area,
3810   // although the first ones are often in registers.
3811 
3812   unsigned ArgOffset = LinkageSize;
3813   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3814   SmallVector<SDValue, 8> MemOps;
3815   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3816   unsigned CurArgIdx = 0;
3817   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3818     SDValue ArgVal;
3819     bool needsLoad = false;
3820     EVT ObjectVT = Ins[ArgNo].VT;
3821     EVT OrigVT = Ins[ArgNo].ArgVT;
3822     unsigned ObjSize = ObjectVT.getStoreSize();
3823     unsigned ArgSize = ObjSize;
3824     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3825     if (Ins[ArgNo].isOrigArg()) {
3826       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3827       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3828     }
3829     // We re-align the argument offset for each argument, except when using the
3830     // fast calling convention, when we need to make sure we do that only when
3831     // we'll actually use a stack slot.
3832     unsigned CurArgOffset;
3833     Align Alignment;
3834     auto ComputeArgOffset = [&]() {
3835       /* Respect alignment of argument on the stack.  */
3836       Alignment =
3837           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3838       ArgOffset = alignTo(ArgOffset, Alignment);
3839       CurArgOffset = ArgOffset;
3840     };
3841 
3842     if (CallConv != CallingConv::Fast) {
3843       ComputeArgOffset();
3844 
3845       /* Compute GPR index associated with argument offset.  */
3846       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3847       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3848     }
3849 
3850     // FIXME the codegen can be much improved in some cases.
3851     // We do not have to keep everything in memory.
3852     if (Flags.isByVal()) {
3853       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3854 
3855       if (CallConv == CallingConv::Fast)
3856         ComputeArgOffset();
3857 
3858       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3859       ObjSize = Flags.getByValSize();
3860       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3861       // Empty aggregate parameters do not take up registers.  Examples:
3862       //   struct { } a;
3863       //   union  { } b;
3864       //   int c[0];
3865       // etc.  However, we have to provide a place-holder in InVals, so
3866       // pretend we have an 8-byte item at the current address for that
3867       // purpose.
3868       if (!ObjSize) {
3869         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3870         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3871         InVals.push_back(FIN);
3872         continue;
3873       }
3874 
3875       // Create a stack object covering all stack doublewords occupied
3876       // by the argument.  If the argument is (fully or partially) on
3877       // the stack, or if the argument is fully in registers but the
3878       // caller has allocated the parameter save anyway, we can refer
3879       // directly to the caller's stack frame.  Otherwise, create a
3880       // local copy in our own frame.
3881       int FI;
3882       if (HasParameterArea ||
3883           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3884         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3885       else
3886         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3887       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3888 
3889       // Handle aggregates smaller than 8 bytes.
3890       if (ObjSize < PtrByteSize) {
3891         // The value of the object is its address, which differs from the
3892         // address of the enclosing doubleword on big-endian systems.
3893         SDValue Arg = FIN;
3894         if (!isLittleEndian) {
3895           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3896           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3897         }
3898         InVals.push_back(Arg);
3899 
3900         if (GPR_idx != Num_GPR_Regs) {
3901           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3902           FuncInfo->addLiveInAttr(VReg, Flags);
3903           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3904           SDValue Store;
3905 
3906           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3907             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3908                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3909             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3910                                       MachinePointerInfo(&*FuncArg), ObjType);
3911           } else {
3912             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3913             // store the whole register as-is to the parameter save area
3914             // slot.
3915             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3916                                  MachinePointerInfo(&*FuncArg));
3917           }
3918 
3919           MemOps.push_back(Store);
3920         }
3921         // Whether we copied from a register or not, advance the offset
3922         // into the parameter save area by a full doubleword.
3923         ArgOffset += PtrByteSize;
3924         continue;
3925       }
3926 
3927       // The value of the object is its address, which is the address of
3928       // its first stack doubleword.
3929       InVals.push_back(FIN);
3930 
3931       // Store whatever pieces of the object are in registers to memory.
3932       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3933         if (GPR_idx == Num_GPR_Regs)
3934           break;
3935 
3936         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3937         FuncInfo->addLiveInAttr(VReg, Flags);
3938         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3939         SDValue Addr = FIN;
3940         if (j) {
3941           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3942           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3943         }
3944         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3945                                      MachinePointerInfo(&*FuncArg, j));
3946         MemOps.push_back(Store);
3947         ++GPR_idx;
3948       }
3949       ArgOffset += ArgSize;
3950       continue;
3951     }
3952 
3953     switch (ObjectVT.getSimpleVT().SimpleTy) {
3954     default: llvm_unreachable("Unhandled argument type!");
3955     case MVT::i1:
3956     case MVT::i32:
3957     case MVT::i64:
3958       if (Flags.isNest()) {
3959         // The 'nest' parameter, if any, is passed in R11.
3960         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3961         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3962 
3963         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3964           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3965 
3966         break;
3967       }
3968 
3969       // These can be scalar arguments or elements of an integer array type
3970       // passed directly.  Clang may use those instead of "byval" aggregate
3971       // types to avoid forcing arguments to memory unnecessarily.
3972       if (GPR_idx != Num_GPR_Regs) {
3973         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3974         FuncInfo->addLiveInAttr(VReg, Flags);
3975         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3976 
3977         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3978           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3979           // value to MVT::i64 and then truncate to the correct register size.
3980           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3981       } else {
3982         if (CallConv == CallingConv::Fast)
3983           ComputeArgOffset();
3984 
3985         needsLoad = true;
3986         ArgSize = PtrByteSize;
3987       }
3988       if (CallConv != CallingConv::Fast || needsLoad)
3989         ArgOffset += 8;
3990       break;
3991 
3992     case MVT::f32:
3993     case MVT::f64:
3994       // These can be scalar arguments or elements of a float array type
3995       // passed directly.  The latter are used to implement ELFv2 homogenous
3996       // float aggregates.
3997       if (FPR_idx != Num_FPR_Regs) {
3998         unsigned VReg;
3999 
4000         if (ObjectVT == MVT::f32)
4001           VReg = MF.addLiveIn(FPR[FPR_idx],
4002                               Subtarget.hasP8Vector()
4003                                   ? &PPC::VSSRCRegClass
4004                                   : &PPC::F4RCRegClass);
4005         else
4006           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4007                                                 ? &PPC::VSFRCRegClass
4008                                                 : &PPC::F8RCRegClass);
4009 
4010         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4011         ++FPR_idx;
4012       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4013         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4014         // once we support fp <-> gpr moves.
4015 
4016         // This can only ever happen in the presence of f32 array types,
4017         // since otherwise we never run out of FPRs before running out
4018         // of GPRs.
4019         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4020         FuncInfo->addLiveInAttr(VReg, Flags);
4021         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4022 
4023         if (ObjectVT == MVT::f32) {
4024           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4025             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4026                                  DAG.getConstant(32, dl, MVT::i32));
4027           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4028         }
4029 
4030         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4031       } else {
4032         if (CallConv == CallingConv::Fast)
4033           ComputeArgOffset();
4034 
4035         needsLoad = true;
4036       }
4037 
4038       // When passing an array of floats, the array occupies consecutive
4039       // space in the argument area; only round up to the next doubleword
4040       // at the end of the array.  Otherwise, each float takes 8 bytes.
4041       if (CallConv != CallingConv::Fast || needsLoad) {
4042         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4043         ArgOffset += ArgSize;
4044         if (Flags.isInConsecutiveRegsLast())
4045           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4046       }
4047       break;
4048     case MVT::v4f32:
4049     case MVT::v4i32:
4050     case MVT::v8i16:
4051     case MVT::v16i8:
4052     case MVT::v2f64:
4053     case MVT::v2i64:
4054     case MVT::v1i128:
4055     case MVT::f128:
4056       // These can be scalar arguments or elements of a vector array type
4057       // passed directly.  The latter are used to implement ELFv2 homogenous
4058       // vector aggregates.
4059       if (VR_idx != Num_VR_Regs) {
4060         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4061         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4062         ++VR_idx;
4063       } else {
4064         if (CallConv == CallingConv::Fast)
4065           ComputeArgOffset();
4066         needsLoad = true;
4067       }
4068       if (CallConv != CallingConv::Fast || needsLoad)
4069         ArgOffset += 16;
4070       break;
4071     }
4072 
4073     // We need to load the argument to a virtual register if we determined
4074     // above that we ran out of physical registers of the appropriate type.
4075     if (needsLoad) {
4076       if (ObjSize < ArgSize && !isLittleEndian)
4077         CurArgOffset += ArgSize - ObjSize;
4078       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4079       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4080       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4081     }
4082 
4083     InVals.push_back(ArgVal);
4084   }
4085 
4086   // Area that is at least reserved in the caller of this function.
4087   unsigned MinReservedArea;
4088   if (HasParameterArea)
4089     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4090   else
4091     MinReservedArea = LinkageSize;
4092 
4093   // Set the size that is at least reserved in caller of this function.  Tail
4094   // call optimized functions' reserved stack space needs to be aligned so that
4095   // taking the difference between two stack areas will result in an aligned
4096   // stack.
4097   MinReservedArea =
4098       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4099   FuncInfo->setMinReservedArea(MinReservedArea);
4100 
4101   // If the function takes variable number of arguments, make a frame index for
4102   // the start of the first vararg value... for expansion of llvm.va_start.
4103   // On ELFv2ABI spec, it writes:
4104   // C programs that are intended to be *portable* across different compilers
4105   // and architectures must use the header file <stdarg.h> to deal with variable
4106   // argument lists.
4107   if (isVarArg && MFI.hasVAStart()) {
4108     int Depth = ArgOffset;
4109 
4110     FuncInfo->setVarArgsFrameIndex(
4111       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4112     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4113 
4114     // If this function is vararg, store any remaining integer argument regs
4115     // to their spots on the stack so that they may be loaded by dereferencing
4116     // the result of va_next.
4117     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4118          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4119       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4120       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4121       SDValue Store =
4122           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4123       MemOps.push_back(Store);
4124       // Increment the address by four for the next argument to store
4125       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4126       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4127     }
4128   }
4129 
4130   if (!MemOps.empty())
4131     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4132 
4133   return Chain;
4134 }
4135 
4136 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4137     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4138     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4139     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4140   // TODO: add description of PPC stack frame format, or at least some docs.
4141   //
4142   MachineFunction &MF = DAG.getMachineFunction();
4143   MachineFrameInfo &MFI = MF.getFrameInfo();
4144   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4145 
4146   EVT PtrVT = getPointerTy(MF.getDataLayout());
4147   bool isPPC64 = PtrVT == MVT::i64;
4148   // Potential tail calls could cause overwriting of argument stack slots.
4149   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4150                        (CallConv == CallingConv::Fast));
4151   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4152   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4153   unsigned ArgOffset = LinkageSize;
4154   // Area that is at least reserved in caller of this function.
4155   unsigned MinReservedArea = ArgOffset;
4156 
4157   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4158     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4159     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4160   };
4161   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4162     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4163     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4164   };
4165   static const MCPhysReg VR[] = {
4166     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4167     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4168   };
4169 
4170   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4171   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4172   const unsigned Num_VR_Regs  = array_lengthof( VR);
4173 
4174   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4175 
4176   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4177 
4178   // In 32-bit non-varargs functions, the stack space for vectors is after the
4179   // stack space for non-vectors.  We do not use this space unless we have
4180   // too many vectors to fit in registers, something that only occurs in
4181   // constructed examples:), but we have to walk the arglist to figure
4182   // that out...for the pathological case, compute VecArgOffset as the
4183   // start of the vector parameter area.  Computing VecArgOffset is the
4184   // entire point of the following loop.
4185   unsigned VecArgOffset = ArgOffset;
4186   if (!isVarArg && !isPPC64) {
4187     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4188          ++ArgNo) {
4189       EVT ObjectVT = Ins[ArgNo].VT;
4190       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4191 
4192       if (Flags.isByVal()) {
4193         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4194         unsigned ObjSize = Flags.getByValSize();
4195         unsigned ArgSize =
4196                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4197         VecArgOffset += ArgSize;
4198         continue;
4199       }
4200 
4201       switch(ObjectVT.getSimpleVT().SimpleTy) {
4202       default: llvm_unreachable("Unhandled argument type!");
4203       case MVT::i1:
4204       case MVT::i32:
4205       case MVT::f32:
4206         VecArgOffset += 4;
4207         break;
4208       case MVT::i64:  // PPC64
4209       case MVT::f64:
4210         // FIXME: We are guaranteed to be !isPPC64 at this point.
4211         // Does MVT::i64 apply?
4212         VecArgOffset += 8;
4213         break;
4214       case MVT::v4f32:
4215       case MVT::v4i32:
4216       case MVT::v8i16:
4217       case MVT::v16i8:
4218         // Nothing to do, we're only looking at Nonvector args here.
4219         break;
4220       }
4221     }
4222   }
4223   // We've found where the vector parameter area in memory is.  Skip the
4224   // first 12 parameters; these don't use that memory.
4225   VecArgOffset = ((VecArgOffset+15)/16)*16;
4226   VecArgOffset += 12*16;
4227 
4228   // Add DAG nodes to load the arguments or copy them out of registers.  On
4229   // entry to a function on PPC, the arguments start after the linkage area,
4230   // although the first ones are often in registers.
4231 
4232   SmallVector<SDValue, 8> MemOps;
4233   unsigned nAltivecParamsAtEnd = 0;
4234   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4235   unsigned CurArgIdx = 0;
4236   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4237     SDValue ArgVal;
4238     bool needsLoad = false;
4239     EVT ObjectVT = Ins[ArgNo].VT;
4240     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4241     unsigned ArgSize = ObjSize;
4242     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4243     if (Ins[ArgNo].isOrigArg()) {
4244       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4245       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4246     }
4247     unsigned CurArgOffset = ArgOffset;
4248 
4249     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4250     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4251         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4252       if (isVarArg || isPPC64) {
4253         MinReservedArea = ((MinReservedArea+15)/16)*16;
4254         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4255                                                   Flags,
4256                                                   PtrByteSize);
4257       } else  nAltivecParamsAtEnd++;
4258     } else
4259       // Calculate min reserved area.
4260       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4261                                                 Flags,
4262                                                 PtrByteSize);
4263 
4264     // FIXME the codegen can be much improved in some cases.
4265     // We do not have to keep everything in memory.
4266     if (Flags.isByVal()) {
4267       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4268 
4269       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4270       ObjSize = Flags.getByValSize();
4271       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4272       // Objects of size 1 and 2 are right justified, everything else is
4273       // left justified.  This means the memory address is adjusted forwards.
4274       if (ObjSize==1 || ObjSize==2) {
4275         CurArgOffset = CurArgOffset + (4 - ObjSize);
4276       }
4277       // The value of the object is its address.
4278       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4279       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4280       InVals.push_back(FIN);
4281       if (ObjSize==1 || ObjSize==2) {
4282         if (GPR_idx != Num_GPR_Regs) {
4283           unsigned VReg;
4284           if (isPPC64)
4285             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4286           else
4287             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4288           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4289           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4290           SDValue Store =
4291               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4292                                 MachinePointerInfo(&*FuncArg), ObjType);
4293           MemOps.push_back(Store);
4294           ++GPR_idx;
4295         }
4296 
4297         ArgOffset += PtrByteSize;
4298 
4299         continue;
4300       }
4301       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4302         // Store whatever pieces of the object are in registers
4303         // to memory.  ArgOffset will be the address of the beginning
4304         // of the object.
4305         if (GPR_idx != Num_GPR_Regs) {
4306           unsigned VReg;
4307           if (isPPC64)
4308             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4309           else
4310             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4311           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4312           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4313           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4314           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4315                                        MachinePointerInfo(&*FuncArg, j));
4316           MemOps.push_back(Store);
4317           ++GPR_idx;
4318           ArgOffset += PtrByteSize;
4319         } else {
4320           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4321           break;
4322         }
4323       }
4324       continue;
4325     }
4326 
4327     switch (ObjectVT.getSimpleVT().SimpleTy) {
4328     default: llvm_unreachable("Unhandled argument type!");
4329     case MVT::i1:
4330     case MVT::i32:
4331       if (!isPPC64) {
4332         if (GPR_idx != Num_GPR_Regs) {
4333           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4334           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4335 
4336           if (ObjectVT == MVT::i1)
4337             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4338 
4339           ++GPR_idx;
4340         } else {
4341           needsLoad = true;
4342           ArgSize = PtrByteSize;
4343         }
4344         // All int arguments reserve stack space in the Darwin ABI.
4345         ArgOffset += PtrByteSize;
4346         break;
4347       }
4348       LLVM_FALLTHROUGH;
4349     case MVT::i64:  // PPC64
4350       if (GPR_idx != Num_GPR_Regs) {
4351         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4352         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4353 
4354         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4355           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4356           // value to MVT::i64 and then truncate to the correct register size.
4357           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4358 
4359         ++GPR_idx;
4360       } else {
4361         needsLoad = true;
4362         ArgSize = PtrByteSize;
4363       }
4364       // All int arguments reserve stack space in the Darwin ABI.
4365       ArgOffset += 8;
4366       break;
4367 
4368     case MVT::f32:
4369     case MVT::f64:
4370       // Every 4 bytes of argument space consumes one of the GPRs available for
4371       // argument passing.
4372       if (GPR_idx != Num_GPR_Regs) {
4373         ++GPR_idx;
4374         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4375           ++GPR_idx;
4376       }
4377       if (FPR_idx != Num_FPR_Regs) {
4378         unsigned VReg;
4379 
4380         if (ObjectVT == MVT::f32)
4381           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4382         else
4383           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4384 
4385         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4386         ++FPR_idx;
4387       } else {
4388         needsLoad = true;
4389       }
4390 
4391       // All FP arguments reserve stack space in the Darwin ABI.
4392       ArgOffset += isPPC64 ? 8 : ObjSize;
4393       break;
4394     case MVT::v4f32:
4395     case MVT::v4i32:
4396     case MVT::v8i16:
4397     case MVT::v16i8:
4398       // Note that vector arguments in registers don't reserve stack space,
4399       // except in varargs functions.
4400       if (VR_idx != Num_VR_Regs) {
4401         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4402         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4403         if (isVarArg) {
4404           while ((ArgOffset % 16) != 0) {
4405             ArgOffset += PtrByteSize;
4406             if (GPR_idx != Num_GPR_Regs)
4407               GPR_idx++;
4408           }
4409           ArgOffset += 16;
4410           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4411         }
4412         ++VR_idx;
4413       } else {
4414         if (!isVarArg && !isPPC64) {
4415           // Vectors go after all the nonvectors.
4416           CurArgOffset = VecArgOffset;
4417           VecArgOffset += 16;
4418         } else {
4419           // Vectors are aligned.
4420           ArgOffset = ((ArgOffset+15)/16)*16;
4421           CurArgOffset = ArgOffset;
4422           ArgOffset += 16;
4423         }
4424         needsLoad = true;
4425       }
4426       break;
4427     }
4428 
4429     // We need to load the argument to a virtual register if we determined above
4430     // that we ran out of physical registers of the appropriate type.
4431     if (needsLoad) {
4432       int FI = MFI.CreateFixedObject(ObjSize,
4433                                      CurArgOffset + (ArgSize - ObjSize),
4434                                      isImmutable);
4435       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4436       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4437     }
4438 
4439     InVals.push_back(ArgVal);
4440   }
4441 
4442   // Allow for Altivec parameters at the end, if needed.
4443   if (nAltivecParamsAtEnd) {
4444     MinReservedArea = ((MinReservedArea+15)/16)*16;
4445     MinReservedArea += 16*nAltivecParamsAtEnd;
4446   }
4447 
4448   // Area that is at least reserved in the caller of this function.
4449   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4450 
4451   // Set the size that is at least reserved in caller of this function.  Tail
4452   // call optimized functions' reserved stack space needs to be aligned so that
4453   // taking the difference between two stack areas will result in an aligned
4454   // stack.
4455   MinReservedArea =
4456       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4457   FuncInfo->setMinReservedArea(MinReservedArea);
4458 
4459   // If the function takes variable number of arguments, make a frame index for
4460   // the start of the first vararg value... for expansion of llvm.va_start.
4461   if (isVarArg) {
4462     int Depth = ArgOffset;
4463 
4464     FuncInfo->setVarArgsFrameIndex(
4465       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4466                             Depth, true));
4467     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4468 
4469     // If this function is vararg, store any remaining integer argument regs
4470     // to their spots on the stack so that they may be loaded by dereferencing
4471     // the result of va_next.
4472     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4473       unsigned VReg;
4474 
4475       if (isPPC64)
4476         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4477       else
4478         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4479 
4480       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4481       SDValue Store =
4482           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4483       MemOps.push_back(Store);
4484       // Increment the address by four for the next argument to store
4485       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4486       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4487     }
4488   }
4489 
4490   if (!MemOps.empty())
4491     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4492 
4493   return Chain;
4494 }
4495 
4496 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4497 /// adjusted to accommodate the arguments for the tailcall.
4498 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4499                                    unsigned ParamSize) {
4500 
4501   if (!isTailCall) return 0;
4502 
4503   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4504   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4505   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4506   // Remember only if the new adjustment is bigger.
4507   if (SPDiff < FI->getTailCallSPDelta())
4508     FI->setTailCallSPDelta(SPDiff);
4509 
4510   return SPDiff;
4511 }
4512 
4513 static bool isFunctionGlobalAddress(SDValue Callee);
4514 
4515 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4516                               const TargetMachine &TM) {
4517   // It does not make sense to call callsShareTOCBase() with a caller that
4518   // is PC Relative since PC Relative callers do not have a TOC.
4519 #ifndef NDEBUG
4520   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4521   assert(!STICaller->isUsingPCRelativeCalls() &&
4522          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4523 #endif
4524 
4525   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4526   // don't have enough information to determine if the caller and callee share
4527   // the same  TOC base, so we have to pessimistically assume they don't for
4528   // correctness.
4529   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4530   if (!G)
4531     return false;
4532 
4533   const GlobalValue *GV = G->getGlobal();
4534 
4535   // If the callee is preemptable, then the static linker will use a plt-stub
4536   // which saves the toc to the stack, and needs a nop after the call
4537   // instruction to convert to a toc-restore.
4538   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4539     return false;
4540 
4541   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4542   // We may need a TOC restore in the situation where the caller requires a
4543   // valid TOC but the callee is PC Relative and does not.
4544   const Function *F = dyn_cast<Function>(GV);
4545   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4546 
4547   // If we have an Alias we can try to get the function from there.
4548   if (Alias) {
4549     const GlobalObject *GlobalObj = Alias->getBaseObject();
4550     F = dyn_cast<Function>(GlobalObj);
4551   }
4552 
4553   // If we still have no valid function pointer we do not have enough
4554   // information to determine if the callee uses PC Relative calls so we must
4555   // assume that it does.
4556   if (!F)
4557     return false;
4558 
4559   // If the callee uses PC Relative we cannot guarantee that the callee won't
4560   // clobber the TOC of the caller and so we must assume that the two
4561   // functions do not share a TOC base.
4562   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4563   if (STICallee->isUsingPCRelativeCalls())
4564     return false;
4565 
4566   // The medium and large code models are expected to provide a sufficiently
4567   // large TOC to provide all data addressing needs of a module with a
4568   // single TOC.
4569   if (CodeModel::Medium == TM.getCodeModel() ||
4570       CodeModel::Large == TM.getCodeModel())
4571     return true;
4572 
4573   // Otherwise we need to ensure callee and caller are in the same section,
4574   // since the linker may allocate multiple TOCs, and we don't know which
4575   // sections will belong to the same TOC base.
4576   if (!GV->isStrongDefinitionForLinker())
4577     return false;
4578 
4579   // Any explicitly-specified sections and section prefixes must also match.
4580   // Also, if we're using -ffunction-sections, then each function is always in
4581   // a different section (the same is true for COMDAT functions).
4582   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4583       GV->getSection() != Caller->getSection())
4584     return false;
4585   if (const auto *F = dyn_cast<Function>(GV)) {
4586     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4587       return false;
4588   }
4589 
4590   return true;
4591 }
4592 
4593 static bool
4594 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4595                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4596   assert(Subtarget.is64BitELFABI());
4597 
4598   const unsigned PtrByteSize = 8;
4599   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4600 
4601   static const MCPhysReg GPR[] = {
4602     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4603     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4604   };
4605   static const MCPhysReg VR[] = {
4606     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4607     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4608   };
4609 
4610   const unsigned NumGPRs = array_lengthof(GPR);
4611   const unsigned NumFPRs = 13;
4612   const unsigned NumVRs = array_lengthof(VR);
4613   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4614 
4615   unsigned NumBytes = LinkageSize;
4616   unsigned AvailableFPRs = NumFPRs;
4617   unsigned AvailableVRs = NumVRs;
4618 
4619   for (const ISD::OutputArg& Param : Outs) {
4620     if (Param.Flags.isNest()) continue;
4621 
4622     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4623                                LinkageSize, ParamAreaSize, NumBytes,
4624                                AvailableFPRs, AvailableVRs))
4625       return true;
4626   }
4627   return false;
4628 }
4629 
4630 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4631   if (CB.arg_size() != CallerFn->arg_size())
4632     return false;
4633 
4634   auto CalleeArgIter = CB.arg_begin();
4635   auto CalleeArgEnd = CB.arg_end();
4636   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4637 
4638   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4639     const Value* CalleeArg = *CalleeArgIter;
4640     const Value* CallerArg = &(*CallerArgIter);
4641     if (CalleeArg == CallerArg)
4642       continue;
4643 
4644     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4645     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4646     //      }
4647     // 1st argument of callee is undef and has the same type as caller.
4648     if (CalleeArg->getType() == CallerArg->getType() &&
4649         isa<UndefValue>(CalleeArg))
4650       continue;
4651 
4652     return false;
4653   }
4654 
4655   return true;
4656 }
4657 
4658 // Returns true if TCO is possible between the callers and callees
4659 // calling conventions.
4660 static bool
4661 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4662                                     CallingConv::ID CalleeCC) {
4663   // Tail calls are possible with fastcc and ccc.
4664   auto isTailCallableCC  = [] (CallingConv::ID CC){
4665       return  CC == CallingConv::C || CC == CallingConv::Fast;
4666   };
4667   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4668     return false;
4669 
4670   // We can safely tail call both fastcc and ccc callees from a c calling
4671   // convention caller. If the caller is fastcc, we may have less stack space
4672   // than a non-fastcc caller with the same signature so disable tail-calls in
4673   // that case.
4674   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4675 }
4676 
4677 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4678     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4679     const SmallVectorImpl<ISD::OutputArg> &Outs,
4680     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4681   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4682 
4683   if (DisableSCO && !TailCallOpt) return false;
4684 
4685   // Variadic argument functions are not supported.
4686   if (isVarArg) return false;
4687 
4688   auto &Caller = DAG.getMachineFunction().getFunction();
4689   // Check that the calling conventions are compatible for tco.
4690   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4691     return false;
4692 
4693   // Caller contains any byval parameter is not supported.
4694   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4695     return false;
4696 
4697   // Callee contains any byval parameter is not supported, too.
4698   // Note: This is a quick work around, because in some cases, e.g.
4699   // caller's stack size > callee's stack size, we are still able to apply
4700   // sibling call optimization. For example, gcc is able to do SCO for caller1
4701   // in the following example, but not for caller2.
4702   //   struct test {
4703   //     long int a;
4704   //     char ary[56];
4705   //   } gTest;
4706   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4707   //     b->a = v.a;
4708   //     return 0;
4709   //   }
4710   //   void caller1(struct test a, struct test c, struct test *b) {
4711   //     callee(gTest, b); }
4712   //   void caller2(struct test *b) { callee(gTest, b); }
4713   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4714     return false;
4715 
4716   // If callee and caller use different calling conventions, we cannot pass
4717   // parameters on stack since offsets for the parameter area may be different.
4718   if (Caller.getCallingConv() != CalleeCC &&
4719       needStackSlotPassParameters(Subtarget, Outs))
4720     return false;
4721 
4722   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4723   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4724   // callee potentially have different TOC bases then we cannot tail call since
4725   // we need to restore the TOC pointer after the call.
4726   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4727   // We cannot guarantee this for indirect calls or calls to external functions.
4728   // When PC-Relative addressing is used, the concept of the TOC is no longer
4729   // applicable so this check is not required.
4730   // Check first for indirect calls.
4731   if (!Subtarget.isUsingPCRelativeCalls() &&
4732       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4733     return false;
4734 
4735   // Check if we share the TOC base.
4736   if (!Subtarget.isUsingPCRelativeCalls() &&
4737       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4738     return false;
4739 
4740   // TCO allows altering callee ABI, so we don't have to check further.
4741   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4742     return true;
4743 
4744   if (DisableSCO) return false;
4745 
4746   // If callee use the same argument list that caller is using, then we can
4747   // apply SCO on this case. If it is not, then we need to check if callee needs
4748   // stack for passing arguments.
4749   // PC Relative tail calls may not have a CallBase.
4750   // If there is no CallBase we cannot verify if we have the same argument
4751   // list so assume that we don't have the same argument list.
4752   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4753       needStackSlotPassParameters(Subtarget, Outs))
4754     return false;
4755   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4756     return false;
4757 
4758   return true;
4759 }
4760 
4761 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4762 /// for tail call optimization. Targets which want to do tail call
4763 /// optimization should implement this function.
4764 bool
4765 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4766                                                      CallingConv::ID CalleeCC,
4767                                                      bool isVarArg,
4768                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4769                                                      SelectionDAG& DAG) const {
4770   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4771     return false;
4772 
4773   // Variable argument functions are not supported.
4774   if (isVarArg)
4775     return false;
4776 
4777   MachineFunction &MF = DAG.getMachineFunction();
4778   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4779   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4780     // Functions containing by val parameters are not supported.
4781     for (unsigned i = 0; i != Ins.size(); i++) {
4782        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4783        if (Flags.isByVal()) return false;
4784     }
4785 
4786     // Non-PIC/GOT tail calls are supported.
4787     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4788       return true;
4789 
4790     // At the moment we can only do local tail calls (in same module, hidden
4791     // or protected) if we are generating PIC.
4792     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4793       return G->getGlobal()->hasHiddenVisibility()
4794           || G->getGlobal()->hasProtectedVisibility();
4795   }
4796 
4797   return false;
4798 }
4799 
4800 /// isCallCompatibleAddress - Return the immediate to use if the specified
4801 /// 32-bit value is representable in the immediate field of a BxA instruction.
4802 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4803   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4804   if (!C) return nullptr;
4805 
4806   int Addr = C->getZExtValue();
4807   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4808       SignExtend32<26>(Addr) != Addr)
4809     return nullptr;  // Top 6 bits have to be sext of immediate.
4810 
4811   return DAG
4812       .getConstant(
4813           (int)C->getZExtValue() >> 2, SDLoc(Op),
4814           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4815       .getNode();
4816 }
4817 
4818 namespace {
4819 
4820 struct TailCallArgumentInfo {
4821   SDValue Arg;
4822   SDValue FrameIdxOp;
4823   int FrameIdx = 0;
4824 
4825   TailCallArgumentInfo() = default;
4826 };
4827 
4828 } // end anonymous namespace
4829 
4830 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4831 static void StoreTailCallArgumentsToStackSlot(
4832     SelectionDAG &DAG, SDValue Chain,
4833     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4834     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4835   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4836     SDValue Arg = TailCallArgs[i].Arg;
4837     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4838     int FI = TailCallArgs[i].FrameIdx;
4839     // Store relative to framepointer.
4840     MemOpChains.push_back(DAG.getStore(
4841         Chain, dl, Arg, FIN,
4842         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4843   }
4844 }
4845 
4846 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4847 /// the appropriate stack slot for the tail call optimized function call.
4848 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4849                                              SDValue OldRetAddr, SDValue OldFP,
4850                                              int SPDiff, const SDLoc &dl) {
4851   if (SPDiff) {
4852     // Calculate the new stack slot for the return address.
4853     MachineFunction &MF = DAG.getMachineFunction();
4854     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4855     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4856     bool isPPC64 = Subtarget.isPPC64();
4857     int SlotSize = isPPC64 ? 8 : 4;
4858     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4859     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4860                                                          NewRetAddrLoc, true);
4861     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4862     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4863     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4864                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4865   }
4866   return Chain;
4867 }
4868 
4869 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4870 /// the position of the argument.
4871 static void
4872 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4873                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4874                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4875   int Offset = ArgOffset + SPDiff;
4876   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4877   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4878   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4879   SDValue FIN = DAG.getFrameIndex(FI, VT);
4880   TailCallArgumentInfo Info;
4881   Info.Arg = Arg;
4882   Info.FrameIdxOp = FIN;
4883   Info.FrameIdx = FI;
4884   TailCallArguments.push_back(Info);
4885 }
4886 
4887 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4888 /// stack slot. Returns the chain as result and the loaded frame pointers in
4889 /// LROpOut/FPOpout. Used when tail calling.
4890 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4891     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4892     SDValue &FPOpOut, const SDLoc &dl) const {
4893   if (SPDiff) {
4894     // Load the LR and FP stack slot for later adjusting.
4895     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4896     LROpOut = getReturnAddrFrameIndex(DAG);
4897     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4898     Chain = SDValue(LROpOut.getNode(), 1);
4899   }
4900   return Chain;
4901 }
4902 
4903 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4904 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4905 /// specified by the specific parameter attribute. The copy will be passed as
4906 /// a byval function parameter.
4907 /// Sometimes what we are copying is the end of a larger object, the part that
4908 /// does not fit in registers.
4909 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4910                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4911                                          SelectionDAG &DAG, const SDLoc &dl) {
4912   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4913   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4914                        Flags.getNonZeroByValAlign(), false, false, false,
4915                        MachinePointerInfo(), MachinePointerInfo());
4916 }
4917 
4918 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4919 /// tail calls.
4920 static void LowerMemOpCallTo(
4921     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4922     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4923     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4924     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4925   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4926   if (!isTailCall) {
4927     if (isVector) {
4928       SDValue StackPtr;
4929       if (isPPC64)
4930         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4931       else
4932         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4933       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4934                            DAG.getConstant(ArgOffset, dl, PtrVT));
4935     }
4936     MemOpChains.push_back(
4937         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4938     // Calculate and remember argument location.
4939   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4940                                   TailCallArguments);
4941 }
4942 
4943 static void
4944 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4945                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4946                 SDValue FPOp,
4947                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4948   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4949   // might overwrite each other in case of tail call optimization.
4950   SmallVector<SDValue, 8> MemOpChains2;
4951   // Do not flag preceding copytoreg stuff together with the following stuff.
4952   InFlag = SDValue();
4953   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4954                                     MemOpChains2, dl);
4955   if (!MemOpChains2.empty())
4956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4957 
4958   // Store the return address to the appropriate stack slot.
4959   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4960 
4961   // Emit callseq_end just before tailcall node.
4962   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4963                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4964   InFlag = Chain.getValue(1);
4965 }
4966 
4967 // Is this global address that of a function that can be called by name? (as
4968 // opposed to something that must hold a descriptor for an indirect call).
4969 static bool isFunctionGlobalAddress(SDValue Callee) {
4970   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4971     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4972         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4973       return false;
4974 
4975     return G->getGlobal()->getValueType()->isFunctionTy();
4976   }
4977 
4978   return false;
4979 }
4980 
4981 SDValue PPCTargetLowering::LowerCallResult(
4982     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4983     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4984     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4985   SmallVector<CCValAssign, 16> RVLocs;
4986   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4987                     *DAG.getContext());
4988 
4989   CCRetInfo.AnalyzeCallResult(
4990       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4991                ? RetCC_PPC_Cold
4992                : RetCC_PPC);
4993 
4994   // Copy all of the result registers out of their specified physreg.
4995   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4996     CCValAssign &VA = RVLocs[i];
4997     assert(VA.isRegLoc() && "Can only return in registers!");
4998 
4999     SDValue Val;
5000 
5001     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5002       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5003                                       InFlag);
5004       Chain = Lo.getValue(1);
5005       InFlag = Lo.getValue(2);
5006       VA = RVLocs[++i]; // skip ahead to next loc
5007       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5008                                       InFlag);
5009       Chain = Hi.getValue(1);
5010       InFlag = Hi.getValue(2);
5011       if (!Subtarget.isLittleEndian())
5012         std::swap (Lo, Hi);
5013       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5014     } else {
5015       Val = DAG.getCopyFromReg(Chain, dl,
5016                                VA.getLocReg(), VA.getLocVT(), InFlag);
5017       Chain = Val.getValue(1);
5018       InFlag = Val.getValue(2);
5019     }
5020 
5021     switch (VA.getLocInfo()) {
5022     default: llvm_unreachable("Unknown loc info!");
5023     case CCValAssign::Full: break;
5024     case CCValAssign::AExt:
5025       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5026       break;
5027     case CCValAssign::ZExt:
5028       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5029                         DAG.getValueType(VA.getValVT()));
5030       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5031       break;
5032     case CCValAssign::SExt:
5033       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5034                         DAG.getValueType(VA.getValVT()));
5035       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5036       break;
5037     }
5038 
5039     InVals.push_back(Val);
5040   }
5041 
5042   return Chain;
5043 }
5044 
5045 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5046                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5047   // PatchPoint calls are not indirect.
5048   if (isPatchPoint)
5049     return false;
5050 
5051   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5052     return false;
5053 
5054   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5055   // becuase the immediate function pointer points to a descriptor instead of
5056   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5057   // pointer immediate points to the global entry point, while the BLA would
5058   // need to jump to the local entry point (see rL211174).
5059   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5060       isBLACompatibleAddress(Callee, DAG))
5061     return false;
5062 
5063   return true;
5064 }
5065 
5066 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5067 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5068   return Subtarget.isAIXABI() ||
5069          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5070 }
5071 
5072 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5073                               const Function &Caller,
5074                               const SDValue &Callee,
5075                               const PPCSubtarget &Subtarget,
5076                               const TargetMachine &TM) {
5077   if (CFlags.IsTailCall)
5078     return PPCISD::TC_RETURN;
5079 
5080   // This is a call through a function pointer.
5081   if (CFlags.IsIndirect) {
5082     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5083     // indirect calls. The save of the caller's TOC pointer to the stack will be
5084     // inserted into the DAG as part of call lowering. The restore of the TOC
5085     // pointer is modeled by using a pseudo instruction for the call opcode that
5086     // represents the 2 instruction sequence of an indirect branch and link,
5087     // immediately followed by a load of the TOC pointer from the the stack save
5088     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5089     // as it is not saved or used.
5090     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5091                                                : PPCISD::BCTRL;
5092   }
5093 
5094   if (Subtarget.isUsingPCRelativeCalls()) {
5095     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5096     return PPCISD::CALL_NOTOC;
5097   }
5098 
5099   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5100   // immediately following the call instruction if the caller and callee may
5101   // have different TOC bases. At link time if the linker determines the calls
5102   // may not share a TOC base, the call is redirected to a trampoline inserted
5103   // by the linker. The trampoline will (among other things) save the callers
5104   // TOC pointer at an ABI designated offset in the linkage area and the linker
5105   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5106   // into gpr2.
5107   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5108     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5109                                                   : PPCISD::CALL_NOP;
5110 
5111   return PPCISD::CALL;
5112 }
5113 
5114 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5115                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5116   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5117     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5118       return SDValue(Dest, 0);
5119 
5120   // Returns true if the callee is local, and false otherwise.
5121   auto isLocalCallee = [&]() {
5122     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5123     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5124     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5125 
5126     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5127            !dyn_cast_or_null<GlobalIFunc>(GV);
5128   };
5129 
5130   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5131   // a static relocation model causes some versions of GNU LD (2.17.50, at
5132   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5133   // built with secure-PLT.
5134   bool UsePlt =
5135       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5136       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5137 
5138   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5139     const TargetMachine &TM = Subtarget.getTargetMachine();
5140     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5141     MCSymbolXCOFF *S =
5142         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5143 
5144     if (GV->isDeclaration() && !S->hasRepresentedCsectSet()) {
5145       // On AIX, an undefined symbol needs to be associated with a
5146       // MCSectionXCOFF to get the correct storage mapping class.
5147       // In this case, XCOFF::XMC_PR.
5148       const XCOFF::StorageClass SC =
5149           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GV);
5150       auto &Context = DAG.getMachineFunction().getMMI().getContext();
5151       MCSectionXCOFF *Sec = Context.getXCOFFSection(
5152           S->getSymbolTableName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5153           SectionKind::getMetadata());
5154       S->setRepresentedCsect(Sec);
5155     }
5156 
5157     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5158     return DAG.getMCSymbol(S, PtrVT);
5159   };
5160 
5161   if (isFunctionGlobalAddress(Callee)) {
5162     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5163 
5164     if (Subtarget.isAIXABI()) {
5165       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5166       return getAIXFuncEntryPointSymbolSDNode(GV);
5167     }
5168     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5169                                       UsePlt ? PPCII::MO_PLT : 0);
5170   }
5171 
5172   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5173     const char *SymName = S->getSymbol();
5174     if (Subtarget.isAIXABI()) {
5175       // If there exists a user-declared function whose name is the same as the
5176       // ExternalSymbol's, then we pick up the user-declared version.
5177       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5178       if (const Function *F =
5179               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5180         return getAIXFuncEntryPointSymbolSDNode(F);
5181 
5182       // On AIX, direct function calls reference the symbol for the function's
5183       // entry point, which is named by prepending a "." before the function's
5184       // C-linkage name.
5185       const auto getFunctionEntryPointSymbol = [&](StringRef SymName) {
5186         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5187         return cast<MCSymbolXCOFF>(
5188             Context.getOrCreateSymbol(Twine(".") + Twine(SymName)));
5189       };
5190 
5191       SymName = getFunctionEntryPointSymbol(SymName)->getName().data();
5192     }
5193     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5194                                        UsePlt ? PPCII::MO_PLT : 0);
5195   }
5196 
5197   // No transformation needed.
5198   assert(Callee.getNode() && "What no callee?");
5199   return Callee;
5200 }
5201 
5202 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5203   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5204          "Expected a CALLSEQ_STARTSDNode.");
5205 
5206   // The last operand is the chain, except when the node has glue. If the node
5207   // has glue, then the last operand is the glue, and the chain is the second
5208   // last operand.
5209   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5210   if (LastValue.getValueType() != MVT::Glue)
5211     return LastValue;
5212 
5213   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5214 }
5215 
5216 // Creates the node that moves a functions address into the count register
5217 // to prepare for an indirect call instruction.
5218 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5219                                 SDValue &Glue, SDValue &Chain,
5220                                 const SDLoc &dl) {
5221   SDValue MTCTROps[] = {Chain, Callee, Glue};
5222   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5223   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5224                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5225   // The glue is the second value produced.
5226   Glue = Chain.getValue(1);
5227 }
5228 
5229 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5230                                           SDValue &Glue, SDValue &Chain,
5231                                           SDValue CallSeqStart,
5232                                           const CallBase *CB, const SDLoc &dl,
5233                                           bool hasNest,
5234                                           const PPCSubtarget &Subtarget) {
5235   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5236   // entry point, but to the function descriptor (the function entry point
5237   // address is part of the function descriptor though).
5238   // The function descriptor is a three doubleword structure with the
5239   // following fields: function entry point, TOC base address and
5240   // environment pointer.
5241   // Thus for a call through a function pointer, the following actions need
5242   // to be performed:
5243   //   1. Save the TOC of the caller in the TOC save area of its stack
5244   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5245   //   2. Load the address of the function entry point from the function
5246   //      descriptor.
5247   //   3. Load the TOC of the callee from the function descriptor into r2.
5248   //   4. Load the environment pointer from the function descriptor into
5249   //      r11.
5250   //   5. Branch to the function entry point address.
5251   //   6. On return of the callee, the TOC of the caller needs to be
5252   //      restored (this is done in FinishCall()).
5253   //
5254   // The loads are scheduled at the beginning of the call sequence, and the
5255   // register copies are flagged together to ensure that no other
5256   // operations can be scheduled in between. E.g. without flagging the
5257   // copies together, a TOC access in the caller could be scheduled between
5258   // the assignment of the callee TOC and the branch to the callee, which leads
5259   // to incorrect code.
5260 
5261   // Start by loading the function address from the descriptor.
5262   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5263   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5264                       ? (MachineMemOperand::MODereferenceable |
5265                          MachineMemOperand::MOInvariant)
5266                       : MachineMemOperand::MONone;
5267 
5268   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5269 
5270   // Registers used in building the DAG.
5271   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5272   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5273 
5274   // Offsets of descriptor members.
5275   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5276   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5277 
5278   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5279   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5280 
5281   // One load for the functions entry point address.
5282   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5283                                     Alignment, MMOFlags);
5284 
5285   // One for loading the TOC anchor for the module that contains the called
5286   // function.
5287   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5288   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5289   SDValue TOCPtr =
5290       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5291                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5292 
5293   // One for loading the environment pointer.
5294   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5295   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5296   SDValue LoadEnvPtr =
5297       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5298                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5299 
5300 
5301   // Then copy the newly loaded TOC anchor to the TOC pointer.
5302   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5303   Chain = TOCVal.getValue(0);
5304   Glue = TOCVal.getValue(1);
5305 
5306   // If the function call has an explicit 'nest' parameter, it takes the
5307   // place of the environment pointer.
5308   assert((!hasNest || !Subtarget.isAIXABI()) &&
5309          "Nest parameter is not supported on AIX.");
5310   if (!hasNest) {
5311     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5312     Chain = EnvVal.getValue(0);
5313     Glue = EnvVal.getValue(1);
5314   }
5315 
5316   // The rest of the indirect call sequence is the same as the non-descriptor
5317   // DAG.
5318   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5319 }
5320 
5321 static void
5322 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5323                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5324                   SelectionDAG &DAG,
5325                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5326                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5327                   const PPCSubtarget &Subtarget) {
5328   const bool IsPPC64 = Subtarget.isPPC64();
5329   // MVT for a general purpose register.
5330   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5331 
5332   // First operand is always the chain.
5333   Ops.push_back(Chain);
5334 
5335   // If it's a direct call pass the callee as the second operand.
5336   if (!CFlags.IsIndirect)
5337     Ops.push_back(Callee);
5338   else {
5339     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5340 
5341     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5342     // on the stack (this would have been done in `LowerCall_64SVR4` or
5343     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5344     // represents both the indirect branch and a load that restores the TOC
5345     // pointer from the linkage area. The operand for the TOC restore is an add
5346     // of the TOC save offset to the stack pointer. This must be the second
5347     // operand: after the chain input but before any other variadic arguments.
5348     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5349     // saved or used.
5350     if (isTOCSaveRestoreRequired(Subtarget)) {
5351       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5352 
5353       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5354       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5355       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5356       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5357       Ops.push_back(AddTOC);
5358     }
5359 
5360     // Add the register used for the environment pointer.
5361     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5362       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5363                                     RegVT));
5364 
5365 
5366     // Add CTR register as callee so a bctr can be emitted later.
5367     if (CFlags.IsTailCall)
5368       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5369   }
5370 
5371   // If this is a tail call add stack pointer delta.
5372   if (CFlags.IsTailCall)
5373     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5374 
5375   // Add argument registers to the end of the list so that they are known live
5376   // into the call.
5377   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5378     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5379                                   RegsToPass[i].second.getValueType()));
5380 
5381   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5382   // no way to mark dependencies as implicit here.
5383   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5384   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5385        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5386     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5387 
5388   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5389   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5390     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5391 
5392   // Add a register mask operand representing the call-preserved registers.
5393   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5394   const uint32_t *Mask =
5395       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5396   assert(Mask && "Missing call preserved mask for calling convention");
5397   Ops.push_back(DAG.getRegisterMask(Mask));
5398 
5399   // If the glue is valid, it is the last operand.
5400   if (Glue.getNode())
5401     Ops.push_back(Glue);
5402 }
5403 
5404 SDValue PPCTargetLowering::FinishCall(
5405     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5406     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5407     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5408     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5409     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5410 
5411   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5412       Subtarget.isAIXABI())
5413     setUsesTOCBasePtr(DAG);
5414 
5415   unsigned CallOpc =
5416       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5417                     Subtarget, DAG.getTarget());
5418 
5419   if (!CFlags.IsIndirect)
5420     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5421   else if (Subtarget.usesFunctionDescriptors())
5422     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5423                                   dl, CFlags.HasNest, Subtarget);
5424   else
5425     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5426 
5427   // Build the operand list for the call instruction.
5428   SmallVector<SDValue, 8> Ops;
5429   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5430                     SPDiff, Subtarget);
5431 
5432   // Emit tail call.
5433   if (CFlags.IsTailCall) {
5434     // Indirect tail call when using PC Relative calls do not have the same
5435     // constraints.
5436     assert(((Callee.getOpcode() == ISD::Register &&
5437              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5438             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5439             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5440             isa<ConstantSDNode>(Callee) ||
5441             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5442            "Expecting a global address, external symbol, absolute value, "
5443            "register or an indirect tail call when PC Relative calls are "
5444            "used.");
5445     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5446     assert(CallOpc == PPCISD::TC_RETURN &&
5447            "Unexpected call opcode for a tail call.");
5448     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5449     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5450   }
5451 
5452   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5453   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5454   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5455   Glue = Chain.getValue(1);
5456 
5457   // When performing tail call optimization the callee pops its arguments off
5458   // the stack. Account for this here so these bytes can be pushed back on in
5459   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5460   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5461                          getTargetMachine().Options.GuaranteedTailCallOpt)
5462                             ? NumBytes
5463                             : 0;
5464 
5465   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5466                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5467                              Glue, dl);
5468   Glue = Chain.getValue(1);
5469 
5470   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5471                          DAG, InVals);
5472 }
5473 
5474 SDValue
5475 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5476                              SmallVectorImpl<SDValue> &InVals) const {
5477   SelectionDAG &DAG                     = CLI.DAG;
5478   SDLoc &dl                             = CLI.DL;
5479   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5480   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5481   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5482   SDValue Chain                         = CLI.Chain;
5483   SDValue Callee                        = CLI.Callee;
5484   bool &isTailCall                      = CLI.IsTailCall;
5485   CallingConv::ID CallConv              = CLI.CallConv;
5486   bool isVarArg                         = CLI.IsVarArg;
5487   bool isPatchPoint                     = CLI.IsPatchPoint;
5488   const CallBase *CB                    = CLI.CB;
5489 
5490   if (isTailCall) {
5491     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5492       isTailCall = false;
5493     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5494       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5495           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5496     else
5497       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5498                                                      Ins, DAG);
5499     if (isTailCall) {
5500       ++NumTailCalls;
5501       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5502         ++NumSiblingCalls;
5503 
5504       // PC Relative calls no longer guarantee that the callee is a Global
5505       // Address Node. The callee could be an indirect tail call in which
5506       // case the SDValue for the callee could be a load (to load the address
5507       // of a function pointer) or it may be a register copy (to move the
5508       // address of the callee from a function parameter into a virtual
5509       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5510       assert((Subtarget.isUsingPCRelativeCalls() ||
5511               isa<GlobalAddressSDNode>(Callee)) &&
5512              "Callee should be an llvm::Function object.");
5513 
5514       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5515                         << "\nTCO callee: ");
5516       LLVM_DEBUG(Callee.dump());
5517     }
5518   }
5519 
5520   if (!isTailCall && CB && CB->isMustTailCall())
5521     report_fatal_error("failed to perform tail call elimination on a call "
5522                        "site marked musttail");
5523 
5524   // When long calls (i.e. indirect calls) are always used, calls are always
5525   // made via function pointer. If we have a function name, first translate it
5526   // into a pointer.
5527   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5528       !isTailCall)
5529     Callee = LowerGlobalAddress(Callee, DAG);
5530 
5531   CallFlags CFlags(
5532       CallConv, isTailCall, isVarArg, isPatchPoint,
5533       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5534       // hasNest
5535       Subtarget.is64BitELFABI() &&
5536           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5537       CLI.NoMerge);
5538 
5539   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5540     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5541                             InVals, CB);
5542 
5543   if (Subtarget.isSVR4ABI())
5544     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5545                             InVals, CB);
5546 
5547   if (Subtarget.isAIXABI())
5548     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5549                          InVals, CB);
5550 
5551   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5552                           InVals, CB);
5553 }
5554 
5555 SDValue PPCTargetLowering::LowerCall_32SVR4(
5556     SDValue Chain, SDValue Callee, CallFlags CFlags,
5557     const SmallVectorImpl<ISD::OutputArg> &Outs,
5558     const SmallVectorImpl<SDValue> &OutVals,
5559     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5560     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5561     const CallBase *CB) const {
5562   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5563   // of the 32-bit SVR4 ABI stack frame layout.
5564 
5565   const CallingConv::ID CallConv = CFlags.CallConv;
5566   const bool IsVarArg = CFlags.IsVarArg;
5567   const bool IsTailCall = CFlags.IsTailCall;
5568 
5569   assert((CallConv == CallingConv::C ||
5570           CallConv == CallingConv::Cold ||
5571           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5572 
5573   const Align PtrAlign(4);
5574 
5575   MachineFunction &MF = DAG.getMachineFunction();
5576 
5577   // Mark this function as potentially containing a function that contains a
5578   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5579   // and restoring the callers stack pointer in this functions epilog. This is
5580   // done because by tail calling the called function might overwrite the value
5581   // in this function's (MF) stack pointer stack slot 0(SP).
5582   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5583       CallConv == CallingConv::Fast)
5584     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5585 
5586   // Count how many bytes are to be pushed on the stack, including the linkage
5587   // area, parameter list area and the part of the local variable space which
5588   // contains copies of aggregates which are passed by value.
5589 
5590   // Assign locations to all of the outgoing arguments.
5591   SmallVector<CCValAssign, 16> ArgLocs;
5592   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5593 
5594   // Reserve space for the linkage area on the stack.
5595   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5596                        PtrAlign);
5597   if (useSoftFloat())
5598     CCInfo.PreAnalyzeCallOperands(Outs);
5599 
5600   if (IsVarArg) {
5601     // Handle fixed and variable vector arguments differently.
5602     // Fixed vector arguments go into registers as long as registers are
5603     // available. Variable vector arguments always go into memory.
5604     unsigned NumArgs = Outs.size();
5605 
5606     for (unsigned i = 0; i != NumArgs; ++i) {
5607       MVT ArgVT = Outs[i].VT;
5608       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5609       bool Result;
5610 
5611       if (Outs[i].IsFixed) {
5612         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5613                                CCInfo);
5614       } else {
5615         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5616                                       ArgFlags, CCInfo);
5617       }
5618 
5619       if (Result) {
5620 #ifndef NDEBUG
5621         errs() << "Call operand #" << i << " has unhandled type "
5622              << EVT(ArgVT).getEVTString() << "\n";
5623 #endif
5624         llvm_unreachable(nullptr);
5625       }
5626     }
5627   } else {
5628     // All arguments are treated the same.
5629     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5630   }
5631   CCInfo.clearWasPPCF128();
5632 
5633   // Assign locations to all of the outgoing aggregate by value arguments.
5634   SmallVector<CCValAssign, 16> ByValArgLocs;
5635   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5636 
5637   // Reserve stack space for the allocations in CCInfo.
5638   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5639 
5640   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5641 
5642   // Size of the linkage area, parameter list area and the part of the local
5643   // space variable where copies of aggregates which are passed by value are
5644   // stored.
5645   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5646 
5647   // Calculate by how many bytes the stack has to be adjusted in case of tail
5648   // call optimization.
5649   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5650 
5651   // Adjust the stack pointer for the new arguments...
5652   // These operations are automatically eliminated by the prolog/epilog pass
5653   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5654   SDValue CallSeqStart = Chain;
5655 
5656   // Load the return address and frame pointer so it can be moved somewhere else
5657   // later.
5658   SDValue LROp, FPOp;
5659   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5660 
5661   // Set up a copy of the stack pointer for use loading and storing any
5662   // arguments that may not fit in the registers available for argument
5663   // passing.
5664   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5665 
5666   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5667   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5668   SmallVector<SDValue, 8> MemOpChains;
5669 
5670   bool seenFloatArg = false;
5671   // Walk the register/memloc assignments, inserting copies/loads.
5672   // i - Tracks the index into the list of registers allocated for the call
5673   // RealArgIdx - Tracks the index into the list of actual function arguments
5674   // j - Tracks the index into the list of byval arguments
5675   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5676        i != e;
5677        ++i, ++RealArgIdx) {
5678     CCValAssign &VA = ArgLocs[i];
5679     SDValue Arg = OutVals[RealArgIdx];
5680     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5681 
5682     if (Flags.isByVal()) {
5683       // Argument is an aggregate which is passed by value, thus we need to
5684       // create a copy of it in the local variable space of the current stack
5685       // frame (which is the stack frame of the caller) and pass the address of
5686       // this copy to the callee.
5687       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5688       CCValAssign &ByValVA = ByValArgLocs[j++];
5689       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5690 
5691       // Memory reserved in the local variable space of the callers stack frame.
5692       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5693 
5694       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5695       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5696                            StackPtr, PtrOff);
5697 
5698       // Create a copy of the argument in the local area of the current
5699       // stack frame.
5700       SDValue MemcpyCall =
5701         CreateCopyOfByValArgument(Arg, PtrOff,
5702                                   CallSeqStart.getNode()->getOperand(0),
5703                                   Flags, DAG, dl);
5704 
5705       // This must go outside the CALLSEQ_START..END.
5706       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5707                                                      SDLoc(MemcpyCall));
5708       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5709                              NewCallSeqStart.getNode());
5710       Chain = CallSeqStart = NewCallSeqStart;
5711 
5712       // Pass the address of the aggregate copy on the stack either in a
5713       // physical register or in the parameter list area of the current stack
5714       // frame to the callee.
5715       Arg = PtrOff;
5716     }
5717 
5718     // When useCRBits() is true, there can be i1 arguments.
5719     // It is because getRegisterType(MVT::i1) => MVT::i1,
5720     // and for other integer types getRegisterType() => MVT::i32.
5721     // Extend i1 and ensure callee will get i32.
5722     if (Arg.getValueType() == MVT::i1)
5723       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5724                         dl, MVT::i32, Arg);
5725 
5726     if (VA.isRegLoc()) {
5727       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5728       // Put argument in a physical register.
5729       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5730         bool IsLE = Subtarget.isLittleEndian();
5731         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5732                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5733         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5734         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5735                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5736         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5737                              SVal.getValue(0)));
5738       } else
5739         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5740     } else {
5741       // Put argument in the parameter list area of the current stack frame.
5742       assert(VA.isMemLoc());
5743       unsigned LocMemOffset = VA.getLocMemOffset();
5744 
5745       if (!IsTailCall) {
5746         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5747         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5748                              StackPtr, PtrOff);
5749 
5750         MemOpChains.push_back(
5751             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5752       } else {
5753         // Calculate and remember argument location.
5754         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5755                                  TailCallArguments);
5756       }
5757     }
5758   }
5759 
5760   if (!MemOpChains.empty())
5761     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5762 
5763   // Build a sequence of copy-to-reg nodes chained together with token chain
5764   // and flag operands which copy the outgoing args into the appropriate regs.
5765   SDValue InFlag;
5766   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5767     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5768                              RegsToPass[i].second, InFlag);
5769     InFlag = Chain.getValue(1);
5770   }
5771 
5772   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5773   // registers.
5774   if (IsVarArg) {
5775     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5776     SDValue Ops[] = { Chain, InFlag };
5777 
5778     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5779                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5780 
5781     InFlag = Chain.getValue(1);
5782   }
5783 
5784   if (IsTailCall)
5785     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5786                     TailCallArguments);
5787 
5788   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5789                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5790 }
5791 
5792 // Copy an argument into memory, being careful to do this outside the
5793 // call sequence for the call to which the argument belongs.
5794 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5795     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5796     SelectionDAG &DAG, const SDLoc &dl) const {
5797   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5798                         CallSeqStart.getNode()->getOperand(0),
5799                         Flags, DAG, dl);
5800   // The MEMCPY must go outside the CALLSEQ_START..END.
5801   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5802   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5803                                                  SDLoc(MemcpyCall));
5804   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5805                          NewCallSeqStart.getNode());
5806   return NewCallSeqStart;
5807 }
5808 
5809 SDValue PPCTargetLowering::LowerCall_64SVR4(
5810     SDValue Chain, SDValue Callee, CallFlags CFlags,
5811     const SmallVectorImpl<ISD::OutputArg> &Outs,
5812     const SmallVectorImpl<SDValue> &OutVals,
5813     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5814     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5815     const CallBase *CB) const {
5816   bool isELFv2ABI = Subtarget.isELFv2ABI();
5817   bool isLittleEndian = Subtarget.isLittleEndian();
5818   unsigned NumOps = Outs.size();
5819   bool IsSibCall = false;
5820   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5821 
5822   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5823   unsigned PtrByteSize = 8;
5824 
5825   MachineFunction &MF = DAG.getMachineFunction();
5826 
5827   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5828     IsSibCall = true;
5829 
5830   // Mark this function as potentially containing a function that contains a
5831   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5832   // and restoring the callers stack pointer in this functions epilog. This is
5833   // done because by tail calling the called function might overwrite the value
5834   // in this function's (MF) stack pointer stack slot 0(SP).
5835   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5836     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5837 
5838   assert(!(IsFastCall && CFlags.IsVarArg) &&
5839          "fastcc not supported on varargs functions");
5840 
5841   // Count how many bytes are to be pushed on the stack, including the linkage
5842   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5843   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5844   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5845   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5846   unsigned NumBytes = LinkageSize;
5847   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5848 
5849   static const MCPhysReg GPR[] = {
5850     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5851     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5852   };
5853   static const MCPhysReg VR[] = {
5854     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5855     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5856   };
5857 
5858   const unsigned NumGPRs = array_lengthof(GPR);
5859   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5860   const unsigned NumVRs  = array_lengthof(VR);
5861 
5862   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5863   // can be passed to the callee in registers.
5864   // For the fast calling convention, there is another check below.
5865   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5866   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5867   if (!HasParameterArea) {
5868     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5869     unsigned AvailableFPRs = NumFPRs;
5870     unsigned AvailableVRs = NumVRs;
5871     unsigned NumBytesTmp = NumBytes;
5872     for (unsigned i = 0; i != NumOps; ++i) {
5873       if (Outs[i].Flags.isNest()) continue;
5874       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5875                                  PtrByteSize, LinkageSize, ParamAreaSize,
5876                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5877         HasParameterArea = true;
5878     }
5879   }
5880 
5881   // When using the fast calling convention, we don't provide backing for
5882   // arguments that will be in registers.
5883   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5884 
5885   // Avoid allocating parameter area for fastcc functions if all the arguments
5886   // can be passed in the registers.
5887   if (IsFastCall)
5888     HasParameterArea = false;
5889 
5890   // Add up all the space actually used.
5891   for (unsigned i = 0; i != NumOps; ++i) {
5892     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5893     EVT ArgVT = Outs[i].VT;
5894     EVT OrigVT = Outs[i].ArgVT;
5895 
5896     if (Flags.isNest())
5897       continue;
5898 
5899     if (IsFastCall) {
5900       if (Flags.isByVal()) {
5901         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5902         if (NumGPRsUsed > NumGPRs)
5903           HasParameterArea = true;
5904       } else {
5905         switch (ArgVT.getSimpleVT().SimpleTy) {
5906         default: llvm_unreachable("Unexpected ValueType for argument!");
5907         case MVT::i1:
5908         case MVT::i32:
5909         case MVT::i64:
5910           if (++NumGPRsUsed <= NumGPRs)
5911             continue;
5912           break;
5913         case MVT::v4i32:
5914         case MVT::v8i16:
5915         case MVT::v16i8:
5916         case MVT::v2f64:
5917         case MVT::v2i64:
5918         case MVT::v1i128:
5919         case MVT::f128:
5920           if (++NumVRsUsed <= NumVRs)
5921             continue;
5922           break;
5923         case MVT::v4f32:
5924           if (++NumVRsUsed <= NumVRs)
5925             continue;
5926           break;
5927         case MVT::f32:
5928         case MVT::f64:
5929           if (++NumFPRsUsed <= NumFPRs)
5930             continue;
5931           break;
5932         }
5933         HasParameterArea = true;
5934       }
5935     }
5936 
5937     /* Respect alignment of argument on the stack.  */
5938     auto Alignement =
5939         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5940     NumBytes = alignTo(NumBytes, Alignement);
5941 
5942     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5943     if (Flags.isInConsecutiveRegsLast())
5944       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5945   }
5946 
5947   unsigned NumBytesActuallyUsed = NumBytes;
5948 
5949   // In the old ELFv1 ABI,
5950   // the prolog code of the callee may store up to 8 GPR argument registers to
5951   // the stack, allowing va_start to index over them in memory if its varargs.
5952   // Because we cannot tell if this is needed on the caller side, we have to
5953   // conservatively assume that it is needed.  As such, make sure we have at
5954   // least enough stack space for the caller to store the 8 GPRs.
5955   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5956   // really requires memory operands, e.g. a vararg function.
5957   if (HasParameterArea)
5958     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5959   else
5960     NumBytes = LinkageSize;
5961 
5962   // Tail call needs the stack to be aligned.
5963   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5964     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5965 
5966   int SPDiff = 0;
5967 
5968   // Calculate by how many bytes the stack has to be adjusted in case of tail
5969   // call optimization.
5970   if (!IsSibCall)
5971     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5972 
5973   // To protect arguments on the stack from being clobbered in a tail call,
5974   // force all the loads to happen before doing any other lowering.
5975   if (CFlags.IsTailCall)
5976     Chain = DAG.getStackArgumentTokenFactor(Chain);
5977 
5978   // Adjust the stack pointer for the new arguments...
5979   // These operations are automatically eliminated by the prolog/epilog pass
5980   if (!IsSibCall)
5981     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5982   SDValue CallSeqStart = Chain;
5983 
5984   // Load the return address and frame pointer so it can be move somewhere else
5985   // later.
5986   SDValue LROp, FPOp;
5987   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5988 
5989   // Set up a copy of the stack pointer for use loading and storing any
5990   // arguments that may not fit in the registers available for argument
5991   // passing.
5992   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5993 
5994   // Figure out which arguments are going to go in registers, and which in
5995   // memory.  Also, if this is a vararg function, floating point operations
5996   // must be stored to our stack, and loaded into integer regs as well, if
5997   // any integer regs are available for argument passing.
5998   unsigned ArgOffset = LinkageSize;
5999 
6000   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6001   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6002 
6003   SmallVector<SDValue, 8> MemOpChains;
6004   for (unsigned i = 0; i != NumOps; ++i) {
6005     SDValue Arg = OutVals[i];
6006     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6007     EVT ArgVT = Outs[i].VT;
6008     EVT OrigVT = Outs[i].ArgVT;
6009 
6010     // PtrOff will be used to store the current argument to the stack if a
6011     // register cannot be found for it.
6012     SDValue PtrOff;
6013 
6014     // We re-align the argument offset for each argument, except when using the
6015     // fast calling convention, when we need to make sure we do that only when
6016     // we'll actually use a stack slot.
6017     auto ComputePtrOff = [&]() {
6018       /* Respect alignment of argument on the stack.  */
6019       auto Alignment =
6020           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6021       ArgOffset = alignTo(ArgOffset, Alignment);
6022 
6023       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6024 
6025       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6026     };
6027 
6028     if (!IsFastCall) {
6029       ComputePtrOff();
6030 
6031       /* Compute GPR index associated with argument offset.  */
6032       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6033       GPR_idx = std::min(GPR_idx, NumGPRs);
6034     }
6035 
6036     // Promote integers to 64-bit values.
6037     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6038       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6039       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6040       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6041     }
6042 
6043     // FIXME memcpy is used way more than necessary.  Correctness first.
6044     // Note: "by value" is code for passing a structure by value, not
6045     // basic types.
6046     if (Flags.isByVal()) {
6047       // Note: Size includes alignment padding, so
6048       //   struct x { short a; char b; }
6049       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6050       // These are the proper values we need for right-justifying the
6051       // aggregate in a parameter register.
6052       unsigned Size = Flags.getByValSize();
6053 
6054       // An empty aggregate parameter takes up no storage and no
6055       // registers.
6056       if (Size == 0)
6057         continue;
6058 
6059       if (IsFastCall)
6060         ComputePtrOff();
6061 
6062       // All aggregates smaller than 8 bytes must be passed right-justified.
6063       if (Size==1 || Size==2 || Size==4) {
6064         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6065         if (GPR_idx != NumGPRs) {
6066           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6067                                         MachinePointerInfo(), VT);
6068           MemOpChains.push_back(Load.getValue(1));
6069           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6070 
6071           ArgOffset += PtrByteSize;
6072           continue;
6073         }
6074       }
6075 
6076       if (GPR_idx == NumGPRs && Size < 8) {
6077         SDValue AddPtr = PtrOff;
6078         if (!isLittleEndian) {
6079           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6080                                           PtrOff.getValueType());
6081           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6082         }
6083         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6084                                                           CallSeqStart,
6085                                                           Flags, DAG, dl);
6086         ArgOffset += PtrByteSize;
6087         continue;
6088       }
6089       // Copy entire object into memory.  There are cases where gcc-generated
6090       // code assumes it is there, even if it could be put entirely into
6091       // registers.  (This is not what the doc says.)
6092 
6093       // FIXME: The above statement is likely due to a misunderstanding of the
6094       // documents.  All arguments must be copied into the parameter area BY
6095       // THE CALLEE in the event that the callee takes the address of any
6096       // formal argument.  That has not yet been implemented.  However, it is
6097       // reasonable to use the stack area as a staging area for the register
6098       // load.
6099 
6100       // Skip this for small aggregates, as we will use the same slot for a
6101       // right-justified copy, below.
6102       if (Size >= 8)
6103         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6104                                                           CallSeqStart,
6105                                                           Flags, DAG, dl);
6106 
6107       // When a register is available, pass a small aggregate right-justified.
6108       if (Size < 8 && GPR_idx != NumGPRs) {
6109         // The easiest way to get this right-justified in a register
6110         // is to copy the structure into the rightmost portion of a
6111         // local variable slot, then load the whole slot into the
6112         // register.
6113         // FIXME: The memcpy seems to produce pretty awful code for
6114         // small aggregates, particularly for packed ones.
6115         // FIXME: It would be preferable to use the slot in the
6116         // parameter save area instead of a new local variable.
6117         SDValue AddPtr = PtrOff;
6118         if (!isLittleEndian) {
6119           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6120           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6121         }
6122         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6123                                                           CallSeqStart,
6124                                                           Flags, DAG, dl);
6125 
6126         // Load the slot into the register.
6127         SDValue Load =
6128             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6129         MemOpChains.push_back(Load.getValue(1));
6130         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6131 
6132         // Done with this argument.
6133         ArgOffset += PtrByteSize;
6134         continue;
6135       }
6136 
6137       // For aggregates larger than PtrByteSize, copy the pieces of the
6138       // object that fit into registers from the parameter save area.
6139       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6140         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6141         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6142         if (GPR_idx != NumGPRs) {
6143           SDValue Load =
6144               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6145           MemOpChains.push_back(Load.getValue(1));
6146           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6147           ArgOffset += PtrByteSize;
6148         } else {
6149           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6150           break;
6151         }
6152       }
6153       continue;
6154     }
6155 
6156     switch (Arg.getSimpleValueType().SimpleTy) {
6157     default: llvm_unreachable("Unexpected ValueType for argument!");
6158     case MVT::i1:
6159     case MVT::i32:
6160     case MVT::i64:
6161       if (Flags.isNest()) {
6162         // The 'nest' parameter, if any, is passed in R11.
6163         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6164         break;
6165       }
6166 
6167       // These can be scalar arguments or elements of an integer array type
6168       // passed directly.  Clang may use those instead of "byval" aggregate
6169       // types to avoid forcing arguments to memory unnecessarily.
6170       if (GPR_idx != NumGPRs) {
6171         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6172       } else {
6173         if (IsFastCall)
6174           ComputePtrOff();
6175 
6176         assert(HasParameterArea &&
6177                "Parameter area must exist to pass an argument in memory.");
6178         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6179                          true, CFlags.IsTailCall, false, MemOpChains,
6180                          TailCallArguments, dl);
6181         if (IsFastCall)
6182           ArgOffset += PtrByteSize;
6183       }
6184       if (!IsFastCall)
6185         ArgOffset += PtrByteSize;
6186       break;
6187     case MVT::f32:
6188     case MVT::f64: {
6189       // These can be scalar arguments or elements of a float array type
6190       // passed directly.  The latter are used to implement ELFv2 homogenous
6191       // float aggregates.
6192 
6193       // Named arguments go into FPRs first, and once they overflow, the
6194       // remaining arguments go into GPRs and then the parameter save area.
6195       // Unnamed arguments for vararg functions always go to GPRs and
6196       // then the parameter save area.  For now, put all arguments to vararg
6197       // routines always in both locations (FPR *and* GPR or stack slot).
6198       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6199       bool NeededLoad = false;
6200 
6201       // First load the argument into the next available FPR.
6202       if (FPR_idx != NumFPRs)
6203         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6204 
6205       // Next, load the argument into GPR or stack slot if needed.
6206       if (!NeedGPROrStack)
6207         ;
6208       else if (GPR_idx != NumGPRs && !IsFastCall) {
6209         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6210         // once we support fp <-> gpr moves.
6211 
6212         // In the non-vararg case, this can only ever happen in the
6213         // presence of f32 array types, since otherwise we never run
6214         // out of FPRs before running out of GPRs.
6215         SDValue ArgVal;
6216 
6217         // Double values are always passed in a single GPR.
6218         if (Arg.getValueType() != MVT::f32) {
6219           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6220 
6221         // Non-array float values are extended and passed in a GPR.
6222         } else if (!Flags.isInConsecutiveRegs()) {
6223           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6224           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6225 
6226         // If we have an array of floats, we collect every odd element
6227         // together with its predecessor into one GPR.
6228         } else if (ArgOffset % PtrByteSize != 0) {
6229           SDValue Lo, Hi;
6230           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6231           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6232           if (!isLittleEndian)
6233             std::swap(Lo, Hi);
6234           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6235 
6236         // The final element, if even, goes into the first half of a GPR.
6237         } else if (Flags.isInConsecutiveRegsLast()) {
6238           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6239           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6240           if (!isLittleEndian)
6241             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6242                                  DAG.getConstant(32, dl, MVT::i32));
6243 
6244         // Non-final even elements are skipped; they will be handled
6245         // together the with subsequent argument on the next go-around.
6246         } else
6247           ArgVal = SDValue();
6248 
6249         if (ArgVal.getNode())
6250           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6251       } else {
6252         if (IsFastCall)
6253           ComputePtrOff();
6254 
6255         // Single-precision floating-point values are mapped to the
6256         // second (rightmost) word of the stack doubleword.
6257         if (Arg.getValueType() == MVT::f32 &&
6258             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6259           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6260           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6261         }
6262 
6263         assert(HasParameterArea &&
6264                "Parameter area must exist to pass an argument in memory.");
6265         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6266                          true, CFlags.IsTailCall, false, MemOpChains,
6267                          TailCallArguments, dl);
6268 
6269         NeededLoad = true;
6270       }
6271       // When passing an array of floats, the array occupies consecutive
6272       // space in the argument area; only round up to the next doubleword
6273       // at the end of the array.  Otherwise, each float takes 8 bytes.
6274       if (!IsFastCall || NeededLoad) {
6275         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6276                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6277         if (Flags.isInConsecutiveRegsLast())
6278           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6279       }
6280       break;
6281     }
6282     case MVT::v4f32:
6283     case MVT::v4i32:
6284     case MVT::v8i16:
6285     case MVT::v16i8:
6286     case MVT::v2f64:
6287     case MVT::v2i64:
6288     case MVT::v1i128:
6289     case MVT::f128:
6290       // These can be scalar arguments or elements of a vector array type
6291       // passed directly.  The latter are used to implement ELFv2 homogenous
6292       // vector aggregates.
6293 
6294       // For a varargs call, named arguments go into VRs or on the stack as
6295       // usual; unnamed arguments always go to the stack or the corresponding
6296       // GPRs when within range.  For now, we always put the value in both
6297       // locations (or even all three).
6298       if (CFlags.IsVarArg) {
6299         assert(HasParameterArea &&
6300                "Parameter area must exist if we have a varargs call.");
6301         // We could elide this store in the case where the object fits
6302         // entirely in R registers.  Maybe later.
6303         SDValue Store =
6304             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6305         MemOpChains.push_back(Store);
6306         if (VR_idx != NumVRs) {
6307           SDValue Load =
6308               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6309           MemOpChains.push_back(Load.getValue(1));
6310           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6311         }
6312         ArgOffset += 16;
6313         for (unsigned i=0; i<16; i+=PtrByteSize) {
6314           if (GPR_idx == NumGPRs)
6315             break;
6316           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6317                                    DAG.getConstant(i, dl, PtrVT));
6318           SDValue Load =
6319               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6320           MemOpChains.push_back(Load.getValue(1));
6321           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6322         }
6323         break;
6324       }
6325 
6326       // Non-varargs Altivec params go into VRs or on the stack.
6327       if (VR_idx != NumVRs) {
6328         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6329       } else {
6330         if (IsFastCall)
6331           ComputePtrOff();
6332 
6333         assert(HasParameterArea &&
6334                "Parameter area must exist to pass an argument in memory.");
6335         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6336                          true, CFlags.IsTailCall, true, MemOpChains,
6337                          TailCallArguments, dl);
6338         if (IsFastCall)
6339           ArgOffset += 16;
6340       }
6341 
6342       if (!IsFastCall)
6343         ArgOffset += 16;
6344       break;
6345     }
6346   }
6347 
6348   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6349          "mismatch in size of parameter area");
6350   (void)NumBytesActuallyUsed;
6351 
6352   if (!MemOpChains.empty())
6353     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6354 
6355   // Check if this is an indirect call (MTCTR/BCTRL).
6356   // See prepareDescriptorIndirectCall and buildCallOperands for more
6357   // information about calls through function pointers in the 64-bit SVR4 ABI.
6358   if (CFlags.IsIndirect) {
6359     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6360     // caller in the TOC save area.
6361     if (isTOCSaveRestoreRequired(Subtarget)) {
6362       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6363       // Load r2 into a virtual register and store it to the TOC save area.
6364       setUsesTOCBasePtr(DAG);
6365       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6366       // TOC save area offset.
6367       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6368       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6369       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6370       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6371                            MachinePointerInfo::getStack(
6372                                DAG.getMachineFunction(), TOCSaveOffset));
6373     }
6374     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6375     // This does not mean the MTCTR instruction must use R12; it's easier
6376     // to model this as an extra parameter, so do that.
6377     if (isELFv2ABI && !CFlags.IsPatchPoint)
6378       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6379   }
6380 
6381   // Build a sequence of copy-to-reg nodes chained together with token chain
6382   // and flag operands which copy the outgoing args into the appropriate regs.
6383   SDValue InFlag;
6384   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6385     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6386                              RegsToPass[i].second, InFlag);
6387     InFlag = Chain.getValue(1);
6388   }
6389 
6390   if (CFlags.IsTailCall && !IsSibCall)
6391     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6392                     TailCallArguments);
6393 
6394   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6395                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6396 }
6397 
6398 SDValue PPCTargetLowering::LowerCall_Darwin(
6399     SDValue Chain, SDValue Callee, CallFlags CFlags,
6400     const SmallVectorImpl<ISD::OutputArg> &Outs,
6401     const SmallVectorImpl<SDValue> &OutVals,
6402     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6403     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6404     const CallBase *CB) const {
6405   unsigned NumOps = Outs.size();
6406 
6407   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6408   bool isPPC64 = PtrVT == MVT::i64;
6409   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6410 
6411   MachineFunction &MF = DAG.getMachineFunction();
6412 
6413   // Mark this function as potentially containing a function that contains a
6414   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6415   // and restoring the callers stack pointer in this functions epilog. This is
6416   // done because by tail calling the called function might overwrite the value
6417   // in this function's (MF) stack pointer stack slot 0(SP).
6418   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6419       CFlags.CallConv == CallingConv::Fast)
6420     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6421 
6422   // Count how many bytes are to be pushed on the stack, including the linkage
6423   // area, and parameter passing area.  We start with 24/48 bytes, which is
6424   // prereserved space for [SP][CR][LR][3 x unused].
6425   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6426   unsigned NumBytes = LinkageSize;
6427 
6428   // Add up all the space actually used.
6429   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6430   // they all go in registers, but we must reserve stack space for them for
6431   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6432   // assigned stack space in order, with padding so Altivec parameters are
6433   // 16-byte aligned.
6434   unsigned nAltivecParamsAtEnd = 0;
6435   for (unsigned i = 0; i != NumOps; ++i) {
6436     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6437     EVT ArgVT = Outs[i].VT;
6438     // Varargs Altivec parameters are padded to a 16 byte boundary.
6439     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6440         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6441         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6442       if (!CFlags.IsVarArg && !isPPC64) {
6443         // Non-varargs Altivec parameters go after all the non-Altivec
6444         // parameters; handle those later so we know how much padding we need.
6445         nAltivecParamsAtEnd++;
6446         continue;
6447       }
6448       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6449       NumBytes = ((NumBytes+15)/16)*16;
6450     }
6451     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6452   }
6453 
6454   // Allow for Altivec parameters at the end, if needed.
6455   if (nAltivecParamsAtEnd) {
6456     NumBytes = ((NumBytes+15)/16)*16;
6457     NumBytes += 16*nAltivecParamsAtEnd;
6458   }
6459 
6460   // The prolog code of the callee may store up to 8 GPR argument registers to
6461   // the stack, allowing va_start to index over them in memory if its varargs.
6462   // Because we cannot tell if this is needed on the caller side, we have to
6463   // conservatively assume that it is needed.  As such, make sure we have at
6464   // least enough stack space for the caller to store the 8 GPRs.
6465   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6466 
6467   // Tail call needs the stack to be aligned.
6468   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6469       CFlags.CallConv == CallingConv::Fast)
6470     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6471 
6472   // Calculate by how many bytes the stack has to be adjusted in case of tail
6473   // call optimization.
6474   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6475 
6476   // To protect arguments on the stack from being clobbered in a tail call,
6477   // force all the loads to happen before doing any other lowering.
6478   if (CFlags.IsTailCall)
6479     Chain = DAG.getStackArgumentTokenFactor(Chain);
6480 
6481   // Adjust the stack pointer for the new arguments...
6482   // These operations are automatically eliminated by the prolog/epilog pass
6483   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6484   SDValue CallSeqStart = Chain;
6485 
6486   // Load the return address and frame pointer so it can be move somewhere else
6487   // later.
6488   SDValue LROp, FPOp;
6489   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6490 
6491   // Set up a copy of the stack pointer for use loading and storing any
6492   // arguments that may not fit in the registers available for argument
6493   // passing.
6494   SDValue StackPtr;
6495   if (isPPC64)
6496     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6497   else
6498     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6499 
6500   // Figure out which arguments are going to go in registers, and which in
6501   // memory.  Also, if this is a vararg function, floating point operations
6502   // must be stored to our stack, and loaded into integer regs as well, if
6503   // any integer regs are available for argument passing.
6504   unsigned ArgOffset = LinkageSize;
6505   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6506 
6507   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6508     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6509     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6510   };
6511   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6512     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6513     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6514   };
6515   static const MCPhysReg VR[] = {
6516     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6517     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6518   };
6519   const unsigned NumGPRs = array_lengthof(GPR_32);
6520   const unsigned NumFPRs = 13;
6521   const unsigned NumVRs  = array_lengthof(VR);
6522 
6523   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6524 
6525   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6526   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6527 
6528   SmallVector<SDValue, 8> MemOpChains;
6529   for (unsigned i = 0; i != NumOps; ++i) {
6530     SDValue Arg = OutVals[i];
6531     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6532 
6533     // PtrOff will be used to store the current argument to the stack if a
6534     // register cannot be found for it.
6535     SDValue PtrOff;
6536 
6537     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6538 
6539     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6540 
6541     // On PPC64, promote integers to 64-bit values.
6542     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6543       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6544       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6545       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6546     }
6547 
6548     // FIXME memcpy is used way more than necessary.  Correctness first.
6549     // Note: "by value" is code for passing a structure by value, not
6550     // basic types.
6551     if (Flags.isByVal()) {
6552       unsigned Size = Flags.getByValSize();
6553       // Very small objects are passed right-justified.  Everything else is
6554       // passed left-justified.
6555       if (Size==1 || Size==2) {
6556         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6557         if (GPR_idx != NumGPRs) {
6558           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6559                                         MachinePointerInfo(), VT);
6560           MemOpChains.push_back(Load.getValue(1));
6561           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6562 
6563           ArgOffset += PtrByteSize;
6564         } else {
6565           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6566                                           PtrOff.getValueType());
6567           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6568           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6569                                                             CallSeqStart,
6570                                                             Flags, DAG, dl);
6571           ArgOffset += PtrByteSize;
6572         }
6573         continue;
6574       }
6575       // Copy entire object into memory.  There are cases where gcc-generated
6576       // code assumes it is there, even if it could be put entirely into
6577       // registers.  (This is not what the doc says.)
6578       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6579                                                         CallSeqStart,
6580                                                         Flags, DAG, dl);
6581 
6582       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6583       // copy the pieces of the object that fit into registers from the
6584       // parameter save area.
6585       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6586         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6587         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6588         if (GPR_idx != NumGPRs) {
6589           SDValue Load =
6590               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6591           MemOpChains.push_back(Load.getValue(1));
6592           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6593           ArgOffset += PtrByteSize;
6594         } else {
6595           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6596           break;
6597         }
6598       }
6599       continue;
6600     }
6601 
6602     switch (Arg.getSimpleValueType().SimpleTy) {
6603     default: llvm_unreachable("Unexpected ValueType for argument!");
6604     case MVT::i1:
6605     case MVT::i32:
6606     case MVT::i64:
6607       if (GPR_idx != NumGPRs) {
6608         if (Arg.getValueType() == MVT::i1)
6609           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6610 
6611         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6612       } else {
6613         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6614                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6615                          TailCallArguments, dl);
6616       }
6617       ArgOffset += PtrByteSize;
6618       break;
6619     case MVT::f32:
6620     case MVT::f64:
6621       if (FPR_idx != NumFPRs) {
6622         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6623 
6624         if (CFlags.IsVarArg) {
6625           SDValue Store =
6626               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6627           MemOpChains.push_back(Store);
6628 
6629           // Float varargs are always shadowed in available integer registers
6630           if (GPR_idx != NumGPRs) {
6631             SDValue Load =
6632                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6633             MemOpChains.push_back(Load.getValue(1));
6634             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6635           }
6636           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6637             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6638             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6639             SDValue Load =
6640                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6641             MemOpChains.push_back(Load.getValue(1));
6642             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6643           }
6644         } else {
6645           // If we have any FPRs remaining, we may also have GPRs remaining.
6646           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6647           // GPRs.
6648           if (GPR_idx != NumGPRs)
6649             ++GPR_idx;
6650           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6651               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6652             ++GPR_idx;
6653         }
6654       } else
6655         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6656                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6657                          TailCallArguments, dl);
6658       if (isPPC64)
6659         ArgOffset += 8;
6660       else
6661         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6662       break;
6663     case MVT::v4f32:
6664     case MVT::v4i32:
6665     case MVT::v8i16:
6666     case MVT::v16i8:
6667       if (CFlags.IsVarArg) {
6668         // These go aligned on the stack, or in the corresponding R registers
6669         // when within range.  The Darwin PPC ABI doc claims they also go in
6670         // V registers; in fact gcc does this only for arguments that are
6671         // prototyped, not for those that match the ...  We do it for all
6672         // arguments, seems to work.
6673         while (ArgOffset % 16 !=0) {
6674           ArgOffset += PtrByteSize;
6675           if (GPR_idx != NumGPRs)
6676             GPR_idx++;
6677         }
6678         // We could elide this store in the case where the object fits
6679         // entirely in R registers.  Maybe later.
6680         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6681                              DAG.getConstant(ArgOffset, dl, PtrVT));
6682         SDValue Store =
6683             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6684         MemOpChains.push_back(Store);
6685         if (VR_idx != NumVRs) {
6686           SDValue Load =
6687               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6688           MemOpChains.push_back(Load.getValue(1));
6689           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6690         }
6691         ArgOffset += 16;
6692         for (unsigned i=0; i<16; i+=PtrByteSize) {
6693           if (GPR_idx == NumGPRs)
6694             break;
6695           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6696                                    DAG.getConstant(i, dl, PtrVT));
6697           SDValue Load =
6698               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6699           MemOpChains.push_back(Load.getValue(1));
6700           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6701         }
6702         break;
6703       }
6704 
6705       // Non-varargs Altivec params generally go in registers, but have
6706       // stack space allocated at the end.
6707       if (VR_idx != NumVRs) {
6708         // Doesn't have GPR space allocated.
6709         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6710       } else if (nAltivecParamsAtEnd==0) {
6711         // We are emitting Altivec params in order.
6712         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6713                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6714                          TailCallArguments, dl);
6715         ArgOffset += 16;
6716       }
6717       break;
6718     }
6719   }
6720   // If all Altivec parameters fit in registers, as they usually do,
6721   // they get stack space following the non-Altivec parameters.  We
6722   // don't track this here because nobody below needs it.
6723   // If there are more Altivec parameters than fit in registers emit
6724   // the stores here.
6725   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6726     unsigned j = 0;
6727     // Offset is aligned; skip 1st 12 params which go in V registers.
6728     ArgOffset = ((ArgOffset+15)/16)*16;
6729     ArgOffset += 12*16;
6730     for (unsigned i = 0; i != NumOps; ++i) {
6731       SDValue Arg = OutVals[i];
6732       EVT ArgType = Outs[i].VT;
6733       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6734           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6735         if (++j > NumVRs) {
6736           SDValue PtrOff;
6737           // We are emitting Altivec params in order.
6738           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6739                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6740                            TailCallArguments, dl);
6741           ArgOffset += 16;
6742         }
6743       }
6744     }
6745   }
6746 
6747   if (!MemOpChains.empty())
6748     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6749 
6750   // On Darwin, R12 must contain the address of an indirect callee.  This does
6751   // not mean the MTCTR instruction must use R12; it's easier to model this as
6752   // an extra parameter, so do that.
6753   if (CFlags.IsIndirect) {
6754     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6755     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6756                                                    PPC::R12), Callee));
6757   }
6758 
6759   // Build a sequence of copy-to-reg nodes chained together with token chain
6760   // and flag operands which copy the outgoing args into the appropriate regs.
6761   SDValue InFlag;
6762   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6763     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6764                              RegsToPass[i].second, InFlag);
6765     InFlag = Chain.getValue(1);
6766   }
6767 
6768   if (CFlags.IsTailCall)
6769     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6770                     TailCallArguments);
6771 
6772   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6773                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6774 }
6775 
6776 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6777                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6778                    CCState &State) {
6779 
6780   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6781       State.getMachineFunction().getSubtarget());
6782   const bool IsPPC64 = Subtarget.isPPC64();
6783   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6784   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6785 
6786   assert((!ValVT.isInteger() ||
6787           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6788          "Integer argument exceeds register size: should have been legalized");
6789 
6790   if (ValVT == MVT::f128)
6791     report_fatal_error("f128 is unimplemented on AIX.");
6792 
6793   if (ArgFlags.isNest())
6794     report_fatal_error("Nest arguments are unimplemented.");
6795 
6796   if (ValVT.isVector() || LocVT.isVector())
6797     report_fatal_error("Vector arguments are unimplemented on AIX.");
6798 
6799   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6800                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6801                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6802   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6803                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6804                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6805 
6806   if (ArgFlags.isByVal()) {
6807     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6808       report_fatal_error("Pass-by-value arguments with alignment greater than "
6809                          "register width are not supported.");
6810 
6811     const unsigned ByValSize = ArgFlags.getByValSize();
6812 
6813     // An empty aggregate parameter takes up no storage and no registers,
6814     // but needs a MemLoc for a stack slot for the formal arguments side.
6815     if (ByValSize == 0) {
6816       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6817                                        State.getNextStackOffset(), RegVT,
6818                                        LocInfo));
6819       return false;
6820     }
6821 
6822     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6823     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6824     for (const unsigned E = Offset + StackSize; Offset < E;
6825          Offset += PtrAlign.value()) {
6826       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6827         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6828       else {
6829         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6830                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6831                                          LocInfo));
6832         break;
6833       }
6834     }
6835     return false;
6836   }
6837 
6838   // Arguments always reserve parameter save area.
6839   switch (ValVT.SimpleTy) {
6840   default:
6841     report_fatal_error("Unhandled value type for argument.");
6842   case MVT::i64:
6843     // i64 arguments should have been split to i32 for PPC32.
6844     assert(IsPPC64 && "PPC32 should have split i64 values.");
6845     LLVM_FALLTHROUGH;
6846   case MVT::i1:
6847   case MVT::i32: {
6848     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6849     // AIX integer arguments are always passed in register width.
6850     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6851       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6852                                   : CCValAssign::LocInfo::ZExt;
6853     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6854       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6855     else
6856       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6857 
6858     return false;
6859   }
6860   case MVT::f32:
6861   case MVT::f64: {
6862     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6863     const unsigned StoreSize = LocVT.getStoreSize();
6864     // Floats are always 4-byte aligned in the PSA on AIX.
6865     // This includes f64 in 64-bit mode for ABI compatibility.
6866     const unsigned Offset =
6867         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6868     unsigned FReg = State.AllocateReg(FPR);
6869     if (FReg)
6870       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6871 
6872     // Reserve and initialize GPRs or initialize the PSA as required.
6873     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6874       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6875         assert(FReg && "An FPR should be available when a GPR is reserved.");
6876         if (State.isVarArg()) {
6877           // Successfully reserved GPRs are only initialized for vararg calls.
6878           // Custom handling is required for:
6879           //   f64 in PPC32 needs to be split into 2 GPRs.
6880           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6881           State.addLoc(
6882               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6883         }
6884       } else {
6885         // If there are insufficient GPRs, the PSA needs to be initialized.
6886         // Initialization occurs even if an FPR was initialized for
6887         // compatibility with the AIX XL compiler. The full memory for the
6888         // argument will be initialized even if a prior word is saved in GPR.
6889         // A custom memLoc is used when the argument also passes in FPR so
6890         // that the callee handling can skip over it easily.
6891         State.addLoc(
6892             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6893                                              LocInfo)
6894                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6895         break;
6896       }
6897     }
6898 
6899     return false;
6900   }
6901   }
6902   return true;
6903 }
6904 
6905 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6906                                                     bool IsPPC64) {
6907   assert((IsPPC64 || SVT != MVT::i64) &&
6908          "i64 should have been split for 32-bit codegen.");
6909 
6910   switch (SVT) {
6911   default:
6912     report_fatal_error("Unexpected value type for formal argument");
6913   case MVT::i1:
6914   case MVT::i32:
6915   case MVT::i64:
6916     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6917   case MVT::f32:
6918     return &PPC::F4RCRegClass;
6919   case MVT::f64:
6920     return &PPC::F8RCRegClass;
6921   }
6922 }
6923 
6924 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6925                                         SelectionDAG &DAG, SDValue ArgValue,
6926                                         MVT LocVT, const SDLoc &dl) {
6927   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6928   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6929 
6930   if (Flags.isSExt())
6931     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6932                            DAG.getValueType(ValVT));
6933   else if (Flags.isZExt())
6934     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6935                            DAG.getValueType(ValVT));
6936 
6937   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6938 }
6939 
6940 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6941   const unsigned LASize = FL->getLinkageSize();
6942 
6943   if (PPC::GPRCRegClass.contains(Reg)) {
6944     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6945            "Reg must be a valid argument register!");
6946     return LASize + 4 * (Reg - PPC::R3);
6947   }
6948 
6949   if (PPC::G8RCRegClass.contains(Reg)) {
6950     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6951            "Reg must be a valid argument register!");
6952     return LASize + 8 * (Reg - PPC::X3);
6953   }
6954 
6955   llvm_unreachable("Only general purpose registers expected.");
6956 }
6957 
6958 //   AIX ABI Stack Frame Layout:
6959 //
6960 //   Low Memory +--------------------------------------------+
6961 //   SP   +---> | Back chain                                 | ---+
6962 //        |     +--------------------------------------------+    |
6963 //        |     | Saved Condition Register                   |    |
6964 //        |     +--------------------------------------------+    |
6965 //        |     | Saved Linkage Register                     |    |
6966 //        |     +--------------------------------------------+    | Linkage Area
6967 //        |     | Reserved for compilers                     |    |
6968 //        |     +--------------------------------------------+    |
6969 //        |     | Reserved for binders                       |    |
6970 //        |     +--------------------------------------------+    |
6971 //        |     | Saved TOC pointer                          | ---+
6972 //        |     +--------------------------------------------+
6973 //        |     | Parameter save area                        |
6974 //        |     +--------------------------------------------+
6975 //        |     | Alloca space                               |
6976 //        |     +--------------------------------------------+
6977 //        |     | Local variable space                       |
6978 //        |     +--------------------------------------------+
6979 //        |     | Float/int conversion temporary             |
6980 //        |     +--------------------------------------------+
6981 //        |     | Save area for AltiVec registers            |
6982 //        |     +--------------------------------------------+
6983 //        |     | AltiVec alignment padding                  |
6984 //        |     +--------------------------------------------+
6985 //        |     | Save area for VRSAVE register              |
6986 //        |     +--------------------------------------------+
6987 //        |     | Save area for General Purpose registers    |
6988 //        |     +--------------------------------------------+
6989 //        |     | Save area for Floating Point registers     |
6990 //        |     +--------------------------------------------+
6991 //        +---- | Back chain                                 |
6992 // High Memory  +--------------------------------------------+
6993 //
6994 //  Specifications:
6995 //  AIX 7.2 Assembler Language Reference
6996 //  Subroutine linkage convention
6997 
6998 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6999     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7000     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7001     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7002 
7003   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7004           CallConv == CallingConv::Fast) &&
7005          "Unexpected calling convention!");
7006 
7007   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7008     report_fatal_error("Tail call support is unimplemented on AIX.");
7009 
7010   if (useSoftFloat())
7011     report_fatal_error("Soft float support is unimplemented on AIX.");
7012 
7013   const PPCSubtarget &Subtarget =
7014       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7015 
7016   const bool IsPPC64 = Subtarget.isPPC64();
7017   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7018 
7019   // Assign locations to all of the incoming arguments.
7020   SmallVector<CCValAssign, 16> ArgLocs;
7021   MachineFunction &MF = DAG.getMachineFunction();
7022   MachineFrameInfo &MFI = MF.getFrameInfo();
7023   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7024 
7025   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7026   // Reserve space for the linkage area on the stack.
7027   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7028   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7029   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7030 
7031   SmallVector<SDValue, 8> MemOps;
7032 
7033   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7034     CCValAssign &VA = ArgLocs[I++];
7035     MVT LocVT = VA.getLocVT();
7036     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7037 
7038     // For compatibility with the AIX XL compiler, the float args in the
7039     // parameter save area are initialized even if the argument is available
7040     // in register.  The caller is required to initialize both the register
7041     // and memory, however, the callee can choose to expect it in either.
7042     // The memloc is dismissed here because the argument is retrieved from
7043     // the register.
7044     if (VA.isMemLoc() && VA.needsCustom())
7045       continue;
7046 
7047     if (Flags.isByVal() && VA.isMemLoc()) {
7048       const unsigned Size =
7049           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7050                   PtrByteSize);
7051       const int FI = MF.getFrameInfo().CreateFixedObject(
7052           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7053           /* IsAliased */ true);
7054       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7055       InVals.push_back(FIN);
7056 
7057       continue;
7058     }
7059 
7060     if (Flags.isByVal()) {
7061       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7062 
7063       const MCPhysReg ArgReg = VA.getLocReg();
7064       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7065 
7066       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7067         report_fatal_error("Over aligned byvals not supported yet.");
7068 
7069       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7070       const int FI = MF.getFrameInfo().CreateFixedObject(
7071           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7072           /* IsAliased */ true);
7073       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7074       InVals.push_back(FIN);
7075 
7076       // Add live ins for all the RegLocs for the same ByVal.
7077       const TargetRegisterClass *RegClass =
7078           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7079 
7080       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7081                                                unsigned Offset) {
7082         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7083         // Since the callers side has left justified the aggregate in the
7084         // register, we can simply store the entire register into the stack
7085         // slot.
7086         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7087         // The store to the fixedstack object is needed becuase accessing a
7088         // field of the ByVal will use a gep and load. Ideally we will optimize
7089         // to extracting the value from the register directly, and elide the
7090         // stores when the arguments address is not taken, but that will need to
7091         // be future work.
7092         SDValue Store =
7093             DAG.getStore(CopyFrom.getValue(1), dl, CopyFrom,
7094                          DAG.getObjectPtrOffset(dl, FIN, Offset),
7095                          MachinePointerInfo::getFixedStack(MF, FI, Offset));
7096 
7097         MemOps.push_back(Store);
7098       };
7099 
7100       unsigned Offset = 0;
7101       HandleRegLoc(VA.getLocReg(), Offset);
7102       Offset += PtrByteSize;
7103       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7104            Offset += PtrByteSize) {
7105         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7106                "RegLocs should be for ByVal argument.");
7107 
7108         const CCValAssign RL = ArgLocs[I++];
7109         HandleRegLoc(RL.getLocReg(), Offset);
7110       }
7111 
7112       if (Offset != StackSize) {
7113         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7114                "Expected MemLoc for remaining bytes.");
7115         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7116         // Consume the MemLoc.The InVal has already been emitted, so nothing
7117         // more needs to be done.
7118         ++I;
7119       }
7120 
7121       continue;
7122     }
7123 
7124     EVT ValVT = VA.getValVT();
7125     if (VA.isRegLoc() && !VA.needsCustom()) {
7126       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7127       unsigned VReg =
7128           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7129       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7130       if (ValVT.isScalarInteger() &&
7131           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7132         ArgValue =
7133             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7134       }
7135       InVals.push_back(ArgValue);
7136       continue;
7137     }
7138     if (VA.isMemLoc()) {
7139       const unsigned LocSize = LocVT.getStoreSize();
7140       const unsigned ValSize = ValVT.getStoreSize();
7141       assert((ValSize <= LocSize) &&
7142              "Object size is larger than size of MemLoc");
7143       int CurArgOffset = VA.getLocMemOffset();
7144       // Objects are right-justified because AIX is big-endian.
7145       if (LocSize > ValSize)
7146         CurArgOffset += LocSize - ValSize;
7147       // Potential tail calls could cause overwriting of argument stack slots.
7148       const bool IsImmutable =
7149           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7150             (CallConv == CallingConv::Fast));
7151       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7152       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7153       SDValue ArgValue =
7154           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7155       InVals.push_back(ArgValue);
7156       continue;
7157     }
7158   }
7159 
7160   // On AIX a minimum of 8 words is saved to the parameter save area.
7161   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7162   // Area that is at least reserved in the caller of this function.
7163   unsigned CallerReservedArea =
7164       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7165 
7166   // Set the size that is at least reserved in caller of this function. Tail
7167   // call optimized function's reserved stack space needs to be aligned so
7168   // that taking the difference between two stack areas will result in an
7169   // aligned stack.
7170   CallerReservedArea =
7171       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7172   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7173   FuncInfo->setMinReservedArea(CallerReservedArea);
7174 
7175   if (isVarArg) {
7176     FuncInfo->setVarArgsFrameIndex(
7177         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7178     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7179 
7180     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7181                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7182 
7183     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7184                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7185     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7186 
7187     // The fixed integer arguments of a variadic function are stored to the
7188     // VarArgsFrameIndex on the stack so that they may be loaded by
7189     // dereferencing the result of va_next.
7190     for (unsigned GPRIndex =
7191              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7192          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7193 
7194       const unsigned VReg =
7195           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7196                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7197 
7198       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7199       SDValue Store =
7200           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7201       MemOps.push_back(Store);
7202       // Increment the address for the next argument to store.
7203       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7204       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7205     }
7206   }
7207 
7208   if (!MemOps.empty())
7209     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7210 
7211   return Chain;
7212 }
7213 
7214 SDValue PPCTargetLowering::LowerCall_AIX(
7215     SDValue Chain, SDValue Callee, CallFlags CFlags,
7216     const SmallVectorImpl<ISD::OutputArg> &Outs,
7217     const SmallVectorImpl<SDValue> &OutVals,
7218     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7219     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7220     const CallBase *CB) const {
7221   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7222   // AIX ABI stack frame layout.
7223 
7224   assert((CFlags.CallConv == CallingConv::C ||
7225           CFlags.CallConv == CallingConv::Cold ||
7226           CFlags.CallConv == CallingConv::Fast) &&
7227          "Unexpected calling convention!");
7228 
7229   if (CFlags.IsPatchPoint)
7230     report_fatal_error("This call type is unimplemented on AIX.");
7231 
7232   const PPCSubtarget& Subtarget =
7233       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7234   if (Subtarget.hasAltivec())
7235     report_fatal_error("Altivec support is unimplemented on AIX.");
7236 
7237   MachineFunction &MF = DAG.getMachineFunction();
7238   SmallVector<CCValAssign, 16> ArgLocs;
7239   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7240                  *DAG.getContext());
7241 
7242   // Reserve space for the linkage save area (LSA) on the stack.
7243   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7244   //   [SP][CR][LR][2 x reserved][TOC].
7245   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7246   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7247   const bool IsPPC64 = Subtarget.isPPC64();
7248   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7249   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7250   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7251   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7252 
7253   // The prolog code of the callee may store up to 8 GPR argument registers to
7254   // the stack, allowing va_start to index over them in memory if the callee
7255   // is variadic.
7256   // Because we cannot tell if this is needed on the caller side, we have to
7257   // conservatively assume that it is needed.  As such, make sure we have at
7258   // least enough stack space for the caller to store the 8 GPRs.
7259   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7260   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7261                                      CCInfo.getNextStackOffset());
7262 
7263   // Adjust the stack pointer for the new arguments...
7264   // These operations are automatically eliminated by the prolog/epilog pass.
7265   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7266   SDValue CallSeqStart = Chain;
7267 
7268   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7269   SmallVector<SDValue, 8> MemOpChains;
7270 
7271   // Set up a copy of the stack pointer for loading and storing any
7272   // arguments that may not fit in the registers available for argument
7273   // passing.
7274   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7275                                    : DAG.getRegister(PPC::R1, MVT::i32);
7276 
7277   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7278     const unsigned ValNo = ArgLocs[I].getValNo();
7279     SDValue Arg = OutVals[ValNo];
7280     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7281 
7282     if (Flags.isByVal()) {
7283       const unsigned ByValSize = Flags.getByValSize();
7284 
7285       // Nothing to do for zero-sized ByVals on the caller side.
7286       if (!ByValSize) {
7287         ++I;
7288         continue;
7289       }
7290 
7291       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7292         return DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain,
7293                               (LoadOffset != 0)
7294                                   ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7295                                   : Arg,
7296                               MachinePointerInfo(), VT);
7297       };
7298 
7299       unsigned LoadOffset = 0;
7300 
7301       // Initialize registers, which are fully occupied by the by-val argument.
7302       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7303         SDValue Load = GetLoad(PtrVT, LoadOffset);
7304         MemOpChains.push_back(Load.getValue(1));
7305         LoadOffset += PtrByteSize;
7306         const CCValAssign &ByValVA = ArgLocs[I++];
7307         assert(ByValVA.getValNo() == ValNo &&
7308                "Unexpected location for pass-by-value argument.");
7309         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7310       }
7311 
7312       if (LoadOffset == ByValSize)
7313         continue;
7314 
7315       // There must be one more loc to handle the remainder.
7316       assert(ArgLocs[I].getValNo() == ValNo &&
7317              "Expected additional location for by-value argument.");
7318 
7319       if (ArgLocs[I].isMemLoc()) {
7320         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7321         const CCValAssign &ByValVA = ArgLocs[I++];
7322         ISD::ArgFlagsTy MemcpyFlags = Flags;
7323         // Only memcpy the bytes that don't pass in register.
7324         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7325         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7326             (LoadOffset != 0) ? DAG.getObjectPtrOffset(dl, Arg, LoadOffset)
7327                               : Arg,
7328             DAG.getObjectPtrOffset(dl, StackPtr, ByValVA.getLocMemOffset()),
7329             CallSeqStart, MemcpyFlags, DAG, dl);
7330         continue;
7331       }
7332 
7333       // Initialize the final register residue.
7334       // Any residue that occupies the final by-val arg register must be
7335       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7336       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7337       // 2 and 1 byte loads.
7338       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7339       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7340              "Unexpected register residue for by-value argument.");
7341       SDValue ResidueVal;
7342       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7343         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7344         const MVT VT =
7345             N == 1 ? MVT::i8
7346                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7347         SDValue Load = GetLoad(VT, LoadOffset);
7348         MemOpChains.push_back(Load.getValue(1));
7349         LoadOffset += N;
7350         Bytes += N;
7351 
7352         // By-val arguments are passed left-justfied in register.
7353         // Every load here needs to be shifted, otherwise a full register load
7354         // should have been used.
7355         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7356                "Unexpected load emitted during handling of pass-by-value "
7357                "argument.");
7358         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7359         EVT ShiftAmountTy =
7360             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7361         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7362         SDValue ShiftedLoad =
7363             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7364         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7365                                               ShiftedLoad)
7366                                 : ShiftedLoad;
7367       }
7368 
7369       const CCValAssign &ByValVA = ArgLocs[I++];
7370       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7371       continue;
7372     }
7373 
7374     CCValAssign &VA = ArgLocs[I++];
7375     const MVT LocVT = VA.getLocVT();
7376     const MVT ValVT = VA.getValVT();
7377 
7378     switch (VA.getLocInfo()) {
7379     default:
7380       report_fatal_error("Unexpected argument extension type.");
7381     case CCValAssign::Full:
7382       break;
7383     case CCValAssign::ZExt:
7384       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7385       break;
7386     case CCValAssign::SExt:
7387       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7388       break;
7389     }
7390 
7391     if (VA.isRegLoc() && !VA.needsCustom()) {
7392       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7393       continue;
7394     }
7395 
7396     if (VA.isMemLoc()) {
7397       SDValue PtrOff =
7398           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7399       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7400       MemOpChains.push_back(
7401           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7402 
7403       continue;
7404     }
7405 
7406     // Custom handling is used for GPR initializations for vararg float
7407     // arguments.
7408     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7409            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7410            "Unexpected register handling for calling convention.");
7411 
7412     SDValue ArgAsInt =
7413         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7414 
7415     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7416       // f32 in 32-bit GPR
7417       // f64 in 64-bit GPR
7418       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7419     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7420       // f32 in 64-bit GPR.
7421       RegsToPass.push_back(std::make_pair(
7422           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7423     else {
7424       // f64 in two 32-bit GPRs
7425       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7426       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7427              "Unexpected custom register for argument!");
7428       CCValAssign &GPR1 = VA;
7429       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7430                                      DAG.getConstant(32, dl, MVT::i8));
7431       RegsToPass.push_back(std::make_pair(
7432           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7433 
7434       if (I != E) {
7435         // If only 1 GPR was available, there will only be one custom GPR and
7436         // the argument will also pass in memory.
7437         CCValAssign &PeekArg = ArgLocs[I];
7438         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7439           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7440           CCValAssign &GPR2 = ArgLocs[I++];
7441           RegsToPass.push_back(std::make_pair(
7442               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7443         }
7444       }
7445     }
7446   }
7447 
7448   if (!MemOpChains.empty())
7449     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7450 
7451   // For indirect calls, we need to save the TOC base to the stack for
7452   // restoration after the call.
7453   if (CFlags.IsIndirect) {
7454     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7455     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7456     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7457     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7458     const unsigned TOCSaveOffset =
7459         Subtarget.getFrameLowering()->getTOCSaveOffset();
7460 
7461     setUsesTOCBasePtr(DAG);
7462     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7463     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7464     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7465     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7466     Chain = DAG.getStore(
7467         Val.getValue(1), dl, Val, AddPtr,
7468         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7469   }
7470 
7471   // Build a sequence of copy-to-reg nodes chained together with token chain
7472   // and flag operands which copy the outgoing args into the appropriate regs.
7473   SDValue InFlag;
7474   for (auto Reg : RegsToPass) {
7475     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7476     InFlag = Chain.getValue(1);
7477   }
7478 
7479   const int SPDiff = 0;
7480   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7481                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7482 }
7483 
7484 bool
7485 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7486                                   MachineFunction &MF, bool isVarArg,
7487                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7488                                   LLVMContext &Context) const {
7489   SmallVector<CCValAssign, 16> RVLocs;
7490   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7491   return CCInfo.CheckReturn(
7492       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7493                 ? RetCC_PPC_Cold
7494                 : RetCC_PPC);
7495 }
7496 
7497 SDValue
7498 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7499                                bool isVarArg,
7500                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7501                                const SmallVectorImpl<SDValue> &OutVals,
7502                                const SDLoc &dl, SelectionDAG &DAG) const {
7503   SmallVector<CCValAssign, 16> RVLocs;
7504   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7505                  *DAG.getContext());
7506   CCInfo.AnalyzeReturn(Outs,
7507                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7508                            ? RetCC_PPC_Cold
7509                            : RetCC_PPC);
7510 
7511   SDValue Flag;
7512   SmallVector<SDValue, 4> RetOps(1, Chain);
7513 
7514   // Copy the result values into the output registers.
7515   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7516     CCValAssign &VA = RVLocs[i];
7517     assert(VA.isRegLoc() && "Can only return in registers!");
7518 
7519     SDValue Arg = OutVals[RealResIdx];
7520 
7521     switch (VA.getLocInfo()) {
7522     default: llvm_unreachable("Unknown loc info!");
7523     case CCValAssign::Full: break;
7524     case CCValAssign::AExt:
7525       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7526       break;
7527     case CCValAssign::ZExt:
7528       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7529       break;
7530     case CCValAssign::SExt:
7531       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7532       break;
7533     }
7534     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7535       bool isLittleEndian = Subtarget.isLittleEndian();
7536       // Legalize ret f64 -> ret 2 x i32.
7537       SDValue SVal =
7538           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7539                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7540       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7541       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7542       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7543                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7544       Flag = Chain.getValue(1);
7545       VA = RVLocs[++i]; // skip ahead to next loc
7546       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7547     } else
7548       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7549     Flag = Chain.getValue(1);
7550     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7551   }
7552 
7553   RetOps[0] = Chain;  // Update chain.
7554 
7555   // Add the flag if we have it.
7556   if (Flag.getNode())
7557     RetOps.push_back(Flag);
7558 
7559   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7560 }
7561 
7562 SDValue
7563 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7564                                                 SelectionDAG &DAG) const {
7565   SDLoc dl(Op);
7566 
7567   // Get the correct type for integers.
7568   EVT IntVT = Op.getValueType();
7569 
7570   // Get the inputs.
7571   SDValue Chain = Op.getOperand(0);
7572   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7573   // Build a DYNAREAOFFSET node.
7574   SDValue Ops[2] = {Chain, FPSIdx};
7575   SDVTList VTs = DAG.getVTList(IntVT);
7576   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7577 }
7578 
7579 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7580                                              SelectionDAG &DAG) const {
7581   // When we pop the dynamic allocation we need to restore the SP link.
7582   SDLoc dl(Op);
7583 
7584   // Get the correct type for pointers.
7585   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7586 
7587   // Construct the stack pointer operand.
7588   bool isPPC64 = Subtarget.isPPC64();
7589   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7590   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7591 
7592   // Get the operands for the STACKRESTORE.
7593   SDValue Chain = Op.getOperand(0);
7594   SDValue SaveSP = Op.getOperand(1);
7595 
7596   // Load the old link SP.
7597   SDValue LoadLinkSP =
7598       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7599 
7600   // Restore the stack pointer.
7601   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7602 
7603   // Store the old link SP.
7604   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7605 }
7606 
7607 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7608   MachineFunction &MF = DAG.getMachineFunction();
7609   bool isPPC64 = Subtarget.isPPC64();
7610   EVT PtrVT = getPointerTy(MF.getDataLayout());
7611 
7612   // Get current frame pointer save index.  The users of this index will be
7613   // primarily DYNALLOC instructions.
7614   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7615   int RASI = FI->getReturnAddrSaveIndex();
7616 
7617   // If the frame pointer save index hasn't been defined yet.
7618   if (!RASI) {
7619     // Find out what the fix offset of the frame pointer save area.
7620     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7621     // Allocate the frame index for frame pointer save area.
7622     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7623     // Save the result.
7624     FI->setReturnAddrSaveIndex(RASI);
7625   }
7626   return DAG.getFrameIndex(RASI, PtrVT);
7627 }
7628 
7629 SDValue
7630 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7631   MachineFunction &MF = DAG.getMachineFunction();
7632   bool isPPC64 = Subtarget.isPPC64();
7633   EVT PtrVT = getPointerTy(MF.getDataLayout());
7634 
7635   // Get current frame pointer save index.  The users of this index will be
7636   // primarily DYNALLOC instructions.
7637   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7638   int FPSI = FI->getFramePointerSaveIndex();
7639 
7640   // If the frame pointer save index hasn't been defined yet.
7641   if (!FPSI) {
7642     // Find out what the fix offset of the frame pointer save area.
7643     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7644     // Allocate the frame index for frame pointer save area.
7645     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7646     // Save the result.
7647     FI->setFramePointerSaveIndex(FPSI);
7648   }
7649   return DAG.getFrameIndex(FPSI, PtrVT);
7650 }
7651 
7652 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7653                                                    SelectionDAG &DAG) const {
7654   MachineFunction &MF = DAG.getMachineFunction();
7655   // Get the inputs.
7656   SDValue Chain = Op.getOperand(0);
7657   SDValue Size  = Op.getOperand(1);
7658   SDLoc dl(Op);
7659 
7660   // Get the correct type for pointers.
7661   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7662   // Negate the size.
7663   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7664                                 DAG.getConstant(0, dl, PtrVT), Size);
7665   // Construct a node for the frame pointer save index.
7666   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7667   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7668   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7669   if (hasInlineStackProbe(MF))
7670     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7671   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7672 }
7673 
7674 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7675                                                      SelectionDAG &DAG) const {
7676   MachineFunction &MF = DAG.getMachineFunction();
7677 
7678   bool isPPC64 = Subtarget.isPPC64();
7679   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7680 
7681   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7682   return DAG.getFrameIndex(FI, PtrVT);
7683 }
7684 
7685 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7686                                                SelectionDAG &DAG) const {
7687   SDLoc DL(Op);
7688   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7689                      DAG.getVTList(MVT::i32, MVT::Other),
7690                      Op.getOperand(0), Op.getOperand(1));
7691 }
7692 
7693 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7694                                                 SelectionDAG &DAG) const {
7695   SDLoc DL(Op);
7696   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7697                      Op.getOperand(0), Op.getOperand(1));
7698 }
7699 
7700 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7701 
7702   assert(Op.getValueType() == MVT::i1 &&
7703          "Custom lowering only for i1 loads");
7704 
7705   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7706 
7707   SDLoc dl(Op);
7708   LoadSDNode *LD = cast<LoadSDNode>(Op);
7709 
7710   SDValue Chain = LD->getChain();
7711   SDValue BasePtr = LD->getBasePtr();
7712   MachineMemOperand *MMO = LD->getMemOperand();
7713 
7714   SDValue NewLD =
7715       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7716                      BasePtr, MVT::i8, MMO);
7717   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7718 
7719   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7720   return DAG.getMergeValues(Ops, dl);
7721 }
7722 
7723 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7724   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7725          "Custom lowering only for i1 stores");
7726 
7727   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7728 
7729   SDLoc dl(Op);
7730   StoreSDNode *ST = cast<StoreSDNode>(Op);
7731 
7732   SDValue Chain = ST->getChain();
7733   SDValue BasePtr = ST->getBasePtr();
7734   SDValue Value = ST->getValue();
7735   MachineMemOperand *MMO = ST->getMemOperand();
7736 
7737   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7738                       Value);
7739   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7740 }
7741 
7742 // FIXME: Remove this once the ANDI glue bug is fixed:
7743 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7744   assert(Op.getValueType() == MVT::i1 &&
7745          "Custom lowering only for i1 results");
7746 
7747   SDLoc DL(Op);
7748   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7749 }
7750 
7751 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7752                                                SelectionDAG &DAG) const {
7753 
7754   // Implements a vector truncate that fits in a vector register as a shuffle.
7755   // We want to legalize vector truncates down to where the source fits in
7756   // a vector register (and target is therefore smaller than vector register
7757   // size).  At that point legalization will try to custom lower the sub-legal
7758   // result and get here - where we can contain the truncate as a single target
7759   // operation.
7760 
7761   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7762   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7763   //
7764   // We will implement it for big-endian ordering as this (where x denotes
7765   // undefined):
7766   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7767   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7768   //
7769   // The same operation in little-endian ordering will be:
7770   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7771   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7772 
7773   assert(Op.getValueType().isVector() && "Vector type expected.");
7774 
7775   SDLoc DL(Op);
7776   SDValue N1 = Op.getOperand(0);
7777   unsigned SrcSize = N1.getValueType().getSizeInBits();
7778   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7779   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7780 
7781   EVT TrgVT = Op.getValueType();
7782   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7783   EVT EltVT = TrgVT.getVectorElementType();
7784   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7785   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7786 
7787   // First list the elements we want to keep.
7788   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7789   SmallVector<int, 16> ShuffV;
7790   if (Subtarget.isLittleEndian())
7791     for (unsigned i = 0; i < TrgNumElts; ++i)
7792       ShuffV.push_back(i * SizeMult);
7793   else
7794     for (unsigned i = 1; i <= TrgNumElts; ++i)
7795       ShuffV.push_back(i * SizeMult - 1);
7796 
7797   // Populate the remaining elements with undefs.
7798   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7799     // ShuffV.push_back(i + WideNumElts);
7800     ShuffV.push_back(WideNumElts + 1);
7801 
7802   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7803   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7804 }
7805 
7806 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7807 /// possible.
7808 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7809   // Not FP, or using SPE? Not a fsel.
7810   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7811       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7812     return Op;
7813 
7814   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7815 
7816   EVT ResVT = Op.getValueType();
7817   EVT CmpVT = Op.getOperand(0).getValueType();
7818   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7819   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7820   SDLoc dl(Op);
7821   SDNodeFlags Flags = Op.getNode()->getFlags();
7822 
7823   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7824   // presence of infinities.
7825   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7826     switch (CC) {
7827     default:
7828       break;
7829     case ISD::SETOGT:
7830     case ISD::SETGT:
7831       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7832     case ISD::SETOLT:
7833     case ISD::SETLT:
7834       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7835     }
7836   }
7837 
7838   // We might be able to do better than this under some circumstances, but in
7839   // general, fsel-based lowering of select is a finite-math-only optimization.
7840   // For more information, see section F.3 of the 2.06 ISA specification.
7841   // With ISA 3.0
7842   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7843       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7844     return Op;
7845 
7846   // If the RHS of the comparison is a 0.0, we don't need to do the
7847   // subtraction at all.
7848   SDValue Sel1;
7849   if (isFloatingPointZero(RHS))
7850     switch (CC) {
7851     default: break;       // SETUO etc aren't handled by fsel.
7852     case ISD::SETNE:
7853       std::swap(TV, FV);
7854       LLVM_FALLTHROUGH;
7855     case ISD::SETEQ:
7856       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7857         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7858       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7859       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7860         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7861       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7862                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7863     case ISD::SETULT:
7864     case ISD::SETLT:
7865       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7866       LLVM_FALLTHROUGH;
7867     case ISD::SETOGE:
7868     case ISD::SETGE:
7869       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7870         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7871       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7872     case ISD::SETUGT:
7873     case ISD::SETGT:
7874       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7875       LLVM_FALLTHROUGH;
7876     case ISD::SETOLE:
7877     case ISD::SETLE:
7878       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7879         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7880       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7881                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7882     }
7883 
7884   SDValue Cmp;
7885   switch (CC) {
7886   default: break;       // SETUO etc aren't handled by fsel.
7887   case ISD::SETNE:
7888     std::swap(TV, FV);
7889     LLVM_FALLTHROUGH;
7890   case ISD::SETEQ:
7891     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7892     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7893       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7894     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7895     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7896       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7897     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7898                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7899   case ISD::SETULT:
7900   case ISD::SETLT:
7901     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7902     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7903       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7904     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7905   case ISD::SETOGE:
7906   case ISD::SETGE:
7907     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7908     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7909       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7910     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7911   case ISD::SETUGT:
7912   case ISD::SETGT:
7913     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7914     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7915       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7916     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7917   case ISD::SETOLE:
7918   case ISD::SETLE:
7919     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7920     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7921       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7922     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7923   }
7924   return Op;
7925 }
7926 
7927 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7928                               const PPCSubtarget &Subtarget) {
7929   SDLoc dl(Op);
7930   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7931   SDValue Src = Op.getOperand(0);
7932   assert(Src.getValueType().isFloatingPoint());
7933   if (Src.getValueType() == MVT::f32)
7934     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7935   SDValue Conv;
7936   switch (Op.getSimpleValueType().SimpleTy) {
7937   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7938   case MVT::i32:
7939     Conv = DAG.getNode(
7940         IsSigned ? PPCISD::FCTIWZ
7941                  : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7942         dl, MVT::f64, Src);
7943     break;
7944   case MVT::i64:
7945     assert((IsSigned || Subtarget.hasFPCVT()) &&
7946            "i64 FP_TO_UINT is supported only with FPCVT");
7947     Conv = DAG.getNode(IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ, dl,
7948                        MVT::f64, Src);
7949   }
7950   return Conv;
7951 }
7952 
7953 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7954                                                SelectionDAG &DAG,
7955                                                const SDLoc &dl) const {
7956   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
7957   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
7958 
7959   // Convert the FP value to an int value through memory.
7960   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7961                   (IsSigned || Subtarget.hasFPCVT());
7962   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7963   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7964   MachinePointerInfo MPI =
7965       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7966 
7967   // Emit a store to the stack slot.
7968   SDValue Chain;
7969   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
7970   if (i32Stack) {
7971     MachineFunction &MF = DAG.getMachineFunction();
7972     Alignment = Align(4);
7973     MachineMemOperand *MMO =
7974         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
7975     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7976     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7977               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7978   } else
7979     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI, Alignment);
7980 
7981   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7982   // add in a bias on big endian.
7983   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7984     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7985                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7986     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7987   }
7988 
7989   RLI.Chain = Chain;
7990   RLI.Ptr = FIPtr;
7991   RLI.MPI = MPI;
7992   RLI.Alignment = Alignment;
7993 }
7994 
7995 /// Custom lowers floating point to integer conversions to use
7996 /// the direct move instructions available in ISA 2.07 to avoid the
7997 /// need for load/store combinations.
7998 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7999                                                     SelectionDAG &DAG,
8000                                                     const SDLoc &dl) const {
8001   assert(Op.getOperand(0).getValueType().isFloatingPoint());
8002   return DAG.getNode(PPCISD::MFVSR, dl, Op.getSimpleValueType().SimpleTy,
8003                      convertFPToInt(Op, DAG, Subtarget));
8004 }
8005 
8006 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8007                                           const SDLoc &dl) const {
8008   SDValue Src = Op.getOperand(0);
8009   // FP to INT conversions are legal for f128.
8010   if (Src.getValueType() == MVT::f128)
8011     return Op;
8012 
8013   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8014   // PPC (the libcall is not available).
8015   if (Src.getValueType() == MVT::ppcf128) {
8016     if (Op.getValueType() == MVT::i32) {
8017       if (Op.getOpcode() == ISD::FP_TO_SINT) {
8018         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8019                                  DAG.getIntPtrConstant(0, dl));
8020         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8021                                  DAG.getIntPtrConstant(1, dl));
8022 
8023         // Add the two halves of the long double in round-to-zero mode.
8024         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8025 
8026         // Now use a smaller FP_TO_SINT.
8027         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8028       }
8029       if (Op.getOpcode() == ISD::FP_TO_UINT) {
8030         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8031         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8032         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8033         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8034         // FIXME: generated code sucks.
8035         // TODO: Are there fast-math-flags to propagate to this FSUB?
8036         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8037         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8038         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8039                            DAG.getConstant(0x80000000, dl, MVT::i32));
8040         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8041         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8042       }
8043     }
8044 
8045     return SDValue();
8046   }
8047 
8048   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8049     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8050 
8051   ReuseLoadInfo RLI;
8052   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8053 
8054   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8055                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8056 }
8057 
8058 // We're trying to insert a regular store, S, and then a load, L. If the
8059 // incoming value, O, is a load, we might just be able to have our load use the
8060 // address used by O. However, we don't know if anything else will store to
8061 // that address before we can load from it. To prevent this situation, we need
8062 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8063 // the same chain operand as O, we create a token factor from the chain results
8064 // of O and L, and we replace all uses of O's chain result with that token
8065 // factor (see spliceIntoChain below for this last part).
8066 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8067                                             ReuseLoadInfo &RLI,
8068                                             SelectionDAG &DAG,
8069                                             ISD::LoadExtType ET) const {
8070   SDLoc dl(Op);
8071   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8072                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8073   if (ET == ISD::NON_EXTLOAD &&
8074       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8075       isOperationLegalOrCustom(Op.getOpcode(),
8076                                Op.getOperand(0).getValueType())) {
8077 
8078     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8079     return true;
8080   }
8081 
8082   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8083   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8084       LD->isNonTemporal())
8085     return false;
8086   if (LD->getMemoryVT() != MemVT)
8087     return false;
8088 
8089   RLI.Ptr = LD->getBasePtr();
8090   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8091     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8092            "Non-pre-inc AM on PPC?");
8093     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8094                           LD->getOffset());
8095   }
8096 
8097   RLI.Chain = LD->getChain();
8098   RLI.MPI = LD->getPointerInfo();
8099   RLI.IsDereferenceable = LD->isDereferenceable();
8100   RLI.IsInvariant = LD->isInvariant();
8101   RLI.Alignment = LD->getAlign();
8102   RLI.AAInfo = LD->getAAInfo();
8103   RLI.Ranges = LD->getRanges();
8104 
8105   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8106   return true;
8107 }
8108 
8109 // Given the head of the old chain, ResChain, insert a token factor containing
8110 // it and NewResChain, and make users of ResChain now be users of that token
8111 // factor.
8112 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8113 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8114                                         SDValue NewResChain,
8115                                         SelectionDAG &DAG) const {
8116   if (!ResChain)
8117     return;
8118 
8119   SDLoc dl(NewResChain);
8120 
8121   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8122                            NewResChain, DAG.getUNDEF(MVT::Other));
8123   assert(TF.getNode() != NewResChain.getNode() &&
8124          "A new TF really is required here");
8125 
8126   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8127   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8128 }
8129 
8130 /// Analyze profitability of direct move
8131 /// prefer float load to int load plus direct move
8132 /// when there is no integer use of int load
8133 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8134   SDNode *Origin = Op.getOperand(0).getNode();
8135   if (Origin->getOpcode() != ISD::LOAD)
8136     return true;
8137 
8138   // If there is no LXSIBZX/LXSIHZX, like Power8,
8139   // prefer direct move if the memory size is 1 or 2 bytes.
8140   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8141   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8142     return true;
8143 
8144   for (SDNode::use_iterator UI = Origin->use_begin(),
8145                             UE = Origin->use_end();
8146        UI != UE; ++UI) {
8147 
8148     // Only look at the users of the loaded value.
8149     if (UI.getUse().get().getResNo() != 0)
8150       continue;
8151 
8152     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8153         UI->getOpcode() != ISD::UINT_TO_FP)
8154       return true;
8155   }
8156 
8157   return false;
8158 }
8159 
8160 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8161                               const PPCSubtarget &Subtarget) {
8162   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8163   SDLoc dl(Op);
8164   // If we have FCFIDS, then use it when converting to single-precision.
8165   // Otherwise, convert to double-precision and then round.
8166   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8167   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8168                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8169   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8170   return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8171 }
8172 
8173 /// Custom lowers integer to floating point conversions to use
8174 /// the direct move instructions available in ISA 2.07 to avoid the
8175 /// need for load/store combinations.
8176 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8177                                                     SelectionDAG &DAG,
8178                                                     const SDLoc &dl) const {
8179   assert((Op.getValueType() == MVT::f32 ||
8180           Op.getValueType() == MVT::f64) &&
8181          "Invalid floating point type as target of conversion");
8182   assert(Subtarget.hasFPCVT() &&
8183          "Int to FP conversions with direct moves require FPCVT");
8184   SDValue Src = Op.getOperand(0);
8185   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8186   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8187   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8188   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8189   return convertIntToFP(Op, Mov, DAG, Subtarget);
8190 }
8191 
8192 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8193 
8194   EVT VecVT = Vec.getValueType();
8195   assert(VecVT.isVector() && "Expected a vector type.");
8196   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8197 
8198   EVT EltVT = VecVT.getVectorElementType();
8199   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8200   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8201 
8202   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8203   SmallVector<SDValue, 16> Ops(NumConcat);
8204   Ops[0] = Vec;
8205   SDValue UndefVec = DAG.getUNDEF(VecVT);
8206   for (unsigned i = 1; i < NumConcat; ++i)
8207     Ops[i] = UndefVec;
8208 
8209   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8210 }
8211 
8212 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8213                                                 const SDLoc &dl) const {
8214 
8215   unsigned Opc = Op.getOpcode();
8216   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8217          "Unexpected conversion type");
8218   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8219          "Supports conversions to v2f64/v4f32 only.");
8220 
8221   bool SignedConv = Opc == ISD::SINT_TO_FP;
8222   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8223 
8224   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8225   EVT WideVT = Wide.getValueType();
8226   unsigned WideNumElts = WideVT.getVectorNumElements();
8227   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8228 
8229   SmallVector<int, 16> ShuffV;
8230   for (unsigned i = 0; i < WideNumElts; ++i)
8231     ShuffV.push_back(i + WideNumElts);
8232 
8233   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8234   int SaveElts = FourEltRes ? 4 : 2;
8235   if (Subtarget.isLittleEndian())
8236     for (int i = 0; i < SaveElts; i++)
8237       ShuffV[i * Stride] = i;
8238   else
8239     for (int i = 1; i <= SaveElts; i++)
8240       ShuffV[i * Stride - 1] = i - 1;
8241 
8242   SDValue ShuffleSrc2 =
8243       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8244   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8245 
8246   SDValue Extend;
8247   if (SignedConv) {
8248     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8249     EVT ExtVT = Op.getOperand(0).getValueType();
8250     if (Subtarget.hasP9Altivec())
8251       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8252                                IntermediateVT.getVectorNumElements());
8253 
8254     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8255                          DAG.getValueType(ExtVT));
8256   } else
8257     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8258 
8259   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8260 }
8261 
8262 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8263                                           SelectionDAG &DAG) const {
8264   SDLoc dl(Op);
8265   SDValue Src = Op.getOperand(0);
8266   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8267 
8268   EVT InVT = Src.getValueType();
8269   EVT OutVT = Op.getValueType();
8270   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8271       isOperationCustom(Op.getOpcode(), InVT))
8272     return LowerINT_TO_FPVector(Op, DAG, dl);
8273 
8274   // Conversions to f128 are legal.
8275   if (Op.getValueType() == MVT::f128)
8276     return Op;
8277 
8278   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8279   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8280     return SDValue();
8281 
8282   if (Src.getValueType() == MVT::i1)
8283     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8284                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8285                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8286 
8287   // If we have direct moves, we can do all the conversion, skip the store/load
8288   // however, without FPCVT we can't do most conversions.
8289   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8290       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8291     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8292 
8293   assert((IsSigned || Subtarget.hasFPCVT()) &&
8294          "UINT_TO_FP is supported only with FPCVT");
8295 
8296   if (Src.getValueType() == MVT::i64) {
8297     SDValue SINT = Src;
8298     // When converting to single-precision, we actually need to convert
8299     // to double-precision first and then round to single-precision.
8300     // To avoid double-rounding effects during that operation, we have
8301     // to prepare the input operand.  Bits that might be truncated when
8302     // converting to double-precision are replaced by a bit that won't
8303     // be lost at this stage, but is below the single-precision rounding
8304     // position.
8305     //
8306     // However, if -enable-unsafe-fp-math is in effect, accept double
8307     // rounding to avoid the extra overhead.
8308     if (Op.getValueType() == MVT::f32 &&
8309         !Subtarget.hasFPCVT() &&
8310         !DAG.getTarget().Options.UnsafeFPMath) {
8311 
8312       // Twiddle input to make sure the low 11 bits are zero.  (If this
8313       // is the case, we are guaranteed the value will fit into the 53 bit
8314       // mantissa of an IEEE double-precision value without rounding.)
8315       // If any of those low 11 bits were not zero originally, make sure
8316       // bit 12 (value 2048) is set instead, so that the final rounding
8317       // to single-precision gets the correct result.
8318       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8319                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8320       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8321                           Round, DAG.getConstant(2047, dl, MVT::i64));
8322       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8323       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8324                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8325 
8326       // However, we cannot use that value unconditionally: if the magnitude
8327       // of the input value is small, the bit-twiddling we did above might
8328       // end up visibly changing the output.  Fortunately, in that case, we
8329       // don't need to twiddle bits since the original input will convert
8330       // exactly to double-precision floating-point already.  Therefore,
8331       // construct a conditional to use the original value if the top 11
8332       // bits are all sign-bit copies, and use the rounded value computed
8333       // above otherwise.
8334       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8335                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8336       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8337                          Cond, DAG.getConstant(1, dl, MVT::i64));
8338       Cond = DAG.getSetCC(
8339           dl,
8340           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8341           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8342 
8343       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8344     }
8345 
8346     ReuseLoadInfo RLI;
8347     SDValue Bits;
8348 
8349     MachineFunction &MF = DAG.getMachineFunction();
8350     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8351       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8352                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8353       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8354     } else if (Subtarget.hasLFIWAX() &&
8355                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8356       MachineMemOperand *MMO =
8357         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8358                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8359       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8360       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8361                                      DAG.getVTList(MVT::f64, MVT::Other),
8362                                      Ops, MVT::i32, MMO);
8363       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8364     } else if (Subtarget.hasFPCVT() &&
8365                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8366       MachineMemOperand *MMO =
8367         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8368                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8369       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8370       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8371                                      DAG.getVTList(MVT::f64, MVT::Other),
8372                                      Ops, MVT::i32, MMO);
8373       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8374     } else if (((Subtarget.hasLFIWAX() &&
8375                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8376                 (Subtarget.hasFPCVT() &&
8377                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8378                SINT.getOperand(0).getValueType() == MVT::i32) {
8379       MachineFrameInfo &MFI = MF.getFrameInfo();
8380       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8381 
8382       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8383       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8384 
8385       SDValue Store =
8386           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8387                        MachinePointerInfo::getFixedStack(
8388                            DAG.getMachineFunction(), FrameIdx));
8389 
8390       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8391              "Expected an i32 store");
8392 
8393       RLI.Ptr = FIdx;
8394       RLI.Chain = Store;
8395       RLI.MPI =
8396           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8397       RLI.Alignment = Align(4);
8398 
8399       MachineMemOperand *MMO =
8400         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8401                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8402       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8403       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8404                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8405                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8406                                      Ops, MVT::i32, MMO);
8407     } else
8408       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8409 
8410     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget);
8411 
8412     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8413       FP = DAG.getNode(ISD::FP_ROUND, dl,
8414                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8415     return FP;
8416   }
8417 
8418   assert(Src.getValueType() == MVT::i32 &&
8419          "Unhandled INT_TO_FP type in custom expander!");
8420   // Since we only generate this in 64-bit mode, we can take advantage of
8421   // 64-bit registers.  In particular, sign extend the input value into the
8422   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8423   // then lfd it and fcfid it.
8424   MachineFunction &MF = DAG.getMachineFunction();
8425   MachineFrameInfo &MFI = MF.getFrameInfo();
8426   EVT PtrVT = getPointerTy(MF.getDataLayout());
8427 
8428   SDValue Ld;
8429   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8430     ReuseLoadInfo RLI;
8431     bool ReusingLoad;
8432     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8433       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8434       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8435 
8436       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx,
8437                                    MachinePointerInfo::getFixedStack(
8438                                        DAG.getMachineFunction(), FrameIdx));
8439 
8440       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8441              "Expected an i32 store");
8442 
8443       RLI.Ptr = FIdx;
8444       RLI.Chain = Store;
8445       RLI.MPI =
8446           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8447       RLI.Alignment = Align(4);
8448     }
8449 
8450     MachineMemOperand *MMO =
8451       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8452                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8453     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8454     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8455                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8456                                  MVT::i32, MMO);
8457     if (ReusingLoad)
8458       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8459   } else {
8460     assert(Subtarget.isPPC64() &&
8461            "i32->FP without LFIWAX supported only on PPC64");
8462 
8463     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8464     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8465 
8466     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8467 
8468     // STD the extended value into the stack slot.
8469     SDValue Store = DAG.getStore(
8470         DAG.getEntryNode(), dl, Ext64, FIdx,
8471         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8472 
8473     // Load the value as a double.
8474     Ld = DAG.getLoad(
8475         MVT::f64, dl, Store, FIdx,
8476         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8477   }
8478 
8479   // FCFID it and return it.
8480   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget);
8481   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8482     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8483                      DAG.getIntPtrConstant(0, dl));
8484   return FP;
8485 }
8486 
8487 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8488                                             SelectionDAG &DAG) const {
8489   SDLoc dl(Op);
8490   /*
8491    The rounding mode is in bits 30:31 of FPSR, and has the following
8492    settings:
8493      00 Round to nearest
8494      01 Round to 0
8495      10 Round to +inf
8496      11 Round to -inf
8497 
8498   FLT_ROUNDS, on the other hand, expects the following:
8499     -1 Undefined
8500      0 Round to 0
8501      1 Round to nearest
8502      2 Round to +inf
8503      3 Round to -inf
8504 
8505   To perform the conversion, we do:
8506     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8507   */
8508 
8509   MachineFunction &MF = DAG.getMachineFunction();
8510   EVT VT = Op.getValueType();
8511   EVT PtrVT = getPointerTy(MF.getDataLayout());
8512 
8513   // Save FP Control Word to register
8514   SDValue Chain = Op.getOperand(0);
8515   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8516   Chain = MFFS.getValue(1);
8517 
8518   // Save FP register to stack slot
8519   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8520   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8521   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8522 
8523   // Load FP Control Word from low 32 bits of stack slot.
8524   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8525   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8526   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8527   Chain = CWD.getValue(1);
8528 
8529   // Transform as necessary
8530   SDValue CWD1 =
8531     DAG.getNode(ISD::AND, dl, MVT::i32,
8532                 CWD, DAG.getConstant(3, dl, MVT::i32));
8533   SDValue CWD2 =
8534     DAG.getNode(ISD::SRL, dl, MVT::i32,
8535                 DAG.getNode(ISD::AND, dl, MVT::i32,
8536                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8537                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8538                             DAG.getConstant(3, dl, MVT::i32)),
8539                 DAG.getConstant(1, dl, MVT::i32));
8540 
8541   SDValue RetVal =
8542     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8543 
8544   RetVal =
8545       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8546                   dl, VT, RetVal);
8547 
8548   return DAG.getMergeValues({RetVal, Chain}, dl);
8549 }
8550 
8551 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8552   EVT VT = Op.getValueType();
8553   unsigned BitWidth = VT.getSizeInBits();
8554   SDLoc dl(Op);
8555   assert(Op.getNumOperands() == 3 &&
8556          VT == Op.getOperand(1).getValueType() &&
8557          "Unexpected SHL!");
8558 
8559   // Expand into a bunch of logical ops.  Note that these ops
8560   // depend on the PPC behavior for oversized shift amounts.
8561   SDValue Lo = Op.getOperand(0);
8562   SDValue Hi = Op.getOperand(1);
8563   SDValue Amt = Op.getOperand(2);
8564   EVT AmtVT = Amt.getValueType();
8565 
8566   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8567                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8568   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8569   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8570   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8571   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8572                              DAG.getConstant(-BitWidth, dl, AmtVT));
8573   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8574   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8575   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8576   SDValue OutOps[] = { OutLo, OutHi };
8577   return DAG.getMergeValues(OutOps, dl);
8578 }
8579 
8580 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8581   EVT VT = Op.getValueType();
8582   SDLoc dl(Op);
8583   unsigned BitWidth = VT.getSizeInBits();
8584   assert(Op.getNumOperands() == 3 &&
8585          VT == Op.getOperand(1).getValueType() &&
8586          "Unexpected SRL!");
8587 
8588   // Expand into a bunch of logical ops.  Note that these ops
8589   // depend on the PPC behavior for oversized shift amounts.
8590   SDValue Lo = Op.getOperand(0);
8591   SDValue Hi = Op.getOperand(1);
8592   SDValue Amt = Op.getOperand(2);
8593   EVT AmtVT = Amt.getValueType();
8594 
8595   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8596                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8597   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8598   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8599   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8600   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8601                              DAG.getConstant(-BitWidth, dl, AmtVT));
8602   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8603   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8604   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8605   SDValue OutOps[] = { OutLo, OutHi };
8606   return DAG.getMergeValues(OutOps, dl);
8607 }
8608 
8609 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8610   SDLoc dl(Op);
8611   EVT VT = Op.getValueType();
8612   unsigned BitWidth = VT.getSizeInBits();
8613   assert(Op.getNumOperands() == 3 &&
8614          VT == Op.getOperand(1).getValueType() &&
8615          "Unexpected SRA!");
8616 
8617   // Expand into a bunch of logical ops, followed by a select_cc.
8618   SDValue Lo = Op.getOperand(0);
8619   SDValue Hi = Op.getOperand(1);
8620   SDValue Amt = Op.getOperand(2);
8621   EVT AmtVT = Amt.getValueType();
8622 
8623   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8624                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8625   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8626   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8627   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8628   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8629                              DAG.getConstant(-BitWidth, dl, AmtVT));
8630   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8631   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8632   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8633                                   Tmp4, Tmp6, ISD::SETLE);
8634   SDValue OutOps[] = { OutLo, OutHi };
8635   return DAG.getMergeValues(OutOps, dl);
8636 }
8637 
8638 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8639                                             SelectionDAG &DAG) const {
8640   SDLoc dl(Op);
8641   EVT VT = Op.getValueType();
8642   unsigned BitWidth = VT.getSizeInBits();
8643 
8644   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8645   SDValue X = Op.getOperand(0);
8646   SDValue Y = Op.getOperand(1);
8647   SDValue Z = Op.getOperand(2);
8648   EVT AmtVT = Z.getValueType();
8649 
8650   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8651   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8652   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8653   // on PowerPC shift by BW being well defined.
8654   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8655                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8656   SDValue SubZ =
8657       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8658   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8659   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8660   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8661 }
8662 
8663 //===----------------------------------------------------------------------===//
8664 // Vector related lowering.
8665 //
8666 
8667 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8668 /// element size of SplatSize. Cast the result to VT.
8669 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8670                                       SelectionDAG &DAG, const SDLoc &dl) {
8671   static const MVT VTys[] = { // canonical VT to use for each size.
8672     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8673   };
8674 
8675   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8676 
8677   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8678   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8679     SplatSize = 1;
8680     Val = 0xFF;
8681   }
8682 
8683   EVT CanonicalVT = VTys[SplatSize-1];
8684 
8685   // Build a canonical splat for this value.
8686   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8687 }
8688 
8689 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8690 /// specified intrinsic ID.
8691 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8692                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8693   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8694   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8695                      DAG.getConstant(IID, dl, MVT::i32), Op);
8696 }
8697 
8698 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8699 /// specified intrinsic ID.
8700 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8701                                 SelectionDAG &DAG, const SDLoc &dl,
8702                                 EVT DestVT = MVT::Other) {
8703   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8704   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8705                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8706 }
8707 
8708 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8709 /// specified intrinsic ID.
8710 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8711                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8712                                 EVT DestVT = MVT::Other) {
8713   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8714   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8715                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8716 }
8717 
8718 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8719 /// amount.  The result has the specified value type.
8720 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8721                            SelectionDAG &DAG, const SDLoc &dl) {
8722   // Force LHS/RHS to be the right type.
8723   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8724   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8725 
8726   int Ops[16];
8727   for (unsigned i = 0; i != 16; ++i)
8728     Ops[i] = i + Amt;
8729   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8730   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8731 }
8732 
8733 /// Do we have an efficient pattern in a .td file for this node?
8734 ///
8735 /// \param V - pointer to the BuildVectorSDNode being matched
8736 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8737 ///
8738 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8739 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8740 /// the opposite is true (expansion is beneficial) are:
8741 /// - The node builds a vector out of integers that are not 32 or 64-bits
8742 /// - The node builds a vector out of constants
8743 /// - The node is a "load-and-splat"
8744 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8745 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8746                                             bool HasDirectMove,
8747                                             bool HasP8Vector) {
8748   EVT VecVT = V->getValueType(0);
8749   bool RightType = VecVT == MVT::v2f64 ||
8750     (HasP8Vector && VecVT == MVT::v4f32) ||
8751     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8752   if (!RightType)
8753     return false;
8754 
8755   bool IsSplat = true;
8756   bool IsLoad = false;
8757   SDValue Op0 = V->getOperand(0);
8758 
8759   // This function is called in a block that confirms the node is not a constant
8760   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8761   // different constants.
8762   if (V->isConstant())
8763     return false;
8764   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8765     if (V->getOperand(i).isUndef())
8766       return false;
8767     // We want to expand nodes that represent load-and-splat even if the
8768     // loaded value is a floating point truncation or conversion to int.
8769     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8770         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8771          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8772         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8773          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8774         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8775          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8776       IsLoad = true;
8777     // If the operands are different or the input is not a load and has more
8778     // uses than just this BV node, then it isn't a splat.
8779     if (V->getOperand(i) != Op0 ||
8780         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8781       IsSplat = false;
8782   }
8783   return !(IsSplat && IsLoad);
8784 }
8785 
8786 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8787 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8788 
8789   SDLoc dl(Op);
8790   SDValue Op0 = Op->getOperand(0);
8791 
8792   if ((Op.getValueType() != MVT::f128) ||
8793       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8794       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8795       (Op0.getOperand(1).getValueType() != MVT::i64))
8796     return SDValue();
8797 
8798   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8799                      Op0.getOperand(1));
8800 }
8801 
8802 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8803   const SDValue *InputLoad = &Op;
8804   if (InputLoad->getOpcode() == ISD::BITCAST)
8805     InputLoad = &InputLoad->getOperand(0);
8806   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8807       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8808     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8809     InputLoad = &InputLoad->getOperand(0);
8810   }
8811   if (InputLoad->getOpcode() != ISD::LOAD)
8812     return nullptr;
8813   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8814   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8815 }
8816 
8817 // Convert the argument APFloat to a single precision APFloat if there is no
8818 // loss in information during the conversion to single precision APFloat and the
8819 // resulting number is not a denormal number. Return true if successful.
8820 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8821   APFloat APFloatToConvert = ArgAPFloat;
8822   bool LosesInfo = true;
8823   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8824                            &LosesInfo);
8825   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8826   if (Success)
8827     ArgAPFloat = APFloatToConvert;
8828   return Success;
8829 }
8830 
8831 // Bitcast the argument APInt to a double and convert it to a single precision
8832 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8833 // argument if there is no loss in information during the conversion from
8834 // double to single precision APFloat and the resulting number is not a denormal
8835 // number. Return true if successful.
8836 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8837   double DpValue = ArgAPInt.bitsToDouble();
8838   APFloat APFloatDp(DpValue);
8839   bool Success = convertToNonDenormSingle(APFloatDp);
8840   if (Success)
8841     ArgAPInt = APFloatDp.bitcastToAPInt();
8842   return Success;
8843 }
8844 
8845 // If this is a case we can't handle, return null and let the default
8846 // expansion code take care of it.  If we CAN select this case, and if it
8847 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8848 // this case more efficiently than a constant pool load, lower it to the
8849 // sequence of ops that should be used.
8850 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8851                                              SelectionDAG &DAG) const {
8852   SDLoc dl(Op);
8853   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8854   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8855 
8856   // Check if this is a splat of a constant value.
8857   APInt APSplatBits, APSplatUndef;
8858   unsigned SplatBitSize;
8859   bool HasAnyUndefs;
8860   bool BVNIsConstantSplat =
8861       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8862                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8863 
8864   // If it is a splat of a double, check if we can shrink it to a 32 bit
8865   // non-denormal float which when converted back to double gives us the same
8866   // double. This is to exploit the XXSPLTIDP instruction.
8867   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
8868       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
8869       convertToNonDenormSingle(APSplatBits)) {
8870     SDValue SplatNode = DAG.getNode(
8871         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8872         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8873     return DAG.getBitcast(Op.getValueType(), SplatNode);
8874   }
8875 
8876   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8877 
8878     bool IsPermutedLoad = false;
8879     const SDValue *InputLoad =
8880         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8881     // Handle load-and-splat patterns as we have instructions that will do this
8882     // in one go.
8883     if (InputLoad && DAG.isSplatValue(Op, true)) {
8884       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8885 
8886       // We have handling for 4 and 8 byte elements.
8887       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8888 
8889       // Checking for a single use of this load, we have to check for vector
8890       // width (128 bits) / ElementSize uses (since each operand of the
8891       // BUILD_VECTOR is a separate use of the value.
8892       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8893           ((Subtarget.hasVSX() && ElementSize == 64) ||
8894            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8895         SDValue Ops[] = {
8896           LD->getChain(),    // Chain
8897           LD->getBasePtr(),  // Ptr
8898           DAG.getValueType(Op.getValueType()) // VT
8899         };
8900         return
8901           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8902                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8903                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8904       }
8905     }
8906 
8907     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8908     // lowered to VSX instructions under certain conditions.
8909     // Without VSX, there is no pattern more efficient than expanding the node.
8910     if (Subtarget.hasVSX() &&
8911         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8912                                         Subtarget.hasP8Vector()))
8913       return Op;
8914     return SDValue();
8915   }
8916 
8917   uint64_t SplatBits = APSplatBits.getZExtValue();
8918   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8919   unsigned SplatSize = SplatBitSize / 8;
8920 
8921   // First, handle single instruction cases.
8922 
8923   // All zeros?
8924   if (SplatBits == 0) {
8925     // Canonicalize all zero vectors to be v4i32.
8926     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8927       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8928       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8929     }
8930     return Op;
8931   }
8932 
8933   // We have XXSPLTIW for constant splats four bytes wide.
8934   // Given vector length is a multiple of 4, 2-byte splats can be replaced
8935   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
8936   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
8937   // turned into a 4-byte splat of 0xABABABAB.
8938   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
8939     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
8940                                   Op.getValueType(), DAG, dl);
8941 
8942   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
8943     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8944                                   dl);
8945 
8946   // We have XXSPLTIB for constant splats one byte wide.
8947   if (Subtarget.hasP9Vector() && SplatSize == 1)
8948     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
8949                                   dl);
8950 
8951   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8952   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8953                     (32-SplatBitSize));
8954   if (SextVal >= -16 && SextVal <= 15)
8955     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
8956                                   dl);
8957 
8958   // Two instruction sequences.
8959 
8960   // If this value is in the range [-32,30] and is even, use:
8961   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8962   // If this value is in the range [17,31] and is odd, use:
8963   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8964   // If this value is in the range [-31,-17] and is odd, use:
8965   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8966   // Note the last two are three-instruction sequences.
8967   if (SextVal >= -32 && SextVal <= 31) {
8968     // To avoid having these optimizations undone by constant folding,
8969     // we convert to a pseudo that will be expanded later into one of
8970     // the above forms.
8971     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8972     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8973               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8974     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8975     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8976     if (VT == Op.getValueType())
8977       return RetVal;
8978     else
8979       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8980   }
8981 
8982   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8983   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8984   // for fneg/fabs.
8985   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8986     // Make -1 and vspltisw -1:
8987     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
8988 
8989     // Make the VSLW intrinsic, computing 0x8000_0000.
8990     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8991                                    OnesV, DAG, dl);
8992 
8993     // xor by OnesV to invert it.
8994     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8995     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8996   }
8997 
8998   // Check to see if this is a wide variety of vsplti*, binop self cases.
8999   static const signed char SplatCsts[] = {
9000     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9001     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9002   };
9003 
9004   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9005     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9006     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9007     int i = SplatCsts[idx];
9008 
9009     // Figure out what shift amount will be used by altivec if shifted by i in
9010     // this splat size.
9011     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9012 
9013     // vsplti + shl self.
9014     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9015       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9016       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9017         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9018         Intrinsic::ppc_altivec_vslw
9019       };
9020       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9021       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9022     }
9023 
9024     // vsplti + srl self.
9025     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9026       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9027       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9028         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9029         Intrinsic::ppc_altivec_vsrw
9030       };
9031       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9032       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9033     }
9034 
9035     // vsplti + sra self.
9036     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9037       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9038       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9039         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9040         Intrinsic::ppc_altivec_vsraw
9041       };
9042       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9043       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9044     }
9045 
9046     // vsplti + rol self.
9047     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9048                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9049       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9050       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9051         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9052         Intrinsic::ppc_altivec_vrlw
9053       };
9054       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9055       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9056     }
9057 
9058     // t = vsplti c, result = vsldoi t, t, 1
9059     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9060       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9061       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9062       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9063     }
9064     // t = vsplti c, result = vsldoi t, t, 2
9065     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9066       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9067       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9068       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9069     }
9070     // t = vsplti c, result = vsldoi t, t, 3
9071     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9072       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9073       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9074       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9075     }
9076   }
9077 
9078   return SDValue();
9079 }
9080 
9081 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9082 /// the specified operations to build the shuffle.
9083 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9084                                       SDValue RHS, SelectionDAG &DAG,
9085                                       const SDLoc &dl) {
9086   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9087   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9088   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9089 
9090   enum {
9091     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9092     OP_VMRGHW,
9093     OP_VMRGLW,
9094     OP_VSPLTISW0,
9095     OP_VSPLTISW1,
9096     OP_VSPLTISW2,
9097     OP_VSPLTISW3,
9098     OP_VSLDOI4,
9099     OP_VSLDOI8,
9100     OP_VSLDOI12
9101   };
9102 
9103   if (OpNum == OP_COPY) {
9104     if (LHSID == (1*9+2)*9+3) return LHS;
9105     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9106     return RHS;
9107   }
9108 
9109   SDValue OpLHS, OpRHS;
9110   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9111   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9112 
9113   int ShufIdxs[16];
9114   switch (OpNum) {
9115   default: llvm_unreachable("Unknown i32 permute!");
9116   case OP_VMRGHW:
9117     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9118     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9119     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9120     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9121     break;
9122   case OP_VMRGLW:
9123     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9124     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9125     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9126     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9127     break;
9128   case OP_VSPLTISW0:
9129     for (unsigned i = 0; i != 16; ++i)
9130       ShufIdxs[i] = (i&3)+0;
9131     break;
9132   case OP_VSPLTISW1:
9133     for (unsigned i = 0; i != 16; ++i)
9134       ShufIdxs[i] = (i&3)+4;
9135     break;
9136   case OP_VSPLTISW2:
9137     for (unsigned i = 0; i != 16; ++i)
9138       ShufIdxs[i] = (i&3)+8;
9139     break;
9140   case OP_VSPLTISW3:
9141     for (unsigned i = 0; i != 16; ++i)
9142       ShufIdxs[i] = (i&3)+12;
9143     break;
9144   case OP_VSLDOI4:
9145     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9146   case OP_VSLDOI8:
9147     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9148   case OP_VSLDOI12:
9149     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9150   }
9151   EVT VT = OpLHS.getValueType();
9152   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9153   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9154   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9155   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9156 }
9157 
9158 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9159 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9160 /// SDValue.
9161 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9162                                            SelectionDAG &DAG) const {
9163   const unsigned BytesInVector = 16;
9164   bool IsLE = Subtarget.isLittleEndian();
9165   SDLoc dl(N);
9166   SDValue V1 = N->getOperand(0);
9167   SDValue V2 = N->getOperand(1);
9168   unsigned ShiftElts = 0, InsertAtByte = 0;
9169   bool Swap = false;
9170 
9171   // Shifts required to get the byte we want at element 7.
9172   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9173                                    0, 15, 14, 13, 12, 11, 10, 9};
9174   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9175                                 1, 2,  3,  4,  5,  6,  7,  8};
9176 
9177   ArrayRef<int> Mask = N->getMask();
9178   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9179 
9180   // For each mask element, find out if we're just inserting something
9181   // from V2 into V1 or vice versa.
9182   // Possible permutations inserting an element from V2 into V1:
9183   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9184   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9185   //   ...
9186   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9187   // Inserting from V1 into V2 will be similar, except mask range will be
9188   // [16,31].
9189 
9190   bool FoundCandidate = false;
9191   // If both vector operands for the shuffle are the same vector, the mask
9192   // will contain only elements from the first one and the second one will be
9193   // undef.
9194   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9195   // Go through the mask of half-words to find an element that's being moved
9196   // from one vector to the other.
9197   for (unsigned i = 0; i < BytesInVector; ++i) {
9198     unsigned CurrentElement = Mask[i];
9199     // If 2nd operand is undefined, we should only look for element 7 in the
9200     // Mask.
9201     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9202       continue;
9203 
9204     bool OtherElementsInOrder = true;
9205     // Examine the other elements in the Mask to see if they're in original
9206     // order.
9207     for (unsigned j = 0; j < BytesInVector; ++j) {
9208       if (j == i)
9209         continue;
9210       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9211       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9212       // in which we always assume we're always picking from the 1st operand.
9213       int MaskOffset =
9214           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9215       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9216         OtherElementsInOrder = false;
9217         break;
9218       }
9219     }
9220     // If other elements are in original order, we record the number of shifts
9221     // we need to get the element we want into element 7. Also record which byte
9222     // in the vector we should insert into.
9223     if (OtherElementsInOrder) {
9224       // If 2nd operand is undefined, we assume no shifts and no swapping.
9225       if (V2.isUndef()) {
9226         ShiftElts = 0;
9227         Swap = false;
9228       } else {
9229         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9230         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9231                          : BigEndianShifts[CurrentElement & 0xF];
9232         Swap = CurrentElement < BytesInVector;
9233       }
9234       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9235       FoundCandidate = true;
9236       break;
9237     }
9238   }
9239 
9240   if (!FoundCandidate)
9241     return SDValue();
9242 
9243   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9244   // optionally with VECSHL if shift is required.
9245   if (Swap)
9246     std::swap(V1, V2);
9247   if (V2.isUndef())
9248     V2 = V1;
9249   if (ShiftElts) {
9250     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9251                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9252     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9253                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9254   }
9255   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9256                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9257 }
9258 
9259 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9260 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9261 /// SDValue.
9262 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9263                                            SelectionDAG &DAG) const {
9264   const unsigned NumHalfWords = 8;
9265   const unsigned BytesInVector = NumHalfWords * 2;
9266   // Check that the shuffle is on half-words.
9267   if (!isNByteElemShuffleMask(N, 2, 1))
9268     return SDValue();
9269 
9270   bool IsLE = Subtarget.isLittleEndian();
9271   SDLoc dl(N);
9272   SDValue V1 = N->getOperand(0);
9273   SDValue V2 = N->getOperand(1);
9274   unsigned ShiftElts = 0, InsertAtByte = 0;
9275   bool Swap = false;
9276 
9277   // Shifts required to get the half-word we want at element 3.
9278   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9279   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9280 
9281   uint32_t Mask = 0;
9282   uint32_t OriginalOrderLow = 0x1234567;
9283   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9284   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9285   // 32-bit space, only need 4-bit nibbles per element.
9286   for (unsigned i = 0; i < NumHalfWords; ++i) {
9287     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9288     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9289   }
9290 
9291   // For each mask element, find out if we're just inserting something
9292   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9293   // from V2 into V1:
9294   //   X, 1, 2, 3, 4, 5, 6, 7
9295   //   0, X, 2, 3, 4, 5, 6, 7
9296   //   0, 1, X, 3, 4, 5, 6, 7
9297   //   0, 1, 2, X, 4, 5, 6, 7
9298   //   0, 1, 2, 3, X, 5, 6, 7
9299   //   0, 1, 2, 3, 4, X, 6, 7
9300   //   0, 1, 2, 3, 4, 5, X, 7
9301   //   0, 1, 2, 3, 4, 5, 6, X
9302   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9303 
9304   bool FoundCandidate = false;
9305   // Go through the mask of half-words to find an element that's being moved
9306   // from one vector to the other.
9307   for (unsigned i = 0; i < NumHalfWords; ++i) {
9308     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9309     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9310     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9311     uint32_t TargetOrder = 0x0;
9312 
9313     // If both vector operands for the shuffle are the same vector, the mask
9314     // will contain only elements from the first one and the second one will be
9315     // undef.
9316     if (V2.isUndef()) {
9317       ShiftElts = 0;
9318       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9319       TargetOrder = OriginalOrderLow;
9320       Swap = false;
9321       // Skip if not the correct element or mask of other elements don't equal
9322       // to our expected order.
9323       if (MaskOneElt == VINSERTHSrcElem &&
9324           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9325         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9326         FoundCandidate = true;
9327         break;
9328       }
9329     } else { // If both operands are defined.
9330       // Target order is [8,15] if the current mask is between [0,7].
9331       TargetOrder =
9332           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9333       // Skip if mask of other elements don't equal our expected order.
9334       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9335         // We only need the last 3 bits for the number of shifts.
9336         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9337                          : BigEndianShifts[MaskOneElt & 0x7];
9338         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9339         Swap = MaskOneElt < NumHalfWords;
9340         FoundCandidate = true;
9341         break;
9342       }
9343     }
9344   }
9345 
9346   if (!FoundCandidate)
9347     return SDValue();
9348 
9349   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9350   // optionally with VECSHL if shift is required.
9351   if (Swap)
9352     std::swap(V1, V2);
9353   if (V2.isUndef())
9354     V2 = V1;
9355   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9356   if (ShiftElts) {
9357     // Double ShiftElts because we're left shifting on v16i8 type.
9358     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9359                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9360     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9361     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9362                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9363     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9364   }
9365   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9366   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9367                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9368   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9369 }
9370 
9371 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9372 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9373 /// return the default SDValue.
9374 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9375                                               SelectionDAG &DAG) const {
9376   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9377   // to v16i8. Peek through the bitcasts to get the actual operands.
9378   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9379   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9380 
9381   auto ShuffleMask = SVN->getMask();
9382   SDValue VecShuffle(SVN, 0);
9383   SDLoc DL(SVN);
9384 
9385   // Check that we have a four byte shuffle.
9386   if (!isNByteElemShuffleMask(SVN, 4, 1))
9387     return SDValue();
9388 
9389   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9390   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9391     std::swap(LHS, RHS);
9392     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9393     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9394   }
9395 
9396   // Ensure that the RHS is a vector of constants.
9397   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9398   if (!BVN)
9399     return SDValue();
9400 
9401   // Check if RHS is a splat of 4-bytes (or smaller).
9402   APInt APSplatValue, APSplatUndef;
9403   unsigned SplatBitSize;
9404   bool HasAnyUndefs;
9405   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9406                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9407       SplatBitSize > 32)
9408     return SDValue();
9409 
9410   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9411   // The instruction splats a constant C into two words of the source vector
9412   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9413   // Thus we check that the shuffle mask is the equivalent  of
9414   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9415   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9416   // within each word are consecutive, so we only need to check the first byte.
9417   SDValue Index;
9418   bool IsLE = Subtarget.isLittleEndian();
9419   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9420       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9421        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9422     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9423   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9424            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9425             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9426     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9427   else
9428     return SDValue();
9429 
9430   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9431   // for XXSPLTI32DX.
9432   unsigned SplatVal = APSplatValue.getZExtValue();
9433   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9434     SplatVal |= (SplatVal << SplatBitSize);
9435 
9436   SDValue SplatNode = DAG.getNode(
9437       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9438       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9439   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9440 }
9441 
9442 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9443 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9444 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9445 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9446 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9447   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9448   assert(Op.getValueType() == MVT::v1i128 &&
9449          "Only set v1i128 as custom, other type shouldn't reach here!");
9450   SDLoc dl(Op);
9451   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9452   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9453   unsigned SHLAmt = N1.getConstantOperandVal(0);
9454   if (SHLAmt % 8 == 0) {
9455     SmallVector<int, 16> Mask(16, 0);
9456     std::iota(Mask.begin(), Mask.end(), 0);
9457     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9458     if (SDValue Shuffle =
9459             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9460                                  DAG.getUNDEF(MVT::v16i8), Mask))
9461       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9462   }
9463   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9464   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9465                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9466   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9467                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9468   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9469   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9470 }
9471 
9472 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9473 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9474 /// return the code it can be lowered into.  Worst case, it can always be
9475 /// lowered into a vperm.
9476 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9477                                                SelectionDAG &DAG) const {
9478   SDLoc dl(Op);
9479   SDValue V1 = Op.getOperand(0);
9480   SDValue V2 = Op.getOperand(1);
9481   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9482 
9483   // Any nodes that were combined in the target-independent combiner prior
9484   // to vector legalization will not be sent to the target combine. Try to
9485   // combine it here.
9486   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9487     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9488       return NewShuffle;
9489     Op = NewShuffle;
9490     SVOp = cast<ShuffleVectorSDNode>(Op);
9491     V1 = Op.getOperand(0);
9492     V2 = Op.getOperand(1);
9493   }
9494   EVT VT = Op.getValueType();
9495   bool isLittleEndian = Subtarget.isLittleEndian();
9496 
9497   unsigned ShiftElts, InsertAtByte;
9498   bool Swap = false;
9499 
9500   // If this is a load-and-splat, we can do that with a single instruction
9501   // in some cases. However if the load has multiple uses, we don't want to
9502   // combine it because that will just produce multiple loads.
9503   bool IsPermutedLoad = false;
9504   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9505   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9506       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9507       InputLoad->hasOneUse()) {
9508     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9509     int SplatIdx =
9510       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9511 
9512     // The splat index for permuted loads will be in the left half of the vector
9513     // which is strictly wider than the loaded value by 8 bytes. So we need to
9514     // adjust the splat index to point to the correct address in memory.
9515     if (IsPermutedLoad) {
9516       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9517       SplatIdx += IsFourByte ? 2 : 1;
9518       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9519              "Splat of a value outside of the loaded memory");
9520     }
9521 
9522     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9523     // For 4-byte load-and-splat, we need Power9.
9524     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9525       uint64_t Offset = 0;
9526       if (IsFourByte)
9527         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9528       else
9529         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9530 
9531       SDValue BasePtr = LD->getBasePtr();
9532       if (Offset != 0)
9533         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9534                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9535       SDValue Ops[] = {
9536         LD->getChain(),    // Chain
9537         BasePtr,           // BasePtr
9538         DAG.getValueType(Op.getValueType()) // VT
9539       };
9540       SDVTList VTL =
9541         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9542       SDValue LdSplt =
9543         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9544                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9545       if (LdSplt.getValueType() != SVOp->getValueType(0))
9546         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9547       return LdSplt;
9548     }
9549   }
9550   if (Subtarget.hasP9Vector() &&
9551       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9552                            isLittleEndian)) {
9553     if (Swap)
9554       std::swap(V1, V2);
9555     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9556     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9557     if (ShiftElts) {
9558       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9559                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9560       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9561                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9562       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9563     }
9564     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9565                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9566     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9567   }
9568 
9569   if (Subtarget.hasPrefixInstrs()) {
9570     SDValue SplatInsertNode;
9571     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9572       return SplatInsertNode;
9573   }
9574 
9575   if (Subtarget.hasP9Altivec()) {
9576     SDValue NewISDNode;
9577     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9578       return NewISDNode;
9579 
9580     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9581       return NewISDNode;
9582   }
9583 
9584   if (Subtarget.hasVSX() &&
9585       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9586     if (Swap)
9587       std::swap(V1, V2);
9588     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9589     SDValue Conv2 =
9590         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9591 
9592     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9593                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9594     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9595   }
9596 
9597   if (Subtarget.hasVSX() &&
9598     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9599     if (Swap)
9600       std::swap(V1, V2);
9601     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9602     SDValue Conv2 =
9603         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9604 
9605     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9606                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9607     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9608   }
9609 
9610   if (Subtarget.hasP9Vector()) {
9611      if (PPC::isXXBRHShuffleMask(SVOp)) {
9612       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9613       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9614       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9615     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9616       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9617       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9618       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9619     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9620       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9621       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9622       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9623     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9624       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9625       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9626       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9627     }
9628   }
9629 
9630   if (Subtarget.hasVSX()) {
9631     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9632       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9633 
9634       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9635       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9636                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9637       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9638     }
9639 
9640     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9641     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9642       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9643       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9644       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9645     }
9646   }
9647 
9648   // Cases that are handled by instructions that take permute immediates
9649   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9650   // selected by the instruction selector.
9651   if (V2.isUndef()) {
9652     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9653         PPC::isSplatShuffleMask(SVOp, 2) ||
9654         PPC::isSplatShuffleMask(SVOp, 4) ||
9655         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9656         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9657         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9658         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9659         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9660         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9661         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9662         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9663         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9664         (Subtarget.hasP8Altivec() && (
9665          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9666          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9667          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9668       return Op;
9669     }
9670   }
9671 
9672   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9673   // and produce a fixed permutation.  If any of these match, do not lower to
9674   // VPERM.
9675   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9676   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9677       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9678       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9679       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9680       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9681       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9682       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9683       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9684       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9685       (Subtarget.hasP8Altivec() && (
9686        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9687        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9688        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9689     return Op;
9690 
9691   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9692   // perfect shuffle table to emit an optimal matching sequence.
9693   ArrayRef<int> PermMask = SVOp->getMask();
9694 
9695   unsigned PFIndexes[4];
9696   bool isFourElementShuffle = true;
9697   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9698     unsigned EltNo = 8;   // Start out undef.
9699     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9700       if (PermMask[i*4+j] < 0)
9701         continue;   // Undef, ignore it.
9702 
9703       unsigned ByteSource = PermMask[i*4+j];
9704       if ((ByteSource & 3) != j) {
9705         isFourElementShuffle = false;
9706         break;
9707       }
9708 
9709       if (EltNo == 8) {
9710         EltNo = ByteSource/4;
9711       } else if (EltNo != ByteSource/4) {
9712         isFourElementShuffle = false;
9713         break;
9714       }
9715     }
9716     PFIndexes[i] = EltNo;
9717   }
9718 
9719   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9720   // perfect shuffle vector to determine if it is cost effective to do this as
9721   // discrete instructions, or whether we should use a vperm.
9722   // For now, we skip this for little endian until such time as we have a
9723   // little-endian perfect shuffle table.
9724   if (isFourElementShuffle && !isLittleEndian) {
9725     // Compute the index in the perfect shuffle table.
9726     unsigned PFTableIndex =
9727       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9728 
9729     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9730     unsigned Cost  = (PFEntry >> 30);
9731 
9732     // Determining when to avoid vperm is tricky.  Many things affect the cost
9733     // of vperm, particularly how many times the perm mask needs to be computed.
9734     // For example, if the perm mask can be hoisted out of a loop or is already
9735     // used (perhaps because there are multiple permutes with the same shuffle
9736     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9737     // the loop requires an extra register.
9738     //
9739     // As a compromise, we only emit discrete instructions if the shuffle can be
9740     // generated in 3 or fewer operations.  When we have loop information
9741     // available, if this block is within a loop, we should avoid using vperm
9742     // for 3-operation perms and use a constant pool load instead.
9743     if (Cost < 3)
9744       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9745   }
9746 
9747   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9748   // vector that will get spilled to the constant pool.
9749   if (V2.isUndef()) V2 = V1;
9750 
9751   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9752   // that it is in input element units, not in bytes.  Convert now.
9753 
9754   // For little endian, the order of the input vectors is reversed, and
9755   // the permutation mask is complemented with respect to 31.  This is
9756   // necessary to produce proper semantics with the big-endian-biased vperm
9757   // instruction.
9758   EVT EltVT = V1.getValueType().getVectorElementType();
9759   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9760 
9761   SmallVector<SDValue, 16> ResultMask;
9762   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9763     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9764 
9765     for (unsigned j = 0; j != BytesPerElement; ++j)
9766       if (isLittleEndian)
9767         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9768                                              dl, MVT::i32));
9769       else
9770         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9771                                              MVT::i32));
9772   }
9773 
9774   ShufflesHandledWithVPERM++;
9775   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9776   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9777   LLVM_DEBUG(SVOp->dump());
9778   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9779   LLVM_DEBUG(VPermMask.dump());
9780 
9781   if (isLittleEndian)
9782     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9783                        V2, V1, VPermMask);
9784   else
9785     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9786                        V1, V2, VPermMask);
9787 }
9788 
9789 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9790 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9791 /// information about the intrinsic.
9792 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9793                                  bool &isDot, const PPCSubtarget &Subtarget) {
9794   unsigned IntrinsicID =
9795       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9796   CompareOpc = -1;
9797   isDot = false;
9798   switch (IntrinsicID) {
9799   default:
9800     return false;
9801   // Comparison predicates.
9802   case Intrinsic::ppc_altivec_vcmpbfp_p:
9803     CompareOpc = 966;
9804     isDot = true;
9805     break;
9806   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9807     CompareOpc = 198;
9808     isDot = true;
9809     break;
9810   case Intrinsic::ppc_altivec_vcmpequb_p:
9811     CompareOpc = 6;
9812     isDot = true;
9813     break;
9814   case Intrinsic::ppc_altivec_vcmpequh_p:
9815     CompareOpc = 70;
9816     isDot = true;
9817     break;
9818   case Intrinsic::ppc_altivec_vcmpequw_p:
9819     CompareOpc = 134;
9820     isDot = true;
9821     break;
9822   case Intrinsic::ppc_altivec_vcmpequd_p:
9823     if (Subtarget.hasP8Altivec()) {
9824       CompareOpc = 199;
9825       isDot = true;
9826     } else
9827       return false;
9828     break;
9829   case Intrinsic::ppc_altivec_vcmpneb_p:
9830   case Intrinsic::ppc_altivec_vcmpneh_p:
9831   case Intrinsic::ppc_altivec_vcmpnew_p:
9832   case Intrinsic::ppc_altivec_vcmpnezb_p:
9833   case Intrinsic::ppc_altivec_vcmpnezh_p:
9834   case Intrinsic::ppc_altivec_vcmpnezw_p:
9835     if (Subtarget.hasP9Altivec()) {
9836       switch (IntrinsicID) {
9837       default:
9838         llvm_unreachable("Unknown comparison intrinsic.");
9839       case Intrinsic::ppc_altivec_vcmpneb_p:
9840         CompareOpc = 7;
9841         break;
9842       case Intrinsic::ppc_altivec_vcmpneh_p:
9843         CompareOpc = 71;
9844         break;
9845       case Intrinsic::ppc_altivec_vcmpnew_p:
9846         CompareOpc = 135;
9847         break;
9848       case Intrinsic::ppc_altivec_vcmpnezb_p:
9849         CompareOpc = 263;
9850         break;
9851       case Intrinsic::ppc_altivec_vcmpnezh_p:
9852         CompareOpc = 327;
9853         break;
9854       case Intrinsic::ppc_altivec_vcmpnezw_p:
9855         CompareOpc = 391;
9856         break;
9857       }
9858       isDot = true;
9859     } else
9860       return false;
9861     break;
9862   case Intrinsic::ppc_altivec_vcmpgefp_p:
9863     CompareOpc = 454;
9864     isDot = true;
9865     break;
9866   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9867     CompareOpc = 710;
9868     isDot = true;
9869     break;
9870   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9871     CompareOpc = 774;
9872     isDot = true;
9873     break;
9874   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9875     CompareOpc = 838;
9876     isDot = true;
9877     break;
9878   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9879     CompareOpc = 902;
9880     isDot = true;
9881     break;
9882   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9883     if (Subtarget.hasP8Altivec()) {
9884       CompareOpc = 967;
9885       isDot = true;
9886     } else
9887       return false;
9888     break;
9889   case Intrinsic::ppc_altivec_vcmpgtub_p:
9890     CompareOpc = 518;
9891     isDot = true;
9892     break;
9893   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9894     CompareOpc = 582;
9895     isDot = true;
9896     break;
9897   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9898     CompareOpc = 646;
9899     isDot = true;
9900     break;
9901   case Intrinsic::ppc_altivec_vcmpgtud_p:
9902     if (Subtarget.hasP8Altivec()) {
9903       CompareOpc = 711;
9904       isDot = true;
9905     } else
9906       return false;
9907     break;
9908 
9909   // VSX predicate comparisons use the same infrastructure
9910   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9911   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9912   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9913   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9914   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9915   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9916     if (Subtarget.hasVSX()) {
9917       switch (IntrinsicID) {
9918       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9919         CompareOpc = 99;
9920         break;
9921       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9922         CompareOpc = 115;
9923         break;
9924       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9925         CompareOpc = 107;
9926         break;
9927       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9928         CompareOpc = 67;
9929         break;
9930       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9931         CompareOpc = 83;
9932         break;
9933       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9934         CompareOpc = 75;
9935         break;
9936       }
9937       isDot = true;
9938     } else
9939       return false;
9940     break;
9941 
9942   // Normal Comparisons.
9943   case Intrinsic::ppc_altivec_vcmpbfp:
9944     CompareOpc = 966;
9945     break;
9946   case Intrinsic::ppc_altivec_vcmpeqfp:
9947     CompareOpc = 198;
9948     break;
9949   case Intrinsic::ppc_altivec_vcmpequb:
9950     CompareOpc = 6;
9951     break;
9952   case Intrinsic::ppc_altivec_vcmpequh:
9953     CompareOpc = 70;
9954     break;
9955   case Intrinsic::ppc_altivec_vcmpequw:
9956     CompareOpc = 134;
9957     break;
9958   case Intrinsic::ppc_altivec_vcmpequd:
9959     if (Subtarget.hasP8Altivec())
9960       CompareOpc = 199;
9961     else
9962       return false;
9963     break;
9964   case Intrinsic::ppc_altivec_vcmpneb:
9965   case Intrinsic::ppc_altivec_vcmpneh:
9966   case Intrinsic::ppc_altivec_vcmpnew:
9967   case Intrinsic::ppc_altivec_vcmpnezb:
9968   case Intrinsic::ppc_altivec_vcmpnezh:
9969   case Intrinsic::ppc_altivec_vcmpnezw:
9970     if (Subtarget.hasP9Altivec())
9971       switch (IntrinsicID) {
9972       default:
9973         llvm_unreachable("Unknown comparison intrinsic.");
9974       case Intrinsic::ppc_altivec_vcmpneb:
9975         CompareOpc = 7;
9976         break;
9977       case Intrinsic::ppc_altivec_vcmpneh:
9978         CompareOpc = 71;
9979         break;
9980       case Intrinsic::ppc_altivec_vcmpnew:
9981         CompareOpc = 135;
9982         break;
9983       case Intrinsic::ppc_altivec_vcmpnezb:
9984         CompareOpc = 263;
9985         break;
9986       case Intrinsic::ppc_altivec_vcmpnezh:
9987         CompareOpc = 327;
9988         break;
9989       case Intrinsic::ppc_altivec_vcmpnezw:
9990         CompareOpc = 391;
9991         break;
9992       }
9993     else
9994       return false;
9995     break;
9996   case Intrinsic::ppc_altivec_vcmpgefp:
9997     CompareOpc = 454;
9998     break;
9999   case Intrinsic::ppc_altivec_vcmpgtfp:
10000     CompareOpc = 710;
10001     break;
10002   case Intrinsic::ppc_altivec_vcmpgtsb:
10003     CompareOpc = 774;
10004     break;
10005   case Intrinsic::ppc_altivec_vcmpgtsh:
10006     CompareOpc = 838;
10007     break;
10008   case Intrinsic::ppc_altivec_vcmpgtsw:
10009     CompareOpc = 902;
10010     break;
10011   case Intrinsic::ppc_altivec_vcmpgtsd:
10012     if (Subtarget.hasP8Altivec())
10013       CompareOpc = 967;
10014     else
10015       return false;
10016     break;
10017   case Intrinsic::ppc_altivec_vcmpgtub:
10018     CompareOpc = 518;
10019     break;
10020   case Intrinsic::ppc_altivec_vcmpgtuh:
10021     CompareOpc = 582;
10022     break;
10023   case Intrinsic::ppc_altivec_vcmpgtuw:
10024     CompareOpc = 646;
10025     break;
10026   case Intrinsic::ppc_altivec_vcmpgtud:
10027     if (Subtarget.hasP8Altivec())
10028       CompareOpc = 711;
10029     else
10030       return false;
10031     break;
10032   }
10033   return true;
10034 }
10035 
10036 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10037 /// lower, do it, otherwise return null.
10038 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10039                                                    SelectionDAG &DAG) const {
10040   unsigned IntrinsicID =
10041     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10042 
10043   SDLoc dl(Op);
10044 
10045   if (IntrinsicID == Intrinsic::thread_pointer) {
10046     // Reads the thread pointer register, used for __builtin_thread_pointer.
10047     if (Subtarget.isPPC64())
10048       return DAG.getRegister(PPC::X13, MVT::i64);
10049     return DAG.getRegister(PPC::R2, MVT::i32);
10050   }
10051 
10052   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10053   // opcode number of the comparison.
10054   int CompareOpc;
10055   bool isDot;
10056   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10057     return SDValue();    // Don't custom lower most intrinsics.
10058 
10059   // If this is a non-dot comparison, make the VCMP node and we are done.
10060   if (!isDot) {
10061     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10062                               Op.getOperand(1), Op.getOperand(2),
10063                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10064     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10065   }
10066 
10067   // Create the PPCISD altivec 'dot' comparison node.
10068   SDValue Ops[] = {
10069     Op.getOperand(2),  // LHS
10070     Op.getOperand(3),  // RHS
10071     DAG.getConstant(CompareOpc, dl, MVT::i32)
10072   };
10073   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10074   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10075 
10076   // Now that we have the comparison, emit a copy from the CR to a GPR.
10077   // This is flagged to the above dot comparison.
10078   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10079                                 DAG.getRegister(PPC::CR6, MVT::i32),
10080                                 CompNode.getValue(1));
10081 
10082   // Unpack the result based on how the target uses it.
10083   unsigned BitNo;   // Bit # of CR6.
10084   bool InvertBit;   // Invert result?
10085   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10086   default:  // Can't happen, don't crash on invalid number though.
10087   case 0:   // Return the value of the EQ bit of CR6.
10088     BitNo = 0; InvertBit = false;
10089     break;
10090   case 1:   // Return the inverted value of the EQ bit of CR6.
10091     BitNo = 0; InvertBit = true;
10092     break;
10093   case 2:   // Return the value of the LT bit of CR6.
10094     BitNo = 2; InvertBit = false;
10095     break;
10096   case 3:   // Return the inverted value of the LT bit of CR6.
10097     BitNo = 2; InvertBit = true;
10098     break;
10099   }
10100 
10101   // Shift the bit into the low position.
10102   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10103                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10104   // Isolate the bit.
10105   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10106                       DAG.getConstant(1, dl, MVT::i32));
10107 
10108   // If we are supposed to, toggle the bit.
10109   if (InvertBit)
10110     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10111                         DAG.getConstant(1, dl, MVT::i32));
10112   return Flags;
10113 }
10114 
10115 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10116                                                SelectionDAG &DAG) const {
10117   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10118   // the beginning of the argument list.
10119   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10120   SDLoc DL(Op);
10121   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10122   case Intrinsic::ppc_cfence: {
10123     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10124     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10125     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10126                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10127                                                   Op.getOperand(ArgStart + 1)),
10128                                       Op.getOperand(0)),
10129                    0);
10130   }
10131   default:
10132     break;
10133   }
10134   return SDValue();
10135 }
10136 
10137 // Lower scalar BSWAP64 to xxbrd.
10138 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10139   SDLoc dl(Op);
10140   // MTVSRDD
10141   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10142                    Op.getOperand(0));
10143   // XXBRD
10144   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10145   // MFVSRD
10146   int VectorIndex = 0;
10147   if (Subtarget.isLittleEndian())
10148     VectorIndex = 1;
10149   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10150                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10151   return Op;
10152 }
10153 
10154 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10155 // compared to a value that is atomically loaded (atomic loads zero-extend).
10156 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10157                                                 SelectionDAG &DAG) const {
10158   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10159          "Expecting an atomic compare-and-swap here.");
10160   SDLoc dl(Op);
10161   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10162   EVT MemVT = AtomicNode->getMemoryVT();
10163   if (MemVT.getSizeInBits() >= 32)
10164     return Op;
10165 
10166   SDValue CmpOp = Op.getOperand(2);
10167   // If this is already correctly zero-extended, leave it alone.
10168   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10169   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10170     return Op;
10171 
10172   // Clear the high bits of the compare operand.
10173   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10174   SDValue NewCmpOp =
10175     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10176                 DAG.getConstant(MaskVal, dl, MVT::i32));
10177 
10178   // Replace the existing compare operand with the properly zero-extended one.
10179   SmallVector<SDValue, 4> Ops;
10180   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10181     Ops.push_back(AtomicNode->getOperand(i));
10182   Ops[2] = NewCmpOp;
10183   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10184   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10185   auto NodeTy =
10186     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10187   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10188 }
10189 
10190 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10191                                                  SelectionDAG &DAG) const {
10192   SDLoc dl(Op);
10193   // Create a stack slot that is 16-byte aligned.
10194   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10195   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10196   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10197   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10198 
10199   // Store the input value into Value#0 of the stack slot.
10200   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10201                                MachinePointerInfo());
10202   // Load it out.
10203   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10204 }
10205 
10206 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10207                                                   SelectionDAG &DAG) const {
10208   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10209          "Should only be called for ISD::INSERT_VECTOR_ELT");
10210 
10211   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10212   // We have legal lowering for constant indices but not for variable ones.
10213   if (!C)
10214     return SDValue();
10215 
10216   EVT VT = Op.getValueType();
10217   SDLoc dl(Op);
10218   SDValue V1 = Op.getOperand(0);
10219   SDValue V2 = Op.getOperand(1);
10220   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10221   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10222     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10223     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10224     unsigned InsertAtElement = C->getZExtValue();
10225     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10226     if (Subtarget.isLittleEndian()) {
10227       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10228     }
10229     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10230                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10231   }
10232   return Op;
10233 }
10234 
10235 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10236   SDLoc dl(Op);
10237   if (Op.getValueType() == MVT::v4i32) {
10238     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10239 
10240     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10241     // +16 as shift amt.
10242     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10243     SDValue RHSSwap =   // = vrlw RHS, 16
10244       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10245 
10246     // Shrinkify inputs to v8i16.
10247     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10248     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10249     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10250 
10251     // Low parts multiplied together, generating 32-bit results (we ignore the
10252     // top parts).
10253     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10254                                         LHS, RHS, DAG, dl, MVT::v4i32);
10255 
10256     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10257                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10258     // Shift the high parts up 16 bits.
10259     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10260                               Neg16, DAG, dl);
10261     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10262   } else if (Op.getValueType() == MVT::v16i8) {
10263     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10264     bool isLittleEndian = Subtarget.isLittleEndian();
10265 
10266     // Multiply the even 8-bit parts, producing 16-bit sums.
10267     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10268                                            LHS, RHS, DAG, dl, MVT::v8i16);
10269     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10270 
10271     // Multiply the odd 8-bit parts, producing 16-bit sums.
10272     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10273                                           LHS, RHS, DAG, dl, MVT::v8i16);
10274     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10275 
10276     // Merge the results together.  Because vmuleub and vmuloub are
10277     // instructions with a big-endian bias, we must reverse the
10278     // element numbering and reverse the meaning of "odd" and "even"
10279     // when generating little endian code.
10280     int Ops[16];
10281     for (unsigned i = 0; i != 8; ++i) {
10282       if (isLittleEndian) {
10283         Ops[i*2  ] = 2*i;
10284         Ops[i*2+1] = 2*i+16;
10285       } else {
10286         Ops[i*2  ] = 2*i+1;
10287         Ops[i*2+1] = 2*i+1+16;
10288       }
10289     }
10290     if (isLittleEndian)
10291       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10292     else
10293       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10294   } else {
10295     llvm_unreachable("Unknown mul to lower!");
10296   }
10297 }
10298 
10299 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10300 
10301   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10302 
10303   EVT VT = Op.getValueType();
10304   assert(VT.isVector() &&
10305          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10306   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10307           VT == MVT::v16i8) &&
10308          "Unexpected vector element type!");
10309   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10310          "Current subtarget doesn't support smax v2i64!");
10311 
10312   // For vector abs, it can be lowered to:
10313   // abs x
10314   // ==>
10315   // y = -x
10316   // smax(x, y)
10317 
10318   SDLoc dl(Op);
10319   SDValue X = Op.getOperand(0);
10320   SDValue Zero = DAG.getConstant(0, dl, VT);
10321   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10322 
10323   // SMAX patch https://reviews.llvm.org/D47332
10324   // hasn't landed yet, so use intrinsic first here.
10325   // TODO: Should use SMAX directly once SMAX patch landed
10326   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10327   if (VT == MVT::v2i64)
10328     BifID = Intrinsic::ppc_altivec_vmaxsd;
10329   else if (VT == MVT::v8i16)
10330     BifID = Intrinsic::ppc_altivec_vmaxsh;
10331   else if (VT == MVT::v16i8)
10332     BifID = Intrinsic::ppc_altivec_vmaxsb;
10333 
10334   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10335 }
10336 
10337 // Custom lowering for fpext vf32 to v2f64
10338 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10339 
10340   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10341          "Should only be called for ISD::FP_EXTEND");
10342 
10343   // FIXME: handle extends from half precision float vectors on P9.
10344   // We only want to custom lower an extend from v2f32 to v2f64.
10345   if (Op.getValueType() != MVT::v2f64 ||
10346       Op.getOperand(0).getValueType() != MVT::v2f32)
10347     return SDValue();
10348 
10349   SDLoc dl(Op);
10350   SDValue Op0 = Op.getOperand(0);
10351 
10352   switch (Op0.getOpcode()) {
10353   default:
10354     return SDValue();
10355   case ISD::EXTRACT_SUBVECTOR: {
10356     assert(Op0.getNumOperands() == 2 &&
10357            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10358            "Node should have 2 operands with second one being a constant!");
10359 
10360     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10361       return SDValue();
10362 
10363     // Custom lower is only done for high or low doubleword.
10364     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10365     if (Idx % 2 != 0)
10366       return SDValue();
10367 
10368     // Since input is v4f32, at this point Idx is either 0 or 2.
10369     // Shift to get the doubleword position we want.
10370     int DWord = Idx >> 1;
10371 
10372     // High and low word positions are different on little endian.
10373     if (Subtarget.isLittleEndian())
10374       DWord ^= 0x1;
10375 
10376     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10377                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10378   }
10379   case ISD::FADD:
10380   case ISD::FMUL:
10381   case ISD::FSUB: {
10382     SDValue NewLoad[2];
10383     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10384       // Ensure both input are loads.
10385       SDValue LdOp = Op0.getOperand(i);
10386       if (LdOp.getOpcode() != ISD::LOAD)
10387         return SDValue();
10388       // Generate new load node.
10389       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10390       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10391       NewLoad[i] = DAG.getMemIntrinsicNode(
10392           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10393           LD->getMemoryVT(), LD->getMemOperand());
10394     }
10395     SDValue NewOp =
10396         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10397                     NewLoad[1], Op0.getNode()->getFlags());
10398     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10399                        DAG.getConstant(0, dl, MVT::i32));
10400   }
10401   case ISD::LOAD: {
10402     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10403     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10404     SDValue NewLd = DAG.getMemIntrinsicNode(
10405         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10406         LD->getMemoryVT(), LD->getMemOperand());
10407     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10408                        DAG.getConstant(0, dl, MVT::i32));
10409   }
10410   }
10411   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10412 }
10413 
10414 /// LowerOperation - Provide custom lowering hooks for some operations.
10415 ///
10416 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10417   switch (Op.getOpcode()) {
10418   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10419   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10420   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10421   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10422   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10423   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10424   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10425   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10426   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10427 
10428   // Variable argument lowering.
10429   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10430   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10431   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10432 
10433   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10434   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10435   case ISD::GET_DYNAMIC_AREA_OFFSET:
10436     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10437 
10438   // Exception handling lowering.
10439   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10440   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10441   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10442 
10443   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10444   case ISD::STORE:              return LowerSTORE(Op, DAG);
10445   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10446   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10447   case ISD::FP_TO_UINT:
10448   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10449   case ISD::UINT_TO_FP:
10450   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10451   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10452 
10453   // Lower 64-bit shifts.
10454   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10455   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10456   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10457 
10458   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10459   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10460 
10461   // Vector-related lowering.
10462   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10463   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10464   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10465   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10466   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10467   case ISD::MUL:                return LowerMUL(Op, DAG);
10468   case ISD::ABS:                return LowerABS(Op, DAG);
10469   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10470   case ISD::ROTL:               return LowerROTL(Op, DAG);
10471 
10472   // For counter-based loop handling.
10473   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10474 
10475   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10476 
10477   // Frame & Return address.
10478   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10479   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10480 
10481   case ISD::INTRINSIC_VOID:
10482     return LowerINTRINSIC_VOID(Op, DAG);
10483   case ISD::BSWAP:
10484     return LowerBSWAP(Op, DAG);
10485   case ISD::ATOMIC_CMP_SWAP:
10486     return LowerATOMIC_CMP_SWAP(Op, DAG);
10487   }
10488 }
10489 
10490 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10491                                            SmallVectorImpl<SDValue>&Results,
10492                                            SelectionDAG &DAG) const {
10493   SDLoc dl(N);
10494   switch (N->getOpcode()) {
10495   default:
10496     llvm_unreachable("Do not know how to custom type legalize this operation!");
10497   case ISD::READCYCLECOUNTER: {
10498     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10499     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10500 
10501     Results.push_back(
10502         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10503     Results.push_back(RTB.getValue(2));
10504     break;
10505   }
10506   case ISD::INTRINSIC_W_CHAIN: {
10507     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10508         Intrinsic::loop_decrement)
10509       break;
10510 
10511     assert(N->getValueType(0) == MVT::i1 &&
10512            "Unexpected result type for CTR decrement intrinsic");
10513     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10514                                  N->getValueType(0));
10515     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10516     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10517                                  N->getOperand(1));
10518 
10519     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10520     Results.push_back(NewInt.getValue(1));
10521     break;
10522   }
10523   case ISD::VAARG: {
10524     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10525       return;
10526 
10527     EVT VT = N->getValueType(0);
10528 
10529     if (VT == MVT::i64) {
10530       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10531 
10532       Results.push_back(NewNode);
10533       Results.push_back(NewNode.getValue(1));
10534     }
10535     return;
10536   }
10537   case ISD::FP_TO_SINT:
10538   case ISD::FP_TO_UINT:
10539     // LowerFP_TO_INT() can only handle f32 and f64.
10540     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10541       return;
10542     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10543     return;
10544   case ISD::TRUNCATE: {
10545     EVT TrgVT = N->getValueType(0);
10546     EVT OpVT = N->getOperand(0).getValueType();
10547     if (TrgVT.isVector() &&
10548         isOperationCustom(N->getOpcode(), TrgVT) &&
10549         OpVT.getSizeInBits() <= 128 &&
10550         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10551       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10552     return;
10553   }
10554   case ISD::BITCAST:
10555     // Don't handle bitcast here.
10556     return;
10557   case ISD::FP_EXTEND:
10558     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10559     if (Lowered)
10560       Results.push_back(Lowered);
10561     return;
10562   }
10563 }
10564 
10565 //===----------------------------------------------------------------------===//
10566 //  Other Lowering Code
10567 //===----------------------------------------------------------------------===//
10568 
10569 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10570   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10571   Function *Func = Intrinsic::getDeclaration(M, Id);
10572   return Builder.CreateCall(Func, {});
10573 }
10574 
10575 // The mappings for emitLeading/TrailingFence is taken from
10576 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10577 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10578                                                  Instruction *Inst,
10579                                                  AtomicOrdering Ord) const {
10580   if (Ord == AtomicOrdering::SequentiallyConsistent)
10581     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10582   if (isReleaseOrStronger(Ord))
10583     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10584   return nullptr;
10585 }
10586 
10587 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10588                                                   Instruction *Inst,
10589                                                   AtomicOrdering Ord) const {
10590   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10591     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10592     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10593     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10594     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10595       return Builder.CreateCall(
10596           Intrinsic::getDeclaration(
10597               Builder.GetInsertBlock()->getParent()->getParent(),
10598               Intrinsic::ppc_cfence, {Inst->getType()}),
10599           {Inst});
10600     // FIXME: Can use isync for rmw operation.
10601     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10602   }
10603   return nullptr;
10604 }
10605 
10606 MachineBasicBlock *
10607 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10608                                     unsigned AtomicSize,
10609                                     unsigned BinOpcode,
10610                                     unsigned CmpOpcode,
10611                                     unsigned CmpPred) const {
10612   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10613   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10614 
10615   auto LoadMnemonic = PPC::LDARX;
10616   auto StoreMnemonic = PPC::STDCX;
10617   switch (AtomicSize) {
10618   default:
10619     llvm_unreachable("Unexpected size of atomic entity");
10620   case 1:
10621     LoadMnemonic = PPC::LBARX;
10622     StoreMnemonic = PPC::STBCX;
10623     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10624     break;
10625   case 2:
10626     LoadMnemonic = PPC::LHARX;
10627     StoreMnemonic = PPC::STHCX;
10628     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10629     break;
10630   case 4:
10631     LoadMnemonic = PPC::LWARX;
10632     StoreMnemonic = PPC::STWCX;
10633     break;
10634   case 8:
10635     LoadMnemonic = PPC::LDARX;
10636     StoreMnemonic = PPC::STDCX;
10637     break;
10638   }
10639 
10640   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10641   MachineFunction *F = BB->getParent();
10642   MachineFunction::iterator It = ++BB->getIterator();
10643 
10644   Register dest = MI.getOperand(0).getReg();
10645   Register ptrA = MI.getOperand(1).getReg();
10646   Register ptrB = MI.getOperand(2).getReg();
10647   Register incr = MI.getOperand(3).getReg();
10648   DebugLoc dl = MI.getDebugLoc();
10649 
10650   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10651   MachineBasicBlock *loop2MBB =
10652     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10653   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10654   F->insert(It, loopMBB);
10655   if (CmpOpcode)
10656     F->insert(It, loop2MBB);
10657   F->insert(It, exitMBB);
10658   exitMBB->splice(exitMBB->begin(), BB,
10659                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10660   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10661 
10662   MachineRegisterInfo &RegInfo = F->getRegInfo();
10663   Register TmpReg = (!BinOpcode) ? incr :
10664     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10665                                            : &PPC::GPRCRegClass);
10666 
10667   //  thisMBB:
10668   //   ...
10669   //   fallthrough --> loopMBB
10670   BB->addSuccessor(loopMBB);
10671 
10672   //  loopMBB:
10673   //   l[wd]arx dest, ptr
10674   //   add r0, dest, incr
10675   //   st[wd]cx. r0, ptr
10676   //   bne- loopMBB
10677   //   fallthrough --> exitMBB
10678 
10679   // For max/min...
10680   //  loopMBB:
10681   //   l[wd]arx dest, ptr
10682   //   cmpl?[wd] incr, dest
10683   //   bgt exitMBB
10684   //  loop2MBB:
10685   //   st[wd]cx. dest, ptr
10686   //   bne- loopMBB
10687   //   fallthrough --> exitMBB
10688 
10689   BB = loopMBB;
10690   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10691     .addReg(ptrA).addReg(ptrB);
10692   if (BinOpcode)
10693     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10694   if (CmpOpcode) {
10695     // Signed comparisons of byte or halfword values must be sign-extended.
10696     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10697       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10698       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10699               ExtReg).addReg(dest);
10700       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10701         .addReg(incr).addReg(ExtReg);
10702     } else
10703       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10704         .addReg(incr).addReg(dest);
10705 
10706     BuildMI(BB, dl, TII->get(PPC::BCC))
10707       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10708     BB->addSuccessor(loop2MBB);
10709     BB->addSuccessor(exitMBB);
10710     BB = loop2MBB;
10711   }
10712   BuildMI(BB, dl, TII->get(StoreMnemonic))
10713     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10714   BuildMI(BB, dl, TII->get(PPC::BCC))
10715     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10716   BB->addSuccessor(loopMBB);
10717   BB->addSuccessor(exitMBB);
10718 
10719   //  exitMBB:
10720   //   ...
10721   BB = exitMBB;
10722   return BB;
10723 }
10724 
10725 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10726     MachineInstr &MI, MachineBasicBlock *BB,
10727     bool is8bit, // operation
10728     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10729   // If we support part-word atomic mnemonics, just use them
10730   if (Subtarget.hasPartwordAtomics())
10731     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10732                             CmpPred);
10733 
10734   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10735   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10736   // In 64 bit mode we have to use 64 bits for addresses, even though the
10737   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10738   // registers without caring whether they're 32 or 64, but here we're
10739   // doing actual arithmetic on the addresses.
10740   bool is64bit = Subtarget.isPPC64();
10741   bool isLittleEndian = Subtarget.isLittleEndian();
10742   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10743 
10744   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10745   MachineFunction *F = BB->getParent();
10746   MachineFunction::iterator It = ++BB->getIterator();
10747 
10748   Register dest = MI.getOperand(0).getReg();
10749   Register ptrA = MI.getOperand(1).getReg();
10750   Register ptrB = MI.getOperand(2).getReg();
10751   Register incr = MI.getOperand(3).getReg();
10752   DebugLoc dl = MI.getDebugLoc();
10753 
10754   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10755   MachineBasicBlock *loop2MBB =
10756       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10757   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10758   F->insert(It, loopMBB);
10759   if (CmpOpcode)
10760     F->insert(It, loop2MBB);
10761   F->insert(It, exitMBB);
10762   exitMBB->splice(exitMBB->begin(), BB,
10763                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10764   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10765 
10766   MachineRegisterInfo &RegInfo = F->getRegInfo();
10767   const TargetRegisterClass *RC =
10768       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10769   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10770 
10771   Register PtrReg = RegInfo.createVirtualRegister(RC);
10772   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10773   Register ShiftReg =
10774       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10775   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10776   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10777   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10778   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10779   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10780   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10781   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10782   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10783   Register Ptr1Reg;
10784   Register TmpReg =
10785       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10786 
10787   //  thisMBB:
10788   //   ...
10789   //   fallthrough --> loopMBB
10790   BB->addSuccessor(loopMBB);
10791 
10792   // The 4-byte load must be aligned, while a char or short may be
10793   // anywhere in the word.  Hence all this nasty bookkeeping code.
10794   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10795   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10796   //   xori shift, shift1, 24 [16]
10797   //   rlwinm ptr, ptr1, 0, 0, 29
10798   //   slw incr2, incr, shift
10799   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10800   //   slw mask, mask2, shift
10801   //  loopMBB:
10802   //   lwarx tmpDest, ptr
10803   //   add tmp, tmpDest, incr2
10804   //   andc tmp2, tmpDest, mask
10805   //   and tmp3, tmp, mask
10806   //   or tmp4, tmp3, tmp2
10807   //   stwcx. tmp4, ptr
10808   //   bne- loopMBB
10809   //   fallthrough --> exitMBB
10810   //   srw dest, tmpDest, shift
10811   if (ptrA != ZeroReg) {
10812     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10813     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10814         .addReg(ptrA)
10815         .addReg(ptrB);
10816   } else {
10817     Ptr1Reg = ptrB;
10818   }
10819   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10820   // mode.
10821   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10822       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10823       .addImm(3)
10824       .addImm(27)
10825       .addImm(is8bit ? 28 : 27);
10826   if (!isLittleEndian)
10827     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10828         .addReg(Shift1Reg)
10829         .addImm(is8bit ? 24 : 16);
10830   if (is64bit)
10831     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10832         .addReg(Ptr1Reg)
10833         .addImm(0)
10834         .addImm(61);
10835   else
10836     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10837         .addReg(Ptr1Reg)
10838         .addImm(0)
10839         .addImm(0)
10840         .addImm(29);
10841   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10842   if (is8bit)
10843     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10844   else {
10845     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10846     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10847         .addReg(Mask3Reg)
10848         .addImm(65535);
10849   }
10850   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10851       .addReg(Mask2Reg)
10852       .addReg(ShiftReg);
10853 
10854   BB = loopMBB;
10855   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10856       .addReg(ZeroReg)
10857       .addReg(PtrReg);
10858   if (BinOpcode)
10859     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10860         .addReg(Incr2Reg)
10861         .addReg(TmpDestReg);
10862   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10863       .addReg(TmpDestReg)
10864       .addReg(MaskReg);
10865   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10866   if (CmpOpcode) {
10867     // For unsigned comparisons, we can directly compare the shifted values.
10868     // For signed comparisons we shift and sign extend.
10869     Register SReg = RegInfo.createVirtualRegister(GPRC);
10870     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10871         .addReg(TmpDestReg)
10872         .addReg(MaskReg);
10873     unsigned ValueReg = SReg;
10874     unsigned CmpReg = Incr2Reg;
10875     if (CmpOpcode == PPC::CMPW) {
10876       ValueReg = RegInfo.createVirtualRegister(GPRC);
10877       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10878           .addReg(SReg)
10879           .addReg(ShiftReg);
10880       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10881       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10882           .addReg(ValueReg);
10883       ValueReg = ValueSReg;
10884       CmpReg = incr;
10885     }
10886     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10887         .addReg(CmpReg)
10888         .addReg(ValueReg);
10889     BuildMI(BB, dl, TII->get(PPC::BCC))
10890         .addImm(CmpPred)
10891         .addReg(PPC::CR0)
10892         .addMBB(exitMBB);
10893     BB->addSuccessor(loop2MBB);
10894     BB->addSuccessor(exitMBB);
10895     BB = loop2MBB;
10896   }
10897   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10898   BuildMI(BB, dl, TII->get(PPC::STWCX))
10899       .addReg(Tmp4Reg)
10900       .addReg(ZeroReg)
10901       .addReg(PtrReg);
10902   BuildMI(BB, dl, TII->get(PPC::BCC))
10903       .addImm(PPC::PRED_NE)
10904       .addReg(PPC::CR0)
10905       .addMBB(loopMBB);
10906   BB->addSuccessor(loopMBB);
10907   BB->addSuccessor(exitMBB);
10908 
10909   //  exitMBB:
10910   //   ...
10911   BB = exitMBB;
10912   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10913       .addReg(TmpDestReg)
10914       .addReg(ShiftReg);
10915   return BB;
10916 }
10917 
10918 llvm::MachineBasicBlock *
10919 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10920                                     MachineBasicBlock *MBB) const {
10921   DebugLoc DL = MI.getDebugLoc();
10922   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10923   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10924 
10925   MachineFunction *MF = MBB->getParent();
10926   MachineRegisterInfo &MRI = MF->getRegInfo();
10927 
10928   const BasicBlock *BB = MBB->getBasicBlock();
10929   MachineFunction::iterator I = ++MBB->getIterator();
10930 
10931   Register DstReg = MI.getOperand(0).getReg();
10932   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10933   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10934   Register mainDstReg = MRI.createVirtualRegister(RC);
10935   Register restoreDstReg = MRI.createVirtualRegister(RC);
10936 
10937   MVT PVT = getPointerTy(MF->getDataLayout());
10938   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10939          "Invalid Pointer Size!");
10940   // For v = setjmp(buf), we generate
10941   //
10942   // thisMBB:
10943   //  SjLjSetup mainMBB
10944   //  bl mainMBB
10945   //  v_restore = 1
10946   //  b sinkMBB
10947   //
10948   // mainMBB:
10949   //  buf[LabelOffset] = LR
10950   //  v_main = 0
10951   //
10952   // sinkMBB:
10953   //  v = phi(main, restore)
10954   //
10955 
10956   MachineBasicBlock *thisMBB = MBB;
10957   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10958   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10959   MF->insert(I, mainMBB);
10960   MF->insert(I, sinkMBB);
10961 
10962   MachineInstrBuilder MIB;
10963 
10964   // Transfer the remainder of BB and its successor edges to sinkMBB.
10965   sinkMBB->splice(sinkMBB->begin(), MBB,
10966                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10967   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10968 
10969   // Note that the structure of the jmp_buf used here is not compatible
10970   // with that used by libc, and is not designed to be. Specifically, it
10971   // stores only those 'reserved' registers that LLVM does not otherwise
10972   // understand how to spill. Also, by convention, by the time this
10973   // intrinsic is called, Clang has already stored the frame address in the
10974   // first slot of the buffer and stack address in the third. Following the
10975   // X86 target code, we'll store the jump address in the second slot. We also
10976   // need to save the TOC pointer (R2) to handle jumps between shared
10977   // libraries, and that will be stored in the fourth slot. The thread
10978   // identifier (R13) is not affected.
10979 
10980   // thisMBB:
10981   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10982   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10983   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10984 
10985   // Prepare IP either in reg.
10986   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10987   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10988   Register BufReg = MI.getOperand(1).getReg();
10989 
10990   if (Subtarget.is64BitELFABI()) {
10991     setUsesTOCBasePtr(*MBB->getParent());
10992     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10993               .addReg(PPC::X2)
10994               .addImm(TOCOffset)
10995               .addReg(BufReg)
10996               .cloneMemRefs(MI);
10997   }
10998 
10999   // Naked functions never have a base pointer, and so we use r1. For all
11000   // other functions, this decision must be delayed until during PEI.
11001   unsigned BaseReg;
11002   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11003     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11004   else
11005     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11006 
11007   MIB = BuildMI(*thisMBB, MI, DL,
11008                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11009             .addReg(BaseReg)
11010             .addImm(BPOffset)
11011             .addReg(BufReg)
11012             .cloneMemRefs(MI);
11013 
11014   // Setup
11015   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11016   MIB.addRegMask(TRI->getNoPreservedMask());
11017 
11018   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11019 
11020   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11021           .addMBB(mainMBB);
11022   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11023 
11024   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11025   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11026 
11027   // mainMBB:
11028   //  mainDstReg = 0
11029   MIB =
11030       BuildMI(mainMBB, DL,
11031               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11032 
11033   // Store IP
11034   if (Subtarget.isPPC64()) {
11035     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11036             .addReg(LabelReg)
11037             .addImm(LabelOffset)
11038             .addReg(BufReg);
11039   } else {
11040     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11041             .addReg(LabelReg)
11042             .addImm(LabelOffset)
11043             .addReg(BufReg);
11044   }
11045   MIB.cloneMemRefs(MI);
11046 
11047   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11048   mainMBB->addSuccessor(sinkMBB);
11049 
11050   // sinkMBB:
11051   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11052           TII->get(PPC::PHI), DstReg)
11053     .addReg(mainDstReg).addMBB(mainMBB)
11054     .addReg(restoreDstReg).addMBB(thisMBB);
11055 
11056   MI.eraseFromParent();
11057   return sinkMBB;
11058 }
11059 
11060 MachineBasicBlock *
11061 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11062                                      MachineBasicBlock *MBB) const {
11063   DebugLoc DL = MI.getDebugLoc();
11064   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11065 
11066   MachineFunction *MF = MBB->getParent();
11067   MachineRegisterInfo &MRI = MF->getRegInfo();
11068 
11069   MVT PVT = getPointerTy(MF->getDataLayout());
11070   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11071          "Invalid Pointer Size!");
11072 
11073   const TargetRegisterClass *RC =
11074     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11075   Register Tmp = MRI.createVirtualRegister(RC);
11076   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11077   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11078   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11079   unsigned BP =
11080       (PVT == MVT::i64)
11081           ? PPC::X30
11082           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11083                                                               : PPC::R30);
11084 
11085   MachineInstrBuilder MIB;
11086 
11087   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11088   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11089   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11090   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11091 
11092   Register BufReg = MI.getOperand(0).getReg();
11093 
11094   // Reload FP (the jumped-to function may not have had a
11095   // frame pointer, and if so, then its r31 will be restored
11096   // as necessary).
11097   if (PVT == MVT::i64) {
11098     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11099             .addImm(0)
11100             .addReg(BufReg);
11101   } else {
11102     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11103             .addImm(0)
11104             .addReg(BufReg);
11105   }
11106   MIB.cloneMemRefs(MI);
11107 
11108   // Reload IP
11109   if (PVT == MVT::i64) {
11110     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11111             .addImm(LabelOffset)
11112             .addReg(BufReg);
11113   } else {
11114     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11115             .addImm(LabelOffset)
11116             .addReg(BufReg);
11117   }
11118   MIB.cloneMemRefs(MI);
11119 
11120   // Reload SP
11121   if (PVT == MVT::i64) {
11122     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11123             .addImm(SPOffset)
11124             .addReg(BufReg);
11125   } else {
11126     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11127             .addImm(SPOffset)
11128             .addReg(BufReg);
11129   }
11130   MIB.cloneMemRefs(MI);
11131 
11132   // Reload BP
11133   if (PVT == MVT::i64) {
11134     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11135             .addImm(BPOffset)
11136             .addReg(BufReg);
11137   } else {
11138     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11139             .addImm(BPOffset)
11140             .addReg(BufReg);
11141   }
11142   MIB.cloneMemRefs(MI);
11143 
11144   // Reload TOC
11145   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11146     setUsesTOCBasePtr(*MBB->getParent());
11147     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11148               .addImm(TOCOffset)
11149               .addReg(BufReg)
11150               .cloneMemRefs(MI);
11151   }
11152 
11153   // Jump
11154   BuildMI(*MBB, MI, DL,
11155           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11156   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11157 
11158   MI.eraseFromParent();
11159   return MBB;
11160 }
11161 
11162 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11163   // If the function specifically requests inline stack probes, emit them.
11164   if (MF.getFunction().hasFnAttribute("probe-stack"))
11165     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11166            "inline-asm";
11167   return false;
11168 }
11169 
11170 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11171   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11172   unsigned StackAlign = TFI->getStackAlignment();
11173   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11174          "Unexpected stack alignment");
11175   // The default stack probe size is 4096 if the function has no
11176   // stack-probe-size attribute.
11177   unsigned StackProbeSize = 4096;
11178   const Function &Fn = MF.getFunction();
11179   if (Fn.hasFnAttribute("stack-probe-size"))
11180     Fn.getFnAttribute("stack-probe-size")
11181         .getValueAsString()
11182         .getAsInteger(0, StackProbeSize);
11183   // Round down to the stack alignment.
11184   StackProbeSize &= ~(StackAlign - 1);
11185   return StackProbeSize ? StackProbeSize : StackAlign;
11186 }
11187 
11188 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11189 // into three phases. In the first phase, it uses pseudo instruction
11190 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11191 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11192 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11193 // MaxCallFrameSize so that it can calculate correct data area pointer.
11194 MachineBasicBlock *
11195 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11196                                     MachineBasicBlock *MBB) const {
11197   const bool isPPC64 = Subtarget.isPPC64();
11198   MachineFunction *MF = MBB->getParent();
11199   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11200   DebugLoc DL = MI.getDebugLoc();
11201   const unsigned ProbeSize = getStackProbeSize(*MF);
11202   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11203   MachineRegisterInfo &MRI = MF->getRegInfo();
11204   // The CFG of probing stack looks as
11205   //         +-----+
11206   //         | MBB |
11207   //         +--+--+
11208   //            |
11209   //       +----v----+
11210   //  +--->+ TestMBB +---+
11211   //  |    +----+----+   |
11212   //  |         |        |
11213   //  |   +-----v----+   |
11214   //  +---+ BlockMBB |   |
11215   //      +----------+   |
11216   //                     |
11217   //       +---------+   |
11218   //       | TailMBB +<--+
11219   //       +---------+
11220   // In MBB, calculate previous frame pointer and final stack pointer.
11221   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11222   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11223   // TailMBB is spliced via \p MI.
11224   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11225   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11226   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11227 
11228   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11229   MF->insert(MBBIter, TestMBB);
11230   MF->insert(MBBIter, BlockMBB);
11231   MF->insert(MBBIter, TailMBB);
11232 
11233   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11234   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11235 
11236   Register DstReg = MI.getOperand(0).getReg();
11237   Register NegSizeReg = MI.getOperand(1).getReg();
11238   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11239   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11240   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11241   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11242 
11243   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11244   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11245   // NegSize.
11246   unsigned ProbeOpc;
11247   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11248     ProbeOpc =
11249         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11250   else
11251     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11252     // and NegSizeReg will be allocated in the same phyreg to avoid
11253     // redundant copy when NegSizeReg has only one use which is current MI and
11254     // will be replaced by PREPARE_PROBED_ALLOCA then.
11255     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11256                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11257   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11258       .addDef(ActualNegSizeReg)
11259       .addReg(NegSizeReg)
11260       .add(MI.getOperand(2))
11261       .add(MI.getOperand(3));
11262 
11263   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11264   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11265           FinalStackPtr)
11266       .addReg(SPReg)
11267       .addReg(ActualNegSizeReg);
11268 
11269   // Materialize a scratch register for update.
11270   int64_t NegProbeSize = -(int64_t)ProbeSize;
11271   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11272   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11273   if (!isInt<16>(NegProbeSize)) {
11274     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11275     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11276         .addImm(NegProbeSize >> 16);
11277     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11278             ScratchReg)
11279         .addReg(TempReg)
11280         .addImm(NegProbeSize & 0xFFFF);
11281   } else
11282     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11283         .addImm(NegProbeSize);
11284 
11285   {
11286     // Probing leading residual part.
11287     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11288     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11289         .addReg(ActualNegSizeReg)
11290         .addReg(ScratchReg);
11291     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11292     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11293         .addReg(Div)
11294         .addReg(ScratchReg);
11295     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11296     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11297         .addReg(Mul)
11298         .addReg(ActualNegSizeReg);
11299     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11300         .addReg(FramePointer)
11301         .addReg(SPReg)
11302         .addReg(NegMod);
11303   }
11304 
11305   {
11306     // Remaining part should be multiple of ProbeSize.
11307     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11308     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11309         .addReg(SPReg)
11310         .addReg(FinalStackPtr);
11311     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11312         .addImm(PPC::PRED_EQ)
11313         .addReg(CmpResult)
11314         .addMBB(TailMBB);
11315     TestMBB->addSuccessor(BlockMBB);
11316     TestMBB->addSuccessor(TailMBB);
11317   }
11318 
11319   {
11320     // Touch the block.
11321     // |P...|P...|P...
11322     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11323         .addReg(FramePointer)
11324         .addReg(SPReg)
11325         .addReg(ScratchReg);
11326     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11327     BlockMBB->addSuccessor(TestMBB);
11328   }
11329 
11330   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11331   // DYNAREAOFFSET pseudo instruction to get the future result.
11332   Register MaxCallFrameSizeReg =
11333       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11334   BuildMI(TailMBB, DL,
11335           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11336           MaxCallFrameSizeReg)
11337       .add(MI.getOperand(2))
11338       .add(MI.getOperand(3));
11339   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11340       .addReg(SPReg)
11341       .addReg(MaxCallFrameSizeReg);
11342 
11343   // Splice instructions after MI to TailMBB.
11344   TailMBB->splice(TailMBB->end(), MBB,
11345                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11346   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11347   MBB->addSuccessor(TestMBB);
11348 
11349   // Delete the pseudo instruction.
11350   MI.eraseFromParent();
11351 
11352   ++NumDynamicAllocaProbed;
11353   return TailMBB;
11354 }
11355 
11356 MachineBasicBlock *
11357 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11358                                                MachineBasicBlock *BB) const {
11359   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11360       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11361     if (Subtarget.is64BitELFABI() &&
11362         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11363         !Subtarget.isUsingPCRelativeCalls()) {
11364       // Call lowering should have added an r2 operand to indicate a dependence
11365       // on the TOC base pointer value. It can't however, because there is no
11366       // way to mark the dependence as implicit there, and so the stackmap code
11367       // will confuse it with a regular operand. Instead, add the dependence
11368       // here.
11369       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11370     }
11371 
11372     return emitPatchPoint(MI, BB);
11373   }
11374 
11375   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11376       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11377     return emitEHSjLjSetJmp(MI, BB);
11378   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11379              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11380     return emitEHSjLjLongJmp(MI, BB);
11381   }
11382 
11383   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11384 
11385   // To "insert" these instructions we actually have to insert their
11386   // control-flow patterns.
11387   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11388   MachineFunction::iterator It = ++BB->getIterator();
11389 
11390   MachineFunction *F = BB->getParent();
11391 
11392   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11393       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11394       MI.getOpcode() == PPC::SELECT_I8) {
11395     SmallVector<MachineOperand, 2> Cond;
11396     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11397         MI.getOpcode() == PPC::SELECT_CC_I8)
11398       Cond.push_back(MI.getOperand(4));
11399     else
11400       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11401     Cond.push_back(MI.getOperand(1));
11402 
11403     DebugLoc dl = MI.getDebugLoc();
11404     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11405                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11406   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11407              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11408              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11409              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11410              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11411              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11412              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11413              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11414              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11415              MI.getOpcode() == PPC::SELECT_F4 ||
11416              MI.getOpcode() == PPC::SELECT_F8 ||
11417              MI.getOpcode() == PPC::SELECT_F16 ||
11418              MI.getOpcode() == PPC::SELECT_SPE ||
11419              MI.getOpcode() == PPC::SELECT_SPE4 ||
11420              MI.getOpcode() == PPC::SELECT_VRRC ||
11421              MI.getOpcode() == PPC::SELECT_VSFRC ||
11422              MI.getOpcode() == PPC::SELECT_VSSRC ||
11423              MI.getOpcode() == PPC::SELECT_VSRC) {
11424     // The incoming instruction knows the destination vreg to set, the
11425     // condition code register to branch on, the true/false values to
11426     // select between, and a branch opcode to use.
11427 
11428     //  thisMBB:
11429     //  ...
11430     //   TrueVal = ...
11431     //   cmpTY ccX, r1, r2
11432     //   bCC copy1MBB
11433     //   fallthrough --> copy0MBB
11434     MachineBasicBlock *thisMBB = BB;
11435     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11436     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11437     DebugLoc dl = MI.getDebugLoc();
11438     F->insert(It, copy0MBB);
11439     F->insert(It, sinkMBB);
11440 
11441     // Transfer the remainder of BB and its successor edges to sinkMBB.
11442     sinkMBB->splice(sinkMBB->begin(), BB,
11443                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11444     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11445 
11446     // Next, add the true and fallthrough blocks as its successors.
11447     BB->addSuccessor(copy0MBB);
11448     BB->addSuccessor(sinkMBB);
11449 
11450     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11451         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11452         MI.getOpcode() == PPC::SELECT_F16 ||
11453         MI.getOpcode() == PPC::SELECT_SPE4 ||
11454         MI.getOpcode() == PPC::SELECT_SPE ||
11455         MI.getOpcode() == PPC::SELECT_VRRC ||
11456         MI.getOpcode() == PPC::SELECT_VSFRC ||
11457         MI.getOpcode() == PPC::SELECT_VSSRC ||
11458         MI.getOpcode() == PPC::SELECT_VSRC) {
11459       BuildMI(BB, dl, TII->get(PPC::BC))
11460           .addReg(MI.getOperand(1).getReg())
11461           .addMBB(sinkMBB);
11462     } else {
11463       unsigned SelectPred = MI.getOperand(4).getImm();
11464       BuildMI(BB, dl, TII->get(PPC::BCC))
11465           .addImm(SelectPred)
11466           .addReg(MI.getOperand(1).getReg())
11467           .addMBB(sinkMBB);
11468     }
11469 
11470     //  copy0MBB:
11471     //   %FalseValue = ...
11472     //   # fallthrough to sinkMBB
11473     BB = copy0MBB;
11474 
11475     // Update machine-CFG edges
11476     BB->addSuccessor(sinkMBB);
11477 
11478     //  sinkMBB:
11479     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11480     //  ...
11481     BB = sinkMBB;
11482     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11483         .addReg(MI.getOperand(3).getReg())
11484         .addMBB(copy0MBB)
11485         .addReg(MI.getOperand(2).getReg())
11486         .addMBB(thisMBB);
11487   } else if (MI.getOpcode() == PPC::ReadTB) {
11488     // To read the 64-bit time-base register on a 32-bit target, we read the
11489     // two halves. Should the counter have wrapped while it was being read, we
11490     // need to try again.
11491     // ...
11492     // readLoop:
11493     // mfspr Rx,TBU # load from TBU
11494     // mfspr Ry,TB  # load from TB
11495     // mfspr Rz,TBU # load from TBU
11496     // cmpw crX,Rx,Rz # check if 'old'='new'
11497     // bne readLoop   # branch if they're not equal
11498     // ...
11499 
11500     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11501     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11502     DebugLoc dl = MI.getDebugLoc();
11503     F->insert(It, readMBB);
11504     F->insert(It, sinkMBB);
11505 
11506     // Transfer the remainder of BB and its successor edges to sinkMBB.
11507     sinkMBB->splice(sinkMBB->begin(), BB,
11508                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11509     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11510 
11511     BB->addSuccessor(readMBB);
11512     BB = readMBB;
11513 
11514     MachineRegisterInfo &RegInfo = F->getRegInfo();
11515     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11516     Register LoReg = MI.getOperand(0).getReg();
11517     Register HiReg = MI.getOperand(1).getReg();
11518 
11519     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11520     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11521     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11522 
11523     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11524 
11525     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11526         .addReg(HiReg)
11527         .addReg(ReadAgainReg);
11528     BuildMI(BB, dl, TII->get(PPC::BCC))
11529         .addImm(PPC::PRED_NE)
11530         .addReg(CmpReg)
11531         .addMBB(readMBB);
11532 
11533     BB->addSuccessor(readMBB);
11534     BB->addSuccessor(sinkMBB);
11535   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11536     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11537   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11538     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11539   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11540     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11541   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11542     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11543 
11544   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11545     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11546   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11547     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11548   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11549     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11550   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11551     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11552 
11553   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11554     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11555   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11556     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11557   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11558     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11559   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11560     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11561 
11562   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11563     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11564   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11565     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11566   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11567     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11568   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11569     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11570 
11571   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11572     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11573   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11574     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11575   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11576     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11577   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11578     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11579 
11580   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11581     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11582   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11583     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11584   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11585     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11586   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11587     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11588 
11589   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11590     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11591   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11592     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11593   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11594     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11595   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11596     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11597 
11598   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11599     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11600   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11601     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11602   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11603     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11604   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11605     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11606 
11607   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11608     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11609   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11610     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11611   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11612     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11613   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11614     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11615 
11616   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11617     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11618   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11619     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11620   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11621     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11622   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11623     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11624 
11625   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11626     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11627   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11628     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11629   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11630     BB = EmitAtomicBinary(MI, BB, 4, 0);
11631   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11632     BB = EmitAtomicBinary(MI, BB, 8, 0);
11633   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11634            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11635            (Subtarget.hasPartwordAtomics() &&
11636             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11637            (Subtarget.hasPartwordAtomics() &&
11638             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11639     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11640 
11641     auto LoadMnemonic = PPC::LDARX;
11642     auto StoreMnemonic = PPC::STDCX;
11643     switch (MI.getOpcode()) {
11644     default:
11645       llvm_unreachable("Compare and swap of unknown size");
11646     case PPC::ATOMIC_CMP_SWAP_I8:
11647       LoadMnemonic = PPC::LBARX;
11648       StoreMnemonic = PPC::STBCX;
11649       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11650       break;
11651     case PPC::ATOMIC_CMP_SWAP_I16:
11652       LoadMnemonic = PPC::LHARX;
11653       StoreMnemonic = PPC::STHCX;
11654       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11655       break;
11656     case PPC::ATOMIC_CMP_SWAP_I32:
11657       LoadMnemonic = PPC::LWARX;
11658       StoreMnemonic = PPC::STWCX;
11659       break;
11660     case PPC::ATOMIC_CMP_SWAP_I64:
11661       LoadMnemonic = PPC::LDARX;
11662       StoreMnemonic = PPC::STDCX;
11663       break;
11664     }
11665     Register dest = MI.getOperand(0).getReg();
11666     Register ptrA = MI.getOperand(1).getReg();
11667     Register ptrB = MI.getOperand(2).getReg();
11668     Register oldval = MI.getOperand(3).getReg();
11669     Register newval = MI.getOperand(4).getReg();
11670     DebugLoc dl = MI.getDebugLoc();
11671 
11672     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11673     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11674     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11675     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11676     F->insert(It, loop1MBB);
11677     F->insert(It, loop2MBB);
11678     F->insert(It, midMBB);
11679     F->insert(It, exitMBB);
11680     exitMBB->splice(exitMBB->begin(), BB,
11681                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11682     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11683 
11684     //  thisMBB:
11685     //   ...
11686     //   fallthrough --> loopMBB
11687     BB->addSuccessor(loop1MBB);
11688 
11689     // loop1MBB:
11690     //   l[bhwd]arx dest, ptr
11691     //   cmp[wd] dest, oldval
11692     //   bne- midMBB
11693     // loop2MBB:
11694     //   st[bhwd]cx. newval, ptr
11695     //   bne- loopMBB
11696     //   b exitBB
11697     // midMBB:
11698     //   st[bhwd]cx. dest, ptr
11699     // exitBB:
11700     BB = loop1MBB;
11701     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11702     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11703         .addReg(oldval)
11704         .addReg(dest);
11705     BuildMI(BB, dl, TII->get(PPC::BCC))
11706         .addImm(PPC::PRED_NE)
11707         .addReg(PPC::CR0)
11708         .addMBB(midMBB);
11709     BB->addSuccessor(loop2MBB);
11710     BB->addSuccessor(midMBB);
11711 
11712     BB = loop2MBB;
11713     BuildMI(BB, dl, TII->get(StoreMnemonic))
11714         .addReg(newval)
11715         .addReg(ptrA)
11716         .addReg(ptrB);
11717     BuildMI(BB, dl, TII->get(PPC::BCC))
11718         .addImm(PPC::PRED_NE)
11719         .addReg(PPC::CR0)
11720         .addMBB(loop1MBB);
11721     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11722     BB->addSuccessor(loop1MBB);
11723     BB->addSuccessor(exitMBB);
11724 
11725     BB = midMBB;
11726     BuildMI(BB, dl, TII->get(StoreMnemonic))
11727         .addReg(dest)
11728         .addReg(ptrA)
11729         .addReg(ptrB);
11730     BB->addSuccessor(exitMBB);
11731 
11732     //  exitMBB:
11733     //   ...
11734     BB = exitMBB;
11735   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11736              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11737     // We must use 64-bit registers for addresses when targeting 64-bit,
11738     // since we're actually doing arithmetic on them.  Other registers
11739     // can be 32-bit.
11740     bool is64bit = Subtarget.isPPC64();
11741     bool isLittleEndian = Subtarget.isLittleEndian();
11742     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11743 
11744     Register dest = MI.getOperand(0).getReg();
11745     Register ptrA = MI.getOperand(1).getReg();
11746     Register ptrB = MI.getOperand(2).getReg();
11747     Register oldval = MI.getOperand(3).getReg();
11748     Register newval = MI.getOperand(4).getReg();
11749     DebugLoc dl = MI.getDebugLoc();
11750 
11751     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11752     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11753     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11754     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11755     F->insert(It, loop1MBB);
11756     F->insert(It, loop2MBB);
11757     F->insert(It, midMBB);
11758     F->insert(It, exitMBB);
11759     exitMBB->splice(exitMBB->begin(), BB,
11760                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11761     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11762 
11763     MachineRegisterInfo &RegInfo = F->getRegInfo();
11764     const TargetRegisterClass *RC =
11765         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11766     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11767 
11768     Register PtrReg = RegInfo.createVirtualRegister(RC);
11769     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11770     Register ShiftReg =
11771         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11772     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11773     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11774     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11775     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11776     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11777     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11778     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11779     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11780     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11781     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11782     Register Ptr1Reg;
11783     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11784     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11785     //  thisMBB:
11786     //   ...
11787     //   fallthrough --> loopMBB
11788     BB->addSuccessor(loop1MBB);
11789 
11790     // The 4-byte load must be aligned, while a char or short may be
11791     // anywhere in the word.  Hence all this nasty bookkeeping code.
11792     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11793     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11794     //   xori shift, shift1, 24 [16]
11795     //   rlwinm ptr, ptr1, 0, 0, 29
11796     //   slw newval2, newval, shift
11797     //   slw oldval2, oldval,shift
11798     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11799     //   slw mask, mask2, shift
11800     //   and newval3, newval2, mask
11801     //   and oldval3, oldval2, mask
11802     // loop1MBB:
11803     //   lwarx tmpDest, ptr
11804     //   and tmp, tmpDest, mask
11805     //   cmpw tmp, oldval3
11806     //   bne- midMBB
11807     // loop2MBB:
11808     //   andc tmp2, tmpDest, mask
11809     //   or tmp4, tmp2, newval3
11810     //   stwcx. tmp4, ptr
11811     //   bne- loop1MBB
11812     //   b exitBB
11813     // midMBB:
11814     //   stwcx. tmpDest, ptr
11815     // exitBB:
11816     //   srw dest, tmpDest, shift
11817     if (ptrA != ZeroReg) {
11818       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11819       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11820           .addReg(ptrA)
11821           .addReg(ptrB);
11822     } else {
11823       Ptr1Reg = ptrB;
11824     }
11825 
11826     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11827     // mode.
11828     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11829         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11830         .addImm(3)
11831         .addImm(27)
11832         .addImm(is8bit ? 28 : 27);
11833     if (!isLittleEndian)
11834       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11835           .addReg(Shift1Reg)
11836           .addImm(is8bit ? 24 : 16);
11837     if (is64bit)
11838       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11839           .addReg(Ptr1Reg)
11840           .addImm(0)
11841           .addImm(61);
11842     else
11843       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11844           .addReg(Ptr1Reg)
11845           .addImm(0)
11846           .addImm(0)
11847           .addImm(29);
11848     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11849         .addReg(newval)
11850         .addReg(ShiftReg);
11851     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11852         .addReg(oldval)
11853         .addReg(ShiftReg);
11854     if (is8bit)
11855       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11856     else {
11857       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11858       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11859           .addReg(Mask3Reg)
11860           .addImm(65535);
11861     }
11862     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11863         .addReg(Mask2Reg)
11864         .addReg(ShiftReg);
11865     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11866         .addReg(NewVal2Reg)
11867         .addReg(MaskReg);
11868     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11869         .addReg(OldVal2Reg)
11870         .addReg(MaskReg);
11871 
11872     BB = loop1MBB;
11873     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11874         .addReg(ZeroReg)
11875         .addReg(PtrReg);
11876     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11877         .addReg(TmpDestReg)
11878         .addReg(MaskReg);
11879     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11880         .addReg(TmpReg)
11881         .addReg(OldVal3Reg);
11882     BuildMI(BB, dl, TII->get(PPC::BCC))
11883         .addImm(PPC::PRED_NE)
11884         .addReg(PPC::CR0)
11885         .addMBB(midMBB);
11886     BB->addSuccessor(loop2MBB);
11887     BB->addSuccessor(midMBB);
11888 
11889     BB = loop2MBB;
11890     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11891         .addReg(TmpDestReg)
11892         .addReg(MaskReg);
11893     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11894         .addReg(Tmp2Reg)
11895         .addReg(NewVal3Reg);
11896     BuildMI(BB, dl, TII->get(PPC::STWCX))
11897         .addReg(Tmp4Reg)
11898         .addReg(ZeroReg)
11899         .addReg(PtrReg);
11900     BuildMI(BB, dl, TII->get(PPC::BCC))
11901         .addImm(PPC::PRED_NE)
11902         .addReg(PPC::CR0)
11903         .addMBB(loop1MBB);
11904     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11905     BB->addSuccessor(loop1MBB);
11906     BB->addSuccessor(exitMBB);
11907 
11908     BB = midMBB;
11909     BuildMI(BB, dl, TII->get(PPC::STWCX))
11910         .addReg(TmpDestReg)
11911         .addReg(ZeroReg)
11912         .addReg(PtrReg);
11913     BB->addSuccessor(exitMBB);
11914 
11915     //  exitMBB:
11916     //   ...
11917     BB = exitMBB;
11918     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11919         .addReg(TmpReg)
11920         .addReg(ShiftReg);
11921   } else if (MI.getOpcode() == PPC::FADDrtz) {
11922     // This pseudo performs an FADD with rounding mode temporarily forced
11923     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11924     // is not modeled at the SelectionDAG level.
11925     Register Dest = MI.getOperand(0).getReg();
11926     Register Src1 = MI.getOperand(1).getReg();
11927     Register Src2 = MI.getOperand(2).getReg();
11928     DebugLoc dl = MI.getDebugLoc();
11929 
11930     MachineRegisterInfo &RegInfo = F->getRegInfo();
11931     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11932 
11933     // Save FPSCR value.
11934     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11935 
11936     // Set rounding mode to round-to-zero.
11937     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
11938         .addImm(31)
11939         .addReg(PPC::RM, RegState::ImplicitDefine);
11940 
11941     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
11942         .addImm(30)
11943         .addReg(PPC::RM, RegState::ImplicitDefine);
11944 
11945     // Perform addition.
11946     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11947 
11948     // Restore FPSCR value.
11949     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11950   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11951              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11952              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11953              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11954     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11955                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11956                           ? PPC::ANDI8_rec
11957                           : PPC::ANDI_rec;
11958     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11959                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11960 
11961     MachineRegisterInfo &RegInfo = F->getRegInfo();
11962     Register Dest = RegInfo.createVirtualRegister(
11963         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11964 
11965     DebugLoc Dl = MI.getDebugLoc();
11966     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11967         .addReg(MI.getOperand(1).getReg())
11968         .addImm(1);
11969     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11970             MI.getOperand(0).getReg())
11971         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11972   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11973     DebugLoc Dl = MI.getDebugLoc();
11974     MachineRegisterInfo &RegInfo = F->getRegInfo();
11975     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11976     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11977     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11978             MI.getOperand(0).getReg())
11979         .addReg(CRReg);
11980   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11981     DebugLoc Dl = MI.getDebugLoc();
11982     unsigned Imm = MI.getOperand(1).getImm();
11983     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11984     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11985             MI.getOperand(0).getReg())
11986         .addReg(PPC::CR0EQ);
11987   } else if (MI.getOpcode() == PPC::SETRNDi) {
11988     DebugLoc dl = MI.getDebugLoc();
11989     Register OldFPSCRReg = MI.getOperand(0).getReg();
11990 
11991     // Save FPSCR value.
11992     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11993 
11994     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11995     // the following settings:
11996     //   00 Round to nearest
11997     //   01 Round to 0
11998     //   10 Round to +inf
11999     //   11 Round to -inf
12000 
12001     // When the operand is immediate, using the two least significant bits of
12002     // the immediate to set the bits 62:63 of FPSCR.
12003     unsigned Mode = MI.getOperand(1).getImm();
12004     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12005         .addImm(31)
12006         .addReg(PPC::RM, RegState::ImplicitDefine);
12007 
12008     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12009         .addImm(30)
12010         .addReg(PPC::RM, RegState::ImplicitDefine);
12011   } else if (MI.getOpcode() == PPC::SETRND) {
12012     DebugLoc dl = MI.getDebugLoc();
12013 
12014     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12015     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12016     // If the target doesn't have DirectMove, we should use stack to do the
12017     // conversion, because the target doesn't have the instructions like mtvsrd
12018     // or mfvsrd to do this conversion directly.
12019     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12020       if (Subtarget.hasDirectMove()) {
12021         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12022           .addReg(SrcReg);
12023       } else {
12024         // Use stack to do the register copy.
12025         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12026         MachineRegisterInfo &RegInfo = F->getRegInfo();
12027         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12028         if (RC == &PPC::F8RCRegClass) {
12029           // Copy register from F8RCRegClass to G8RCRegclass.
12030           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12031                  "Unsupported RegClass.");
12032 
12033           StoreOp = PPC::STFD;
12034           LoadOp = PPC::LD;
12035         } else {
12036           // Copy register from G8RCRegClass to F8RCRegclass.
12037           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12038                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12039                  "Unsupported RegClass.");
12040         }
12041 
12042         MachineFrameInfo &MFI = F->getFrameInfo();
12043         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12044 
12045         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12046             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12047             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12048             MFI.getObjectAlign(FrameIdx));
12049 
12050         // Store the SrcReg into the stack.
12051         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12052           .addReg(SrcReg)
12053           .addImm(0)
12054           .addFrameIndex(FrameIdx)
12055           .addMemOperand(MMOStore);
12056 
12057         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12058             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12059             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12060             MFI.getObjectAlign(FrameIdx));
12061 
12062         // Load from the stack where SrcReg is stored, and save to DestReg,
12063         // so we have done the RegClass conversion from RegClass::SrcReg to
12064         // RegClass::DestReg.
12065         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12066           .addImm(0)
12067           .addFrameIndex(FrameIdx)
12068           .addMemOperand(MMOLoad);
12069       }
12070     };
12071 
12072     Register OldFPSCRReg = MI.getOperand(0).getReg();
12073 
12074     // Save FPSCR value.
12075     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12076 
12077     // When the operand is gprc register, use two least significant bits of the
12078     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12079     //
12080     // copy OldFPSCRTmpReg, OldFPSCRReg
12081     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12082     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12083     // copy NewFPSCRReg, NewFPSCRTmpReg
12084     // mtfsf 255, NewFPSCRReg
12085     MachineOperand SrcOp = MI.getOperand(1);
12086     MachineRegisterInfo &RegInfo = F->getRegInfo();
12087     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12088 
12089     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12090 
12091     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12092     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12093 
12094     // The first operand of INSERT_SUBREG should be a register which has
12095     // subregisters, we only care about its RegClass, so we should use an
12096     // IMPLICIT_DEF register.
12097     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12098     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12099       .addReg(ImDefReg)
12100       .add(SrcOp)
12101       .addImm(1);
12102 
12103     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12104     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12105       .addReg(OldFPSCRTmpReg)
12106       .addReg(ExtSrcReg)
12107       .addImm(0)
12108       .addImm(62);
12109 
12110     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12111     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12112 
12113     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12114     // bits of FPSCR.
12115     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12116       .addImm(255)
12117       .addReg(NewFPSCRReg)
12118       .addImm(0)
12119       .addImm(0);
12120   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12121              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12122     return emitProbedAlloca(MI, BB);
12123   } else {
12124     llvm_unreachable("Unexpected instr type to insert");
12125   }
12126 
12127   MI.eraseFromParent(); // The pseudo instruction is gone now.
12128   return BB;
12129 }
12130 
12131 //===----------------------------------------------------------------------===//
12132 // Target Optimization Hooks
12133 //===----------------------------------------------------------------------===//
12134 
12135 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12136   // For the estimates, convergence is quadratic, so we essentially double the
12137   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12138   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12139   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12140   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12141   if (VT.getScalarType() == MVT::f64)
12142     RefinementSteps++;
12143   return RefinementSteps;
12144 }
12145 
12146 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12147                                            int Enabled, int &RefinementSteps,
12148                                            bool &UseOneConstNR,
12149                                            bool Reciprocal) const {
12150   EVT VT = Operand.getValueType();
12151   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12152       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12153       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12154       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12155     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12156       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12157 
12158     // The Newton-Raphson computation with a single constant does not provide
12159     // enough accuracy on some CPUs.
12160     UseOneConstNR = !Subtarget.needsTwoConstNR();
12161     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12162   }
12163   return SDValue();
12164 }
12165 
12166 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12167                                             int Enabled,
12168                                             int &RefinementSteps) const {
12169   EVT VT = Operand.getValueType();
12170   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12171       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12172       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12173       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12174     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12175       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12176     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12177   }
12178   return SDValue();
12179 }
12180 
12181 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12182   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12183   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12184   // enabled for division), this functionality is redundant with the default
12185   // combiner logic (once the division -> reciprocal/multiply transformation
12186   // has taken place). As a result, this matters more for older cores than for
12187   // newer ones.
12188 
12189   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12190   // reciprocal if there are two or more FDIVs (for embedded cores with only
12191   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12192   switch (Subtarget.getCPUDirective()) {
12193   default:
12194     return 3;
12195   case PPC::DIR_440:
12196   case PPC::DIR_A2:
12197   case PPC::DIR_E500:
12198   case PPC::DIR_E500mc:
12199   case PPC::DIR_E5500:
12200     return 2;
12201   }
12202 }
12203 
12204 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12205 // collapsed, and so we need to look through chains of them.
12206 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12207                                      int64_t& Offset, SelectionDAG &DAG) {
12208   if (DAG.isBaseWithConstantOffset(Loc)) {
12209     Base = Loc.getOperand(0);
12210     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12211 
12212     // The base might itself be a base plus an offset, and if so, accumulate
12213     // that as well.
12214     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12215   }
12216 }
12217 
12218 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12219                             unsigned Bytes, int Dist,
12220                             SelectionDAG &DAG) {
12221   if (VT.getSizeInBits() / 8 != Bytes)
12222     return false;
12223 
12224   SDValue BaseLoc = Base->getBasePtr();
12225   if (Loc.getOpcode() == ISD::FrameIndex) {
12226     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12227       return false;
12228     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12229     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12230     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12231     int FS  = MFI.getObjectSize(FI);
12232     int BFS = MFI.getObjectSize(BFI);
12233     if (FS != BFS || FS != (int)Bytes) return false;
12234     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12235   }
12236 
12237   SDValue Base1 = Loc, Base2 = BaseLoc;
12238   int64_t Offset1 = 0, Offset2 = 0;
12239   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12240   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12241   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12242     return true;
12243 
12244   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12245   const GlobalValue *GV1 = nullptr;
12246   const GlobalValue *GV2 = nullptr;
12247   Offset1 = 0;
12248   Offset2 = 0;
12249   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12250   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12251   if (isGA1 && isGA2 && GV1 == GV2)
12252     return Offset1 == (Offset2 + Dist*Bytes);
12253   return false;
12254 }
12255 
12256 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12257 // not enforce equality of the chain operands.
12258 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12259                             unsigned Bytes, int Dist,
12260                             SelectionDAG &DAG) {
12261   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12262     EVT VT = LS->getMemoryVT();
12263     SDValue Loc = LS->getBasePtr();
12264     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12265   }
12266 
12267   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12268     EVT VT;
12269     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12270     default: return false;
12271     case Intrinsic::ppc_altivec_lvx:
12272     case Intrinsic::ppc_altivec_lvxl:
12273     case Intrinsic::ppc_vsx_lxvw4x:
12274     case Intrinsic::ppc_vsx_lxvw4x_be:
12275       VT = MVT::v4i32;
12276       break;
12277     case Intrinsic::ppc_vsx_lxvd2x:
12278     case Intrinsic::ppc_vsx_lxvd2x_be:
12279       VT = MVT::v2f64;
12280       break;
12281     case Intrinsic::ppc_altivec_lvebx:
12282       VT = MVT::i8;
12283       break;
12284     case Intrinsic::ppc_altivec_lvehx:
12285       VT = MVT::i16;
12286       break;
12287     case Intrinsic::ppc_altivec_lvewx:
12288       VT = MVT::i32;
12289       break;
12290     }
12291 
12292     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12293   }
12294 
12295   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12296     EVT VT;
12297     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12298     default: return false;
12299     case Intrinsic::ppc_altivec_stvx:
12300     case Intrinsic::ppc_altivec_stvxl:
12301     case Intrinsic::ppc_vsx_stxvw4x:
12302       VT = MVT::v4i32;
12303       break;
12304     case Intrinsic::ppc_vsx_stxvd2x:
12305       VT = MVT::v2f64;
12306       break;
12307     case Intrinsic::ppc_vsx_stxvw4x_be:
12308       VT = MVT::v4i32;
12309       break;
12310     case Intrinsic::ppc_vsx_stxvd2x_be:
12311       VT = MVT::v2f64;
12312       break;
12313     case Intrinsic::ppc_altivec_stvebx:
12314       VT = MVT::i8;
12315       break;
12316     case Intrinsic::ppc_altivec_stvehx:
12317       VT = MVT::i16;
12318       break;
12319     case Intrinsic::ppc_altivec_stvewx:
12320       VT = MVT::i32;
12321       break;
12322     }
12323 
12324     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12325   }
12326 
12327   return false;
12328 }
12329 
12330 // Return true is there is a nearyby consecutive load to the one provided
12331 // (regardless of alignment). We search up and down the chain, looking though
12332 // token factors and other loads (but nothing else). As a result, a true result
12333 // indicates that it is safe to create a new consecutive load adjacent to the
12334 // load provided.
12335 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12336   SDValue Chain = LD->getChain();
12337   EVT VT = LD->getMemoryVT();
12338 
12339   SmallSet<SDNode *, 16> LoadRoots;
12340   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12341   SmallSet<SDNode *, 16> Visited;
12342 
12343   // First, search up the chain, branching to follow all token-factor operands.
12344   // If we find a consecutive load, then we're done, otherwise, record all
12345   // nodes just above the top-level loads and token factors.
12346   while (!Queue.empty()) {
12347     SDNode *ChainNext = Queue.pop_back_val();
12348     if (!Visited.insert(ChainNext).second)
12349       continue;
12350 
12351     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12352       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12353         return true;
12354 
12355       if (!Visited.count(ChainLD->getChain().getNode()))
12356         Queue.push_back(ChainLD->getChain().getNode());
12357     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12358       for (const SDUse &O : ChainNext->ops())
12359         if (!Visited.count(O.getNode()))
12360           Queue.push_back(O.getNode());
12361     } else
12362       LoadRoots.insert(ChainNext);
12363   }
12364 
12365   // Second, search down the chain, starting from the top-level nodes recorded
12366   // in the first phase. These top-level nodes are the nodes just above all
12367   // loads and token factors. Starting with their uses, recursively look though
12368   // all loads (just the chain uses) and token factors to find a consecutive
12369   // load.
12370   Visited.clear();
12371   Queue.clear();
12372 
12373   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12374        IE = LoadRoots.end(); I != IE; ++I) {
12375     Queue.push_back(*I);
12376 
12377     while (!Queue.empty()) {
12378       SDNode *LoadRoot = Queue.pop_back_val();
12379       if (!Visited.insert(LoadRoot).second)
12380         continue;
12381 
12382       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12383         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12384           return true;
12385 
12386       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12387            UE = LoadRoot->use_end(); UI != UE; ++UI)
12388         if (((isa<MemSDNode>(*UI) &&
12389             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12390             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12391           Queue.push_back(*UI);
12392     }
12393   }
12394 
12395   return false;
12396 }
12397 
12398 /// This function is called when we have proved that a SETCC node can be replaced
12399 /// by subtraction (and other supporting instructions) so that the result of
12400 /// comparison is kept in a GPR instead of CR. This function is purely for
12401 /// codegen purposes and has some flags to guide the codegen process.
12402 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12403                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12404   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12405 
12406   // Zero extend the operands to the largest legal integer. Originally, they
12407   // must be of a strictly smaller size.
12408   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12409                          DAG.getConstant(Size, DL, MVT::i32));
12410   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12411                          DAG.getConstant(Size, DL, MVT::i32));
12412 
12413   // Swap if needed. Depends on the condition code.
12414   if (Swap)
12415     std::swap(Op0, Op1);
12416 
12417   // Subtract extended integers.
12418   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12419 
12420   // Move the sign bit to the least significant position and zero out the rest.
12421   // Now the least significant bit carries the result of original comparison.
12422   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12423                              DAG.getConstant(Size - 1, DL, MVT::i32));
12424   auto Final = Shifted;
12425 
12426   // Complement the result if needed. Based on the condition code.
12427   if (Complement)
12428     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12429                         DAG.getConstant(1, DL, MVT::i64));
12430 
12431   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12432 }
12433 
12434 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12435                                                   DAGCombinerInfo &DCI) const {
12436   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12437 
12438   SelectionDAG &DAG = DCI.DAG;
12439   SDLoc DL(N);
12440 
12441   // Size of integers being compared has a critical role in the following
12442   // analysis, so we prefer to do this when all types are legal.
12443   if (!DCI.isAfterLegalizeDAG())
12444     return SDValue();
12445 
12446   // If all users of SETCC extend its value to a legal integer type
12447   // then we replace SETCC with a subtraction
12448   for (SDNode::use_iterator UI = N->use_begin(),
12449        UE = N->use_end(); UI != UE; ++UI) {
12450     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12451       return SDValue();
12452   }
12453 
12454   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12455   auto OpSize = N->getOperand(0).getValueSizeInBits();
12456 
12457   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12458 
12459   if (OpSize < Size) {
12460     switch (CC) {
12461     default: break;
12462     case ISD::SETULT:
12463       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12464     case ISD::SETULE:
12465       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12466     case ISD::SETUGT:
12467       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12468     case ISD::SETUGE:
12469       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12470     }
12471   }
12472 
12473   return SDValue();
12474 }
12475 
12476 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12477                                                   DAGCombinerInfo &DCI) const {
12478   SelectionDAG &DAG = DCI.DAG;
12479   SDLoc dl(N);
12480 
12481   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12482   // If we're tracking CR bits, we need to be careful that we don't have:
12483   //   trunc(binary-ops(zext(x), zext(y)))
12484   // or
12485   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12486   // such that we're unnecessarily moving things into GPRs when it would be
12487   // better to keep them in CR bits.
12488 
12489   // Note that trunc here can be an actual i1 trunc, or can be the effective
12490   // truncation that comes from a setcc or select_cc.
12491   if (N->getOpcode() == ISD::TRUNCATE &&
12492       N->getValueType(0) != MVT::i1)
12493     return SDValue();
12494 
12495   if (N->getOperand(0).getValueType() != MVT::i32 &&
12496       N->getOperand(0).getValueType() != MVT::i64)
12497     return SDValue();
12498 
12499   if (N->getOpcode() == ISD::SETCC ||
12500       N->getOpcode() == ISD::SELECT_CC) {
12501     // If we're looking at a comparison, then we need to make sure that the
12502     // high bits (all except for the first) don't matter the result.
12503     ISD::CondCode CC =
12504       cast<CondCodeSDNode>(N->getOperand(
12505         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12506     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12507 
12508     if (ISD::isSignedIntSetCC(CC)) {
12509       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12510           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12511         return SDValue();
12512     } else if (ISD::isUnsignedIntSetCC(CC)) {
12513       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12514                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12515           !DAG.MaskedValueIsZero(N->getOperand(1),
12516                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12517         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12518                                              : SDValue());
12519     } else {
12520       // This is neither a signed nor an unsigned comparison, just make sure
12521       // that the high bits are equal.
12522       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12523       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12524 
12525       // We don't really care about what is known about the first bit (if
12526       // anything), so clear it in all masks prior to comparing them.
12527       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12528       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12529 
12530       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12531         return SDValue();
12532     }
12533   }
12534 
12535   // We now know that the higher-order bits are irrelevant, we just need to
12536   // make sure that all of the intermediate operations are bit operations, and
12537   // all inputs are extensions.
12538   if (N->getOperand(0).getOpcode() != ISD::AND &&
12539       N->getOperand(0).getOpcode() != ISD::OR  &&
12540       N->getOperand(0).getOpcode() != ISD::XOR &&
12541       N->getOperand(0).getOpcode() != ISD::SELECT &&
12542       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12543       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12544       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12545       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12546       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12547     return SDValue();
12548 
12549   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12550       N->getOperand(1).getOpcode() != ISD::AND &&
12551       N->getOperand(1).getOpcode() != ISD::OR  &&
12552       N->getOperand(1).getOpcode() != ISD::XOR &&
12553       N->getOperand(1).getOpcode() != ISD::SELECT &&
12554       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12555       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12556       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12557       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12558       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12559     return SDValue();
12560 
12561   SmallVector<SDValue, 4> Inputs;
12562   SmallVector<SDValue, 8> BinOps, PromOps;
12563   SmallPtrSet<SDNode *, 16> Visited;
12564 
12565   for (unsigned i = 0; i < 2; ++i) {
12566     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12567           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12568           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12569           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12570         isa<ConstantSDNode>(N->getOperand(i)))
12571       Inputs.push_back(N->getOperand(i));
12572     else
12573       BinOps.push_back(N->getOperand(i));
12574 
12575     if (N->getOpcode() == ISD::TRUNCATE)
12576       break;
12577   }
12578 
12579   // Visit all inputs, collect all binary operations (and, or, xor and
12580   // select) that are all fed by extensions.
12581   while (!BinOps.empty()) {
12582     SDValue BinOp = BinOps.back();
12583     BinOps.pop_back();
12584 
12585     if (!Visited.insert(BinOp.getNode()).second)
12586       continue;
12587 
12588     PromOps.push_back(BinOp);
12589 
12590     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12591       // The condition of the select is not promoted.
12592       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12593         continue;
12594       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12595         continue;
12596 
12597       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12598             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12599             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12600            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12601           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12602         Inputs.push_back(BinOp.getOperand(i));
12603       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12604                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12605                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12606                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12607                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12608                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12609                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12610                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12611                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12612         BinOps.push_back(BinOp.getOperand(i));
12613       } else {
12614         // We have an input that is not an extension or another binary
12615         // operation; we'll abort this transformation.
12616         return SDValue();
12617       }
12618     }
12619   }
12620 
12621   // Make sure that this is a self-contained cluster of operations (which
12622   // is not quite the same thing as saying that everything has only one
12623   // use).
12624   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12625     if (isa<ConstantSDNode>(Inputs[i]))
12626       continue;
12627 
12628     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12629                               UE = Inputs[i].getNode()->use_end();
12630          UI != UE; ++UI) {
12631       SDNode *User = *UI;
12632       if (User != N && !Visited.count(User))
12633         return SDValue();
12634 
12635       // Make sure that we're not going to promote the non-output-value
12636       // operand(s) or SELECT or SELECT_CC.
12637       // FIXME: Although we could sometimes handle this, and it does occur in
12638       // practice that one of the condition inputs to the select is also one of
12639       // the outputs, we currently can't deal with this.
12640       if (User->getOpcode() == ISD::SELECT) {
12641         if (User->getOperand(0) == Inputs[i])
12642           return SDValue();
12643       } else if (User->getOpcode() == ISD::SELECT_CC) {
12644         if (User->getOperand(0) == Inputs[i] ||
12645             User->getOperand(1) == Inputs[i])
12646           return SDValue();
12647       }
12648     }
12649   }
12650 
12651   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12652     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12653                               UE = PromOps[i].getNode()->use_end();
12654          UI != UE; ++UI) {
12655       SDNode *User = *UI;
12656       if (User != N && !Visited.count(User))
12657         return SDValue();
12658 
12659       // Make sure that we're not going to promote the non-output-value
12660       // operand(s) or SELECT or SELECT_CC.
12661       // FIXME: Although we could sometimes handle this, and it does occur in
12662       // practice that one of the condition inputs to the select is also one of
12663       // the outputs, we currently can't deal with this.
12664       if (User->getOpcode() == ISD::SELECT) {
12665         if (User->getOperand(0) == PromOps[i])
12666           return SDValue();
12667       } else if (User->getOpcode() == ISD::SELECT_CC) {
12668         if (User->getOperand(0) == PromOps[i] ||
12669             User->getOperand(1) == PromOps[i])
12670           return SDValue();
12671       }
12672     }
12673   }
12674 
12675   // Replace all inputs with the extension operand.
12676   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12677     // Constants may have users outside the cluster of to-be-promoted nodes,
12678     // and so we need to replace those as we do the promotions.
12679     if (isa<ConstantSDNode>(Inputs[i]))
12680       continue;
12681     else
12682       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12683   }
12684 
12685   std::list<HandleSDNode> PromOpHandles;
12686   for (auto &PromOp : PromOps)
12687     PromOpHandles.emplace_back(PromOp);
12688 
12689   // Replace all operations (these are all the same, but have a different
12690   // (i1) return type). DAG.getNode will validate that the types of
12691   // a binary operator match, so go through the list in reverse so that
12692   // we've likely promoted both operands first. Any intermediate truncations or
12693   // extensions disappear.
12694   while (!PromOpHandles.empty()) {
12695     SDValue PromOp = PromOpHandles.back().getValue();
12696     PromOpHandles.pop_back();
12697 
12698     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12699         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12700         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12701         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12702       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12703           PromOp.getOperand(0).getValueType() != MVT::i1) {
12704         // The operand is not yet ready (see comment below).
12705         PromOpHandles.emplace_front(PromOp);
12706         continue;
12707       }
12708 
12709       SDValue RepValue = PromOp.getOperand(0);
12710       if (isa<ConstantSDNode>(RepValue))
12711         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12712 
12713       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12714       continue;
12715     }
12716 
12717     unsigned C;
12718     switch (PromOp.getOpcode()) {
12719     default:             C = 0; break;
12720     case ISD::SELECT:    C = 1; break;
12721     case ISD::SELECT_CC: C = 2; break;
12722     }
12723 
12724     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12725          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12726         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12727          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12728       // The to-be-promoted operands of this node have not yet been
12729       // promoted (this should be rare because we're going through the
12730       // list backward, but if one of the operands has several users in
12731       // this cluster of to-be-promoted nodes, it is possible).
12732       PromOpHandles.emplace_front(PromOp);
12733       continue;
12734     }
12735 
12736     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12737                                 PromOp.getNode()->op_end());
12738 
12739     // If there are any constant inputs, make sure they're replaced now.
12740     for (unsigned i = 0; i < 2; ++i)
12741       if (isa<ConstantSDNode>(Ops[C+i]))
12742         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12743 
12744     DAG.ReplaceAllUsesOfValueWith(PromOp,
12745       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12746   }
12747 
12748   // Now we're left with the initial truncation itself.
12749   if (N->getOpcode() == ISD::TRUNCATE)
12750     return N->getOperand(0);
12751 
12752   // Otherwise, this is a comparison. The operands to be compared have just
12753   // changed type (to i1), but everything else is the same.
12754   return SDValue(N, 0);
12755 }
12756 
12757 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12758                                                   DAGCombinerInfo &DCI) const {
12759   SelectionDAG &DAG = DCI.DAG;
12760   SDLoc dl(N);
12761 
12762   // If we're tracking CR bits, we need to be careful that we don't have:
12763   //   zext(binary-ops(trunc(x), trunc(y)))
12764   // or
12765   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12766   // such that we're unnecessarily moving things into CR bits that can more
12767   // efficiently stay in GPRs. Note that if we're not certain that the high
12768   // bits are set as required by the final extension, we still may need to do
12769   // some masking to get the proper behavior.
12770 
12771   // This same functionality is important on PPC64 when dealing with
12772   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12773   // the return values of functions. Because it is so similar, it is handled
12774   // here as well.
12775 
12776   if (N->getValueType(0) != MVT::i32 &&
12777       N->getValueType(0) != MVT::i64)
12778     return SDValue();
12779 
12780   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12781         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12782     return SDValue();
12783 
12784   if (N->getOperand(0).getOpcode() != ISD::AND &&
12785       N->getOperand(0).getOpcode() != ISD::OR  &&
12786       N->getOperand(0).getOpcode() != ISD::XOR &&
12787       N->getOperand(0).getOpcode() != ISD::SELECT &&
12788       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12789     return SDValue();
12790 
12791   SmallVector<SDValue, 4> Inputs;
12792   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12793   SmallPtrSet<SDNode *, 16> Visited;
12794 
12795   // Visit all inputs, collect all binary operations (and, or, xor and
12796   // select) that are all fed by truncations.
12797   while (!BinOps.empty()) {
12798     SDValue BinOp = BinOps.back();
12799     BinOps.pop_back();
12800 
12801     if (!Visited.insert(BinOp.getNode()).second)
12802       continue;
12803 
12804     PromOps.push_back(BinOp);
12805 
12806     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12807       // The condition of the select is not promoted.
12808       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12809         continue;
12810       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12811         continue;
12812 
12813       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12814           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12815         Inputs.push_back(BinOp.getOperand(i));
12816       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12817                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12818                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12819                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12820                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12821         BinOps.push_back(BinOp.getOperand(i));
12822       } else {
12823         // We have an input that is not a truncation or another binary
12824         // operation; we'll abort this transformation.
12825         return SDValue();
12826       }
12827     }
12828   }
12829 
12830   // The operands of a select that must be truncated when the select is
12831   // promoted because the operand is actually part of the to-be-promoted set.
12832   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12833 
12834   // Make sure that this is a self-contained cluster of operations (which
12835   // is not quite the same thing as saying that everything has only one
12836   // use).
12837   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12838     if (isa<ConstantSDNode>(Inputs[i]))
12839       continue;
12840 
12841     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12842                               UE = Inputs[i].getNode()->use_end();
12843          UI != UE; ++UI) {
12844       SDNode *User = *UI;
12845       if (User != N && !Visited.count(User))
12846         return SDValue();
12847 
12848       // If we're going to promote the non-output-value operand(s) or SELECT or
12849       // SELECT_CC, record them for truncation.
12850       if (User->getOpcode() == ISD::SELECT) {
12851         if (User->getOperand(0) == Inputs[i])
12852           SelectTruncOp[0].insert(std::make_pair(User,
12853                                     User->getOperand(0).getValueType()));
12854       } else if (User->getOpcode() == ISD::SELECT_CC) {
12855         if (User->getOperand(0) == Inputs[i])
12856           SelectTruncOp[0].insert(std::make_pair(User,
12857                                     User->getOperand(0).getValueType()));
12858         if (User->getOperand(1) == Inputs[i])
12859           SelectTruncOp[1].insert(std::make_pair(User,
12860                                     User->getOperand(1).getValueType()));
12861       }
12862     }
12863   }
12864 
12865   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12866     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12867                               UE = PromOps[i].getNode()->use_end();
12868          UI != UE; ++UI) {
12869       SDNode *User = *UI;
12870       if (User != N && !Visited.count(User))
12871         return SDValue();
12872 
12873       // If we're going to promote the non-output-value operand(s) or SELECT or
12874       // SELECT_CC, record them for truncation.
12875       if (User->getOpcode() == ISD::SELECT) {
12876         if (User->getOperand(0) == PromOps[i])
12877           SelectTruncOp[0].insert(std::make_pair(User,
12878                                     User->getOperand(0).getValueType()));
12879       } else if (User->getOpcode() == ISD::SELECT_CC) {
12880         if (User->getOperand(0) == PromOps[i])
12881           SelectTruncOp[0].insert(std::make_pair(User,
12882                                     User->getOperand(0).getValueType()));
12883         if (User->getOperand(1) == PromOps[i])
12884           SelectTruncOp[1].insert(std::make_pair(User,
12885                                     User->getOperand(1).getValueType()));
12886       }
12887     }
12888   }
12889 
12890   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12891   bool ReallyNeedsExt = false;
12892   if (N->getOpcode() != ISD::ANY_EXTEND) {
12893     // If all of the inputs are not already sign/zero extended, then
12894     // we'll still need to do that at the end.
12895     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12896       if (isa<ConstantSDNode>(Inputs[i]))
12897         continue;
12898 
12899       unsigned OpBits =
12900         Inputs[i].getOperand(0).getValueSizeInBits();
12901       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12902 
12903       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12904            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12905                                   APInt::getHighBitsSet(OpBits,
12906                                                         OpBits-PromBits))) ||
12907           (N->getOpcode() == ISD::SIGN_EXTEND &&
12908            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12909              (OpBits-(PromBits-1)))) {
12910         ReallyNeedsExt = true;
12911         break;
12912       }
12913     }
12914   }
12915 
12916   // Replace all inputs, either with the truncation operand, or a
12917   // truncation or extension to the final output type.
12918   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12919     // Constant inputs need to be replaced with the to-be-promoted nodes that
12920     // use them because they might have users outside of the cluster of
12921     // promoted nodes.
12922     if (isa<ConstantSDNode>(Inputs[i]))
12923       continue;
12924 
12925     SDValue InSrc = Inputs[i].getOperand(0);
12926     if (Inputs[i].getValueType() == N->getValueType(0))
12927       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12928     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12929       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12930         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12931     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12932       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12933         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12934     else
12935       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12936         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12937   }
12938 
12939   std::list<HandleSDNode> PromOpHandles;
12940   for (auto &PromOp : PromOps)
12941     PromOpHandles.emplace_back(PromOp);
12942 
12943   // Replace all operations (these are all the same, but have a different
12944   // (promoted) return type). DAG.getNode will validate that the types of
12945   // a binary operator match, so go through the list in reverse so that
12946   // we've likely promoted both operands first.
12947   while (!PromOpHandles.empty()) {
12948     SDValue PromOp = PromOpHandles.back().getValue();
12949     PromOpHandles.pop_back();
12950 
12951     unsigned C;
12952     switch (PromOp.getOpcode()) {
12953     default:             C = 0; break;
12954     case ISD::SELECT:    C = 1; break;
12955     case ISD::SELECT_CC: C = 2; break;
12956     }
12957 
12958     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12959          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12960         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12961          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12962       // The to-be-promoted operands of this node have not yet been
12963       // promoted (this should be rare because we're going through the
12964       // list backward, but if one of the operands has several users in
12965       // this cluster of to-be-promoted nodes, it is possible).
12966       PromOpHandles.emplace_front(PromOp);
12967       continue;
12968     }
12969 
12970     // For SELECT and SELECT_CC nodes, we do a similar check for any
12971     // to-be-promoted comparison inputs.
12972     if (PromOp.getOpcode() == ISD::SELECT ||
12973         PromOp.getOpcode() == ISD::SELECT_CC) {
12974       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12975            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12976           (SelectTruncOp[1].count(PromOp.getNode()) &&
12977            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12978         PromOpHandles.emplace_front(PromOp);
12979         continue;
12980       }
12981     }
12982 
12983     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12984                                 PromOp.getNode()->op_end());
12985 
12986     // If this node has constant inputs, then they'll need to be promoted here.
12987     for (unsigned i = 0; i < 2; ++i) {
12988       if (!isa<ConstantSDNode>(Ops[C+i]))
12989         continue;
12990       if (Ops[C+i].getValueType() == N->getValueType(0))
12991         continue;
12992 
12993       if (N->getOpcode() == ISD::SIGN_EXTEND)
12994         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12995       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12996         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12997       else
12998         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12999     }
13000 
13001     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13002     // truncate them again to the original value type.
13003     if (PromOp.getOpcode() == ISD::SELECT ||
13004         PromOp.getOpcode() == ISD::SELECT_CC) {
13005       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13006       if (SI0 != SelectTruncOp[0].end())
13007         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13008       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13009       if (SI1 != SelectTruncOp[1].end())
13010         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13011     }
13012 
13013     DAG.ReplaceAllUsesOfValueWith(PromOp,
13014       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13015   }
13016 
13017   // Now we're left with the initial extension itself.
13018   if (!ReallyNeedsExt)
13019     return N->getOperand(0);
13020 
13021   // To zero extend, just mask off everything except for the first bit (in the
13022   // i1 case).
13023   if (N->getOpcode() == ISD::ZERO_EXTEND)
13024     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13025                        DAG.getConstant(APInt::getLowBitsSet(
13026                                          N->getValueSizeInBits(0), PromBits),
13027                                        dl, N->getValueType(0)));
13028 
13029   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13030          "Invalid extension type");
13031   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13032   SDValue ShiftCst =
13033       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13034   return DAG.getNode(
13035       ISD::SRA, dl, N->getValueType(0),
13036       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13037       ShiftCst);
13038 }
13039 
13040 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13041                                         DAGCombinerInfo &DCI) const {
13042   assert(N->getOpcode() == ISD::SETCC &&
13043          "Should be called with a SETCC node");
13044 
13045   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13046   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13047     SDValue LHS = N->getOperand(0);
13048     SDValue RHS = N->getOperand(1);
13049 
13050     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13051     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13052         LHS.hasOneUse())
13053       std::swap(LHS, RHS);
13054 
13055     // x == 0-y --> x+y == 0
13056     // x != 0-y --> x+y != 0
13057     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13058         RHS.hasOneUse()) {
13059       SDLoc DL(N);
13060       SelectionDAG &DAG = DCI.DAG;
13061       EVT VT = N->getValueType(0);
13062       EVT OpVT = LHS.getValueType();
13063       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13064       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13065     }
13066   }
13067 
13068   return DAGCombineTruncBoolExt(N, DCI);
13069 }
13070 
13071 // Is this an extending load from an f32 to an f64?
13072 static bool isFPExtLoad(SDValue Op) {
13073   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13074     return LD->getExtensionType() == ISD::EXTLOAD &&
13075       Op.getValueType() == MVT::f64;
13076   return false;
13077 }
13078 
13079 /// Reduces the number of fp-to-int conversion when building a vector.
13080 ///
13081 /// If this vector is built out of floating to integer conversions,
13082 /// transform it to a vector built out of floating point values followed by a
13083 /// single floating to integer conversion of the vector.
13084 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13085 /// becomes (fptosi (build_vector ($A, $B, ...)))
13086 SDValue PPCTargetLowering::
13087 combineElementTruncationToVectorTruncation(SDNode *N,
13088                                            DAGCombinerInfo &DCI) const {
13089   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13090          "Should be called with a BUILD_VECTOR node");
13091 
13092   SelectionDAG &DAG = DCI.DAG;
13093   SDLoc dl(N);
13094 
13095   SDValue FirstInput = N->getOperand(0);
13096   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13097          "The input operand must be an fp-to-int conversion.");
13098 
13099   // This combine happens after legalization so the fp_to_[su]i nodes are
13100   // already converted to PPCSISD nodes.
13101   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13102   if (FirstConversion == PPCISD::FCTIDZ ||
13103       FirstConversion == PPCISD::FCTIDUZ ||
13104       FirstConversion == PPCISD::FCTIWZ ||
13105       FirstConversion == PPCISD::FCTIWUZ) {
13106     bool IsSplat = true;
13107     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13108       FirstConversion == PPCISD::FCTIWUZ;
13109     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13110     SmallVector<SDValue, 4> Ops;
13111     EVT TargetVT = N->getValueType(0);
13112     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13113       SDValue NextOp = N->getOperand(i);
13114       if (NextOp.getOpcode() != PPCISD::MFVSR)
13115         return SDValue();
13116       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13117       if (NextConversion != FirstConversion)
13118         return SDValue();
13119       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13120       // This is not valid if the input was originally double precision. It is
13121       // also not profitable to do unless this is an extending load in which
13122       // case doing this combine will allow us to combine consecutive loads.
13123       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13124         return SDValue();
13125       if (N->getOperand(i) != FirstInput)
13126         IsSplat = false;
13127     }
13128 
13129     // If this is a splat, we leave it as-is since there will be only a single
13130     // fp-to-int conversion followed by a splat of the integer. This is better
13131     // for 32-bit and smaller ints and neutral for 64-bit ints.
13132     if (IsSplat)
13133       return SDValue();
13134 
13135     // Now that we know we have the right type of node, get its operands
13136     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13137       SDValue In = N->getOperand(i).getOperand(0);
13138       if (Is32Bit) {
13139         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13140         // here, we know that all inputs are extending loads so this is safe).
13141         if (In.isUndef())
13142           Ops.push_back(DAG.getUNDEF(SrcVT));
13143         else {
13144           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13145                                       MVT::f32, In.getOperand(0),
13146                                       DAG.getIntPtrConstant(1, dl));
13147           Ops.push_back(Trunc);
13148         }
13149       } else
13150         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13151     }
13152 
13153     unsigned Opcode;
13154     if (FirstConversion == PPCISD::FCTIDZ ||
13155         FirstConversion == PPCISD::FCTIWZ)
13156       Opcode = ISD::FP_TO_SINT;
13157     else
13158       Opcode = ISD::FP_TO_UINT;
13159 
13160     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13161     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13162     return DAG.getNode(Opcode, dl, TargetVT, BV);
13163   }
13164   return SDValue();
13165 }
13166 
13167 /// Reduce the number of loads when building a vector.
13168 ///
13169 /// Building a vector out of multiple loads can be converted to a load
13170 /// of the vector type if the loads are consecutive. If the loads are
13171 /// consecutive but in descending order, a shuffle is added at the end
13172 /// to reorder the vector.
13173 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13174   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13175          "Should be called with a BUILD_VECTOR node");
13176 
13177   SDLoc dl(N);
13178 
13179   // Return early for non byte-sized type, as they can't be consecutive.
13180   if (!N->getValueType(0).getVectorElementType().isByteSized())
13181     return SDValue();
13182 
13183   bool InputsAreConsecutiveLoads = true;
13184   bool InputsAreReverseConsecutive = true;
13185   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13186   SDValue FirstInput = N->getOperand(0);
13187   bool IsRoundOfExtLoad = false;
13188 
13189   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13190       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13191     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13192     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13193   }
13194   // Not a build vector of (possibly fp_rounded) loads.
13195   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13196       N->getNumOperands() == 1)
13197     return SDValue();
13198 
13199   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13200     // If any inputs are fp_round(extload), they all must be.
13201     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13202       return SDValue();
13203 
13204     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13205       N->getOperand(i);
13206     if (NextInput.getOpcode() != ISD::LOAD)
13207       return SDValue();
13208 
13209     SDValue PreviousInput =
13210       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13211     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13212     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13213 
13214     // If any inputs are fp_round(extload), they all must be.
13215     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13216       return SDValue();
13217 
13218     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13219       InputsAreConsecutiveLoads = false;
13220     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13221       InputsAreReverseConsecutive = false;
13222 
13223     // Exit early if the loads are neither consecutive nor reverse consecutive.
13224     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13225       return SDValue();
13226   }
13227 
13228   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13229          "The loads cannot be both consecutive and reverse consecutive.");
13230 
13231   SDValue FirstLoadOp =
13232     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13233   SDValue LastLoadOp =
13234     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13235                        N->getOperand(N->getNumOperands()-1);
13236 
13237   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13238   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13239   if (InputsAreConsecutiveLoads) {
13240     assert(LD1 && "Input needs to be a LoadSDNode.");
13241     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13242                        LD1->getBasePtr(), LD1->getPointerInfo(),
13243                        LD1->getAlignment());
13244   }
13245   if (InputsAreReverseConsecutive) {
13246     assert(LDL && "Input needs to be a LoadSDNode.");
13247     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13248                                LDL->getBasePtr(), LDL->getPointerInfo(),
13249                                LDL->getAlignment());
13250     SmallVector<int, 16> Ops;
13251     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13252       Ops.push_back(i);
13253 
13254     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13255                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13256   }
13257   return SDValue();
13258 }
13259 
13260 // This function adds the required vector_shuffle needed to get
13261 // the elements of the vector extract in the correct position
13262 // as specified by the CorrectElems encoding.
13263 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13264                                       SDValue Input, uint64_t Elems,
13265                                       uint64_t CorrectElems) {
13266   SDLoc dl(N);
13267 
13268   unsigned NumElems = Input.getValueType().getVectorNumElements();
13269   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13270 
13271   // Knowing the element indices being extracted from the original
13272   // vector and the order in which they're being inserted, just put
13273   // them at element indices required for the instruction.
13274   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13275     if (DAG.getDataLayout().isLittleEndian())
13276       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13277     else
13278       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13279     CorrectElems = CorrectElems >> 8;
13280     Elems = Elems >> 8;
13281   }
13282 
13283   SDValue Shuffle =
13284       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13285                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13286 
13287   EVT VT = N->getValueType(0);
13288   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13289 
13290   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13291                                Input.getValueType().getVectorElementType(),
13292                                VT.getVectorNumElements());
13293   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13294                      DAG.getValueType(ExtVT));
13295 }
13296 
13297 // Look for build vector patterns where input operands come from sign
13298 // extended vector_extract elements of specific indices. If the correct indices
13299 // aren't used, add a vector shuffle to fix up the indices and create
13300 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13301 // during instruction selection.
13302 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13303   // This array encodes the indices that the vector sign extend instructions
13304   // extract from when extending from one type to another for both BE and LE.
13305   // The right nibble of each byte corresponds to the LE incides.
13306   // and the left nibble of each byte corresponds to the BE incides.
13307   // For example: 0x3074B8FC  byte->word
13308   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13309   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13310   // For example: 0x000070F8  byte->double word
13311   // For LE: the allowed indices are: 0x0,0x8
13312   // For BE: the allowed indices are: 0x7,0xF
13313   uint64_t TargetElems[] = {
13314       0x3074B8FC, // b->w
13315       0x000070F8, // b->d
13316       0x10325476, // h->w
13317       0x00003074, // h->d
13318       0x00001032, // w->d
13319   };
13320 
13321   uint64_t Elems = 0;
13322   int Index;
13323   SDValue Input;
13324 
13325   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13326     if (!Op)
13327       return false;
13328     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13329         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13330       return false;
13331 
13332     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13333     // of the right width.
13334     SDValue Extract = Op.getOperand(0);
13335     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13336       Extract = Extract.getOperand(0);
13337     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13338       return false;
13339 
13340     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13341     if (!ExtOp)
13342       return false;
13343 
13344     Index = ExtOp->getZExtValue();
13345     if (Input && Input != Extract.getOperand(0))
13346       return false;
13347 
13348     if (!Input)
13349       Input = Extract.getOperand(0);
13350 
13351     Elems = Elems << 8;
13352     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13353     Elems |= Index;
13354 
13355     return true;
13356   };
13357 
13358   // If the build vector operands aren't sign extended vector extracts,
13359   // of the same input vector, then return.
13360   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13361     if (!isSExtOfVecExtract(N->getOperand(i))) {
13362       return SDValue();
13363     }
13364   }
13365 
13366   // If the vector extract indicies are not correct, add the appropriate
13367   // vector_shuffle.
13368   int TgtElemArrayIdx;
13369   int InputSize = Input.getValueType().getScalarSizeInBits();
13370   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13371   if (InputSize + OutputSize == 40)
13372     TgtElemArrayIdx = 0;
13373   else if (InputSize + OutputSize == 72)
13374     TgtElemArrayIdx = 1;
13375   else if (InputSize + OutputSize == 48)
13376     TgtElemArrayIdx = 2;
13377   else if (InputSize + OutputSize == 80)
13378     TgtElemArrayIdx = 3;
13379   else if (InputSize + OutputSize == 96)
13380     TgtElemArrayIdx = 4;
13381   else
13382     return SDValue();
13383 
13384   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13385   CorrectElems = DAG.getDataLayout().isLittleEndian()
13386                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13387                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13388   if (Elems != CorrectElems) {
13389     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13390   }
13391 
13392   // Regular lowering will catch cases where a shuffle is not needed.
13393   return SDValue();
13394 }
13395 
13396 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13397                                                  DAGCombinerInfo &DCI) const {
13398   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13399          "Should be called with a BUILD_VECTOR node");
13400 
13401   SelectionDAG &DAG = DCI.DAG;
13402   SDLoc dl(N);
13403 
13404   if (!Subtarget.hasVSX())
13405     return SDValue();
13406 
13407   // The target independent DAG combiner will leave a build_vector of
13408   // float-to-int conversions intact. We can generate MUCH better code for
13409   // a float-to-int conversion of a vector of floats.
13410   SDValue FirstInput = N->getOperand(0);
13411   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13412     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13413     if (Reduced)
13414       return Reduced;
13415   }
13416 
13417   // If we're building a vector out of consecutive loads, just load that
13418   // vector type.
13419   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13420   if (Reduced)
13421     return Reduced;
13422 
13423   // If we're building a vector out of extended elements from another vector
13424   // we have P9 vector integer extend instructions. The code assumes legal
13425   // input types (i.e. it can't handle things like v4i16) so do not run before
13426   // legalization.
13427   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13428     Reduced = combineBVOfVecSExt(N, DAG);
13429     if (Reduced)
13430       return Reduced;
13431   }
13432 
13433 
13434   if (N->getValueType(0) != MVT::v2f64)
13435     return SDValue();
13436 
13437   // Looking for:
13438   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13439   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13440       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13441     return SDValue();
13442   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13443       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13444     return SDValue();
13445   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13446     return SDValue();
13447 
13448   SDValue Ext1 = FirstInput.getOperand(0);
13449   SDValue Ext2 = N->getOperand(1).getOperand(0);
13450   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13451      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13452     return SDValue();
13453 
13454   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13455   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13456   if (!Ext1Op || !Ext2Op)
13457     return SDValue();
13458   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13459       Ext1.getOperand(0) != Ext2.getOperand(0))
13460     return SDValue();
13461 
13462   int FirstElem = Ext1Op->getZExtValue();
13463   int SecondElem = Ext2Op->getZExtValue();
13464   int SubvecIdx;
13465   if (FirstElem == 0 && SecondElem == 1)
13466     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13467   else if (FirstElem == 2 && SecondElem == 3)
13468     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13469   else
13470     return SDValue();
13471 
13472   SDValue SrcVec = Ext1.getOperand(0);
13473   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13474     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13475   return DAG.getNode(NodeType, dl, MVT::v2f64,
13476                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13477 }
13478 
13479 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13480                                               DAGCombinerInfo &DCI) const {
13481   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13482           N->getOpcode() == ISD::UINT_TO_FP) &&
13483          "Need an int -> FP conversion node here");
13484 
13485   if (useSoftFloat() || !Subtarget.has64BitSupport())
13486     return SDValue();
13487 
13488   SelectionDAG &DAG = DCI.DAG;
13489   SDLoc dl(N);
13490   SDValue Op(N, 0);
13491 
13492   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13493   // from the hardware.
13494   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13495     return SDValue();
13496   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13497       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13498     return SDValue();
13499 
13500   SDValue FirstOperand(Op.getOperand(0));
13501   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13502     (FirstOperand.getValueType() == MVT::i8 ||
13503      FirstOperand.getValueType() == MVT::i16);
13504   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13505     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13506     bool DstDouble = Op.getValueType() == MVT::f64;
13507     unsigned ConvOp = Signed ?
13508       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13509       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13510     SDValue WidthConst =
13511       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13512                             dl, false);
13513     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13514     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13515     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13516                                          DAG.getVTList(MVT::f64, MVT::Other),
13517                                          Ops, MVT::i8, LDN->getMemOperand());
13518 
13519     // For signed conversion, we need to sign-extend the value in the VSR
13520     if (Signed) {
13521       SDValue ExtOps[] = { Ld, WidthConst };
13522       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13523       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13524     } else
13525       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13526   }
13527 
13528 
13529   // For i32 intermediate values, unfortunately, the conversion functions
13530   // leave the upper 32 bits of the value are undefined. Within the set of
13531   // scalar instructions, we have no method for zero- or sign-extending the
13532   // value. Thus, we cannot handle i32 intermediate values here.
13533   if (Op.getOperand(0).getValueType() == MVT::i32)
13534     return SDValue();
13535 
13536   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13537          "UINT_TO_FP is supported only with FPCVT");
13538 
13539   // If we have FCFIDS, then use it when converting to single-precision.
13540   // Otherwise, convert to double-precision and then round.
13541   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13542                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13543                                                             : PPCISD::FCFIDS)
13544                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13545                                                             : PPCISD::FCFID);
13546   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13547                   ? MVT::f32
13548                   : MVT::f64;
13549 
13550   // If we're converting from a float, to an int, and back to a float again,
13551   // then we don't need the store/load pair at all.
13552   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13553        Subtarget.hasFPCVT()) ||
13554       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13555     SDValue Src = Op.getOperand(0).getOperand(0);
13556     if (Src.getValueType() == MVT::f32) {
13557       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13558       DCI.AddToWorklist(Src.getNode());
13559     } else if (Src.getValueType() != MVT::f64) {
13560       // Make sure that we don't pick up a ppc_fp128 source value.
13561       return SDValue();
13562     }
13563 
13564     unsigned FCTOp =
13565       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13566                                                         PPCISD::FCTIDUZ;
13567 
13568     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13569     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13570 
13571     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13572       FP = DAG.getNode(ISD::FP_ROUND, dl,
13573                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13574       DCI.AddToWorklist(FP.getNode());
13575     }
13576 
13577     return FP;
13578   }
13579 
13580   return SDValue();
13581 }
13582 
13583 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13584 // builtins) into loads with swaps.
13585 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13586                                               DAGCombinerInfo &DCI) const {
13587   SelectionDAG &DAG = DCI.DAG;
13588   SDLoc dl(N);
13589   SDValue Chain;
13590   SDValue Base;
13591   MachineMemOperand *MMO;
13592 
13593   switch (N->getOpcode()) {
13594   default:
13595     llvm_unreachable("Unexpected opcode for little endian VSX load");
13596   case ISD::LOAD: {
13597     LoadSDNode *LD = cast<LoadSDNode>(N);
13598     Chain = LD->getChain();
13599     Base = LD->getBasePtr();
13600     MMO = LD->getMemOperand();
13601     // If the MMO suggests this isn't a load of a full vector, leave
13602     // things alone.  For a built-in, we have to make the change for
13603     // correctness, so if there is a size problem that will be a bug.
13604     if (MMO->getSize() < 16)
13605       return SDValue();
13606     break;
13607   }
13608   case ISD::INTRINSIC_W_CHAIN: {
13609     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13610     Chain = Intrin->getChain();
13611     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13612     // us what we want. Get operand 2 instead.
13613     Base = Intrin->getOperand(2);
13614     MMO = Intrin->getMemOperand();
13615     break;
13616   }
13617   }
13618 
13619   MVT VecTy = N->getValueType(0).getSimpleVT();
13620 
13621   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13622   // aligned and the type is a vector with elements up to 4 bytes
13623   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13624       VecTy.getScalarSizeInBits() <= 32) {
13625     return SDValue();
13626   }
13627 
13628   SDValue LoadOps[] = { Chain, Base };
13629   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13630                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13631                                          LoadOps, MVT::v2f64, MMO);
13632 
13633   DCI.AddToWorklist(Load.getNode());
13634   Chain = Load.getValue(1);
13635   SDValue Swap = DAG.getNode(
13636       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13637   DCI.AddToWorklist(Swap.getNode());
13638 
13639   // Add a bitcast if the resulting load type doesn't match v2f64.
13640   if (VecTy != MVT::v2f64) {
13641     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13642     DCI.AddToWorklist(N.getNode());
13643     // Package {bitcast value, swap's chain} to match Load's shape.
13644     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13645                        N, Swap.getValue(1));
13646   }
13647 
13648   return Swap;
13649 }
13650 
13651 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13652 // builtins) into stores with swaps.
13653 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13654                                                DAGCombinerInfo &DCI) const {
13655   SelectionDAG &DAG = DCI.DAG;
13656   SDLoc dl(N);
13657   SDValue Chain;
13658   SDValue Base;
13659   unsigned SrcOpnd;
13660   MachineMemOperand *MMO;
13661 
13662   switch (N->getOpcode()) {
13663   default:
13664     llvm_unreachable("Unexpected opcode for little endian VSX store");
13665   case ISD::STORE: {
13666     StoreSDNode *ST = cast<StoreSDNode>(N);
13667     Chain = ST->getChain();
13668     Base = ST->getBasePtr();
13669     MMO = ST->getMemOperand();
13670     SrcOpnd = 1;
13671     // If the MMO suggests this isn't a store of a full vector, leave
13672     // things alone.  For a built-in, we have to make the change for
13673     // correctness, so if there is a size problem that will be a bug.
13674     if (MMO->getSize() < 16)
13675       return SDValue();
13676     break;
13677   }
13678   case ISD::INTRINSIC_VOID: {
13679     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13680     Chain = Intrin->getChain();
13681     // Intrin->getBasePtr() oddly does not get what we want.
13682     Base = Intrin->getOperand(3);
13683     MMO = Intrin->getMemOperand();
13684     SrcOpnd = 2;
13685     break;
13686   }
13687   }
13688 
13689   SDValue Src = N->getOperand(SrcOpnd);
13690   MVT VecTy = Src.getValueType().getSimpleVT();
13691 
13692   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13693   // aligned and the type is a vector with elements up to 4 bytes
13694   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13695       VecTy.getScalarSizeInBits() <= 32) {
13696     return SDValue();
13697   }
13698 
13699   // All stores are done as v2f64 and possible bit cast.
13700   if (VecTy != MVT::v2f64) {
13701     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13702     DCI.AddToWorklist(Src.getNode());
13703   }
13704 
13705   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13706                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13707   DCI.AddToWorklist(Swap.getNode());
13708   Chain = Swap.getValue(1);
13709   SDValue StoreOps[] = { Chain, Swap, Base };
13710   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13711                                           DAG.getVTList(MVT::Other),
13712                                           StoreOps, VecTy, MMO);
13713   DCI.AddToWorklist(Store.getNode());
13714   return Store;
13715 }
13716 
13717 // Handle DAG combine for STORE (FP_TO_INT F).
13718 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13719                                                DAGCombinerInfo &DCI) const {
13720 
13721   SelectionDAG &DAG = DCI.DAG;
13722   SDLoc dl(N);
13723   unsigned Opcode = N->getOperand(1).getOpcode();
13724 
13725   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13726          && "Not a FP_TO_INT Instruction!");
13727 
13728   SDValue Val = N->getOperand(1).getOperand(0);
13729   EVT Op1VT = N->getOperand(1).getValueType();
13730   EVT ResVT = Val.getValueType();
13731 
13732   // Floating point types smaller than 32 bits are not legal on Power.
13733   if (ResVT.getScalarSizeInBits() < 32)
13734     return SDValue();
13735 
13736   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13737   bool ValidTypeForStoreFltAsInt =
13738         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13739          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13740 
13741   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13742       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13743     return SDValue();
13744 
13745   // Extend f32 values to f64
13746   if (ResVT.getScalarSizeInBits() == 32) {
13747     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13748     DCI.AddToWorklist(Val.getNode());
13749   }
13750 
13751   // Set signed or unsigned conversion opcode.
13752   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13753                           PPCISD::FP_TO_SINT_IN_VSR :
13754                           PPCISD::FP_TO_UINT_IN_VSR;
13755 
13756   Val = DAG.getNode(ConvOpcode,
13757                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13758   DCI.AddToWorklist(Val.getNode());
13759 
13760   // Set number of bytes being converted.
13761   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13762   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13763                     DAG.getIntPtrConstant(ByteSize, dl, false),
13764                     DAG.getValueType(Op1VT) };
13765 
13766   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13767           DAG.getVTList(MVT::Other), Ops,
13768           cast<StoreSDNode>(N)->getMemoryVT(),
13769           cast<StoreSDNode>(N)->getMemOperand());
13770 
13771   DCI.AddToWorklist(Val.getNode());
13772   return Val;
13773 }
13774 
13775 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13776   // Check that the source of the element keeps flipping
13777   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
13778   bool PrevElemFromFirstVec = Mask[0] < NumElts;
13779   for (int i = 1, e = Mask.size(); i < e; i++) {
13780     if (PrevElemFromFirstVec && Mask[i] < NumElts)
13781       return false;
13782     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
13783       return false;
13784     PrevElemFromFirstVec = !PrevElemFromFirstVec;
13785   }
13786   return true;
13787 }
13788 
13789 static bool isSplatBV(SDValue Op) {
13790   if (Op.getOpcode() != ISD::BUILD_VECTOR)
13791     return false;
13792   SDValue FirstOp;
13793 
13794   // Find first non-undef input.
13795   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
13796     FirstOp = Op.getOperand(i);
13797     if (!FirstOp.isUndef())
13798       break;
13799   }
13800 
13801   // All inputs are undef or the same as the first non-undef input.
13802   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
13803     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
13804       return false;
13805   return true;
13806 }
13807 
13808 static SDValue isScalarToVec(SDValue Op) {
13809   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13810     return Op;
13811   if (Op.getOpcode() != ISD::BITCAST)
13812     return SDValue();
13813   Op = Op.getOperand(0);
13814   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13815     return Op;
13816   return SDValue();
13817 }
13818 
13819 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
13820                                             int LHSMaxIdx, int RHSMinIdx,
13821                                             int RHSMaxIdx, int HalfVec) {
13822   for (int i = 0, e = ShuffV.size(); i < e; i++) {
13823     int Idx = ShuffV[i];
13824     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
13825       ShuffV[i] += HalfVec;
13826   }
13827   return;
13828 }
13829 
13830 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
13831 // the original is:
13832 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
13833 // In such a case, just change the shuffle mask to extract the element
13834 // from the permuted index.
13835 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
13836   SDLoc dl(OrigSToV);
13837   EVT VT = OrigSToV.getValueType();
13838   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13839          "Expecting a SCALAR_TO_VECTOR here");
13840   SDValue Input = OrigSToV.getOperand(0);
13841 
13842   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13843     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
13844     SDValue OrigVector = Input.getOperand(0);
13845 
13846     // Can't handle non-const element indices or different vector types
13847     // for the input to the extract and the output of the scalar_to_vector.
13848     if (Idx && VT == OrigVector.getValueType()) {
13849       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
13850       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
13851       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
13852     }
13853   }
13854   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
13855                      OrigSToV.getOperand(0));
13856 }
13857 
13858 // On little endian subtargets, combine shuffles such as:
13859 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
13860 // into:
13861 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
13862 // because the latter can be matched to a single instruction merge.
13863 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
13864 // to put the value into element zero. Adjust the shuffle mask so that the
13865 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
13866 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
13867                                                 SelectionDAG &DAG) const {
13868   SDValue LHS = SVN->getOperand(0);
13869   SDValue RHS = SVN->getOperand(1);
13870   auto Mask = SVN->getMask();
13871   int NumElts = LHS.getValueType().getVectorNumElements();
13872   SDValue Res(SVN, 0);
13873   SDLoc dl(SVN);
13874 
13875   // None of these combines are useful on big endian systems since the ISA
13876   // already has a big endian bias.
13877   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13878     return Res;
13879 
13880   // If this is not a shuffle of a shuffle and the first element comes from
13881   // the second vector, canonicalize to the commuted form. This will make it
13882   // more likely to match one of the single instruction patterns.
13883   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13884       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
13885     std::swap(LHS, RHS);
13886     Res = DAG.getCommutedVectorShuffle(*SVN);
13887     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13888   }
13889 
13890   // Adjust the shuffle mask if either input vector comes from a
13891   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
13892   // form (to prevent the need for a swap).
13893   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
13894   SDValue SToVLHS = isScalarToVec(LHS);
13895   SDValue SToVRHS = isScalarToVec(RHS);
13896   if (SToVLHS || SToVRHS) {
13897     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
13898                             : SToVRHS.getValueType().getVectorNumElements();
13899     int NumEltsOut = ShuffV.size();
13900 
13901     // Initially assume that neither input is permuted. These will be adjusted
13902     // accordingly if either input is.
13903     int LHSMaxIdx = -1;
13904     int RHSMinIdx = -1;
13905     int RHSMaxIdx = -1;
13906     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
13907 
13908     // Get the permuted scalar to vector nodes for the source(s) that come from
13909     // ISD::SCALAR_TO_VECTOR.
13910     if (SToVLHS) {
13911       // Set up the values for the shuffle vector fixup.
13912       LHSMaxIdx = NumEltsOut / NumEltsIn;
13913       SToVLHS = getSToVPermuted(SToVLHS, DAG);
13914       if (SToVLHS.getValueType() != LHS.getValueType())
13915         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
13916       LHS = SToVLHS;
13917     }
13918     if (SToVRHS) {
13919       RHSMinIdx = NumEltsOut;
13920       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
13921       SToVRHS = getSToVPermuted(SToVRHS, DAG);
13922       if (SToVRHS.getValueType() != RHS.getValueType())
13923         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
13924       RHS = SToVRHS;
13925     }
13926 
13927     // Fix up the shuffle mask to reflect where the desired element actually is.
13928     // The minimum and maximum indices that correspond to element zero for both
13929     // the LHS and RHS are computed and will control which shuffle mask entries
13930     // are to be changed. For example, if the RHS is permuted, any shuffle mask
13931     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
13932     // HalfVec to refer to the corresponding element in the permuted vector.
13933     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
13934                                     HalfVec);
13935     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
13936 
13937     // We may have simplified away the shuffle. We won't be able to do anything
13938     // further with it here.
13939     if (!isa<ShuffleVectorSDNode>(Res))
13940       return Res;
13941     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13942   }
13943 
13944   // The common case after we commuted the shuffle is that the RHS is a splat
13945   // and we have elements coming in from the splat at indices that are not
13946   // conducive to using a merge.
13947   // Example:
13948   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
13949   if (!isSplatBV(RHS))
13950     return Res;
13951 
13952   // We are looking for a mask such that all even elements are from
13953   // one vector and all odd elements from the other.
13954   if (!isAlternatingShuffMask(Mask, NumElts))
13955     return Res;
13956 
13957   // Adjust the mask so we are pulling in the same index from the splat
13958   // as the index from the interesting vector in consecutive elements.
13959   // Example (even elements from first vector):
13960   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
13961   if (Mask[0] < NumElts)
13962     for (int i = 1, e = Mask.size(); i < e; i += 2)
13963       ShuffV[i] = (ShuffV[i - 1] + NumElts);
13964   // Example (odd elements from first vector):
13965   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
13966   else
13967     for (int i = 0, e = Mask.size(); i < e; i += 2)
13968       ShuffV[i] = (ShuffV[i + 1] + NumElts);
13969 
13970   // If the RHS has undefs, we need to remove them since we may have created
13971   // a shuffle that adds those instead of the splat value.
13972   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
13973   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
13974 
13975   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
13976   return Res;
13977 }
13978 
13979 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13980                                                 LSBaseSDNode *LSBase,
13981                                                 DAGCombinerInfo &DCI) const {
13982   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13983         "Not a reverse memop pattern!");
13984 
13985   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13986     auto Mask = SVN->getMask();
13987     int i = 0;
13988     auto I = Mask.rbegin();
13989     auto E = Mask.rend();
13990 
13991     for (; I != E; ++I) {
13992       if (*I != i)
13993         return false;
13994       i++;
13995     }
13996     return true;
13997   };
13998 
13999   SelectionDAG &DAG = DCI.DAG;
14000   EVT VT = SVN->getValueType(0);
14001 
14002   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14003     return SDValue();
14004 
14005   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14006   // See comment in PPCVSXSwapRemoval.cpp.
14007   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14008   if (!Subtarget.hasP9Vector())
14009     return SDValue();
14010 
14011   if(!IsElementReverse(SVN))
14012     return SDValue();
14013 
14014   if (LSBase->getOpcode() == ISD::LOAD) {
14015     SDLoc dl(SVN);
14016     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14017     return DAG.getMemIntrinsicNode(
14018         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14019         LSBase->getMemoryVT(), LSBase->getMemOperand());
14020   }
14021 
14022   if (LSBase->getOpcode() == ISD::STORE) {
14023     SDLoc dl(LSBase);
14024     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14025                           LSBase->getBasePtr()};
14026     return DAG.getMemIntrinsicNode(
14027         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14028         LSBase->getMemoryVT(), LSBase->getMemOperand());
14029   }
14030 
14031   llvm_unreachable("Expected a load or store node here");
14032 }
14033 
14034 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14035                                              DAGCombinerInfo &DCI) const {
14036   SelectionDAG &DAG = DCI.DAG;
14037   SDLoc dl(N);
14038   switch (N->getOpcode()) {
14039   default: break;
14040   case ISD::ADD:
14041     return combineADD(N, DCI);
14042   case ISD::SHL:
14043     return combineSHL(N, DCI);
14044   case ISD::SRA:
14045     return combineSRA(N, DCI);
14046   case ISD::SRL:
14047     return combineSRL(N, DCI);
14048   case ISD::MUL:
14049     return combineMUL(N, DCI);
14050   case ISD::FMA:
14051   case PPCISD::FNMSUB:
14052     return combineFMALike(N, DCI);
14053   case PPCISD::SHL:
14054     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14055         return N->getOperand(0);
14056     break;
14057   case PPCISD::SRL:
14058     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14059         return N->getOperand(0);
14060     break;
14061   case PPCISD::SRA:
14062     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14063       if (C->isNullValue() ||   //  0 >>s V -> 0.
14064           C->isAllOnesValue())    // -1 >>s V -> -1.
14065         return N->getOperand(0);
14066     }
14067     break;
14068   case ISD::SIGN_EXTEND:
14069   case ISD::ZERO_EXTEND:
14070   case ISD::ANY_EXTEND:
14071     return DAGCombineExtBoolTrunc(N, DCI);
14072   case ISD::TRUNCATE:
14073     return combineTRUNCATE(N, DCI);
14074   case ISD::SETCC:
14075     if (SDValue CSCC = combineSetCC(N, DCI))
14076       return CSCC;
14077     LLVM_FALLTHROUGH;
14078   case ISD::SELECT_CC:
14079     return DAGCombineTruncBoolExt(N, DCI);
14080   case ISD::SINT_TO_FP:
14081   case ISD::UINT_TO_FP:
14082     return combineFPToIntToFP(N, DCI);
14083   case ISD::VECTOR_SHUFFLE:
14084     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14085       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14086       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14087     }
14088     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14089   case ISD::STORE: {
14090 
14091     EVT Op1VT = N->getOperand(1).getValueType();
14092     unsigned Opcode = N->getOperand(1).getOpcode();
14093 
14094     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14095       SDValue Val= combineStoreFPToInt(N, DCI);
14096       if (Val)
14097         return Val;
14098     }
14099 
14100     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14101       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14102       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14103       if (Val)
14104         return Val;
14105     }
14106 
14107     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14108     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14109         N->getOperand(1).getNode()->hasOneUse() &&
14110         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14111          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14112 
14113       // STBRX can only handle simple types and it makes no sense to store less
14114       // two bytes in byte-reversed order.
14115       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14116       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14117         break;
14118 
14119       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14120       // Do an any-extend to 32-bits if this is a half-word input.
14121       if (BSwapOp.getValueType() == MVT::i16)
14122         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14123 
14124       // If the type of BSWAP operand is wider than stored memory width
14125       // it need to be shifted to the right side before STBRX.
14126       if (Op1VT.bitsGT(mVT)) {
14127         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14128         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14129                               DAG.getConstant(Shift, dl, MVT::i32));
14130         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14131         if (Op1VT == MVT::i64)
14132           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14133       }
14134 
14135       SDValue Ops[] = {
14136         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14137       };
14138       return
14139         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14140                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14141                                 cast<StoreSDNode>(N)->getMemOperand());
14142     }
14143 
14144     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14145     // So it can increase the chance of CSE constant construction.
14146     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14147         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14148       // Need to sign-extended to 64-bits to handle negative values.
14149       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14150       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14151                                     MemVT.getSizeInBits());
14152       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14153 
14154       // DAG.getTruncStore() can't be used here because it doesn't accept
14155       // the general (base + offset) addressing mode.
14156       // So we use UpdateNodeOperands and setTruncatingStore instead.
14157       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14158                              N->getOperand(3));
14159       cast<StoreSDNode>(N)->setTruncatingStore(true);
14160       return SDValue(N, 0);
14161     }
14162 
14163     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14164     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14165     if (Op1VT.isSimple()) {
14166       MVT StoreVT = Op1VT.getSimpleVT();
14167       if (Subtarget.needsSwapsForVSXMemOps() &&
14168           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14169            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14170         return expandVSXStoreForLE(N, DCI);
14171     }
14172     break;
14173   }
14174   case ISD::LOAD: {
14175     LoadSDNode *LD = cast<LoadSDNode>(N);
14176     EVT VT = LD->getValueType(0);
14177 
14178     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14179     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14180     if (VT.isSimple()) {
14181       MVT LoadVT = VT.getSimpleVT();
14182       if (Subtarget.needsSwapsForVSXMemOps() &&
14183           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14184            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14185         return expandVSXLoadForLE(N, DCI);
14186     }
14187 
14188     // We sometimes end up with a 64-bit integer load, from which we extract
14189     // two single-precision floating-point numbers. This happens with
14190     // std::complex<float>, and other similar structures, because of the way we
14191     // canonicalize structure copies. However, if we lack direct moves,
14192     // then the final bitcasts from the extracted integer values to the
14193     // floating-point numbers turn into store/load pairs. Even with direct moves,
14194     // just loading the two floating-point numbers is likely better.
14195     auto ReplaceTwoFloatLoad = [&]() {
14196       if (VT != MVT::i64)
14197         return false;
14198 
14199       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14200           LD->isVolatile())
14201         return false;
14202 
14203       //  We're looking for a sequence like this:
14204       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14205       //      t16: i64 = srl t13, Constant:i32<32>
14206       //    t17: i32 = truncate t16
14207       //  t18: f32 = bitcast t17
14208       //    t19: i32 = truncate t13
14209       //  t20: f32 = bitcast t19
14210 
14211       if (!LD->hasNUsesOfValue(2, 0))
14212         return false;
14213 
14214       auto UI = LD->use_begin();
14215       while (UI.getUse().getResNo() != 0) ++UI;
14216       SDNode *Trunc = *UI++;
14217       while (UI.getUse().getResNo() != 0) ++UI;
14218       SDNode *RightShift = *UI;
14219       if (Trunc->getOpcode() != ISD::TRUNCATE)
14220         std::swap(Trunc, RightShift);
14221 
14222       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14223           Trunc->getValueType(0) != MVT::i32 ||
14224           !Trunc->hasOneUse())
14225         return false;
14226       if (RightShift->getOpcode() != ISD::SRL ||
14227           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14228           RightShift->getConstantOperandVal(1) != 32 ||
14229           !RightShift->hasOneUse())
14230         return false;
14231 
14232       SDNode *Trunc2 = *RightShift->use_begin();
14233       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14234           Trunc2->getValueType(0) != MVT::i32 ||
14235           !Trunc2->hasOneUse())
14236         return false;
14237 
14238       SDNode *Bitcast = *Trunc->use_begin();
14239       SDNode *Bitcast2 = *Trunc2->use_begin();
14240 
14241       if (Bitcast->getOpcode() != ISD::BITCAST ||
14242           Bitcast->getValueType(0) != MVT::f32)
14243         return false;
14244       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14245           Bitcast2->getValueType(0) != MVT::f32)
14246         return false;
14247 
14248       if (Subtarget.isLittleEndian())
14249         std::swap(Bitcast, Bitcast2);
14250 
14251       // Bitcast has the second float (in memory-layout order) and Bitcast2
14252       // has the first one.
14253 
14254       SDValue BasePtr = LD->getBasePtr();
14255       if (LD->isIndexed()) {
14256         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14257                "Non-pre-inc AM on PPC?");
14258         BasePtr =
14259           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14260                       LD->getOffset());
14261       }
14262 
14263       auto MMOFlags =
14264           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14265       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14266                                       LD->getPointerInfo(), LD->getAlignment(),
14267                                       MMOFlags, LD->getAAInfo());
14268       SDValue AddPtr =
14269         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14270                     BasePtr, DAG.getIntPtrConstant(4, dl));
14271       SDValue FloatLoad2 = DAG.getLoad(
14272           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14273           LD->getPointerInfo().getWithOffset(4),
14274           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14275 
14276       if (LD->isIndexed()) {
14277         // Note that DAGCombine should re-form any pre-increment load(s) from
14278         // what is produced here if that makes sense.
14279         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14280       }
14281 
14282       DCI.CombineTo(Bitcast2, FloatLoad);
14283       DCI.CombineTo(Bitcast, FloatLoad2);
14284 
14285       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14286                                     SDValue(FloatLoad2.getNode(), 1));
14287       return true;
14288     };
14289 
14290     if (ReplaceTwoFloatLoad())
14291       return SDValue(N, 0);
14292 
14293     EVT MemVT = LD->getMemoryVT();
14294     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14295     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14296     if (LD->isUnindexed() && VT.isVector() &&
14297         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14298           // P8 and later hardware should just use LOAD.
14299           !Subtarget.hasP8Vector() &&
14300           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14301            VT == MVT::v4f32))) &&
14302         LD->getAlign() < ABIAlignment) {
14303       // This is a type-legal unaligned Altivec load.
14304       SDValue Chain = LD->getChain();
14305       SDValue Ptr = LD->getBasePtr();
14306       bool isLittleEndian = Subtarget.isLittleEndian();
14307 
14308       // This implements the loading of unaligned vectors as described in
14309       // the venerable Apple Velocity Engine overview. Specifically:
14310       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14311       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14312       //
14313       // The general idea is to expand a sequence of one or more unaligned
14314       // loads into an alignment-based permutation-control instruction (lvsl
14315       // or lvsr), a series of regular vector loads (which always truncate
14316       // their input address to an aligned address), and a series of
14317       // permutations.  The results of these permutations are the requested
14318       // loaded values.  The trick is that the last "extra" load is not taken
14319       // from the address you might suspect (sizeof(vector) bytes after the
14320       // last requested load), but rather sizeof(vector) - 1 bytes after the
14321       // last requested vector. The point of this is to avoid a page fault if
14322       // the base address happened to be aligned. This works because if the
14323       // base address is aligned, then adding less than a full vector length
14324       // will cause the last vector in the sequence to be (re)loaded.
14325       // Otherwise, the next vector will be fetched as you might suspect was
14326       // necessary.
14327 
14328       // We might be able to reuse the permutation generation from
14329       // a different base address offset from this one by an aligned amount.
14330       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14331       // optimization later.
14332       Intrinsic::ID Intr, IntrLD, IntrPerm;
14333       MVT PermCntlTy, PermTy, LDTy;
14334       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14335                             : Intrinsic::ppc_altivec_lvsl;
14336       IntrLD = Intrinsic::ppc_altivec_lvx;
14337       IntrPerm = Intrinsic::ppc_altivec_vperm;
14338       PermCntlTy = MVT::v16i8;
14339       PermTy = MVT::v4i32;
14340       LDTy = MVT::v4i32;
14341 
14342       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14343 
14344       // Create the new MMO for the new base load. It is like the original MMO,
14345       // but represents an area in memory almost twice the vector size centered
14346       // on the original address. If the address is unaligned, we might start
14347       // reading up to (sizeof(vector)-1) bytes below the address of the
14348       // original unaligned load.
14349       MachineFunction &MF = DAG.getMachineFunction();
14350       MachineMemOperand *BaseMMO =
14351         MF.getMachineMemOperand(LD->getMemOperand(),
14352                                 -(long)MemVT.getStoreSize()+1,
14353                                 2*MemVT.getStoreSize()-1);
14354 
14355       // Create the new base load.
14356       SDValue LDXIntID =
14357           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14358       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14359       SDValue BaseLoad =
14360         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14361                                 DAG.getVTList(PermTy, MVT::Other),
14362                                 BaseLoadOps, LDTy, BaseMMO);
14363 
14364       // Note that the value of IncOffset (which is provided to the next
14365       // load's pointer info offset value, and thus used to calculate the
14366       // alignment), and the value of IncValue (which is actually used to
14367       // increment the pointer value) are different! This is because we
14368       // require the next load to appear to be aligned, even though it
14369       // is actually offset from the base pointer by a lesser amount.
14370       int IncOffset = VT.getSizeInBits() / 8;
14371       int IncValue = IncOffset;
14372 
14373       // Walk (both up and down) the chain looking for another load at the real
14374       // (aligned) offset (the alignment of the other load does not matter in
14375       // this case). If found, then do not use the offset reduction trick, as
14376       // that will prevent the loads from being later combined (as they would
14377       // otherwise be duplicates).
14378       if (!findConsecutiveLoad(LD, DAG))
14379         --IncValue;
14380 
14381       SDValue Increment =
14382           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14383       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14384 
14385       MachineMemOperand *ExtraMMO =
14386         MF.getMachineMemOperand(LD->getMemOperand(),
14387                                 1, 2*MemVT.getStoreSize()-1);
14388       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14389       SDValue ExtraLoad =
14390         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14391                                 DAG.getVTList(PermTy, MVT::Other),
14392                                 ExtraLoadOps, LDTy, ExtraMMO);
14393 
14394       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14395         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14396 
14397       // Because vperm has a big-endian bias, we must reverse the order
14398       // of the input vectors and complement the permute control vector
14399       // when generating little endian code.  We have already handled the
14400       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14401       // and ExtraLoad here.
14402       SDValue Perm;
14403       if (isLittleEndian)
14404         Perm = BuildIntrinsicOp(IntrPerm,
14405                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14406       else
14407         Perm = BuildIntrinsicOp(IntrPerm,
14408                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14409 
14410       if (VT != PermTy)
14411         Perm = Subtarget.hasAltivec()
14412                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14413                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14414                                  DAG.getTargetConstant(1, dl, MVT::i64));
14415                                // second argument is 1 because this rounding
14416                                // is always exact.
14417 
14418       // The output of the permutation is our loaded result, the TokenFactor is
14419       // our new chain.
14420       DCI.CombineTo(N, Perm, TF);
14421       return SDValue(N, 0);
14422     }
14423     }
14424     break;
14425     case ISD::INTRINSIC_WO_CHAIN: {
14426       bool isLittleEndian = Subtarget.isLittleEndian();
14427       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14428       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14429                                            : Intrinsic::ppc_altivec_lvsl);
14430       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14431         SDValue Add = N->getOperand(1);
14432 
14433         int Bits = 4 /* 16 byte alignment */;
14434 
14435         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14436                                   APInt::getAllOnesValue(Bits /* alignment */)
14437                                       .zext(Add.getScalarValueSizeInBits()))) {
14438           SDNode *BasePtr = Add->getOperand(0).getNode();
14439           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14440                                     UE = BasePtr->use_end();
14441                UI != UE; ++UI) {
14442             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14443                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14444                     IID) {
14445               // We've found another LVSL/LVSR, and this address is an aligned
14446               // multiple of that one. The results will be the same, so use the
14447               // one we've just found instead.
14448 
14449               return SDValue(*UI, 0);
14450             }
14451           }
14452         }
14453 
14454         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14455           SDNode *BasePtr = Add->getOperand(0).getNode();
14456           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14457                UE = BasePtr->use_end(); UI != UE; ++UI) {
14458             if (UI->getOpcode() == ISD::ADD &&
14459                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14460                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14461                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14462                 (1ULL << Bits) == 0) {
14463               SDNode *OtherAdd = *UI;
14464               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14465                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14466                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14467                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14468                   return SDValue(*VI, 0);
14469                 }
14470               }
14471             }
14472           }
14473         }
14474       }
14475 
14476       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14477       // Expose the vabsduw/h/b opportunity for down stream
14478       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14479           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14480            IID == Intrinsic::ppc_altivec_vmaxsh ||
14481            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14482         SDValue V1 = N->getOperand(1);
14483         SDValue V2 = N->getOperand(2);
14484         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14485              V1.getSimpleValueType() == MVT::v8i16 ||
14486              V1.getSimpleValueType() == MVT::v16i8) &&
14487             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14488           // (0-a, a)
14489           if (V1.getOpcode() == ISD::SUB &&
14490               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14491               V1.getOperand(1) == V2) {
14492             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14493           }
14494           // (a, 0-a)
14495           if (V2.getOpcode() == ISD::SUB &&
14496               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14497               V2.getOperand(1) == V1) {
14498             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14499           }
14500           // (x-y, y-x)
14501           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14502               V1.getOperand(0) == V2.getOperand(1) &&
14503               V1.getOperand(1) == V2.getOperand(0)) {
14504             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14505           }
14506         }
14507       }
14508     }
14509 
14510     break;
14511   case ISD::INTRINSIC_W_CHAIN:
14512     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14513     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14514     if (Subtarget.needsSwapsForVSXMemOps()) {
14515       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14516       default:
14517         break;
14518       case Intrinsic::ppc_vsx_lxvw4x:
14519       case Intrinsic::ppc_vsx_lxvd2x:
14520         return expandVSXLoadForLE(N, DCI);
14521       }
14522     }
14523     break;
14524   case ISD::INTRINSIC_VOID:
14525     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14526     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14527     if (Subtarget.needsSwapsForVSXMemOps()) {
14528       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14529       default:
14530         break;
14531       case Intrinsic::ppc_vsx_stxvw4x:
14532       case Intrinsic::ppc_vsx_stxvd2x:
14533         return expandVSXStoreForLE(N, DCI);
14534       }
14535     }
14536     break;
14537   case ISD::BSWAP:
14538     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14539     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14540         N->getOperand(0).hasOneUse() &&
14541         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14542          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14543           N->getValueType(0) == MVT::i64))) {
14544       SDValue Load = N->getOperand(0);
14545       LoadSDNode *LD = cast<LoadSDNode>(Load);
14546       // Create the byte-swapping load.
14547       SDValue Ops[] = {
14548         LD->getChain(),    // Chain
14549         LD->getBasePtr(),  // Ptr
14550         DAG.getValueType(N->getValueType(0)) // VT
14551       };
14552       SDValue BSLoad =
14553         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14554                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14555                                               MVT::i64 : MVT::i32, MVT::Other),
14556                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14557 
14558       // If this is an i16 load, insert the truncate.
14559       SDValue ResVal = BSLoad;
14560       if (N->getValueType(0) == MVT::i16)
14561         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14562 
14563       // First, combine the bswap away.  This makes the value produced by the
14564       // load dead.
14565       DCI.CombineTo(N, ResVal);
14566 
14567       // Next, combine the load away, we give it a bogus result value but a real
14568       // chain result.  The result value is dead because the bswap is dead.
14569       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14570 
14571       // Return N so it doesn't get rechecked!
14572       return SDValue(N, 0);
14573     }
14574     break;
14575   case PPCISD::VCMP:
14576     // If a VCMPo node already exists with exactly the same operands as this
14577     // node, use its result instead of this node (VCMPo computes both a CR6 and
14578     // a normal output).
14579     //
14580     if (!N->getOperand(0).hasOneUse() &&
14581         !N->getOperand(1).hasOneUse() &&
14582         !N->getOperand(2).hasOneUse()) {
14583 
14584       // Scan all of the users of the LHS, looking for VCMPo's that match.
14585       SDNode *VCMPoNode = nullptr;
14586 
14587       SDNode *LHSN = N->getOperand(0).getNode();
14588       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14589            UI != E; ++UI)
14590         if (UI->getOpcode() == PPCISD::VCMPo &&
14591             UI->getOperand(1) == N->getOperand(1) &&
14592             UI->getOperand(2) == N->getOperand(2) &&
14593             UI->getOperand(0) == N->getOperand(0)) {
14594           VCMPoNode = *UI;
14595           break;
14596         }
14597 
14598       // If there is no VCMPo node, or if the flag value has a single use, don't
14599       // transform this.
14600       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14601         break;
14602 
14603       // Look at the (necessarily single) use of the flag value.  If it has a
14604       // chain, this transformation is more complex.  Note that multiple things
14605       // could use the value result, which we should ignore.
14606       SDNode *FlagUser = nullptr;
14607       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14608            FlagUser == nullptr; ++UI) {
14609         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14610         SDNode *User = *UI;
14611         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14612           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14613             FlagUser = User;
14614             break;
14615           }
14616         }
14617       }
14618 
14619       // If the user is a MFOCRF instruction, we know this is safe.
14620       // Otherwise we give up for right now.
14621       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14622         return SDValue(VCMPoNode, 0);
14623     }
14624     break;
14625   case ISD::BRCOND: {
14626     SDValue Cond = N->getOperand(1);
14627     SDValue Target = N->getOperand(2);
14628 
14629     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14630         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14631           Intrinsic::loop_decrement) {
14632 
14633       // We now need to make the intrinsic dead (it cannot be instruction
14634       // selected).
14635       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14636       assert(Cond.getNode()->hasOneUse() &&
14637              "Counter decrement has more than one use");
14638 
14639       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14640                          N->getOperand(0), Target);
14641     }
14642   }
14643   break;
14644   case ISD::BR_CC: {
14645     // If this is a branch on an altivec predicate comparison, lower this so
14646     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14647     // lowering is done pre-legalize, because the legalizer lowers the predicate
14648     // compare down to code that is difficult to reassemble.
14649     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14650     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14651 
14652     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14653     // value. If so, pass-through the AND to get to the intrinsic.
14654     if (LHS.getOpcode() == ISD::AND &&
14655         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14656         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14657           Intrinsic::loop_decrement &&
14658         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14659         !isNullConstant(LHS.getOperand(1)))
14660       LHS = LHS.getOperand(0);
14661 
14662     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14663         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14664           Intrinsic::loop_decrement &&
14665         isa<ConstantSDNode>(RHS)) {
14666       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14667              "Counter decrement comparison is not EQ or NE");
14668 
14669       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14670       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14671                     (CC == ISD::SETNE && !Val);
14672 
14673       // We now need to make the intrinsic dead (it cannot be instruction
14674       // selected).
14675       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14676       assert(LHS.getNode()->hasOneUse() &&
14677              "Counter decrement has more than one use");
14678 
14679       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14680                          N->getOperand(0), N->getOperand(4));
14681     }
14682 
14683     int CompareOpc;
14684     bool isDot;
14685 
14686     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14687         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14688         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14689       assert(isDot && "Can't compare against a vector result!");
14690 
14691       // If this is a comparison against something other than 0/1, then we know
14692       // that the condition is never/always true.
14693       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14694       if (Val != 0 && Val != 1) {
14695         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14696           return N->getOperand(0);
14697         // Always !=, turn it into an unconditional branch.
14698         return DAG.getNode(ISD::BR, dl, MVT::Other,
14699                            N->getOperand(0), N->getOperand(4));
14700       }
14701 
14702       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14703 
14704       // Create the PPCISD altivec 'dot' comparison node.
14705       SDValue Ops[] = {
14706         LHS.getOperand(2),  // LHS of compare
14707         LHS.getOperand(3),  // RHS of compare
14708         DAG.getConstant(CompareOpc, dl, MVT::i32)
14709       };
14710       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14711       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14712 
14713       // Unpack the result based on how the target uses it.
14714       PPC::Predicate CompOpc;
14715       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14716       default:  // Can't happen, don't crash on invalid number though.
14717       case 0:   // Branch on the value of the EQ bit of CR6.
14718         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14719         break;
14720       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14721         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14722         break;
14723       case 2:   // Branch on the value of the LT bit of CR6.
14724         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14725         break;
14726       case 3:   // Branch on the inverted value of the LT bit of CR6.
14727         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14728         break;
14729       }
14730 
14731       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14732                          DAG.getConstant(CompOpc, dl, MVT::i32),
14733                          DAG.getRegister(PPC::CR6, MVT::i32),
14734                          N->getOperand(4), CompNode.getValue(1));
14735     }
14736     break;
14737   }
14738   case ISD::BUILD_VECTOR:
14739     return DAGCombineBuildVector(N, DCI);
14740   case ISD::ABS:
14741     return combineABS(N, DCI);
14742   case ISD::VSELECT:
14743     return combineVSelect(N, DCI);
14744   }
14745 
14746   return SDValue();
14747 }
14748 
14749 SDValue
14750 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14751                                  SelectionDAG &DAG,
14752                                  SmallVectorImpl<SDNode *> &Created) const {
14753   // fold (sdiv X, pow2)
14754   EVT VT = N->getValueType(0);
14755   if (VT == MVT::i64 && !Subtarget.isPPC64())
14756     return SDValue();
14757   if ((VT != MVT::i32 && VT != MVT::i64) ||
14758       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14759     return SDValue();
14760 
14761   SDLoc DL(N);
14762   SDValue N0 = N->getOperand(0);
14763 
14764   bool IsNegPow2 = (-Divisor).isPowerOf2();
14765   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14766   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14767 
14768   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14769   Created.push_back(Op.getNode());
14770 
14771   if (IsNegPow2) {
14772     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14773     Created.push_back(Op.getNode());
14774   }
14775 
14776   return Op;
14777 }
14778 
14779 //===----------------------------------------------------------------------===//
14780 // Inline Assembly Support
14781 //===----------------------------------------------------------------------===//
14782 
14783 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14784                                                       KnownBits &Known,
14785                                                       const APInt &DemandedElts,
14786                                                       const SelectionDAG &DAG,
14787                                                       unsigned Depth) const {
14788   Known.resetAll();
14789   switch (Op.getOpcode()) {
14790   default: break;
14791   case PPCISD::LBRX: {
14792     // lhbrx is known to have the top bits cleared out.
14793     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14794       Known.Zero = 0xFFFF0000;
14795     break;
14796   }
14797   case ISD::INTRINSIC_WO_CHAIN: {
14798     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14799     default: break;
14800     case Intrinsic::ppc_altivec_vcmpbfp_p:
14801     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14802     case Intrinsic::ppc_altivec_vcmpequb_p:
14803     case Intrinsic::ppc_altivec_vcmpequh_p:
14804     case Intrinsic::ppc_altivec_vcmpequw_p:
14805     case Intrinsic::ppc_altivec_vcmpequd_p:
14806     case Intrinsic::ppc_altivec_vcmpgefp_p:
14807     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14808     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14809     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14810     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14811     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14812     case Intrinsic::ppc_altivec_vcmpgtub_p:
14813     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14814     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14815     case Intrinsic::ppc_altivec_vcmpgtud_p:
14816       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14817       break;
14818     }
14819   }
14820   }
14821 }
14822 
14823 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14824   switch (Subtarget.getCPUDirective()) {
14825   default: break;
14826   case PPC::DIR_970:
14827   case PPC::DIR_PWR4:
14828   case PPC::DIR_PWR5:
14829   case PPC::DIR_PWR5X:
14830   case PPC::DIR_PWR6:
14831   case PPC::DIR_PWR6X:
14832   case PPC::DIR_PWR7:
14833   case PPC::DIR_PWR8:
14834   case PPC::DIR_PWR9:
14835   case PPC::DIR_PWR10:
14836   case PPC::DIR_PWR_FUTURE: {
14837     if (!ML)
14838       break;
14839 
14840     if (!DisableInnermostLoopAlign32) {
14841       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14842       // so that we can decrease cache misses and branch-prediction misses.
14843       // Actual alignment of the loop will depend on the hotness check and other
14844       // logic in alignBlocks.
14845       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14846         return Align(32);
14847     }
14848 
14849     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14850 
14851     // For small loops (between 5 and 8 instructions), align to a 32-byte
14852     // boundary so that the entire loop fits in one instruction-cache line.
14853     uint64_t LoopSize = 0;
14854     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14855       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14856         LoopSize += TII->getInstSizeInBytes(*J);
14857         if (LoopSize > 32)
14858           break;
14859       }
14860 
14861     if (LoopSize > 16 && LoopSize <= 32)
14862       return Align(32);
14863 
14864     break;
14865   }
14866   }
14867 
14868   return TargetLowering::getPrefLoopAlignment(ML);
14869 }
14870 
14871 /// getConstraintType - Given a constraint, return the type of
14872 /// constraint it is for this target.
14873 PPCTargetLowering::ConstraintType
14874 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14875   if (Constraint.size() == 1) {
14876     switch (Constraint[0]) {
14877     default: break;
14878     case 'b':
14879     case 'r':
14880     case 'f':
14881     case 'd':
14882     case 'v':
14883     case 'y':
14884       return C_RegisterClass;
14885     case 'Z':
14886       // FIXME: While Z does indicate a memory constraint, it specifically
14887       // indicates an r+r address (used in conjunction with the 'y' modifier
14888       // in the replacement string). Currently, we're forcing the base
14889       // register to be r0 in the asm printer (which is interpreted as zero)
14890       // and forming the complete address in the second register. This is
14891       // suboptimal.
14892       return C_Memory;
14893     }
14894   } else if (Constraint == "wc") { // individual CR bits.
14895     return C_RegisterClass;
14896   } else if (Constraint == "wa" || Constraint == "wd" ||
14897              Constraint == "wf" || Constraint == "ws" ||
14898              Constraint == "wi" || Constraint == "ww") {
14899     return C_RegisterClass; // VSX registers.
14900   }
14901   return TargetLowering::getConstraintType(Constraint);
14902 }
14903 
14904 /// Examine constraint type and operand type and determine a weight value.
14905 /// This object must already have been set up with the operand type
14906 /// and the current alternative constraint selected.
14907 TargetLowering::ConstraintWeight
14908 PPCTargetLowering::getSingleConstraintMatchWeight(
14909     AsmOperandInfo &info, const char *constraint) const {
14910   ConstraintWeight weight = CW_Invalid;
14911   Value *CallOperandVal = info.CallOperandVal;
14912     // If we don't have a value, we can't do a match,
14913     // but allow it at the lowest weight.
14914   if (!CallOperandVal)
14915     return CW_Default;
14916   Type *type = CallOperandVal->getType();
14917 
14918   // Look at the constraint type.
14919   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14920     return CW_Register; // an individual CR bit.
14921   else if ((StringRef(constraint) == "wa" ||
14922             StringRef(constraint) == "wd" ||
14923             StringRef(constraint) == "wf") &&
14924            type->isVectorTy())
14925     return CW_Register;
14926   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14927     return CW_Register; // just hold 64-bit integers data.
14928   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14929     return CW_Register;
14930   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14931     return CW_Register;
14932 
14933   switch (*constraint) {
14934   default:
14935     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14936     break;
14937   case 'b':
14938     if (type->isIntegerTy())
14939       weight = CW_Register;
14940     break;
14941   case 'f':
14942     if (type->isFloatTy())
14943       weight = CW_Register;
14944     break;
14945   case 'd':
14946     if (type->isDoubleTy())
14947       weight = CW_Register;
14948     break;
14949   case 'v':
14950     if (type->isVectorTy())
14951       weight = CW_Register;
14952     break;
14953   case 'y':
14954     weight = CW_Register;
14955     break;
14956   case 'Z':
14957     weight = CW_Memory;
14958     break;
14959   }
14960   return weight;
14961 }
14962 
14963 std::pair<unsigned, const TargetRegisterClass *>
14964 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14965                                                 StringRef Constraint,
14966                                                 MVT VT) const {
14967   if (Constraint.size() == 1) {
14968     // GCC RS6000 Constraint Letters
14969     switch (Constraint[0]) {
14970     case 'b':   // R1-R31
14971       if (VT == MVT::i64 && Subtarget.isPPC64())
14972         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14973       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14974     case 'r':   // R0-R31
14975       if (VT == MVT::i64 && Subtarget.isPPC64())
14976         return std::make_pair(0U, &PPC::G8RCRegClass);
14977       return std::make_pair(0U, &PPC::GPRCRegClass);
14978     // 'd' and 'f' constraints are both defined to be "the floating point
14979     // registers", where one is for 32-bit and the other for 64-bit. We don't
14980     // really care overly much here so just give them all the same reg classes.
14981     case 'd':
14982     case 'f':
14983       if (Subtarget.hasSPE()) {
14984         if (VT == MVT::f32 || VT == MVT::i32)
14985           return std::make_pair(0U, &PPC::GPRCRegClass);
14986         if (VT == MVT::f64 || VT == MVT::i64)
14987           return std::make_pair(0U, &PPC::SPERCRegClass);
14988       } else {
14989         if (VT == MVT::f32 || VT == MVT::i32)
14990           return std::make_pair(0U, &PPC::F4RCRegClass);
14991         if (VT == MVT::f64 || VT == MVT::i64)
14992           return std::make_pair(0U, &PPC::F8RCRegClass);
14993       }
14994       break;
14995     case 'v':
14996       if (Subtarget.hasAltivec())
14997         return std::make_pair(0U, &PPC::VRRCRegClass);
14998       break;
14999     case 'y':   // crrc
15000       return std::make_pair(0U, &PPC::CRRCRegClass);
15001     }
15002   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15003     // An individual CR bit.
15004     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15005   } else if ((Constraint == "wa" || Constraint == "wd" ||
15006              Constraint == "wf" || Constraint == "wi") &&
15007              Subtarget.hasVSX()) {
15008     return std::make_pair(0U, &PPC::VSRCRegClass);
15009   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15010     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15011       return std::make_pair(0U, &PPC::VSSRCRegClass);
15012     else
15013       return std::make_pair(0U, &PPC::VSFRCRegClass);
15014   }
15015 
15016   // If we name a VSX register, we can't defer to the base class because it
15017   // will not recognize the correct register (their names will be VSL{0-31}
15018   // and V{0-31} so they won't match). So we match them here.
15019   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15020     int VSNum = atoi(Constraint.data() + 3);
15021     assert(VSNum >= 0 && VSNum <= 63 &&
15022            "Attempted to access a vsr out of range");
15023     if (VSNum < 32)
15024       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15025     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15026   }
15027   std::pair<unsigned, const TargetRegisterClass *> R =
15028       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15029 
15030   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15031   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15032   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15033   // register.
15034   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15035   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15036   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15037       PPC::GPRCRegClass.contains(R.first))
15038     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15039                             PPC::sub_32, &PPC::G8RCRegClass),
15040                           &PPC::G8RCRegClass);
15041 
15042   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15043   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15044     R.first = PPC::CR0;
15045     R.second = &PPC::CRRCRegClass;
15046   }
15047 
15048   return R;
15049 }
15050 
15051 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15052 /// vector.  If it is invalid, don't add anything to Ops.
15053 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15054                                                      std::string &Constraint,
15055                                                      std::vector<SDValue>&Ops,
15056                                                      SelectionDAG &DAG) const {
15057   SDValue Result;
15058 
15059   // Only support length 1 constraints.
15060   if (Constraint.length() > 1) return;
15061 
15062   char Letter = Constraint[0];
15063   switch (Letter) {
15064   default: break;
15065   case 'I':
15066   case 'J':
15067   case 'K':
15068   case 'L':
15069   case 'M':
15070   case 'N':
15071   case 'O':
15072   case 'P': {
15073     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15074     if (!CST) return; // Must be an immediate to match.
15075     SDLoc dl(Op);
15076     int64_t Value = CST->getSExtValue();
15077     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15078                          // numbers are printed as such.
15079     switch (Letter) {
15080     default: llvm_unreachable("Unknown constraint letter!");
15081     case 'I':  // "I" is a signed 16-bit constant.
15082       if (isInt<16>(Value))
15083         Result = DAG.getTargetConstant(Value, dl, TCVT);
15084       break;
15085     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15086       if (isShiftedUInt<16, 16>(Value))
15087         Result = DAG.getTargetConstant(Value, dl, TCVT);
15088       break;
15089     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15090       if (isShiftedInt<16, 16>(Value))
15091         Result = DAG.getTargetConstant(Value, dl, TCVT);
15092       break;
15093     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15094       if (isUInt<16>(Value))
15095         Result = DAG.getTargetConstant(Value, dl, TCVT);
15096       break;
15097     case 'M':  // "M" is a constant that is greater than 31.
15098       if (Value > 31)
15099         Result = DAG.getTargetConstant(Value, dl, TCVT);
15100       break;
15101     case 'N':  // "N" is a positive constant that is an exact power of two.
15102       if (Value > 0 && isPowerOf2_64(Value))
15103         Result = DAG.getTargetConstant(Value, dl, TCVT);
15104       break;
15105     case 'O':  // "O" is the constant zero.
15106       if (Value == 0)
15107         Result = DAG.getTargetConstant(Value, dl, TCVT);
15108       break;
15109     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15110       if (isInt<16>(-Value))
15111         Result = DAG.getTargetConstant(Value, dl, TCVT);
15112       break;
15113     }
15114     break;
15115   }
15116   }
15117 
15118   if (Result.getNode()) {
15119     Ops.push_back(Result);
15120     return;
15121   }
15122 
15123   // Handle standard constraint letters.
15124   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15125 }
15126 
15127 // isLegalAddressingMode - Return true if the addressing mode represented
15128 // by AM is legal for this target, for a load/store of the specified type.
15129 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15130                                               const AddrMode &AM, Type *Ty,
15131                                               unsigned AS,
15132                                               Instruction *I) const {
15133   // Vector type r+i form is supported since power9 as DQ form. We don't check
15134   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15135   // imm form is preferred and the offset can be adjusted to use imm form later
15136   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15137   // max offset to check legal addressing mode, we should be a little aggressive
15138   // to contain other offsets for that LSRUse.
15139   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15140     return false;
15141 
15142   // PPC allows a sign-extended 16-bit immediate field.
15143   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15144     return false;
15145 
15146   // No global is ever allowed as a base.
15147   if (AM.BaseGV)
15148     return false;
15149 
15150   // PPC only support r+r,
15151   switch (AM.Scale) {
15152   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15153     break;
15154   case 1:
15155     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15156       return false;
15157     // Otherwise we have r+r or r+i.
15158     break;
15159   case 2:
15160     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15161       return false;
15162     // Allow 2*r as r+r.
15163     break;
15164   default:
15165     // No other scales are supported.
15166     return false;
15167   }
15168 
15169   return true;
15170 }
15171 
15172 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15173                                            SelectionDAG &DAG) const {
15174   MachineFunction &MF = DAG.getMachineFunction();
15175   MachineFrameInfo &MFI = MF.getFrameInfo();
15176   MFI.setReturnAddressIsTaken(true);
15177 
15178   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15179     return SDValue();
15180 
15181   SDLoc dl(Op);
15182   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15183 
15184   // Make sure the function does not optimize away the store of the RA to
15185   // the stack.
15186   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15187   FuncInfo->setLRStoreRequired();
15188   bool isPPC64 = Subtarget.isPPC64();
15189   auto PtrVT = getPointerTy(MF.getDataLayout());
15190 
15191   if (Depth > 0) {
15192     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15193     SDValue Offset =
15194         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15195                         isPPC64 ? MVT::i64 : MVT::i32);
15196     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15197                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15198                        MachinePointerInfo());
15199   }
15200 
15201   // Just load the return address off the stack.
15202   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15203   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15204                      MachinePointerInfo());
15205 }
15206 
15207 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15208                                           SelectionDAG &DAG) const {
15209   SDLoc dl(Op);
15210   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15211 
15212   MachineFunction &MF = DAG.getMachineFunction();
15213   MachineFrameInfo &MFI = MF.getFrameInfo();
15214   MFI.setFrameAddressIsTaken(true);
15215 
15216   EVT PtrVT = getPointerTy(MF.getDataLayout());
15217   bool isPPC64 = PtrVT == MVT::i64;
15218 
15219   // Naked functions never have a frame pointer, and so we use r1. For all
15220   // other functions, this decision must be delayed until during PEI.
15221   unsigned FrameReg;
15222   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15223     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15224   else
15225     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15226 
15227   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15228                                          PtrVT);
15229   while (Depth--)
15230     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15231                             FrameAddr, MachinePointerInfo());
15232   return FrameAddr;
15233 }
15234 
15235 // FIXME? Maybe this could be a TableGen attribute on some registers and
15236 // this table could be generated automatically from RegInfo.
15237 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15238                                               const MachineFunction &MF) const {
15239   bool isPPC64 = Subtarget.isPPC64();
15240 
15241   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15242   if (!is64Bit && VT != LLT::scalar(32))
15243     report_fatal_error("Invalid register global variable type");
15244 
15245   Register Reg = StringSwitch<Register>(RegName)
15246                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15247                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15248                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15249                      .Default(Register());
15250 
15251   if (Reg)
15252     return Reg;
15253   report_fatal_error("Invalid register name global variable");
15254 }
15255 
15256 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15257   // 32-bit SVR4 ABI access everything as got-indirect.
15258   if (Subtarget.is32BitELFABI())
15259     return true;
15260 
15261   // AIX accesses everything indirectly through the TOC, which is similar to
15262   // the GOT.
15263   if (Subtarget.isAIXABI())
15264     return true;
15265 
15266   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15267   // If it is small or large code model, module locals are accessed
15268   // indirectly by loading their address from .toc/.got.
15269   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15270     return true;
15271 
15272   // JumpTable and BlockAddress are accessed as got-indirect.
15273   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15274     return true;
15275 
15276   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15277     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15278 
15279   return false;
15280 }
15281 
15282 bool
15283 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15284   // The PowerPC target isn't yet aware of offsets.
15285   return false;
15286 }
15287 
15288 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15289                                            const CallInst &I,
15290                                            MachineFunction &MF,
15291                                            unsigned Intrinsic) const {
15292   switch (Intrinsic) {
15293   case Intrinsic::ppc_altivec_lvx:
15294   case Intrinsic::ppc_altivec_lvxl:
15295   case Intrinsic::ppc_altivec_lvebx:
15296   case Intrinsic::ppc_altivec_lvehx:
15297   case Intrinsic::ppc_altivec_lvewx:
15298   case Intrinsic::ppc_vsx_lxvd2x:
15299   case Intrinsic::ppc_vsx_lxvw4x: {
15300     EVT VT;
15301     switch (Intrinsic) {
15302     case Intrinsic::ppc_altivec_lvebx:
15303       VT = MVT::i8;
15304       break;
15305     case Intrinsic::ppc_altivec_lvehx:
15306       VT = MVT::i16;
15307       break;
15308     case Intrinsic::ppc_altivec_lvewx:
15309       VT = MVT::i32;
15310       break;
15311     case Intrinsic::ppc_vsx_lxvd2x:
15312       VT = MVT::v2f64;
15313       break;
15314     default:
15315       VT = MVT::v4i32;
15316       break;
15317     }
15318 
15319     Info.opc = ISD::INTRINSIC_W_CHAIN;
15320     Info.memVT = VT;
15321     Info.ptrVal = I.getArgOperand(0);
15322     Info.offset = -VT.getStoreSize()+1;
15323     Info.size = 2*VT.getStoreSize()-1;
15324     Info.align = Align(1);
15325     Info.flags = MachineMemOperand::MOLoad;
15326     return true;
15327   }
15328   case Intrinsic::ppc_altivec_stvx:
15329   case Intrinsic::ppc_altivec_stvxl:
15330   case Intrinsic::ppc_altivec_stvebx:
15331   case Intrinsic::ppc_altivec_stvehx:
15332   case Intrinsic::ppc_altivec_stvewx:
15333   case Intrinsic::ppc_vsx_stxvd2x:
15334   case Intrinsic::ppc_vsx_stxvw4x: {
15335     EVT VT;
15336     switch (Intrinsic) {
15337     case Intrinsic::ppc_altivec_stvebx:
15338       VT = MVT::i8;
15339       break;
15340     case Intrinsic::ppc_altivec_stvehx:
15341       VT = MVT::i16;
15342       break;
15343     case Intrinsic::ppc_altivec_stvewx:
15344       VT = MVT::i32;
15345       break;
15346     case Intrinsic::ppc_vsx_stxvd2x:
15347       VT = MVT::v2f64;
15348       break;
15349     default:
15350       VT = MVT::v4i32;
15351       break;
15352     }
15353 
15354     Info.opc = ISD::INTRINSIC_VOID;
15355     Info.memVT = VT;
15356     Info.ptrVal = I.getArgOperand(1);
15357     Info.offset = -VT.getStoreSize()+1;
15358     Info.size = 2*VT.getStoreSize()-1;
15359     Info.align = Align(1);
15360     Info.flags = MachineMemOperand::MOStore;
15361     return true;
15362   }
15363   default:
15364     break;
15365   }
15366 
15367   return false;
15368 }
15369 
15370 /// It returns EVT::Other if the type should be determined using generic
15371 /// target-independent logic.
15372 EVT PPCTargetLowering::getOptimalMemOpType(
15373     const MemOp &Op, const AttributeList &FuncAttributes) const {
15374   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15375     // We should use Altivec/VSX loads and stores when available. For unaligned
15376     // addresses, unaligned VSX loads are only fast starting with the P8.
15377     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15378         (Op.isAligned(Align(16)) ||
15379          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15380       return MVT::v4i32;
15381   }
15382 
15383   if (Subtarget.isPPC64()) {
15384     return MVT::i64;
15385   }
15386 
15387   return MVT::i32;
15388 }
15389 
15390 /// Returns true if it is beneficial to convert a load of a constant
15391 /// to just the constant itself.
15392 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15393                                                           Type *Ty) const {
15394   assert(Ty->isIntegerTy());
15395 
15396   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15397   return !(BitSize == 0 || BitSize > 64);
15398 }
15399 
15400 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15401   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15402     return false;
15403   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15404   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15405   return NumBits1 == 64 && NumBits2 == 32;
15406 }
15407 
15408 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15409   if (!VT1.isInteger() || !VT2.isInteger())
15410     return false;
15411   unsigned NumBits1 = VT1.getSizeInBits();
15412   unsigned NumBits2 = VT2.getSizeInBits();
15413   return NumBits1 == 64 && NumBits2 == 32;
15414 }
15415 
15416 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15417   // Generally speaking, zexts are not free, but they are free when they can be
15418   // folded with other operations.
15419   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15420     EVT MemVT = LD->getMemoryVT();
15421     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15422          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15423         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15424          LD->getExtensionType() == ISD::ZEXTLOAD))
15425       return true;
15426   }
15427 
15428   // FIXME: Add other cases...
15429   //  - 32-bit shifts with a zext to i64
15430   //  - zext after ctlz, bswap, etc.
15431   //  - zext after and by a constant mask
15432 
15433   return TargetLowering::isZExtFree(Val, VT2);
15434 }
15435 
15436 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15437   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15438          "invalid fpext types");
15439   // Extending to float128 is not free.
15440   if (DestVT == MVT::f128)
15441     return false;
15442   return true;
15443 }
15444 
15445 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15446   return isInt<16>(Imm) || isUInt<16>(Imm);
15447 }
15448 
15449 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15450   return isInt<16>(Imm) || isUInt<16>(Imm);
15451 }
15452 
15453 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15454                                                        unsigned,
15455                                                        unsigned,
15456                                                        MachineMemOperand::Flags,
15457                                                        bool *Fast) const {
15458   if (DisablePPCUnaligned)
15459     return false;
15460 
15461   // PowerPC supports unaligned memory access for simple non-vector types.
15462   // Although accessing unaligned addresses is not as efficient as accessing
15463   // aligned addresses, it is generally more efficient than manual expansion,
15464   // and generally only traps for software emulation when crossing page
15465   // boundaries.
15466 
15467   if (!VT.isSimple())
15468     return false;
15469 
15470   if (VT.isFloatingPoint() && !VT.isVector() &&
15471       !Subtarget.allowsUnalignedFPAccess())
15472     return false;
15473 
15474   if (VT.getSimpleVT().isVector()) {
15475     if (Subtarget.hasVSX()) {
15476       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15477           VT != MVT::v4f32 && VT != MVT::v4i32)
15478         return false;
15479     } else {
15480       return false;
15481     }
15482   }
15483 
15484   if (VT == MVT::ppcf128)
15485     return false;
15486 
15487   if (Fast)
15488     *Fast = true;
15489 
15490   return true;
15491 }
15492 
15493 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15494                                                    EVT VT) const {
15495   return isFMAFasterThanFMulAndFAdd(
15496       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15497 }
15498 
15499 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15500                                                    Type *Ty) const {
15501   switch (Ty->getScalarType()->getTypeID()) {
15502   case Type::FloatTyID:
15503   case Type::DoubleTyID:
15504     return true;
15505   case Type::FP128TyID:
15506     return Subtarget.hasP9Vector();
15507   default:
15508     return false;
15509   }
15510 }
15511 
15512 // FIXME: add more patterns which are not profitable to hoist.
15513 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15514   if (!I->hasOneUse())
15515     return true;
15516 
15517   Instruction *User = I->user_back();
15518   assert(User && "A single use instruction with no uses.");
15519 
15520   switch (I->getOpcode()) {
15521   case Instruction::FMul: {
15522     // Don't break FMA, PowerPC prefers FMA.
15523     if (User->getOpcode() != Instruction::FSub &&
15524         User->getOpcode() != Instruction::FAdd)
15525       return true;
15526 
15527     const TargetOptions &Options = getTargetMachine().Options;
15528     const Function *F = I->getFunction();
15529     const DataLayout &DL = F->getParent()->getDataLayout();
15530     Type *Ty = User->getOperand(0)->getType();
15531 
15532     return !(
15533         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15534         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15535         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15536   }
15537   case Instruction::Load: {
15538     // Don't break "store (load float*)" pattern, this pattern will be combined
15539     // to "store (load int32)" in later InstCombine pass. See function
15540     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15541     // cycles than loading a 32 bit integer.
15542     LoadInst *LI = cast<LoadInst>(I);
15543     // For the loads that combineLoadToOperationType does nothing, like
15544     // ordered load, it should be profitable to hoist them.
15545     // For swifterror load, it can only be used for pointer to pointer type, so
15546     // later type check should get rid of this case.
15547     if (!LI->isUnordered())
15548       return true;
15549 
15550     if (User->getOpcode() != Instruction::Store)
15551       return true;
15552 
15553     if (I->getType()->getTypeID() != Type::FloatTyID)
15554       return true;
15555 
15556     return false;
15557   }
15558   default:
15559     return true;
15560   }
15561   return true;
15562 }
15563 
15564 const MCPhysReg *
15565 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15566   // LR is a callee-save register, but we must treat it as clobbered by any call
15567   // site. Hence we include LR in the scratch registers, which are in turn added
15568   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15569   // to CTR, which is used by any indirect call.
15570   static const MCPhysReg ScratchRegs[] = {
15571     PPC::X12, PPC::LR8, PPC::CTR8, 0
15572   };
15573 
15574   return ScratchRegs;
15575 }
15576 
15577 Register PPCTargetLowering::getExceptionPointerRegister(
15578     const Constant *PersonalityFn) const {
15579   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15580 }
15581 
15582 Register PPCTargetLowering::getExceptionSelectorRegister(
15583     const Constant *PersonalityFn) const {
15584   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15585 }
15586 
15587 bool
15588 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15589                      EVT VT , unsigned DefinedValues) const {
15590   if (VT == MVT::v2i64)
15591     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15592 
15593   if (Subtarget.hasVSX())
15594     return true;
15595 
15596   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15597 }
15598 
15599 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15600   if (DisableILPPref || Subtarget.enableMachineScheduler())
15601     return TargetLowering::getSchedulingPreference(N);
15602 
15603   return Sched::ILP;
15604 }
15605 
15606 // Create a fast isel object.
15607 FastISel *
15608 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15609                                   const TargetLibraryInfo *LibInfo) const {
15610   return PPC::createFastISel(FuncInfo, LibInfo);
15611 }
15612 
15613 // 'Inverted' means the FMA opcode after negating one multiplicand.
15614 // For example, (fma -a b c) = (fnmsub a b c)
15615 static unsigned invertFMAOpcode(unsigned Opc) {
15616   switch (Opc) {
15617   default:
15618     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15619   case ISD::FMA:
15620     return PPCISD::FNMSUB;
15621   case PPCISD::FNMSUB:
15622     return ISD::FMA;
15623   }
15624 }
15625 
15626 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15627                                                 bool LegalOps, bool OptForSize,
15628                                                 NegatibleCost &Cost,
15629                                                 unsigned Depth) const {
15630   if (Depth > SelectionDAG::MaxRecursionDepth)
15631     return SDValue();
15632 
15633   unsigned Opc = Op.getOpcode();
15634   EVT VT = Op.getValueType();
15635   SDNodeFlags Flags = Op.getNode()->getFlags();
15636 
15637   switch (Opc) {
15638   case PPCISD::FNMSUB:
15639     if (!Op.hasOneUse() || !isTypeLegal(VT))
15640       break;
15641 
15642     const TargetOptions &Options = getTargetMachine().Options;
15643     SDValue N0 = Op.getOperand(0);
15644     SDValue N1 = Op.getOperand(1);
15645     SDValue N2 = Op.getOperand(2);
15646     SDLoc Loc(Op);
15647 
15648     NegatibleCost N2Cost = NegatibleCost::Expensive;
15649     SDValue NegN2 =
15650         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15651 
15652     if (!NegN2)
15653       return SDValue();
15654 
15655     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15656     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15657     // These transformations may change sign of zeroes. For example,
15658     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15659     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15660       // Try and choose the cheaper one to negate.
15661       NegatibleCost N0Cost = NegatibleCost::Expensive;
15662       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15663                                            N0Cost, Depth + 1);
15664 
15665       NegatibleCost N1Cost = NegatibleCost::Expensive;
15666       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15667                                            N1Cost, Depth + 1);
15668 
15669       if (NegN0 && N0Cost <= N1Cost) {
15670         Cost = std::min(N0Cost, N2Cost);
15671         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15672       } else if (NegN1) {
15673         Cost = std::min(N1Cost, N2Cost);
15674         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15675       }
15676     }
15677 
15678     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15679     if (isOperationLegal(ISD::FMA, VT)) {
15680       Cost = N2Cost;
15681       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15682     }
15683 
15684     break;
15685   }
15686 
15687   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15688                                               Cost, Depth);
15689 }
15690 
15691 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15692 bool PPCTargetLowering::useLoadStackGuardNode() const {
15693   if (!Subtarget.isTargetLinux())
15694     return TargetLowering::useLoadStackGuardNode();
15695   return true;
15696 }
15697 
15698 // Override to disable global variable loading on Linux.
15699 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15700   if (!Subtarget.isTargetLinux())
15701     return TargetLowering::insertSSPDeclarations(M);
15702 }
15703 
15704 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15705                                      bool ForCodeSize) const {
15706   if (!VT.isSimple() || !Subtarget.hasVSX())
15707     return false;
15708 
15709   switch(VT.getSimpleVT().SimpleTy) {
15710   default:
15711     // For FP types that are currently not supported by PPC backend, return
15712     // false. Examples: f16, f80.
15713     return false;
15714   case MVT::f32:
15715   case MVT::f64:
15716     if (Subtarget.hasPrefixInstrs()) {
15717       // With prefixed instructions, we can materialize anything that can be
15718       // represented with a 32-bit immediate, not just positive zero.
15719       APFloat APFloatOfImm = Imm;
15720       return convertToNonDenormSingle(APFloatOfImm);
15721     }
15722     LLVM_FALLTHROUGH;
15723   case MVT::ppcf128:
15724     return Imm.isPosZero();
15725   }
15726 }
15727 
15728 // For vector shift operation op, fold
15729 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15730 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15731                                   SelectionDAG &DAG) {
15732   SDValue N0 = N->getOperand(0);
15733   SDValue N1 = N->getOperand(1);
15734   EVT VT = N0.getValueType();
15735   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15736   unsigned Opcode = N->getOpcode();
15737   unsigned TargetOpcode;
15738 
15739   switch (Opcode) {
15740   default:
15741     llvm_unreachable("Unexpected shift operation");
15742   case ISD::SHL:
15743     TargetOpcode = PPCISD::SHL;
15744     break;
15745   case ISD::SRL:
15746     TargetOpcode = PPCISD::SRL;
15747     break;
15748   case ISD::SRA:
15749     TargetOpcode = PPCISD::SRA;
15750     break;
15751   }
15752 
15753   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15754       N1->getOpcode() == ISD::AND)
15755     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15756       if (Mask->getZExtValue() == OpSizeInBits - 1)
15757         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15758 
15759   return SDValue();
15760 }
15761 
15762 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15763   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15764     return Value;
15765 
15766   SDValue N0 = N->getOperand(0);
15767   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15768   if (!Subtarget.isISA3_0() ||
15769       N0.getOpcode() != ISD::SIGN_EXTEND ||
15770       N0.getOperand(0).getValueType() != MVT::i32 ||
15771       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15772     return SDValue();
15773 
15774   // We can't save an operation here if the value is already extended, and
15775   // the existing shift is easier to combine.
15776   SDValue ExtsSrc = N0.getOperand(0);
15777   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15778       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15779     return SDValue();
15780 
15781   SDLoc DL(N0);
15782   SDValue ShiftBy = SDValue(CN1, 0);
15783   // We want the shift amount to be i32 on the extswli, but the shift could
15784   // have an i64.
15785   if (ShiftBy.getValueType() == MVT::i64)
15786     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15787 
15788   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15789                          ShiftBy);
15790 }
15791 
15792 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15793   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15794     return Value;
15795 
15796   return SDValue();
15797 }
15798 
15799 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15800   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15801     return Value;
15802 
15803   return SDValue();
15804 }
15805 
15806 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15807 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15808 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15809 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15810 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15811                                  const PPCSubtarget &Subtarget) {
15812   if (!Subtarget.isPPC64())
15813     return SDValue();
15814 
15815   SDValue LHS = N->getOperand(0);
15816   SDValue RHS = N->getOperand(1);
15817 
15818   auto isZextOfCompareWithConstant = [](SDValue Op) {
15819     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15820         Op.getValueType() != MVT::i64)
15821       return false;
15822 
15823     SDValue Cmp = Op.getOperand(0);
15824     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15825         Cmp.getOperand(0).getValueType() != MVT::i64)
15826       return false;
15827 
15828     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15829       int64_t NegConstant = 0 - Constant->getSExtValue();
15830       // Due to the limitations of the addi instruction,
15831       // -C is required to be [-32768, 32767].
15832       return isInt<16>(NegConstant);
15833     }
15834 
15835     return false;
15836   };
15837 
15838   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15839   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15840 
15841   // If there is a pattern, canonicalize a zext operand to the RHS.
15842   if (LHSHasPattern && !RHSHasPattern)
15843     std::swap(LHS, RHS);
15844   else if (!LHSHasPattern && !RHSHasPattern)
15845     return SDValue();
15846 
15847   SDLoc DL(N);
15848   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15849   SDValue Cmp = RHS.getOperand(0);
15850   SDValue Z = Cmp.getOperand(0);
15851   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15852 
15853   assert(Constant && "Constant Should not be a null pointer.");
15854   int64_t NegConstant = 0 - Constant->getSExtValue();
15855 
15856   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15857   default: break;
15858   case ISD::SETNE: {
15859     //                                 when C == 0
15860     //                             --> addze X, (addic Z, -1).carry
15861     //                            /
15862     // add X, (zext(setne Z, C))--
15863     //                            \    when -32768 <= -C <= 32767 && C != 0
15864     //                             --> addze X, (addic (addi Z, -C), -1).carry
15865     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15866                               DAG.getConstant(NegConstant, DL, MVT::i64));
15867     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15868     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15869                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15870     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15871                        SDValue(Addc.getNode(), 1));
15872     }
15873   case ISD::SETEQ: {
15874     //                                 when C == 0
15875     //                             --> addze X, (subfic Z, 0).carry
15876     //                            /
15877     // add X, (zext(sete  Z, C))--
15878     //                            \    when -32768 <= -C <= 32767 && C != 0
15879     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15880     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15881                               DAG.getConstant(NegConstant, DL, MVT::i64));
15882     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15883     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15884                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15885     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15886                        SDValue(Subc.getNode(), 1));
15887     }
15888   }
15889 
15890   return SDValue();
15891 }
15892 
15893 // Transform
15894 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
15895 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
15896 // In this case both C1 and C2 must be known constants.
15897 // C1+C2 must fit into a 34 bit signed integer.
15898 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
15899                                           const PPCSubtarget &Subtarget) {
15900   if (!Subtarget.isUsingPCRelativeCalls())
15901     return SDValue();
15902 
15903   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
15904   // If we find that node try to cast the Global Address and the Constant.
15905   SDValue LHS = N->getOperand(0);
15906   SDValue RHS = N->getOperand(1);
15907 
15908   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15909     std::swap(LHS, RHS);
15910 
15911   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
15912     return SDValue();
15913 
15914   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
15915   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
15916   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
15917 
15918   // Check that both casts succeeded.
15919   if (!GSDN || !ConstNode)
15920     return SDValue();
15921 
15922   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
15923   SDLoc DL(GSDN);
15924 
15925   // The signed int offset needs to fit in 34 bits.
15926   if (!isInt<34>(NewOffset))
15927     return SDValue();
15928 
15929   // The new global address is a copy of the old global address except
15930   // that it has the updated Offset.
15931   SDValue GA =
15932       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
15933                                  NewOffset, GSDN->getTargetFlags());
15934   SDValue MatPCRel =
15935       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
15936   return MatPCRel;
15937 }
15938 
15939 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15940   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15941     return Value;
15942 
15943   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
15944     return Value;
15945 
15946   return SDValue();
15947 }
15948 
15949 // Detect TRUNCATE operations on bitcasts of float128 values.
15950 // What we are looking for here is the situtation where we extract a subset
15951 // of bits from a 128 bit float.
15952 // This can be of two forms:
15953 // 1) BITCAST of f128 feeding TRUNCATE
15954 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15955 // The reason this is required is because we do not have a legal i128 type
15956 // and so we want to prevent having to store the f128 and then reload part
15957 // of it.
15958 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15959                                            DAGCombinerInfo &DCI) const {
15960   // If we are using CRBits then try that first.
15961   if (Subtarget.useCRBits()) {
15962     // Check if CRBits did anything and return that if it did.
15963     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15964       return CRTruncValue;
15965   }
15966 
15967   SDLoc dl(N);
15968   SDValue Op0 = N->getOperand(0);
15969 
15970   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
15971   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
15972     EVT VT = N->getValueType(0);
15973     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15974       return SDValue();
15975     SDValue Sub = Op0.getOperand(0);
15976     if (Sub.getOpcode() == ISD::SUB) {
15977       SDValue SubOp0 = Sub.getOperand(0);
15978       SDValue SubOp1 = Sub.getOperand(1);
15979       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
15980           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
15981         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
15982                                SubOp1.getOperand(0),
15983                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
15984       }
15985     }
15986   }
15987 
15988   // Looking for a truncate of i128 to i64.
15989   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15990     return SDValue();
15991 
15992   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15993 
15994   // SRL feeding TRUNCATE.
15995   if (Op0.getOpcode() == ISD::SRL) {
15996     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15997     // The right shift has to be by 64 bits.
15998     if (!ConstNode || ConstNode->getZExtValue() != 64)
15999       return SDValue();
16000 
16001     // Switch the element number to extract.
16002     EltToExtract = EltToExtract ? 0 : 1;
16003     // Update Op0 past the SRL.
16004     Op0 = Op0.getOperand(0);
16005   }
16006 
16007   // BITCAST feeding a TRUNCATE possibly via SRL.
16008   if (Op0.getOpcode() == ISD::BITCAST &&
16009       Op0.getValueType() == MVT::i128 &&
16010       Op0.getOperand(0).getValueType() == MVT::f128) {
16011     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16012     return DCI.DAG.getNode(
16013         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16014         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16015   }
16016   return SDValue();
16017 }
16018 
16019 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16020   SelectionDAG &DAG = DCI.DAG;
16021 
16022   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16023   if (!ConstOpOrElement)
16024     return SDValue();
16025 
16026   // An imul is usually smaller than the alternative sequence for legal type.
16027   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16028       isOperationLegal(ISD::MUL, N->getValueType(0)))
16029     return SDValue();
16030 
16031   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16032     switch (this->Subtarget.getCPUDirective()) {
16033     default:
16034       // TODO: enhance the condition for subtarget before pwr8
16035       return false;
16036     case PPC::DIR_PWR8:
16037       //  type        mul     add    shl
16038       // scalar        4       1      1
16039       // vector        7       2      2
16040       return true;
16041     case PPC::DIR_PWR9:
16042     case PPC::DIR_PWR10:
16043     case PPC::DIR_PWR_FUTURE:
16044       //  type        mul     add    shl
16045       // scalar        5       2      2
16046       // vector        7       2      2
16047 
16048       // The cycle RATIO of related operations are showed as a table above.
16049       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16050       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16051       // are 4, it is always profitable; but for 3 instrs patterns
16052       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16053       // So we should only do it for vector type.
16054       return IsAddOne && IsNeg ? VT.isVector() : true;
16055     }
16056   };
16057 
16058   EVT VT = N->getValueType(0);
16059   SDLoc DL(N);
16060 
16061   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16062   bool IsNeg = MulAmt.isNegative();
16063   APInt MulAmtAbs = MulAmt.abs();
16064 
16065   if ((MulAmtAbs - 1).isPowerOf2()) {
16066     // (mul x, 2^N + 1) => (add (shl x, N), x)
16067     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16068 
16069     if (!IsProfitable(IsNeg, true, VT))
16070       return SDValue();
16071 
16072     SDValue Op0 = N->getOperand(0);
16073     SDValue Op1 =
16074         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16075                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16076     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16077 
16078     if (!IsNeg)
16079       return Res;
16080 
16081     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16082   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16083     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16084     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16085 
16086     if (!IsProfitable(IsNeg, false, VT))
16087       return SDValue();
16088 
16089     SDValue Op0 = N->getOperand(0);
16090     SDValue Op1 =
16091         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16092                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16093 
16094     if (!IsNeg)
16095       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16096     else
16097       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16098 
16099   } else {
16100     return SDValue();
16101   }
16102 }
16103 
16104 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16105 // in combiner since we need to check SD flags and other subtarget features.
16106 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16107                                           DAGCombinerInfo &DCI) const {
16108   SDValue N0 = N->getOperand(0);
16109   SDValue N1 = N->getOperand(1);
16110   SDValue N2 = N->getOperand(2);
16111   SDNodeFlags Flags = N->getFlags();
16112   EVT VT = N->getValueType(0);
16113   SelectionDAG &DAG = DCI.DAG;
16114   const TargetOptions &Options = getTargetMachine().Options;
16115   unsigned Opc = N->getOpcode();
16116   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16117   bool LegalOps = !DCI.isBeforeLegalizeOps();
16118   SDLoc Loc(N);
16119 
16120   if (!isOperationLegal(ISD::FMA, VT))
16121     return SDValue();
16122 
16123   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16124   // since (fnmsub a b c)=-0 while c-ab=+0.
16125   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16126     return SDValue();
16127 
16128   // (fma (fneg a) b c) => (fnmsub a b c)
16129   // (fnmsub (fneg a) b c) => (fma a b c)
16130   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16131     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16132 
16133   // (fma a (fneg b) c) => (fnmsub a b c)
16134   // (fnmsub a (fneg b) c) => (fma a b c)
16135   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16136     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16137 
16138   return SDValue();
16139 }
16140 
16141 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16142   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16143   if (!Subtarget.is64BitELFABI())
16144     return false;
16145 
16146   // If not a tail call then no need to proceed.
16147   if (!CI->isTailCall())
16148     return false;
16149 
16150   // If sibling calls have been disabled and tail-calls aren't guaranteed
16151   // there is no reason to duplicate.
16152   auto &TM = getTargetMachine();
16153   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16154     return false;
16155 
16156   // Can't tail call a function called indirectly, or if it has variadic args.
16157   const Function *Callee = CI->getCalledFunction();
16158   if (!Callee || Callee->isVarArg())
16159     return false;
16160 
16161   // Make sure the callee and caller calling conventions are eligible for tco.
16162   const Function *Caller = CI->getParent()->getParent();
16163   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16164                                            CI->getCallingConv()))
16165       return false;
16166 
16167   // If the function is local then we have a good chance at tail-calling it
16168   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16169 }
16170 
16171 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16172   if (!Subtarget.hasVSX())
16173     return false;
16174   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16175     return true;
16176   return VT == MVT::f32 || VT == MVT::f64 ||
16177     VT == MVT::v4f32 || VT == MVT::v2f64;
16178 }
16179 
16180 bool PPCTargetLowering::
16181 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16182   const Value *Mask = AndI.getOperand(1);
16183   // If the mask is suitable for andi. or andis. we should sink the and.
16184   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16185     // Can't handle constants wider than 64-bits.
16186     if (CI->getBitWidth() > 64)
16187       return false;
16188     int64_t ConstVal = CI->getZExtValue();
16189     return isUInt<16>(ConstVal) ||
16190       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16191   }
16192 
16193   // For non-constant masks, we can always use the record-form and.
16194   return true;
16195 }
16196 
16197 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16198 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16199 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16200 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16201 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16202 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16203   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16204   assert(Subtarget.hasP9Altivec() &&
16205          "Only combine this when P9 altivec supported!");
16206   EVT VT = N->getValueType(0);
16207   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16208     return SDValue();
16209 
16210   SelectionDAG &DAG = DCI.DAG;
16211   SDLoc dl(N);
16212   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16213     // Even for signed integers, if it's known to be positive (as signed
16214     // integer) due to zero-extended inputs.
16215     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16216     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16217     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16218          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16219         (SubOpcd1 == ISD::ZERO_EXTEND ||
16220          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16221       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16222                          N->getOperand(0)->getOperand(0),
16223                          N->getOperand(0)->getOperand(1),
16224                          DAG.getTargetConstant(0, dl, MVT::i32));
16225     }
16226 
16227     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16228     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16229         N->getOperand(0).hasOneUse()) {
16230       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16231                          N->getOperand(0)->getOperand(0),
16232                          N->getOperand(0)->getOperand(1),
16233                          DAG.getTargetConstant(1, dl, MVT::i32));
16234     }
16235   }
16236 
16237   return SDValue();
16238 }
16239 
16240 // For type v4i32/v8ii16/v16i8, transform
16241 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16242 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16243 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16244 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16245 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16246                                           DAGCombinerInfo &DCI) const {
16247   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16248   assert(Subtarget.hasP9Altivec() &&
16249          "Only combine this when P9 altivec supported!");
16250 
16251   SelectionDAG &DAG = DCI.DAG;
16252   SDLoc dl(N);
16253   SDValue Cond = N->getOperand(0);
16254   SDValue TrueOpnd = N->getOperand(1);
16255   SDValue FalseOpnd = N->getOperand(2);
16256   EVT VT = N->getOperand(1).getValueType();
16257 
16258   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16259       FalseOpnd.getOpcode() != ISD::SUB)
16260     return SDValue();
16261 
16262   // ABSD only available for type v4i32/v8i16/v16i8
16263   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16264     return SDValue();
16265 
16266   // At least to save one more dependent computation
16267   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16268     return SDValue();
16269 
16270   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16271 
16272   // Can only handle unsigned comparison here
16273   switch (CC) {
16274   default:
16275     return SDValue();
16276   case ISD::SETUGT:
16277   case ISD::SETUGE:
16278     break;
16279   case ISD::SETULT:
16280   case ISD::SETULE:
16281     std::swap(TrueOpnd, FalseOpnd);
16282     break;
16283   }
16284 
16285   SDValue CmpOpnd1 = Cond.getOperand(0);
16286   SDValue CmpOpnd2 = Cond.getOperand(1);
16287 
16288   // SETCC CmpOpnd1 CmpOpnd2 cond
16289   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16290   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16291   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16292       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16293       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16294       FalseOpnd.getOperand(1) == CmpOpnd1) {
16295     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16296                        CmpOpnd1, CmpOpnd2,
16297                        DAG.getTargetConstant(0, dl, MVT::i32));
16298   }
16299 
16300   return SDValue();
16301 }
16302