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 static cl::opt<bool> EnablePPCPCRelTLS(
125     "enable-ppc-pcrel-tls",
126     cl::desc("enable the use of PC relative memops in TLS instructions on PPC"),
127     cl::Hidden);
128 
129 STATISTIC(NumTailCalls, "Number of tail calls");
130 STATISTIC(NumSiblingCalls, "Number of sibling calls");
131 STATISTIC(ShufflesHandledWithVPERM, "Number of shuffles lowered to a VPERM");
132 STATISTIC(NumDynamicAllocaProbed, "Number of dynamic stack allocation probed");
133 
134 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
135 
136 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
137 
138 // FIXME: Remove this once the bug has been fixed!
139 extern cl::opt<bool> ANDIGlueBug;
140 
141 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
142                                      const PPCSubtarget &STI)
143     : TargetLowering(TM), Subtarget(STI) {
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   if (Subtarget.isISA3_0()) {
175     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Legal);
176     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Legal);
177     setTruncStoreAction(MVT::f64, MVT::f16, Legal);
178     setTruncStoreAction(MVT::f32, MVT::f16, Legal);
179   } else {
180     // No extending loads from f16 or HW conversions back and forth.
181     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
182     setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
183     setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
184     setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
185     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
186     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
187     setTruncStoreAction(MVT::f64, MVT::f16, Expand);
188     setTruncStoreAction(MVT::f32, MVT::f16, Expand);
189   }
190 
191   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
192 
193   // PowerPC has pre-inc load and store's.
194   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
195   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
196   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
197   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
198   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
199   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
200   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
201   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
202   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
203   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
204   if (!Subtarget.hasSPE()) {
205     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
206     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
207     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
208     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
209   }
210 
211   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
212   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
213   for (MVT VT : ScalarIntVTs) {
214     setOperationAction(ISD::ADDC, VT, Legal);
215     setOperationAction(ISD::ADDE, VT, Legal);
216     setOperationAction(ISD::SUBC, VT, Legal);
217     setOperationAction(ISD::SUBE, VT, Legal);
218   }
219 
220   if (Subtarget.useCRBits()) {
221     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
222 
223     if (isPPC64 || Subtarget.hasFPCVT()) {
224       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
225       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
226                          isPPC64 ? MVT::i64 : MVT::i32);
227       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
228       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
229                         isPPC64 ? MVT::i64 : MVT::i32);
230     } else {
231       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
232       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
233     }
234 
235     // PowerPC does not support direct load/store of condition registers.
236     setOperationAction(ISD::LOAD, MVT::i1, Custom);
237     setOperationAction(ISD::STORE, MVT::i1, Custom);
238 
239     // FIXME: Remove this once the ANDI glue bug is fixed:
240     if (ANDIGlueBug)
241       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
242 
243     for (MVT VT : MVT::integer_valuetypes()) {
244       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
245       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
246       setTruncStoreAction(VT, MVT::i1, Expand);
247     }
248 
249     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
250   }
251 
252   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
253   // PPC (the libcall is not available).
254   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
255   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
256 
257   // We do not currently implement these libm ops for PowerPC.
258   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
259   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
260   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
261   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
262   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
263   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
264 
265   // PowerPC has no SREM/UREM instructions unless we are on P9
266   // On P9 we may use a hardware instruction to compute the remainder.
267   // When the result of both the remainder and the division is required it is
268   // more efficient to compute the remainder from the result of the division
269   // rather than use the remainder instruction. The instructions are legalized
270   // directly because the DivRemPairsPass performs the transformation at the IR
271   // level.
272   if (Subtarget.isISA3_0()) {
273     setOperationAction(ISD::SREM, MVT::i32, Legal);
274     setOperationAction(ISD::UREM, MVT::i32, Legal);
275     setOperationAction(ISD::SREM, MVT::i64, Legal);
276     setOperationAction(ISD::UREM, MVT::i64, Legal);
277   } else {
278     setOperationAction(ISD::SREM, MVT::i32, Expand);
279     setOperationAction(ISD::UREM, MVT::i32, Expand);
280     setOperationAction(ISD::SREM, MVT::i64, Expand);
281     setOperationAction(ISD::UREM, MVT::i64, Expand);
282   }
283 
284   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
285   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
286   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
287   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
288   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
289   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
290   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
291   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
292   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
293 
294   // Handle constrained floating-point operations of scalar.
295   // TODO: Handle SPE specific operation.
296   setOperationAction(ISD::STRICT_FADD, MVT::f32, Legal);
297   setOperationAction(ISD::STRICT_FSUB, MVT::f32, Legal);
298   setOperationAction(ISD::STRICT_FMUL, MVT::f32, Legal);
299   setOperationAction(ISD::STRICT_FDIV, MVT::f32, Legal);
300   setOperationAction(ISD::STRICT_FMA, MVT::f32, Legal);
301   setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
302 
303   setOperationAction(ISD::STRICT_FADD, MVT::f64, Legal);
304   setOperationAction(ISD::STRICT_FSUB, MVT::f64, Legal);
305   setOperationAction(ISD::STRICT_FMUL, MVT::f64, Legal);
306   setOperationAction(ISD::STRICT_FDIV, MVT::f64, Legal);
307   setOperationAction(ISD::STRICT_FMA, MVT::f64, Legal);
308   if (Subtarget.hasVSX())
309     setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f64, Legal);
310 
311   if (Subtarget.hasFSQRT()) {
312     setOperationAction(ISD::STRICT_FSQRT, MVT::f32, Legal);
313     setOperationAction(ISD::STRICT_FSQRT, MVT::f64, Legal);
314   }
315 
316   if (Subtarget.hasFPRND()) {
317     setOperationAction(ISD::STRICT_FFLOOR, MVT::f32, Legal);
318     setOperationAction(ISD::STRICT_FCEIL,  MVT::f32, Legal);
319     setOperationAction(ISD::STRICT_FTRUNC, MVT::f32, Legal);
320     setOperationAction(ISD::STRICT_FROUND, MVT::f32, Legal);
321 
322     setOperationAction(ISD::STRICT_FFLOOR, MVT::f64, Legal);
323     setOperationAction(ISD::STRICT_FCEIL,  MVT::f64, Legal);
324     setOperationAction(ISD::STRICT_FTRUNC, MVT::f64, Legal);
325     setOperationAction(ISD::STRICT_FROUND, MVT::f64, Legal);
326   }
327 
328   // We don't support sin/cos/sqrt/fmod/pow
329   setOperationAction(ISD::FSIN , MVT::f64, Expand);
330   setOperationAction(ISD::FCOS , MVT::f64, Expand);
331   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
332   setOperationAction(ISD::FREM , MVT::f64, Expand);
333   setOperationAction(ISD::FPOW , MVT::f64, Expand);
334   setOperationAction(ISD::FSIN , MVT::f32, Expand);
335   setOperationAction(ISD::FCOS , MVT::f32, Expand);
336   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
337   setOperationAction(ISD::FREM , MVT::f32, Expand);
338   setOperationAction(ISD::FPOW , MVT::f32, Expand);
339   if (Subtarget.hasSPE()) {
340     setOperationAction(ISD::FMA  , MVT::f64, Expand);
341     setOperationAction(ISD::FMA  , MVT::f32, Expand);
342   } else {
343     setOperationAction(ISD::FMA  , MVT::f64, Legal);
344     setOperationAction(ISD::FMA  , MVT::f32, Legal);
345   }
346 
347   if (Subtarget.hasSPE())
348     setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
349 
350   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
351 
352   // If we're enabling GP optimizations, use hardware square root
353   if (!Subtarget.hasFSQRT() &&
354       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
355         Subtarget.hasFRE()))
356     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
357 
358   if (!Subtarget.hasFSQRT() &&
359       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
360         Subtarget.hasFRES()))
361     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
362 
363   if (Subtarget.hasFCPSGN()) {
364     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
365     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
366   } else {
367     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
368     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
369   }
370 
371   if (Subtarget.hasFPRND()) {
372     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
373     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
374     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
375     setOperationAction(ISD::FROUND, MVT::f64, Legal);
376 
377     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
378     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
379     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
380     setOperationAction(ISD::FROUND, MVT::f32, Legal);
381   }
382 
383   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
384   // to speed up scalar BSWAP64.
385   // CTPOP or CTTZ were introduced in P8/P9 respectively
386   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
387   if (Subtarget.hasP9Vector())
388     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
389   else
390     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
391   if (Subtarget.isISA3_0()) {
392     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
393     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
394   } else {
395     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
396     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
397   }
398 
399   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
400     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
401     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
402   } else {
403     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
404     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
405   }
406 
407   // PowerPC does not have ROTR
408   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
409   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
410 
411   if (!Subtarget.useCRBits()) {
412     // PowerPC does not have Select
413     setOperationAction(ISD::SELECT, MVT::i32, Expand);
414     setOperationAction(ISD::SELECT, MVT::i64, Expand);
415     setOperationAction(ISD::SELECT, MVT::f32, Expand);
416     setOperationAction(ISD::SELECT, MVT::f64, Expand);
417   }
418 
419   // PowerPC wants to turn select_cc of FP into fsel when possible.
420   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
421   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
422 
423   // PowerPC wants to optimize integer setcc a bit
424   if (!Subtarget.useCRBits())
425     setOperationAction(ISD::SETCC, MVT::i32, Custom);
426 
427   if (Subtarget.hasFPU()) {
428     setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Legal);
429     setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Legal);
430     setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Legal);
431 
432     setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Legal);
433     setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Legal);
434     setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Legal);
435   }
436 
437   // PowerPC does not have BRCOND which requires SetCC
438   if (!Subtarget.useCRBits())
439     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
440 
441   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
442 
443   if (Subtarget.hasSPE()) {
444     // SPE has built-in conversions
445     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Legal);
446     setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Legal);
447     setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Legal);
448     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
449     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
450     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
451   } else {
452     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
453     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
454     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
455 
456     // PowerPC does not have [U|S]INT_TO_FP
457     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
458     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
459   }
460 
461   if (Subtarget.hasDirectMove() && isPPC64) {
462     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
463     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
464     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
465     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
466     if (TM.Options.UnsafeFPMath) {
467       setOperationAction(ISD::LRINT, MVT::f64, Legal);
468       setOperationAction(ISD::LRINT, MVT::f32, Legal);
469       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
470       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
471       setOperationAction(ISD::LROUND, MVT::f64, Legal);
472       setOperationAction(ISD::LROUND, MVT::f32, Legal);
473       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
474       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
475     }
476   } else {
477     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
478     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
479     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
480     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
481   }
482 
483   // We cannot sextinreg(i1).  Expand to shifts.
484   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
485 
486   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
487   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
488   // support continuation, user-level threading, and etc.. As a result, no
489   // other SjLj exception interfaces are implemented and please don't build
490   // your own exception handling based on them.
491   // LLVM/Clang supports zero-cost DWARF exception handling.
492   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
493   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
494 
495   // We want to legalize GlobalAddress and ConstantPool nodes into the
496   // appropriate instructions to materialize the address.
497   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
498   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
499   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
500   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
501   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
502   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
503   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
504   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
505   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
506   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
507 
508   // TRAP is legal.
509   setOperationAction(ISD::TRAP, MVT::Other, Legal);
510 
511   // TRAMPOLINE is custom lowered.
512   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
513   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
514 
515   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
516   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
517 
518   if (Subtarget.is64BitELFABI()) {
519     // VAARG always uses double-word chunks, so promote anything smaller.
520     setOperationAction(ISD::VAARG, MVT::i1, Promote);
521     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
522     setOperationAction(ISD::VAARG, MVT::i8, Promote);
523     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
524     setOperationAction(ISD::VAARG, MVT::i16, Promote);
525     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
526     setOperationAction(ISD::VAARG, MVT::i32, Promote);
527     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
528     setOperationAction(ISD::VAARG, MVT::Other, Expand);
529   } else if (Subtarget.is32BitELFABI()) {
530     // VAARG is custom lowered with the 32-bit SVR4 ABI.
531     setOperationAction(ISD::VAARG, MVT::Other, Custom);
532     setOperationAction(ISD::VAARG, MVT::i64, Custom);
533   } else
534     setOperationAction(ISD::VAARG, MVT::Other, Expand);
535 
536   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
537   if (Subtarget.is32BitELFABI())
538     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
539   else
540     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
541 
542   // Use the default implementation.
543   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
544   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
545   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
546   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
547   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
548   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
549   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
550   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
551   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
552 
553   // We want to custom lower some of our intrinsics.
554   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
555 
556   // To handle counter-based loop conditions.
557   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
558 
559   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
560   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
561   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
562   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
563 
564   // Comparisons that require checking two conditions.
565   if (Subtarget.hasSPE()) {
566     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
567     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
568     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
569     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
570   }
571   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
572   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
573   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
574   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
575   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
576   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
577   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
578   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
579   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
580   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
581   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
582   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
583 
584   if (Subtarget.has64BitSupport()) {
585     // They also have instructions for converting between i64 and fp.
586     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
587     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Expand);
588     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
589     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
590     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
591     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
592     // This is just the low 32 bits of a (signed) fp->i64 conversion.
593     // We cannot do this with Promote because i64 is not a legal type.
594     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
595     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
596 
597     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
598       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
599   } else {
600     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
601     if (Subtarget.hasSPE()) {
602       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Legal);
603       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
604     } else {
605       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Expand);
606       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
607     }
608   }
609 
610   // With the instructions enabled under FPCVT, we can do everything.
611   if (Subtarget.hasFPCVT()) {
612     if (Subtarget.has64BitSupport()) {
613       setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
614       setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
615       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
616       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
617       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
618       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
619     }
620 
621     setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
622     setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
623     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
624     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
625     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
626     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
627   }
628 
629   if (Subtarget.use64BitRegs()) {
630     // 64-bit PowerPC implementations can support i64 types directly
631     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
632     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
633     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
634     // 64-bit PowerPC wants to expand i128 shifts itself.
635     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
636     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
637     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
638   } else {
639     // 32-bit PowerPC wants to expand i64 shifts itself.
640     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
641     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
642     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
643   }
644 
645   // PowerPC has better expansions for funnel shifts than the generic
646   // TargetLowering::expandFunnelShift.
647   if (Subtarget.has64BitSupport()) {
648     setOperationAction(ISD::FSHL, MVT::i64, Custom);
649     setOperationAction(ISD::FSHR, MVT::i64, Custom);
650   }
651   setOperationAction(ISD::FSHL, MVT::i32, Custom);
652   setOperationAction(ISD::FSHR, MVT::i32, Custom);
653 
654   if (Subtarget.hasVSX()) {
655     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
656     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
657     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
658     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
659   }
660 
661   if (Subtarget.hasAltivec()) {
662     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
663       setOperationAction(ISD::SADDSAT, VT, Legal);
664       setOperationAction(ISD::SSUBSAT, VT, Legal);
665       setOperationAction(ISD::UADDSAT, VT, Legal);
666       setOperationAction(ISD::USUBSAT, VT, Legal);
667     }
668     // First set operation action for all vector types to expand. Then we
669     // will selectively turn on ones that can be effectively codegen'd.
670     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
671       // add/sub are legal for all supported vector VT's.
672       setOperationAction(ISD::ADD, VT, Legal);
673       setOperationAction(ISD::SUB, VT, Legal);
674 
675       // For v2i64, these are only valid with P8Vector. This is corrected after
676       // the loop.
677       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
678         setOperationAction(ISD::SMAX, VT, Legal);
679         setOperationAction(ISD::SMIN, VT, Legal);
680         setOperationAction(ISD::UMAX, VT, Legal);
681         setOperationAction(ISD::UMIN, VT, Legal);
682       }
683       else {
684         setOperationAction(ISD::SMAX, VT, Expand);
685         setOperationAction(ISD::SMIN, VT, Expand);
686         setOperationAction(ISD::UMAX, VT, Expand);
687         setOperationAction(ISD::UMIN, VT, Expand);
688       }
689 
690       if (Subtarget.hasVSX()) {
691         setOperationAction(ISD::FMAXNUM, VT, Legal);
692         setOperationAction(ISD::FMINNUM, VT, Legal);
693       }
694 
695       // Vector instructions introduced in P8
696       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
697         setOperationAction(ISD::CTPOP, VT, Legal);
698         setOperationAction(ISD::CTLZ, VT, Legal);
699       }
700       else {
701         setOperationAction(ISD::CTPOP, VT, Expand);
702         setOperationAction(ISD::CTLZ, VT, Expand);
703       }
704 
705       // Vector instructions introduced in P9
706       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
707         setOperationAction(ISD::CTTZ, VT, Legal);
708       else
709         setOperationAction(ISD::CTTZ, VT, Expand);
710 
711       // We promote all shuffles to v16i8.
712       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
713       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
714 
715       // We promote all non-typed operations to v4i32.
716       setOperationAction(ISD::AND   , VT, Promote);
717       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
718       setOperationAction(ISD::OR    , VT, Promote);
719       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
720       setOperationAction(ISD::XOR   , VT, Promote);
721       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
722       setOperationAction(ISD::LOAD  , VT, Promote);
723       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
724       setOperationAction(ISD::SELECT, VT, Promote);
725       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
726       setOperationAction(ISD::VSELECT, VT, Legal);
727       setOperationAction(ISD::SELECT_CC, VT, Promote);
728       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
729       setOperationAction(ISD::STORE, VT, Promote);
730       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
731 
732       // No other operations are legal.
733       setOperationAction(ISD::MUL , VT, Expand);
734       setOperationAction(ISD::SDIV, VT, Expand);
735       setOperationAction(ISD::SREM, VT, Expand);
736       setOperationAction(ISD::UDIV, VT, Expand);
737       setOperationAction(ISD::UREM, VT, Expand);
738       setOperationAction(ISD::FDIV, VT, Expand);
739       setOperationAction(ISD::FREM, VT, Expand);
740       setOperationAction(ISD::FNEG, VT, Expand);
741       setOperationAction(ISD::FSQRT, VT, Expand);
742       setOperationAction(ISD::FLOG, VT, Expand);
743       setOperationAction(ISD::FLOG10, VT, Expand);
744       setOperationAction(ISD::FLOG2, VT, Expand);
745       setOperationAction(ISD::FEXP, VT, Expand);
746       setOperationAction(ISD::FEXP2, VT, Expand);
747       setOperationAction(ISD::FSIN, VT, Expand);
748       setOperationAction(ISD::FCOS, VT, Expand);
749       setOperationAction(ISD::FABS, VT, Expand);
750       setOperationAction(ISD::FFLOOR, VT, Expand);
751       setOperationAction(ISD::FCEIL,  VT, Expand);
752       setOperationAction(ISD::FTRUNC, VT, Expand);
753       setOperationAction(ISD::FRINT,  VT, Expand);
754       setOperationAction(ISD::FNEARBYINT, VT, Expand);
755       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
756       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
757       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
758       setOperationAction(ISD::MULHU, VT, Expand);
759       setOperationAction(ISD::MULHS, VT, Expand);
760       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
761       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
762       setOperationAction(ISD::UDIVREM, VT, Expand);
763       setOperationAction(ISD::SDIVREM, VT, Expand);
764       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
765       setOperationAction(ISD::FPOW, VT, Expand);
766       setOperationAction(ISD::BSWAP, VT, Expand);
767       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
768       setOperationAction(ISD::ROTL, VT, Expand);
769       setOperationAction(ISD::ROTR, VT, Expand);
770 
771       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
772         setTruncStoreAction(VT, InnerVT, Expand);
773         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
774         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
775         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
776       }
777     }
778     setOperationAction(ISD::SELECT_CC, MVT::v4i32, Expand);
779     if (!Subtarget.hasP8Vector()) {
780       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
781       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
782       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
783       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
784     }
785 
786     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
787       setOperationAction(ISD::ABS, VT, Custom);
788 
789     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
790     // with merges, splats, etc.
791     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
792 
793     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
794     // are cheap, so handle them before they get expanded to scalar.
795     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
796     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
797     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
798     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
799     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
800 
801     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
802     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
803     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
804     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
805     setOperationAction(ISD::SELECT, MVT::v4i32,
806                        Subtarget.useCRBits() ? Legal : Expand);
807     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
808     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
809     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
810     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
811     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
812     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
813     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
814     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
815     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
816 
817     // Without hasP8Altivec set, v2i64 SMAX isn't available.
818     // But ABS custom lowering requires SMAX support.
819     if (!Subtarget.hasP8Altivec())
820       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
821 
822     // Custom lowering ROTL v1i128 to VECTOR_SHUFFLE v16i8.
823     setOperationAction(ISD::ROTL, MVT::v1i128, Custom);
824     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
825     if (Subtarget.hasAltivec())
826       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
827         setOperationAction(ISD::ROTL, VT, Legal);
828     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
829     if (Subtarget.hasP8Altivec())
830       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
831 
832     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
833     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
834     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
835     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
836 
837     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
838     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
839 
840     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
841       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
842       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
843     }
844 
845     if (Subtarget.hasP8Altivec())
846       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
847     else
848       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
849 
850     if (Subtarget.isISA3_1()) {
851       setOperationAction(ISD::MUL, MVT::v2i64, Legal);
852       setOperationAction(ISD::MULHS, MVT::v2i64, Legal);
853       setOperationAction(ISD::MULHU, MVT::v2i64, Legal);
854       setOperationAction(ISD::MULHS, MVT::v4i32, Legal);
855       setOperationAction(ISD::MULHU, MVT::v4i32, Legal);
856       setOperationAction(ISD::UDIV, MVT::v2i64, Legal);
857       setOperationAction(ISD::SDIV, MVT::v2i64, Legal);
858       setOperationAction(ISD::UDIV, MVT::v4i32, Legal);
859       setOperationAction(ISD::SDIV, MVT::v4i32, Legal);
860       setOperationAction(ISD::UREM, MVT::v2i64, Legal);
861       setOperationAction(ISD::SREM, MVT::v2i64, Legal);
862       setOperationAction(ISD::UREM, MVT::v4i32, Legal);
863       setOperationAction(ISD::SREM, MVT::v4i32, Legal);
864     }
865 
866     setOperationAction(ISD::MUL, MVT::v8i16, Legal);
867     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
868 
869     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
870     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
871 
872     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
873     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
874     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
875     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
876 
877     // Altivec does not contain unordered floating-point compare instructions
878     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
879     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
880     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
881     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
882 
883     if (Subtarget.hasVSX()) {
884       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
885       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
886       if (Subtarget.hasP8Vector()) {
887         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
888         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
889       }
890       if (Subtarget.hasDirectMove() && isPPC64) {
891         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
892         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
893         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
894         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
895         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
896         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
897         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
898         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
899       }
900       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
901 
902       // The nearbyint variants are not allowed to raise the inexact exception
903       // so we can only code-gen them with unsafe math.
904       if (TM.Options.UnsafeFPMath) {
905         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
906         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
907       }
908 
909       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
910       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
911       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
912       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
913       setOperationAction(ISD::FRINT, MVT::v2f64, Legal);
914       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
915       setOperationAction(ISD::FROUND, MVT::f64, Legal);
916       setOperationAction(ISD::FRINT, MVT::f64, Legal);
917 
918       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
919       setOperationAction(ISD::FRINT, MVT::v4f32, Legal);
920       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
921       setOperationAction(ISD::FROUND, MVT::f32, Legal);
922       setOperationAction(ISD::FRINT, MVT::f32, Legal);
923 
924       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
925       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
926 
927       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
928       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
929 
930       // Share the Altivec comparison restrictions.
931       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
932       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
933       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
934       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
935 
936       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
937       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
938 
939       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
940 
941       if (Subtarget.hasP8Vector())
942         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
943 
944       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
945 
946       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
947       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
948       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
949 
950       if (Subtarget.hasP8Altivec()) {
951         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
952         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
953         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
954 
955         // 128 bit shifts can be accomplished via 3 instructions for SHL and
956         // SRL, but not for SRA because of the instructions available:
957         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
958         // doing
959         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
960         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
961         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
962 
963         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
964       }
965       else {
966         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
967         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
968         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
969 
970         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
971 
972         // VSX v2i64 only supports non-arithmetic operations.
973         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
974         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
975       }
976 
977       setOperationAction(ISD::SETCC, MVT::v1i128, Expand);
978 
979       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
980       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
981       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
982       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
983 
984       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
985 
986       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
987       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
988       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
989       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
990 
991       // Custom handling for partial vectors of integers converted to
992       // floating point. We already have optimal handling for v2i32 through
993       // the DAG combine, so those aren't necessary.
994       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
995       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
996       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
997       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
998       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
999       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
1000       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
1001       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
1002 
1003       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
1004       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
1005       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
1006       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
1007       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1008       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
1009 
1010       if (Subtarget.hasDirectMove())
1011         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
1012       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
1013 
1014       // Handle constrained floating-point operations of vector.
1015       // The predictor is `hasVSX` because altivec instruction has
1016       // no exception but VSX vector instruction has.
1017       setOperationAction(ISD::STRICT_FADD, MVT::v4f32, Legal);
1018       setOperationAction(ISD::STRICT_FSUB, MVT::v4f32, Legal);
1019       setOperationAction(ISD::STRICT_FMUL, MVT::v4f32, Legal);
1020       setOperationAction(ISD::STRICT_FDIV, MVT::v4f32, Legal);
1021       setOperationAction(ISD::STRICT_FMA, MVT::v4f32, Legal);
1022       setOperationAction(ISD::STRICT_FSQRT, MVT::v4f32, Legal);
1023       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v4f32, Legal);
1024       setOperationAction(ISD::STRICT_FMINNUM, MVT::v4f32, Legal);
1025       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v4f32, Legal);
1026       setOperationAction(ISD::STRICT_FFLOOR, MVT::v4f32, Legal);
1027       setOperationAction(ISD::STRICT_FCEIL,  MVT::v4f32, Legal);
1028       setOperationAction(ISD::STRICT_FTRUNC, MVT::v4f32, Legal);
1029       setOperationAction(ISD::STRICT_FROUND, MVT::v4f32, Legal);
1030 
1031       setOperationAction(ISD::STRICT_FADD, MVT::v2f64, Legal);
1032       setOperationAction(ISD::STRICT_FSUB, MVT::v2f64, Legal);
1033       setOperationAction(ISD::STRICT_FMUL, MVT::v2f64, Legal);
1034       setOperationAction(ISD::STRICT_FDIV, MVT::v2f64, Legal);
1035       setOperationAction(ISD::STRICT_FMA, MVT::v2f64, Legal);
1036       setOperationAction(ISD::STRICT_FSQRT, MVT::v2f64, Legal);
1037       setOperationAction(ISD::STRICT_FMAXNUM, MVT::v2f64, Legal);
1038       setOperationAction(ISD::STRICT_FMINNUM, MVT::v2f64, Legal);
1039       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::v2f64, Legal);
1040       setOperationAction(ISD::STRICT_FFLOOR, MVT::v2f64, Legal);
1041       setOperationAction(ISD::STRICT_FCEIL,  MVT::v2f64, Legal);
1042       setOperationAction(ISD::STRICT_FTRUNC, MVT::v2f64, Legal);
1043       setOperationAction(ISD::STRICT_FROUND, MVT::v2f64, Legal);
1044 
1045       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
1046     }
1047 
1048     if (Subtarget.hasP8Altivec()) {
1049       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
1050       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
1051     }
1052 
1053     if (Subtarget.hasP9Vector()) {
1054       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
1055       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
1056 
1057       // 128 bit shifts can be accomplished via 3 instructions for SHL and
1058       // SRL, but not for SRA because of the instructions available:
1059       // VS{RL} and VS{RL}O.
1060       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
1061       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
1062       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
1063 
1064       addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
1065       setOperationAction(ISD::FADD, MVT::f128, Legal);
1066       setOperationAction(ISD::FSUB, MVT::f128, Legal);
1067       setOperationAction(ISD::FDIV, MVT::f128, Legal);
1068       setOperationAction(ISD::FMUL, MVT::f128, Legal);
1069       setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
1070       // No extending loads to f128 on PPC.
1071       for (MVT FPT : MVT::fp_valuetypes())
1072         setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
1073       setOperationAction(ISD::FMA, MVT::f128, Legal);
1074       setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
1075       setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
1076       setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
1077       setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
1078       setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
1079       setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
1080 
1081       setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
1082       setOperationAction(ISD::FRINT, MVT::f128, Legal);
1083       setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
1084       setOperationAction(ISD::FCEIL, MVT::f128, Legal);
1085       setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
1086       setOperationAction(ISD::FROUND, MVT::f128, Legal);
1087 
1088       setOperationAction(ISD::SELECT, MVT::f128, Expand);
1089       setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
1090       setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
1091       setTruncStoreAction(MVT::f128, MVT::f64, Expand);
1092       setTruncStoreAction(MVT::f128, MVT::f32, Expand);
1093       setOperationAction(ISD::BITCAST, MVT::i128, Custom);
1094       // No implementation for these ops for PowerPC.
1095       setOperationAction(ISD::FSIN, MVT::f128, Expand);
1096       setOperationAction(ISD::FCOS, MVT::f128, Expand);
1097       setOperationAction(ISD::FPOW, MVT::f128, Expand);
1098       setOperationAction(ISD::FPOWI, MVT::f128, Expand);
1099       setOperationAction(ISD::FREM, MVT::f128, Expand);
1100 
1101       // Handle constrained floating-point operations of fp128
1102       setOperationAction(ISD::STRICT_FADD, MVT::f128, Legal);
1103       setOperationAction(ISD::STRICT_FSUB, MVT::f128, Legal);
1104       setOperationAction(ISD::STRICT_FMUL, MVT::f128, Legal);
1105       setOperationAction(ISD::STRICT_FDIV, MVT::f128, Legal);
1106       setOperationAction(ISD::STRICT_FMA, MVT::f128, Legal);
1107       setOperationAction(ISD::STRICT_FSQRT, MVT::f128, Legal);
1108       setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f128, Legal);
1109       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Legal);
1110       setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
1111       setOperationAction(ISD::STRICT_FRINT, MVT::f128, Legal);
1112       setOperationAction(ISD::STRICT_FNEARBYINT, MVT::f128, Legal);
1113       setOperationAction(ISD::STRICT_FFLOOR, MVT::f128, Legal);
1114       setOperationAction(ISD::STRICT_FCEIL, MVT::f128, Legal);
1115       setOperationAction(ISD::STRICT_FTRUNC, MVT::f128, Legal);
1116       setOperationAction(ISD::STRICT_FROUND, MVT::f128, Legal);
1117       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
1118       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
1119       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
1120       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
1121       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
1122     }
1123 
1124     if (Subtarget.hasP9Altivec()) {
1125       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
1126       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
1127 
1128       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
1129       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
1130       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
1131       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
1132       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
1133       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
1134       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
1135     }
1136   }
1137 
1138   if (Subtarget.has64BitSupport())
1139     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1140 
1141   if (Subtarget.isISA3_1())
1142     setOperationAction(ISD::SRA, MVT::v1i128, Legal);
1143 
1144   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1145 
1146   if (!isPPC64) {
1147     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1148     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1149   }
1150 
1151   setBooleanContents(ZeroOrOneBooleanContent);
1152 
1153   if (Subtarget.hasAltivec()) {
1154     // Altivec instructions set fields to all zeros or all ones.
1155     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1156   }
1157 
1158   if (!isPPC64) {
1159     // These libcalls are not available in 32-bit.
1160     setLibcallName(RTLIB::SHL_I128, nullptr);
1161     setLibcallName(RTLIB::SRL_I128, nullptr);
1162     setLibcallName(RTLIB::SRA_I128, nullptr);
1163   }
1164 
1165   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1166 
1167   // We have target-specific dag combine patterns for the following nodes:
1168   setTargetDAGCombine(ISD::ADD);
1169   setTargetDAGCombine(ISD::SHL);
1170   setTargetDAGCombine(ISD::SRA);
1171   setTargetDAGCombine(ISD::SRL);
1172   setTargetDAGCombine(ISD::MUL);
1173   setTargetDAGCombine(ISD::FMA);
1174   setTargetDAGCombine(ISD::SINT_TO_FP);
1175   setTargetDAGCombine(ISD::BUILD_VECTOR);
1176   if (Subtarget.hasFPCVT())
1177     setTargetDAGCombine(ISD::UINT_TO_FP);
1178   setTargetDAGCombine(ISD::LOAD);
1179   setTargetDAGCombine(ISD::STORE);
1180   setTargetDAGCombine(ISD::BR_CC);
1181   if (Subtarget.useCRBits())
1182     setTargetDAGCombine(ISD::BRCOND);
1183   setTargetDAGCombine(ISD::BSWAP);
1184   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1185   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1186   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1187 
1188   setTargetDAGCombine(ISD::SIGN_EXTEND);
1189   setTargetDAGCombine(ISD::ZERO_EXTEND);
1190   setTargetDAGCombine(ISD::ANY_EXTEND);
1191 
1192   setTargetDAGCombine(ISD::TRUNCATE);
1193   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1194 
1195 
1196   if (Subtarget.useCRBits()) {
1197     setTargetDAGCombine(ISD::TRUNCATE);
1198     setTargetDAGCombine(ISD::SETCC);
1199     setTargetDAGCombine(ISD::SELECT_CC);
1200   }
1201 
1202   // Use reciprocal estimates.
1203   if (TM.Options.UnsafeFPMath) {
1204     setTargetDAGCombine(ISD::FDIV);
1205     setTargetDAGCombine(ISD::FSQRT);
1206   }
1207 
1208   if (Subtarget.hasP9Altivec()) {
1209     setTargetDAGCombine(ISD::ABS);
1210     setTargetDAGCombine(ISD::VSELECT);
1211   }
1212 
1213   setLibcallName(RTLIB::LOG_F128, "logf128");
1214   setLibcallName(RTLIB::LOG2_F128, "log2f128");
1215   setLibcallName(RTLIB::LOG10_F128, "log10f128");
1216   setLibcallName(RTLIB::EXP_F128, "expf128");
1217   setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1218   setLibcallName(RTLIB::SIN_F128, "sinf128");
1219   setLibcallName(RTLIB::COS_F128, "cosf128");
1220   setLibcallName(RTLIB::POW_F128, "powf128");
1221   setLibcallName(RTLIB::FMIN_F128, "fminf128");
1222   setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1223   setLibcallName(RTLIB::POWI_F128, "__powikf2");
1224   setLibcallName(RTLIB::REM_F128, "fmodf128");
1225 
1226   // With 32 condition bits, we don't need to sink (and duplicate) compares
1227   // aggressively in CodeGenPrep.
1228   if (Subtarget.useCRBits()) {
1229     setHasMultipleConditionRegisters();
1230     setJumpIsExpensive();
1231   }
1232 
1233   setMinFunctionAlignment(Align(4));
1234 
1235   switch (Subtarget.getCPUDirective()) {
1236   default: break;
1237   case PPC::DIR_970:
1238   case PPC::DIR_A2:
1239   case PPC::DIR_E500:
1240   case PPC::DIR_E500mc:
1241   case PPC::DIR_E5500:
1242   case PPC::DIR_PWR4:
1243   case PPC::DIR_PWR5:
1244   case PPC::DIR_PWR5X:
1245   case PPC::DIR_PWR6:
1246   case PPC::DIR_PWR6X:
1247   case PPC::DIR_PWR7:
1248   case PPC::DIR_PWR8:
1249   case PPC::DIR_PWR9:
1250   case PPC::DIR_PWR10:
1251   case PPC::DIR_PWR_FUTURE:
1252     setPrefLoopAlignment(Align(16));
1253     setPrefFunctionAlignment(Align(16));
1254     break;
1255   }
1256 
1257   if (Subtarget.enableMachineScheduler())
1258     setSchedulingPreference(Sched::Source);
1259   else
1260     setSchedulingPreference(Sched::Hybrid);
1261 
1262   computeRegisterProperties(STI.getRegisterInfo());
1263 
1264   // The Freescale cores do better with aggressive inlining of memcpy and
1265   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1266   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1267       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1268     MaxStoresPerMemset = 32;
1269     MaxStoresPerMemsetOptSize = 16;
1270     MaxStoresPerMemcpy = 32;
1271     MaxStoresPerMemcpyOptSize = 8;
1272     MaxStoresPerMemmove = 32;
1273     MaxStoresPerMemmoveOptSize = 8;
1274   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1275     // The A2 also benefits from (very) aggressive inlining of memcpy and
1276     // friends. The overhead of a the function call, even when warm, can be
1277     // over one hundred cycles.
1278     MaxStoresPerMemset = 128;
1279     MaxStoresPerMemcpy = 128;
1280     MaxStoresPerMemmove = 128;
1281     MaxLoadsPerMemcmp = 128;
1282   } else {
1283     MaxLoadsPerMemcmp = 8;
1284     MaxLoadsPerMemcmpOptSize = 4;
1285   }
1286 
1287   // Let the subtarget (CPU) decide if a predictable select is more expensive
1288   // than the corresponding branch. This information is used in CGP to decide
1289   // when to convert selects into branches.
1290   PredictableSelectIsExpensive = Subtarget.isPredictableSelectIsExpensive();
1291 }
1292 
1293 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1294 /// the desired ByVal argument alignment.
1295 static void getMaxByValAlign(Type *Ty, Align &MaxAlign, Align MaxMaxAlign) {
1296   if (MaxAlign == MaxMaxAlign)
1297     return;
1298   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1299     if (MaxMaxAlign >= 32 &&
1300         VTy->getPrimitiveSizeInBits().getFixedSize() >= 256)
1301       MaxAlign = Align(32);
1302     else if (VTy->getPrimitiveSizeInBits().getFixedSize() >= 128 &&
1303              MaxAlign < 16)
1304       MaxAlign = Align(16);
1305   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1306     Align EltAlign;
1307     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1308     if (EltAlign > MaxAlign)
1309       MaxAlign = EltAlign;
1310   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1311     for (auto *EltTy : STy->elements()) {
1312       Align EltAlign;
1313       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1314       if (EltAlign > MaxAlign)
1315         MaxAlign = EltAlign;
1316       if (MaxAlign == MaxMaxAlign)
1317         break;
1318     }
1319   }
1320 }
1321 
1322 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1323 /// function arguments in the caller parameter area.
1324 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1325                                                   const DataLayout &DL) const {
1326   // 16byte and wider vectors are passed on 16byte boundary.
1327   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1328   Align Alignment = Subtarget.isPPC64() ? Align(8) : Align(4);
1329   if (Subtarget.hasAltivec())
1330     getMaxByValAlign(Ty, Alignment, Align(16));
1331   return Alignment.value();
1332 }
1333 
1334 bool PPCTargetLowering::useSoftFloat() const {
1335   return Subtarget.useSoftFloat();
1336 }
1337 
1338 bool PPCTargetLowering::hasSPE() const {
1339   return Subtarget.hasSPE();
1340 }
1341 
1342 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1343   return VT.isScalarInteger();
1344 }
1345 
1346 /// isMulhCheaperThanMulShift - Return true if a mulh[s|u] node for a specific
1347 /// type is cheaper than a multiply followed by a shift.
1348 /// This is true for words and doublewords on 64-bit PowerPC.
1349 bool PPCTargetLowering::isMulhCheaperThanMulShift(EVT Type) const {
1350   if (Subtarget.isPPC64() && (isOperationLegal(ISD::MULHS, Type) ||
1351                               isOperationLegal(ISD::MULHU, Type)))
1352     return true;
1353   return TargetLowering::isMulhCheaperThanMulShift(Type);
1354 }
1355 
1356 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1357   switch ((PPCISD::NodeType)Opcode) {
1358   case PPCISD::FIRST_NUMBER:    break;
1359   case PPCISD::FSEL:            return "PPCISD::FSEL";
1360   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1361   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1362   case PPCISD::FCFID:           return "PPCISD::FCFID";
1363   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1364   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1365   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1366   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1367   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1368   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1369   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1370   case PPCISD::FP_TO_UINT_IN_VSR:
1371                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1372   case PPCISD::FP_TO_SINT_IN_VSR:
1373                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1374   case PPCISD::FRE:             return "PPCISD::FRE";
1375   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1376   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1377   case PPCISD::VPERM:           return "PPCISD::VPERM";
1378   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1379   case PPCISD::XXSPLTI_SP_TO_DP:
1380     return "PPCISD::XXSPLTI_SP_TO_DP";
1381   case PPCISD::XXSPLTI32DX:
1382     return "PPCISD::XXSPLTI32DX";
1383   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1384   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1385   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1386   case PPCISD::CMPB:            return "PPCISD::CMPB";
1387   case PPCISD::Hi:              return "PPCISD::Hi";
1388   case PPCISD::Lo:              return "PPCISD::Lo";
1389   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1390   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1391   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1392   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1393   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1394   case PPCISD::PROBED_ALLOCA:   return "PPCISD::PROBED_ALLOCA";
1395   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1396   case PPCISD::SRL:             return "PPCISD::SRL";
1397   case PPCISD::SRA:             return "PPCISD::SRA";
1398   case PPCISD::SHL:             return "PPCISD::SHL";
1399   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1400   case PPCISD::CALL:            return "PPCISD::CALL";
1401   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1402   case PPCISD::CALL_NOTOC:      return "PPCISD::CALL_NOTOC";
1403   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1404   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1405   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1406   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1407   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1408   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1409   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1410   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1411   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1412   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1413   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1414   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1415   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1416   case PPCISD::SCALAR_TO_VECTOR_PERMUTED:
1417     return "PPCISD::SCALAR_TO_VECTOR_PERMUTED";
1418   case PPCISD::ANDI_rec_1_EQ_BIT:
1419     return "PPCISD::ANDI_rec_1_EQ_BIT";
1420   case PPCISD::ANDI_rec_1_GT_BIT:
1421     return "PPCISD::ANDI_rec_1_GT_BIT";
1422   case PPCISD::VCMP:            return "PPCISD::VCMP";
1423   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1424   case PPCISD::LBRX:            return "PPCISD::LBRX";
1425   case PPCISD::STBRX:           return "PPCISD::STBRX";
1426   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1427   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1428   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1429   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1430   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1431   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1432   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1433   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1434   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1435   case PPCISD::ST_VSR_SCAL_INT:
1436                                 return "PPCISD::ST_VSR_SCAL_INT";
1437   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1438   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1439   case PPCISD::BDZ:             return "PPCISD::BDZ";
1440   case PPCISD::MFFS:            return "PPCISD::MFFS";
1441   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1442   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1443   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1444   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1445   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1446   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1447   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1448   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1449   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1450   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1451   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1452   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1453   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1454   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1455   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1456   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1457   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1458   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1459   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1460   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1461   case PPCISD::SC:              return "PPCISD::SC";
1462   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1463   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1464   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1465   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1466   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1467   case PPCISD::VABSD:           return "PPCISD::VABSD";
1468   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1469   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1470   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1471   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1472   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1473   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1474   case PPCISD::MAT_PCREL_ADDR:  return "PPCISD::MAT_PCREL_ADDR";
1475   case PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR:
1476     return "PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR";
1477   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1478   case PPCISD::FNMSUB:          return "PPCISD::FNMSUB";
1479   case PPCISD::STRICT_FCTIDZ:
1480     return "PPCISD::STRICT_FCTIDZ";
1481   case PPCISD::STRICT_FCTIWZ:
1482     return "PPCISD::STRICT_FCTIWZ";
1483   case PPCISD::STRICT_FCTIDUZ:
1484     return "PPCISD::STRICT_FCTIDUZ";
1485   case PPCISD::STRICT_FCTIWUZ:
1486     return "PPCISD::STRICT_FCTIWUZ";
1487   }
1488   return nullptr;
1489 }
1490 
1491 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1492                                           EVT VT) const {
1493   if (!VT.isVector())
1494     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1495 
1496   return VT.changeVectorElementTypeToInteger();
1497 }
1498 
1499 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1500   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1501   return true;
1502 }
1503 
1504 //===----------------------------------------------------------------------===//
1505 // Node matching predicates, for use by the tblgen matching code.
1506 //===----------------------------------------------------------------------===//
1507 
1508 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1509 static bool isFloatingPointZero(SDValue Op) {
1510   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1511     return CFP->getValueAPF().isZero();
1512   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1513     // Maybe this has already been legalized into the constant pool?
1514     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1515       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1516         return CFP->getValueAPF().isZero();
1517   }
1518   return false;
1519 }
1520 
1521 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1522 /// true if Op is undef or if it matches the specified value.
1523 static bool isConstantOrUndef(int Op, int Val) {
1524   return Op < 0 || Op == Val;
1525 }
1526 
1527 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1528 /// VPKUHUM instruction.
1529 /// The ShuffleKind distinguishes between big-endian operations with
1530 /// two different inputs (0), either-endian operations with two identical
1531 /// inputs (1), and little-endian operations with two different inputs (2).
1532 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1533 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1534                                SelectionDAG &DAG) {
1535   bool IsLE = DAG.getDataLayout().isLittleEndian();
1536   if (ShuffleKind == 0) {
1537     if (IsLE)
1538       return false;
1539     for (unsigned i = 0; i != 16; ++i)
1540       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1541         return false;
1542   } else if (ShuffleKind == 2) {
1543     if (!IsLE)
1544       return false;
1545     for (unsigned i = 0; i != 16; ++i)
1546       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1547         return false;
1548   } else if (ShuffleKind == 1) {
1549     unsigned j = IsLE ? 0 : 1;
1550     for (unsigned i = 0; i != 8; ++i)
1551       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1552           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1553         return false;
1554   }
1555   return true;
1556 }
1557 
1558 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1559 /// VPKUWUM instruction.
1560 /// The ShuffleKind distinguishes between big-endian operations with
1561 /// two different inputs (0), either-endian operations with two identical
1562 /// inputs (1), and little-endian operations with two different inputs (2).
1563 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1564 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1565                                SelectionDAG &DAG) {
1566   bool IsLE = DAG.getDataLayout().isLittleEndian();
1567   if (ShuffleKind == 0) {
1568     if (IsLE)
1569       return false;
1570     for (unsigned i = 0; i != 16; i += 2)
1571       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1572           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1573         return false;
1574   } else if (ShuffleKind == 2) {
1575     if (!IsLE)
1576       return false;
1577     for (unsigned i = 0; i != 16; i += 2)
1578       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1579           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1580         return false;
1581   } else if (ShuffleKind == 1) {
1582     unsigned j = IsLE ? 0 : 2;
1583     for (unsigned i = 0; i != 8; i += 2)
1584       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1585           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1586           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1587           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1588         return false;
1589   }
1590   return true;
1591 }
1592 
1593 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1594 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1595 /// current subtarget.
1596 ///
1597 /// The ShuffleKind distinguishes between big-endian operations with
1598 /// two different inputs (0), either-endian operations with two identical
1599 /// inputs (1), and little-endian operations with two different inputs (2).
1600 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1601 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1602                                SelectionDAG &DAG) {
1603   const PPCSubtarget& Subtarget =
1604       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1605   if (!Subtarget.hasP8Vector())
1606     return false;
1607 
1608   bool IsLE = DAG.getDataLayout().isLittleEndian();
1609   if (ShuffleKind == 0) {
1610     if (IsLE)
1611       return false;
1612     for (unsigned i = 0; i != 16; i += 4)
1613       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1614           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1615           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1616           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1617         return false;
1618   } else if (ShuffleKind == 2) {
1619     if (!IsLE)
1620       return false;
1621     for (unsigned i = 0; i != 16; i += 4)
1622       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1623           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1624           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1625           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1626         return false;
1627   } else if (ShuffleKind == 1) {
1628     unsigned j = IsLE ? 0 : 4;
1629     for (unsigned i = 0; i != 8; i += 4)
1630       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1631           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1632           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1633           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1634           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1635           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1636           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1637           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1638         return false;
1639   }
1640   return true;
1641 }
1642 
1643 /// isVMerge - Common function, used to match vmrg* shuffles.
1644 ///
1645 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1646                      unsigned LHSStart, unsigned RHSStart) {
1647   if (N->getValueType(0) != MVT::v16i8)
1648     return false;
1649   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1650          "Unsupported merge size!");
1651 
1652   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1653     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1654       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1655                              LHSStart+j+i*UnitSize) ||
1656           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1657                              RHSStart+j+i*UnitSize))
1658         return false;
1659     }
1660   return true;
1661 }
1662 
1663 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1664 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1665 /// The ShuffleKind distinguishes between big-endian merges with two
1666 /// different inputs (0), either-endian merges with two identical inputs (1),
1667 /// and little-endian merges with two different inputs (2).  For the latter,
1668 /// the input operands are swapped (see PPCInstrAltivec.td).
1669 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1670                              unsigned ShuffleKind, SelectionDAG &DAG) {
1671   if (DAG.getDataLayout().isLittleEndian()) {
1672     if (ShuffleKind == 1) // unary
1673       return isVMerge(N, UnitSize, 0, 0);
1674     else if (ShuffleKind == 2) // swapped
1675       return isVMerge(N, UnitSize, 0, 16);
1676     else
1677       return false;
1678   } else {
1679     if (ShuffleKind == 1) // unary
1680       return isVMerge(N, UnitSize, 8, 8);
1681     else if (ShuffleKind == 0) // normal
1682       return isVMerge(N, UnitSize, 8, 24);
1683     else
1684       return false;
1685   }
1686 }
1687 
1688 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1689 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1690 /// The ShuffleKind distinguishes between big-endian merges with two
1691 /// different inputs (0), either-endian merges with two identical inputs (1),
1692 /// and little-endian merges with two different inputs (2).  For the latter,
1693 /// the input operands are swapped (see PPCInstrAltivec.td).
1694 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1695                              unsigned ShuffleKind, SelectionDAG &DAG) {
1696   if (DAG.getDataLayout().isLittleEndian()) {
1697     if (ShuffleKind == 1) // unary
1698       return isVMerge(N, UnitSize, 8, 8);
1699     else if (ShuffleKind == 2) // swapped
1700       return isVMerge(N, UnitSize, 8, 24);
1701     else
1702       return false;
1703   } else {
1704     if (ShuffleKind == 1) // unary
1705       return isVMerge(N, UnitSize, 0, 0);
1706     else if (ShuffleKind == 0) // normal
1707       return isVMerge(N, UnitSize, 0, 16);
1708     else
1709       return false;
1710   }
1711 }
1712 
1713 /**
1714  * Common function used to match vmrgew and vmrgow shuffles
1715  *
1716  * The indexOffset determines whether to look for even or odd words in
1717  * the shuffle mask. This is based on the of the endianness of the target
1718  * machine.
1719  *   - Little Endian:
1720  *     - Use offset of 0 to check for odd elements
1721  *     - Use offset of 4 to check for even elements
1722  *   - Big Endian:
1723  *     - Use offset of 0 to check for even elements
1724  *     - Use offset of 4 to check for odd elements
1725  * A detailed description of the vector element ordering for little endian and
1726  * big endian can be found at
1727  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1728  * Targeting your applications - what little endian and big endian IBM XL C/C++
1729  * compiler differences mean to you
1730  *
1731  * The mask to the shuffle vector instruction specifies the indices of the
1732  * elements from the two input vectors to place in the result. The elements are
1733  * numbered in array-access order, starting with the first vector. These vectors
1734  * are always of type v16i8, thus each vector will contain 16 elements of size
1735  * 8. More info on the shuffle vector can be found in the
1736  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1737  * Language Reference.
1738  *
1739  * The RHSStartValue indicates whether the same input vectors are used (unary)
1740  * or two different input vectors are used, based on the following:
1741  *   - If the instruction uses the same vector for both inputs, the range of the
1742  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1743  *     be 0.
1744  *   - If the instruction has two different vectors then the range of the
1745  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1746  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1747  *     to 31 specify elements in the second vector).
1748  *
1749  * \param[in] N The shuffle vector SD Node to analyze
1750  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1751  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1752  * vector to the shuffle_vector instruction
1753  * \return true iff this shuffle vector represents an even or odd word merge
1754  */
1755 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1756                      unsigned RHSStartValue) {
1757   if (N->getValueType(0) != MVT::v16i8)
1758     return false;
1759 
1760   for (unsigned i = 0; i < 2; ++i)
1761     for (unsigned j = 0; j < 4; ++j)
1762       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1763                              i*RHSStartValue+j+IndexOffset) ||
1764           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1765                              i*RHSStartValue+j+IndexOffset+8))
1766         return false;
1767   return true;
1768 }
1769 
1770 /**
1771  * Determine if the specified shuffle mask is suitable for the vmrgew or
1772  * vmrgow instructions.
1773  *
1774  * \param[in] N The shuffle vector SD Node to analyze
1775  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1776  * \param[in] ShuffleKind Identify the type of merge:
1777  *   - 0 = big-endian merge with two different inputs;
1778  *   - 1 = either-endian merge with two identical inputs;
1779  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1780  *     little-endian merges).
1781  * \param[in] DAG The current SelectionDAG
1782  * \return true iff this shuffle mask
1783  */
1784 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1785                               unsigned ShuffleKind, SelectionDAG &DAG) {
1786   if (DAG.getDataLayout().isLittleEndian()) {
1787     unsigned indexOffset = CheckEven ? 4 : 0;
1788     if (ShuffleKind == 1) // Unary
1789       return isVMerge(N, indexOffset, 0);
1790     else if (ShuffleKind == 2) // swapped
1791       return isVMerge(N, indexOffset, 16);
1792     else
1793       return false;
1794   }
1795   else {
1796     unsigned indexOffset = CheckEven ? 0 : 4;
1797     if (ShuffleKind == 1) // Unary
1798       return isVMerge(N, indexOffset, 0);
1799     else if (ShuffleKind == 0) // Normal
1800       return isVMerge(N, indexOffset, 16);
1801     else
1802       return false;
1803   }
1804   return false;
1805 }
1806 
1807 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1808 /// amount, otherwise return -1.
1809 /// The ShuffleKind distinguishes between big-endian operations with two
1810 /// different inputs (0), either-endian operations with two identical inputs
1811 /// (1), and little-endian operations with two different inputs (2).  For the
1812 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1813 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1814                              SelectionDAG &DAG) {
1815   if (N->getValueType(0) != MVT::v16i8)
1816     return -1;
1817 
1818   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1819 
1820   // Find the first non-undef value in the shuffle mask.
1821   unsigned i;
1822   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1823     /*search*/;
1824 
1825   if (i == 16) return -1;  // all undef.
1826 
1827   // Otherwise, check to see if the rest of the elements are consecutively
1828   // numbered from this value.
1829   unsigned ShiftAmt = SVOp->getMaskElt(i);
1830   if (ShiftAmt < i) return -1;
1831 
1832   ShiftAmt -= i;
1833   bool isLE = DAG.getDataLayout().isLittleEndian();
1834 
1835   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1836     // Check the rest of the elements to see if they are consecutive.
1837     for (++i; i != 16; ++i)
1838       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1839         return -1;
1840   } else if (ShuffleKind == 1) {
1841     // Check the rest of the elements to see if they are consecutive.
1842     for (++i; i != 16; ++i)
1843       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1844         return -1;
1845   } else
1846     return -1;
1847 
1848   if (isLE)
1849     ShiftAmt = 16 - ShiftAmt;
1850 
1851   return ShiftAmt;
1852 }
1853 
1854 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1855 /// specifies a splat of a single element that is suitable for input to
1856 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1857 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1858   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1859          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1860 
1861   // The consecutive indices need to specify an element, not part of two
1862   // different elements.  So abandon ship early if this isn't the case.
1863   if (N->getMaskElt(0) % EltSize != 0)
1864     return false;
1865 
1866   // This is a splat operation if each element of the permute is the same, and
1867   // if the value doesn't reference the second vector.
1868   unsigned ElementBase = N->getMaskElt(0);
1869 
1870   // FIXME: Handle UNDEF elements too!
1871   if (ElementBase >= 16)
1872     return false;
1873 
1874   // Check that the indices are consecutive, in the case of a multi-byte element
1875   // splatted with a v16i8 mask.
1876   for (unsigned i = 1; i != EltSize; ++i)
1877     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1878       return false;
1879 
1880   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1881     if (N->getMaskElt(i) < 0) continue;
1882     for (unsigned j = 0; j != EltSize; ++j)
1883       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1884         return false;
1885   }
1886   return true;
1887 }
1888 
1889 /// Check that the mask is shuffling N byte elements. Within each N byte
1890 /// element of the mask, the indices could be either in increasing or
1891 /// decreasing order as long as they are consecutive.
1892 /// \param[in] N the shuffle vector SD Node to analyze
1893 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1894 /// Word/DoubleWord/QuadWord).
1895 /// \param[in] StepLen the delta indices number among the N byte element, if
1896 /// the mask is in increasing/decreasing order then it is 1/-1.
1897 /// \return true iff the mask is shuffling N byte elements.
1898 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1899                                    int StepLen) {
1900   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1901          "Unexpected element width.");
1902   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1903 
1904   unsigned NumOfElem = 16 / Width;
1905   unsigned MaskVal[16]; //  Width is never greater than 16
1906   for (unsigned i = 0; i < NumOfElem; ++i) {
1907     MaskVal[0] = N->getMaskElt(i * Width);
1908     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1909       return false;
1910     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1911       return false;
1912     }
1913 
1914     for (unsigned int j = 1; j < Width; ++j) {
1915       MaskVal[j] = N->getMaskElt(i * Width + j);
1916       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1917         return false;
1918       }
1919     }
1920   }
1921 
1922   return true;
1923 }
1924 
1925 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1926                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1927   if (!isNByteElemShuffleMask(N, 4, 1))
1928     return false;
1929 
1930   // Now we look at mask elements 0,4,8,12
1931   unsigned M0 = N->getMaskElt(0) / 4;
1932   unsigned M1 = N->getMaskElt(4) / 4;
1933   unsigned M2 = N->getMaskElt(8) / 4;
1934   unsigned M3 = N->getMaskElt(12) / 4;
1935   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1936   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1937 
1938   // Below, let H and L be arbitrary elements of the shuffle mask
1939   // where H is in the range [4,7] and L is in the range [0,3].
1940   // H, 1, 2, 3 or L, 5, 6, 7
1941   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1942       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1943     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1944     InsertAtByte = IsLE ? 12 : 0;
1945     Swap = M0 < 4;
1946     return true;
1947   }
1948   // 0, H, 2, 3 or 4, L, 6, 7
1949   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1950       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1951     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1952     InsertAtByte = IsLE ? 8 : 4;
1953     Swap = M1 < 4;
1954     return true;
1955   }
1956   // 0, 1, H, 3 or 4, 5, L, 7
1957   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1958       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1959     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1960     InsertAtByte = IsLE ? 4 : 8;
1961     Swap = M2 < 4;
1962     return true;
1963   }
1964   // 0, 1, 2, H or 4, 5, 6, L
1965   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1966       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1967     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1968     InsertAtByte = IsLE ? 0 : 12;
1969     Swap = M3 < 4;
1970     return true;
1971   }
1972 
1973   // If both vector operands for the shuffle are the same vector, the mask will
1974   // contain only elements from the first one and the second one will be undef.
1975   if (N->getOperand(1).isUndef()) {
1976     ShiftElts = 0;
1977     Swap = true;
1978     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1979     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1980       InsertAtByte = IsLE ? 12 : 0;
1981       return true;
1982     }
1983     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1984       InsertAtByte = IsLE ? 8 : 4;
1985       return true;
1986     }
1987     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1988       InsertAtByte = IsLE ? 4 : 8;
1989       return true;
1990     }
1991     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1992       InsertAtByte = IsLE ? 0 : 12;
1993       return true;
1994     }
1995   }
1996 
1997   return false;
1998 }
1999 
2000 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
2001                                bool &Swap, bool IsLE) {
2002   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2003   // Ensure each byte index of the word is consecutive.
2004   if (!isNByteElemShuffleMask(N, 4, 1))
2005     return false;
2006 
2007   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
2008   unsigned M0 = N->getMaskElt(0) / 4;
2009   unsigned M1 = N->getMaskElt(4) / 4;
2010   unsigned M2 = N->getMaskElt(8) / 4;
2011   unsigned M3 = N->getMaskElt(12) / 4;
2012 
2013   // If both vector operands for the shuffle are the same vector, the mask will
2014   // contain only elements from the first one and the second one will be undef.
2015   if (N->getOperand(1).isUndef()) {
2016     assert(M0 < 4 && "Indexing into an undef vector?");
2017     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
2018       return false;
2019 
2020     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
2021     Swap = false;
2022     return true;
2023   }
2024 
2025   // Ensure each word index of the ShuffleVector Mask is consecutive.
2026   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
2027     return false;
2028 
2029   if (IsLE) {
2030     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
2031       // Input vectors don't need to be swapped if the leading element
2032       // of the result is one of the 3 left elements of the second vector
2033       // (or if there is no shift to be done at all).
2034       Swap = false;
2035       ShiftElts = (8 - M0) % 8;
2036     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2037       // Input vectors need to be swapped if the leading element
2038       // of the result is one of the 3 left elements of the first vector
2039       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2040       Swap = true;
2041       ShiftElts = (4 - M0) % 4;
2042     }
2043 
2044     return true;
2045   } else {                                          // BE
2046     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2047       // Input vectors don't need to be swapped if the leading element
2048       // of the result is one of the 4 elements of the first vector.
2049       Swap = false;
2050       ShiftElts = M0;
2051     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2052       // Input vectors need to be swapped if the leading element
2053       // of the result is one of the 4 elements of the right vector.
2054       Swap = true;
2055       ShiftElts = M0 - 4;
2056     }
2057 
2058     return true;
2059   }
2060 }
2061 
2062 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2063   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2064 
2065   if (!isNByteElemShuffleMask(N, Width, -1))
2066     return false;
2067 
2068   for (int i = 0; i < 16; i += Width)
2069     if (N->getMaskElt(i) != i + Width - 1)
2070       return false;
2071 
2072   return true;
2073 }
2074 
2075 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2076   return isXXBRShuffleMaskHelper(N, 2);
2077 }
2078 
2079 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2080   return isXXBRShuffleMaskHelper(N, 4);
2081 }
2082 
2083 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2084   return isXXBRShuffleMaskHelper(N, 8);
2085 }
2086 
2087 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2088   return isXXBRShuffleMaskHelper(N, 16);
2089 }
2090 
2091 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2092 /// if the inputs to the instruction should be swapped and set \p DM to the
2093 /// value for the immediate.
2094 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2095 /// AND element 0 of the result comes from the first input (LE) or second input
2096 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2097 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2098 /// mask.
2099 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2100                                bool &Swap, bool IsLE) {
2101   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2102 
2103   // Ensure each byte index of the double word is consecutive.
2104   if (!isNByteElemShuffleMask(N, 8, 1))
2105     return false;
2106 
2107   unsigned M0 = N->getMaskElt(0) / 8;
2108   unsigned M1 = N->getMaskElt(8) / 8;
2109   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2110 
2111   // If both vector operands for the shuffle are the same vector, the mask will
2112   // contain only elements from the first one and the second one will be undef.
2113   if (N->getOperand(1).isUndef()) {
2114     if ((M0 | M1) < 2) {
2115       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2116       Swap = false;
2117       return true;
2118     } else
2119       return false;
2120   }
2121 
2122   if (IsLE) {
2123     if (M0 > 1 && M1 < 2) {
2124       Swap = false;
2125     } else if (M0 < 2 && M1 > 1) {
2126       M0 = (M0 + 2) % 4;
2127       M1 = (M1 + 2) % 4;
2128       Swap = true;
2129     } else
2130       return false;
2131 
2132     // Note: if control flow comes here that means Swap is already set above
2133     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2134     return true;
2135   } else { // BE
2136     if (M0 < 2 && M1 > 1) {
2137       Swap = false;
2138     } else if (M0 > 1 && M1 < 2) {
2139       M0 = (M0 + 2) % 4;
2140       M1 = (M1 + 2) % 4;
2141       Swap = true;
2142     } else
2143       return false;
2144 
2145     // Note: if control flow comes here that means Swap is already set above
2146     DM = (M0 << 1) + (M1 & 1);
2147     return true;
2148   }
2149 }
2150 
2151 
2152 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2153 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2154 /// elements are counted from the left of the vector register).
2155 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2156                                          SelectionDAG &DAG) {
2157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2158   assert(isSplatShuffleMask(SVOp, EltSize));
2159   if (DAG.getDataLayout().isLittleEndian())
2160     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2161   else
2162     return SVOp->getMaskElt(0) / EltSize;
2163 }
2164 
2165 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2166 /// by using a vspltis[bhw] instruction of the specified element size, return
2167 /// the constant being splatted.  The ByteSize field indicates the number of
2168 /// bytes of each element [124] -> [bhw].
2169 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2170   SDValue OpVal(nullptr, 0);
2171 
2172   // If ByteSize of the splat is bigger than the element size of the
2173   // build_vector, then we have a case where we are checking for a splat where
2174   // multiple elements of the buildvector are folded together into a single
2175   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2176   unsigned EltSize = 16/N->getNumOperands();
2177   if (EltSize < ByteSize) {
2178     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2179     SDValue UniquedVals[4];
2180     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2181 
2182     // See if all of the elements in the buildvector agree across.
2183     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2184       if (N->getOperand(i).isUndef()) continue;
2185       // If the element isn't a constant, bail fully out.
2186       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2187 
2188       if (!UniquedVals[i&(Multiple-1)].getNode())
2189         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2190       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2191         return SDValue();  // no match.
2192     }
2193 
2194     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2195     // either constant or undef values that are identical for each chunk.  See
2196     // if these chunks can form into a larger vspltis*.
2197 
2198     // Check to see if all of the leading entries are either 0 or -1.  If
2199     // neither, then this won't fit into the immediate field.
2200     bool LeadingZero = true;
2201     bool LeadingOnes = true;
2202     for (unsigned i = 0; i != Multiple-1; ++i) {
2203       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2204 
2205       LeadingZero &= isNullConstant(UniquedVals[i]);
2206       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2207     }
2208     // Finally, check the least significant entry.
2209     if (LeadingZero) {
2210       if (!UniquedVals[Multiple-1].getNode())
2211         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2212       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2213       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2214         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2215     }
2216     if (LeadingOnes) {
2217       if (!UniquedVals[Multiple-1].getNode())
2218         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2219       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2220       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2221         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2222     }
2223 
2224     return SDValue();
2225   }
2226 
2227   // Check to see if this buildvec has a single non-undef value in its elements.
2228   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2229     if (N->getOperand(i).isUndef()) continue;
2230     if (!OpVal.getNode())
2231       OpVal = N->getOperand(i);
2232     else if (OpVal != N->getOperand(i))
2233       return SDValue();
2234   }
2235 
2236   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2237 
2238   unsigned ValSizeInBytes = EltSize;
2239   uint64_t Value = 0;
2240   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2241     Value = CN->getZExtValue();
2242   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2243     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2244     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2245   }
2246 
2247   // If the splat value is larger than the element value, then we can never do
2248   // this splat.  The only case that we could fit the replicated bits into our
2249   // immediate field for would be zero, and we prefer to use vxor for it.
2250   if (ValSizeInBytes < ByteSize) return SDValue();
2251 
2252   // If the element value is larger than the splat value, check if it consists
2253   // of a repeated bit pattern of size ByteSize.
2254   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2255     return SDValue();
2256 
2257   // Properly sign extend the value.
2258   int MaskVal = SignExtend32(Value, ByteSize * 8);
2259 
2260   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2261   if (MaskVal == 0) return SDValue();
2262 
2263   // Finally, if this value fits in a 5 bit sext field, return it
2264   if (SignExtend32<5>(MaskVal) == MaskVal)
2265     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2266   return SDValue();
2267 }
2268 
2269 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2270 /// amount, otherwise return -1.
2271 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2272   EVT VT = N->getValueType(0);
2273   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2274     return -1;
2275 
2276   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2277 
2278   // Find the first non-undef value in the shuffle mask.
2279   unsigned i;
2280   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2281     /*search*/;
2282 
2283   if (i == 4) return -1;  // all undef.
2284 
2285   // Otherwise, check to see if the rest of the elements are consecutively
2286   // numbered from this value.
2287   unsigned ShiftAmt = SVOp->getMaskElt(i);
2288   if (ShiftAmt < i) return -1;
2289   ShiftAmt -= i;
2290 
2291   // Check the rest of the elements to see if they are consecutive.
2292   for (++i; i != 4; ++i)
2293     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2294       return -1;
2295 
2296   return ShiftAmt;
2297 }
2298 
2299 //===----------------------------------------------------------------------===//
2300 //  Addressing Mode Selection
2301 //===----------------------------------------------------------------------===//
2302 
2303 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2304 /// or 64-bit immediate, and if the value can be accurately represented as a
2305 /// sign extension from a 16-bit value.  If so, this returns true and the
2306 /// immediate.
2307 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2308   if (!isa<ConstantSDNode>(N))
2309     return false;
2310 
2311   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2312   if (N->getValueType(0) == MVT::i32)
2313     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2314   else
2315     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2316 }
2317 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2318   return isIntS16Immediate(Op.getNode(), Imm);
2319 }
2320 
2321 
2322 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2323 /// be represented as an indexed [r+r] operation.
2324 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2325                                                SDValue &Index,
2326                                                SelectionDAG &DAG) const {
2327   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2328       UI != E; ++UI) {
2329     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2330       if (Memop->getMemoryVT() == MVT::f64) {
2331           Base = N.getOperand(0);
2332           Index = N.getOperand(1);
2333           return true;
2334       }
2335     }
2336   }
2337   return false;
2338 }
2339 
2340 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2341 /// can be represented as an indexed [r+r] operation.  Returns false if it
2342 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2343 /// non-zero and N can be represented by a base register plus a signed 16-bit
2344 /// displacement, make a more precise judgement by checking (displacement % \p
2345 /// EncodingAlignment).
2346 bool PPCTargetLowering::SelectAddressRegReg(
2347     SDValue N, SDValue &Base, SDValue &Index, SelectionDAG &DAG,
2348     MaybeAlign EncodingAlignment) const {
2349   // If we have a PC Relative target flag don't select as [reg+reg]. It will be
2350   // a [pc+imm].
2351   if (SelectAddressPCRel(N, Base))
2352     return false;
2353 
2354   int16_t Imm = 0;
2355   if (N.getOpcode() == ISD::ADD) {
2356     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2357     // SPE load/store can only handle 8-bit offsets.
2358     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2359         return true;
2360     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2361         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2362       return false; // r+i
2363     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2364       return false;    // r+i
2365 
2366     Base = N.getOperand(0);
2367     Index = N.getOperand(1);
2368     return true;
2369   } else if (N.getOpcode() == ISD::OR) {
2370     if (isIntS16Immediate(N.getOperand(1), Imm) &&
2371         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm)))
2372       return false; // r+i can fold it if we can.
2373 
2374     // If this is an or of disjoint bitfields, we can codegen this as an add
2375     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2376     // disjoint.
2377     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2378 
2379     if (LHSKnown.Zero.getBoolValue()) {
2380       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2381       // If all of the bits are known zero on the LHS or RHS, the add won't
2382       // carry.
2383       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2384         Base = N.getOperand(0);
2385         Index = N.getOperand(1);
2386         return true;
2387       }
2388     }
2389   }
2390 
2391   return false;
2392 }
2393 
2394 // If we happen to be doing an i64 load or store into a stack slot that has
2395 // less than a 4-byte alignment, then the frame-index elimination may need to
2396 // use an indexed load or store instruction (because the offset may not be a
2397 // multiple of 4). The extra register needed to hold the offset comes from the
2398 // register scavenger, and it is possible that the scavenger will need to use
2399 // an emergency spill slot. As a result, we need to make sure that a spill slot
2400 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2401 // stack slot.
2402 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2403   // FIXME: This does not handle the LWA case.
2404   if (VT != MVT::i64)
2405     return;
2406 
2407   // NOTE: We'll exclude negative FIs here, which come from argument
2408   // lowering, because there are no known test cases triggering this problem
2409   // using packed structures (or similar). We can remove this exclusion if
2410   // we find such a test case. The reason why this is so test-case driven is
2411   // because this entire 'fixup' is only to prevent crashes (from the
2412   // register scavenger) on not-really-valid inputs. For example, if we have:
2413   //   %a = alloca i1
2414   //   %b = bitcast i1* %a to i64*
2415   //   store i64* a, i64 b
2416   // then the store should really be marked as 'align 1', but is not. If it
2417   // were marked as 'align 1' then the indexed form would have been
2418   // instruction-selected initially, and the problem this 'fixup' is preventing
2419   // won't happen regardless.
2420   if (FrameIdx < 0)
2421     return;
2422 
2423   MachineFunction &MF = DAG.getMachineFunction();
2424   MachineFrameInfo &MFI = MF.getFrameInfo();
2425 
2426   if (MFI.getObjectAlign(FrameIdx) >= Align(4))
2427     return;
2428 
2429   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2430   FuncInfo->setHasNonRISpills();
2431 }
2432 
2433 /// Returns true if the address N can be represented by a base register plus
2434 /// a signed 16-bit displacement [r+imm], and if it is not better
2435 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2436 /// displacements that are multiples of that value.
2437 bool PPCTargetLowering::SelectAddressRegImm(
2438     SDValue N, SDValue &Disp, SDValue &Base, SelectionDAG &DAG,
2439     MaybeAlign EncodingAlignment) const {
2440   // FIXME dl should come from parent load or store, not from address
2441   SDLoc dl(N);
2442 
2443   // If we have a PC Relative target flag don't select as [reg+imm]. It will be
2444   // a [pc+imm].
2445   if (SelectAddressPCRel(N, Base))
2446     return false;
2447 
2448   // If this can be more profitably realized as r+r, fail.
2449   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2450     return false;
2451 
2452   if (N.getOpcode() == ISD::ADD) {
2453     int16_t imm = 0;
2454     if (isIntS16Immediate(N.getOperand(1), imm) &&
2455         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2456       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2457       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2458         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2459         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2460       } else {
2461         Base = N.getOperand(0);
2462       }
2463       return true; // [r+i]
2464     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2465       // Match LOAD (ADD (X, Lo(G))).
2466       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2467              && "Cannot handle constant offsets yet!");
2468       Disp = N.getOperand(1).getOperand(0);  // The global address.
2469       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2470              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2471              Disp.getOpcode() == ISD::TargetConstantPool ||
2472              Disp.getOpcode() == ISD::TargetJumpTable);
2473       Base = N.getOperand(0);
2474       return true;  // [&g+r]
2475     }
2476   } else if (N.getOpcode() == ISD::OR) {
2477     int16_t imm = 0;
2478     if (isIntS16Immediate(N.getOperand(1), imm) &&
2479         (!EncodingAlignment || isAligned(*EncodingAlignment, imm))) {
2480       // If this is an or of disjoint bitfields, we can codegen this as an add
2481       // (for better address arithmetic) if the LHS and RHS of the OR are
2482       // provably disjoint.
2483       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2484 
2485       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2486         // If all of the bits are known zero on the LHS or RHS, the add won't
2487         // carry.
2488         if (FrameIndexSDNode *FI =
2489               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2490           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2491           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2492         } else {
2493           Base = N.getOperand(0);
2494         }
2495         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2496         return true;
2497       }
2498     }
2499   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2500     // Loading from a constant address.
2501 
2502     // If this address fits entirely in a 16-bit sext immediate field, codegen
2503     // this as "d, 0"
2504     int16_t Imm;
2505     if (isIntS16Immediate(CN, Imm) &&
2506         (!EncodingAlignment || isAligned(*EncodingAlignment, Imm))) {
2507       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2508       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2509                              CN->getValueType(0));
2510       return true;
2511     }
2512 
2513     // Handle 32-bit sext immediates with LIS + addr mode.
2514     if ((CN->getValueType(0) == MVT::i32 ||
2515          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2516         (!EncodingAlignment ||
2517          isAligned(*EncodingAlignment, CN->getZExtValue()))) {
2518       int Addr = (int)CN->getZExtValue();
2519 
2520       // Otherwise, break this down into an LIS + disp.
2521       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2522 
2523       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2524                                    MVT::i32);
2525       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2526       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2527       return true;
2528     }
2529   }
2530 
2531   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2532   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2533     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2534     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2535   } else
2536     Base = N;
2537   return true;      // [r+0]
2538 }
2539 
2540 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2541 /// represented as an indexed [r+r] operation.
2542 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2543                                                 SDValue &Index,
2544                                                 SelectionDAG &DAG) const {
2545   // Check to see if we can easily represent this as an [r+r] address.  This
2546   // will fail if it thinks that the address is more profitably represented as
2547   // reg+imm, e.g. where imm = 0.
2548   if (SelectAddressRegReg(N, Base, Index, DAG))
2549     return true;
2550 
2551   // If the address is the result of an add, we will utilize the fact that the
2552   // address calculation includes an implicit add.  However, we can reduce
2553   // register pressure if we do not materialize a constant just for use as the
2554   // index register.  We only get rid of the add if it is not an add of a
2555   // value and a 16-bit signed constant and both have a single use.
2556   int16_t imm = 0;
2557   if (N.getOpcode() == ISD::ADD &&
2558       (!isIntS16Immediate(N.getOperand(1), imm) ||
2559        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2560     Base = N.getOperand(0);
2561     Index = N.getOperand(1);
2562     return true;
2563   }
2564 
2565   // Otherwise, do it the hard way, using R0 as the base register.
2566   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2567                          N.getValueType());
2568   Index = N;
2569   return true;
2570 }
2571 
2572 template <typename Ty> static bool isValidPCRelNode(SDValue N) {
2573   Ty *PCRelCand = dyn_cast<Ty>(N);
2574   return PCRelCand && (PCRelCand->getTargetFlags() & PPCII::MO_PCREL_FLAG);
2575 }
2576 
2577 /// Returns true if this address is a PC Relative address.
2578 /// PC Relative addresses are marked with the flag PPCII::MO_PCREL_FLAG
2579 /// or if the node opcode is PPCISD::MAT_PCREL_ADDR.
2580 bool PPCTargetLowering::SelectAddressPCRel(SDValue N, SDValue &Base) const {
2581   // This is a materialize PC Relative node. Always select this as PC Relative.
2582   Base = N;
2583   if (N.getOpcode() == PPCISD::MAT_PCREL_ADDR)
2584     return true;
2585   if (isValidPCRelNode<ConstantPoolSDNode>(N) ||
2586       isValidPCRelNode<GlobalAddressSDNode>(N) ||
2587       isValidPCRelNode<JumpTableSDNode>(N) ||
2588       isValidPCRelNode<BlockAddressSDNode>(N))
2589     return true;
2590   return false;
2591 }
2592 
2593 /// Returns true if we should use a direct load into vector instruction
2594 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2595 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2596 
2597   // If there are any other uses other than scalar to vector, then we should
2598   // keep it as a scalar load -> direct move pattern to prevent multiple
2599   // loads.
2600   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2601   if (!LD)
2602     return false;
2603 
2604   EVT MemVT = LD->getMemoryVT();
2605   if (!MemVT.isSimple())
2606     return false;
2607   switch(MemVT.getSimpleVT().SimpleTy) {
2608   case MVT::i64:
2609     break;
2610   case MVT::i32:
2611     if (!ST.hasP8Vector())
2612       return false;
2613     break;
2614   case MVT::i16:
2615   case MVT::i8:
2616     if (!ST.hasP9Vector())
2617       return false;
2618     break;
2619   default:
2620     return false;
2621   }
2622 
2623   SDValue LoadedVal(N, 0);
2624   if (!LoadedVal.hasOneUse())
2625     return false;
2626 
2627   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2628        UI != UE; ++UI)
2629     if (UI.getUse().get().getResNo() == 0 &&
2630         UI->getOpcode() != ISD::SCALAR_TO_VECTOR &&
2631         UI->getOpcode() != PPCISD::SCALAR_TO_VECTOR_PERMUTED)
2632       return false;
2633 
2634   return true;
2635 }
2636 
2637 /// getPreIndexedAddressParts - returns true by value, base pointer and
2638 /// offset pointer and addressing mode by reference if the node's address
2639 /// can be legally represented as pre-indexed load / store address.
2640 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2641                                                   SDValue &Offset,
2642                                                   ISD::MemIndexedMode &AM,
2643                                                   SelectionDAG &DAG) const {
2644   if (DisablePPCPreinc) return false;
2645 
2646   bool isLoad = true;
2647   SDValue Ptr;
2648   EVT VT;
2649   unsigned Alignment;
2650   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2651     Ptr = LD->getBasePtr();
2652     VT = LD->getMemoryVT();
2653     Alignment = LD->getAlignment();
2654   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2655     Ptr = ST->getBasePtr();
2656     VT  = ST->getMemoryVT();
2657     Alignment = ST->getAlignment();
2658     isLoad = false;
2659   } else
2660     return false;
2661 
2662   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2663   // instructions because we can fold these into a more efficient instruction
2664   // instead, (such as LXSD).
2665   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2666     return false;
2667   }
2668 
2669   // PowerPC doesn't have preinc load/store instructions for vectors
2670   if (VT.isVector())
2671     return false;
2672 
2673   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2674     // Common code will reject creating a pre-inc form if the base pointer
2675     // is a frame index, or if N is a store and the base pointer is either
2676     // the same as or a predecessor of the value being stored.  Check for
2677     // those situations here, and try with swapped Base/Offset instead.
2678     bool Swap = false;
2679 
2680     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2681       Swap = true;
2682     else if (!isLoad) {
2683       SDValue Val = cast<StoreSDNode>(N)->getValue();
2684       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2685         Swap = true;
2686     }
2687 
2688     if (Swap)
2689       std::swap(Base, Offset);
2690 
2691     AM = ISD::PRE_INC;
2692     return true;
2693   }
2694 
2695   // LDU/STU can only handle immediates that are a multiple of 4.
2696   if (VT != MVT::i64) {
2697     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, None))
2698       return false;
2699   } else {
2700     // LDU/STU need an address with at least 4-byte alignment.
2701     if (Alignment < 4)
2702       return false;
2703 
2704     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, Align(4)))
2705       return false;
2706   }
2707 
2708   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2709     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2710     // sext i32 to i64 when addr mode is r+i.
2711     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2712         LD->getExtensionType() == ISD::SEXTLOAD &&
2713         isa<ConstantSDNode>(Offset))
2714       return false;
2715   }
2716 
2717   AM = ISD::PRE_INC;
2718   return true;
2719 }
2720 
2721 //===----------------------------------------------------------------------===//
2722 //  LowerOperation implementation
2723 //===----------------------------------------------------------------------===//
2724 
2725 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2726 /// and LoOpFlags to the target MO flags.
2727 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2728                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2729                                const GlobalValue *GV = nullptr) {
2730   HiOpFlags = PPCII::MO_HA;
2731   LoOpFlags = PPCII::MO_LO;
2732 
2733   // Don't use the pic base if not in PIC relocation model.
2734   if (IsPIC) {
2735     HiOpFlags |= PPCII::MO_PIC_FLAG;
2736     LoOpFlags |= PPCII::MO_PIC_FLAG;
2737   }
2738 }
2739 
2740 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2741                              SelectionDAG &DAG) {
2742   SDLoc DL(HiPart);
2743   EVT PtrVT = HiPart.getValueType();
2744   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2745 
2746   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2747   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2748 
2749   // With PIC, the first instruction is actually "GR+hi(&G)".
2750   if (isPIC)
2751     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2752                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2753 
2754   // Generate non-pic code that has direct accesses to the constant pool.
2755   // The address of the global is just (hi(&g)+lo(&g)).
2756   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2757 }
2758 
2759 static void setUsesTOCBasePtr(MachineFunction &MF) {
2760   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2761   FuncInfo->setUsesTOCBasePtr();
2762 }
2763 
2764 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2765   setUsesTOCBasePtr(DAG.getMachineFunction());
2766 }
2767 
2768 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2769                                        SDValue GA) const {
2770   const bool Is64Bit = Subtarget.isPPC64();
2771   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2772   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2773                         : Subtarget.isAIXABI()
2774                               ? DAG.getRegister(PPC::R2, VT)
2775                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2776   SDValue Ops[] = { GA, Reg };
2777   return DAG.getMemIntrinsicNode(
2778       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2779       MachinePointerInfo::getGOT(DAG.getMachineFunction()), None,
2780       MachineMemOperand::MOLoad);
2781 }
2782 
2783 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2784                                              SelectionDAG &DAG) const {
2785   EVT PtrVT = Op.getValueType();
2786   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2787   const Constant *C = CP->getConstVal();
2788 
2789   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2790   // The actual address of the GlobalValue is stored in the TOC.
2791   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2792     if (Subtarget.isUsingPCRelativeCalls()) {
2793       SDLoc DL(CP);
2794       EVT Ty = getPointerTy(DAG.getDataLayout());
2795       SDValue ConstPool = DAG.getTargetConstantPool(
2796           C, Ty, CP->getAlign(), CP->getOffset(), PPCII::MO_PCREL_FLAG);
2797       return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, ConstPool);
2798     }
2799     setUsesTOCBasePtr(DAG);
2800     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0);
2801     return getTOCEntry(DAG, SDLoc(CP), GA);
2802   }
2803 
2804   unsigned MOHiFlag, MOLoFlag;
2805   bool IsPIC = isPositionIndependent();
2806   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2807 
2808   if (IsPIC && Subtarget.isSVR4ABI()) {
2809     SDValue GA =
2810         DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), PPCII::MO_PIC_FLAG);
2811     return getTOCEntry(DAG, SDLoc(CP), GA);
2812   }
2813 
2814   SDValue CPIHi =
2815       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOHiFlag);
2816   SDValue CPILo =
2817       DAG.getTargetConstantPool(C, PtrVT, CP->getAlign(), 0, MOLoFlag);
2818   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2819 }
2820 
2821 // For 64-bit PowerPC, prefer the more compact relative encodings.
2822 // This trades 32 bits per jump table entry for one or two instructions
2823 // on the jump site.
2824 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2825   if (isJumpTableRelative())
2826     return MachineJumpTableInfo::EK_LabelDifference32;
2827 
2828   return TargetLowering::getJumpTableEncoding();
2829 }
2830 
2831 bool PPCTargetLowering::isJumpTableRelative() const {
2832   if (UseAbsoluteJumpTables)
2833     return false;
2834   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2835     return true;
2836   return TargetLowering::isJumpTableRelative();
2837 }
2838 
2839 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2840                                                     SelectionDAG &DAG) const {
2841   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2842     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2843 
2844   switch (getTargetMachine().getCodeModel()) {
2845   case CodeModel::Small:
2846   case CodeModel::Medium:
2847     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2848   default:
2849     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2850                        getPointerTy(DAG.getDataLayout()));
2851   }
2852 }
2853 
2854 const MCExpr *
2855 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2856                                                 unsigned JTI,
2857                                                 MCContext &Ctx) const {
2858   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2859     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2860 
2861   switch (getTargetMachine().getCodeModel()) {
2862   case CodeModel::Small:
2863   case CodeModel::Medium:
2864     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2865   default:
2866     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2867   }
2868 }
2869 
2870 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2871   EVT PtrVT = Op.getValueType();
2872   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2873 
2874   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2875   if (Subtarget.isUsingPCRelativeCalls()) {
2876     SDLoc DL(JT);
2877     EVT Ty = getPointerTy(DAG.getDataLayout());
2878     SDValue GA =
2879         DAG.getTargetJumpTable(JT->getIndex(), Ty, PPCII::MO_PCREL_FLAG);
2880     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2881     return MatAddr;
2882   }
2883 
2884   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2885   // The actual address of the GlobalValue is stored in the TOC.
2886   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2887     setUsesTOCBasePtr(DAG);
2888     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2889     return getTOCEntry(DAG, SDLoc(JT), GA);
2890   }
2891 
2892   unsigned MOHiFlag, MOLoFlag;
2893   bool IsPIC = isPositionIndependent();
2894   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2895 
2896   if (IsPIC && Subtarget.isSVR4ABI()) {
2897     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2898                                         PPCII::MO_PIC_FLAG);
2899     return getTOCEntry(DAG, SDLoc(GA), GA);
2900   }
2901 
2902   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2903   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2904   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2905 }
2906 
2907 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2908                                              SelectionDAG &DAG) const {
2909   EVT PtrVT = Op.getValueType();
2910   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2911   const BlockAddress *BA = BASDN->getBlockAddress();
2912 
2913   // isUsingPCRelativeCalls() returns true when PCRelative is enabled
2914   if (Subtarget.isUsingPCRelativeCalls()) {
2915     SDLoc DL(BASDN);
2916     EVT Ty = getPointerTy(DAG.getDataLayout());
2917     SDValue GA = DAG.getTargetBlockAddress(BA, Ty, BASDN->getOffset(),
2918                                            PPCII::MO_PCREL_FLAG);
2919     SDValue MatAddr = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
2920     return MatAddr;
2921   }
2922 
2923   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2924   // The actual BlockAddress is stored in the TOC.
2925   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2926     setUsesTOCBasePtr(DAG);
2927     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2928     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2929   }
2930 
2931   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2932   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2933     return getTOCEntry(
2934         DAG, SDLoc(BASDN),
2935         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2936 
2937   unsigned MOHiFlag, MOLoFlag;
2938   bool IsPIC = isPositionIndependent();
2939   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2940   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2941   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2942   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2943 }
2944 
2945 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2946                                               SelectionDAG &DAG) const {
2947   // FIXME: TLS addresses currently use medium model code sequences,
2948   // which is the most useful form.  Eventually support for small and
2949   // large models could be added if users need it, at the cost of
2950   // additional complexity.
2951   if (Subtarget.isUsingPCRelativeCalls() && !EnablePPCPCRelTLS)
2952     report_fatal_error("Thread local storage is not supported with pc-relative"
2953                        " addressing - please compile with -mno-pcrel");
2954   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2955   if (DAG.getTarget().useEmulatedTLS())
2956     return LowerToTLSEmulatedModel(GA, DAG);
2957 
2958   SDLoc dl(GA);
2959   const GlobalValue *GV = GA->getGlobal();
2960   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2961   bool is64bit = Subtarget.isPPC64();
2962   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2963   PICLevel::Level picLevel = M->getPICLevel();
2964 
2965   const TargetMachine &TM = getTargetMachine();
2966   TLSModel::Model Model = TM.getTLSModel(GV);
2967 
2968   if (Model == TLSModel::LocalExec) {
2969     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2970                                                PPCII::MO_TPREL_HA);
2971     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2972                                                PPCII::MO_TPREL_LO);
2973     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2974                              : DAG.getRegister(PPC::R2, MVT::i32);
2975 
2976     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2977     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2978   }
2979 
2980   if (Model == TLSModel::InitialExec) {
2981     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2982     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2983                                                 PPCII::MO_TLS);
2984     SDValue GOTPtr;
2985     if (is64bit) {
2986       setUsesTOCBasePtr(DAG);
2987       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2988       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2989                            PtrVT, GOTReg, TGA);
2990     } else {
2991       if (!TM.isPositionIndependent())
2992         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2993       else if (picLevel == PICLevel::SmallPIC)
2994         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2995       else
2996         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2997     }
2998     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2999                                    PtrVT, TGA, GOTPtr);
3000     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
3001   }
3002 
3003   if (Model == TLSModel::GeneralDynamic) {
3004     if (Subtarget.isUsingPCRelativeCalls()) {
3005       SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3006                                                PPCII::MO_GOT_TLSGD_PCREL_FLAG);
3007       return DAG.getNode(PPCISD::TLS_DYNAMIC_MAT_PCREL_ADDR, dl, PtrVT, TGA);
3008     }
3009 
3010     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3011     SDValue GOTPtr;
3012     if (is64bit) {
3013       setUsesTOCBasePtr(DAG);
3014       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3015       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
3016                                    GOTReg, TGA);
3017     } else {
3018       if (picLevel == PICLevel::SmallPIC)
3019         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3020       else
3021         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3022     }
3023     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
3024                        GOTPtr, TGA, TGA);
3025   }
3026 
3027   if (Model == TLSModel::LocalDynamic) {
3028     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
3029     SDValue GOTPtr;
3030     if (is64bit) {
3031       setUsesTOCBasePtr(DAG);
3032       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
3033       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
3034                            GOTReg, TGA);
3035     } else {
3036       if (picLevel == PICLevel::SmallPIC)
3037         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
3038       else
3039         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
3040     }
3041     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
3042                                   PtrVT, GOTPtr, TGA, TGA);
3043     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
3044                                       PtrVT, TLSAddr, TGA);
3045     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
3046   }
3047 
3048   llvm_unreachable("Unknown TLS model!");
3049 }
3050 
3051 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
3052                                               SelectionDAG &DAG) const {
3053   EVT PtrVT = Op.getValueType();
3054   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
3055   SDLoc DL(GSDN);
3056   const GlobalValue *GV = GSDN->getGlobal();
3057 
3058   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
3059   // The actual address of the GlobalValue is stored in the TOC.
3060   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
3061     if (Subtarget.isUsingPCRelativeCalls()) {
3062       EVT Ty = getPointerTy(DAG.getDataLayout());
3063       if (isAccessedAsGotIndirect(Op)) {
3064         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3065                                                 PPCII::MO_PCREL_FLAG |
3066                                                     PPCII::MO_GOT_FLAG);
3067         SDValue MatPCRel = DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3068         SDValue Load = DAG.getLoad(MVT::i64, DL, DAG.getEntryNode(), MatPCRel,
3069                                    MachinePointerInfo());
3070         return Load;
3071       } else {
3072         SDValue GA = DAG.getTargetGlobalAddress(GV, DL, Ty, GSDN->getOffset(),
3073                                                 PPCII::MO_PCREL_FLAG);
3074         return DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, Ty, GA);
3075       }
3076     }
3077     setUsesTOCBasePtr(DAG);
3078     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
3079     return getTOCEntry(DAG, DL, GA);
3080   }
3081 
3082   unsigned MOHiFlag, MOLoFlag;
3083   bool IsPIC = isPositionIndependent();
3084   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
3085 
3086   if (IsPIC && Subtarget.isSVR4ABI()) {
3087     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
3088                                             GSDN->getOffset(),
3089                                             PPCII::MO_PIC_FLAG);
3090     return getTOCEntry(DAG, DL, GA);
3091   }
3092 
3093   SDValue GAHi =
3094     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
3095   SDValue GALo =
3096     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
3097 
3098   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
3099 }
3100 
3101 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3102   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3103   SDLoc dl(Op);
3104 
3105   if (Op.getValueType() == MVT::v2i64) {
3106     // When the operands themselves are v2i64 values, we need to do something
3107     // special because VSX has no underlying comparison operations for these.
3108     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3109       // Equality can be handled by casting to the legal type for Altivec
3110       // comparisons, everything else needs to be expanded.
3111       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3112         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3113                  DAG.getSetCC(dl, MVT::v4i32,
3114                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3115                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3116                    CC));
3117       }
3118 
3119       return SDValue();
3120     }
3121 
3122     // We handle most of these in the usual way.
3123     return Op;
3124   }
3125 
3126   // If we're comparing for equality to zero, expose the fact that this is
3127   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3128   // fold the new nodes.
3129   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3130     return V;
3131 
3132   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3133     // Leave comparisons against 0 and -1 alone for now, since they're usually
3134     // optimized.  FIXME: revisit this when we can custom lower all setcc
3135     // optimizations.
3136     if (C->isAllOnesValue() || C->isNullValue())
3137       return SDValue();
3138   }
3139 
3140   // If we have an integer seteq/setne, turn it into a compare against zero
3141   // by xor'ing the rhs with the lhs, which is faster than setting a
3142   // condition register, reading it back out, and masking the correct bit.  The
3143   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3144   // the result to other bit-twiddling opportunities.
3145   EVT LHSVT = Op.getOperand(0).getValueType();
3146   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3147     EVT VT = Op.getValueType();
3148     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3149                                 Op.getOperand(1));
3150     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3151   }
3152   return SDValue();
3153 }
3154 
3155 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3156   SDNode *Node = Op.getNode();
3157   EVT VT = Node->getValueType(0);
3158   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3159   SDValue InChain = Node->getOperand(0);
3160   SDValue VAListPtr = Node->getOperand(1);
3161   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3162   SDLoc dl(Node);
3163 
3164   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3165 
3166   // gpr_index
3167   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3168                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3169   InChain = GprIndex.getValue(1);
3170 
3171   if (VT == MVT::i64) {
3172     // Check if GprIndex is even
3173     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3174                                  DAG.getConstant(1, dl, MVT::i32));
3175     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3176                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3177     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3178                                           DAG.getConstant(1, dl, MVT::i32));
3179     // Align GprIndex to be even if it isn't
3180     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3181                            GprIndex);
3182   }
3183 
3184   // fpr index is 1 byte after gpr
3185   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3186                                DAG.getConstant(1, dl, MVT::i32));
3187 
3188   // fpr
3189   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3190                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3191   InChain = FprIndex.getValue(1);
3192 
3193   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3194                                        DAG.getConstant(8, dl, MVT::i32));
3195 
3196   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3197                                         DAG.getConstant(4, dl, MVT::i32));
3198 
3199   // areas
3200   SDValue OverflowArea =
3201       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3202   InChain = OverflowArea.getValue(1);
3203 
3204   SDValue RegSaveArea =
3205       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3206   InChain = RegSaveArea.getValue(1);
3207 
3208   // select overflow_area if index > 8
3209   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3210                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3211 
3212   // adjustment constant gpr_index * 4/8
3213   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3214                                     VT.isInteger() ? GprIndex : FprIndex,
3215                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3216                                                     MVT::i32));
3217 
3218   // OurReg = RegSaveArea + RegConstant
3219   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3220                                RegConstant);
3221 
3222   // Floating types are 32 bytes into RegSaveArea
3223   if (VT.isFloatingPoint())
3224     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3225                          DAG.getConstant(32, dl, MVT::i32));
3226 
3227   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3228   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3229                                    VT.isInteger() ? GprIndex : FprIndex,
3230                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3231                                                    MVT::i32));
3232 
3233   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3234                               VT.isInteger() ? VAListPtr : FprPtr,
3235                               MachinePointerInfo(SV), MVT::i8);
3236 
3237   // determine if we should load from reg_save_area or overflow_area
3238   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3239 
3240   // increase overflow_area by 4/8 if gpr/fpr > 8
3241   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3242                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3243                                           dl, MVT::i32));
3244 
3245   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3246                              OverflowAreaPlusN);
3247 
3248   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3249                               MachinePointerInfo(), MVT::i32);
3250 
3251   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3252 }
3253 
3254 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3255   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3256 
3257   // We have to copy the entire va_list struct:
3258   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3259   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3260                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3261                        false, true, false, MachinePointerInfo(),
3262                        MachinePointerInfo());
3263 }
3264 
3265 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3266                                                   SelectionDAG &DAG) const {
3267   if (Subtarget.isAIXABI())
3268     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3269 
3270   return Op.getOperand(0);
3271 }
3272 
3273 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3274                                                 SelectionDAG &DAG) const {
3275   if (Subtarget.isAIXABI())
3276     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3277 
3278   SDValue Chain = Op.getOperand(0);
3279   SDValue Trmp = Op.getOperand(1); // trampoline
3280   SDValue FPtr = Op.getOperand(2); // nested function
3281   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3282   SDLoc dl(Op);
3283 
3284   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3285   bool isPPC64 = (PtrVT == MVT::i64);
3286   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3287 
3288   TargetLowering::ArgListTy Args;
3289   TargetLowering::ArgListEntry Entry;
3290 
3291   Entry.Ty = IntPtrTy;
3292   Entry.Node = Trmp; Args.push_back(Entry);
3293 
3294   // TrampSize == (isPPC64 ? 48 : 40);
3295   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3296                                isPPC64 ? MVT::i64 : MVT::i32);
3297   Args.push_back(Entry);
3298 
3299   Entry.Node = FPtr; Args.push_back(Entry);
3300   Entry.Node = Nest; Args.push_back(Entry);
3301 
3302   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3303   TargetLowering::CallLoweringInfo CLI(DAG);
3304   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3305       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3306       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3307 
3308   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3309   return CallResult.second;
3310 }
3311 
3312 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3313   MachineFunction &MF = DAG.getMachineFunction();
3314   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3315   EVT PtrVT = getPointerTy(MF.getDataLayout());
3316 
3317   SDLoc dl(Op);
3318 
3319   if (Subtarget.isPPC64() || Subtarget.isAIXABI()) {
3320     // vastart just stores the address of the VarArgsFrameIndex slot into the
3321     // memory location argument.
3322     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3323     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3324     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3325                         MachinePointerInfo(SV));
3326   }
3327 
3328   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3329   // We suppose the given va_list is already allocated.
3330   //
3331   // typedef struct {
3332   //  char gpr;     /* index into the array of 8 GPRs
3333   //                 * stored in the register save area
3334   //                 * gpr=0 corresponds to r3,
3335   //                 * gpr=1 to r4, etc.
3336   //                 */
3337   //  char fpr;     /* index into the array of 8 FPRs
3338   //                 * stored in the register save area
3339   //                 * fpr=0 corresponds to f1,
3340   //                 * fpr=1 to f2, etc.
3341   //                 */
3342   //  char *overflow_arg_area;
3343   //                /* location on stack that holds
3344   //                 * the next overflow argument
3345   //                 */
3346   //  char *reg_save_area;
3347   //               /* where r3:r10 and f1:f8 (if saved)
3348   //                * are stored
3349   //                */
3350   // } va_list[1];
3351 
3352   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3353   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3354   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3355                                             PtrVT);
3356   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3357                                  PtrVT);
3358 
3359   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3360   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3361 
3362   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3363   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3364 
3365   uint64_t FPROffset = 1;
3366   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3367 
3368   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3369 
3370   // Store first byte : number of int regs
3371   SDValue firstStore =
3372       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3373                         MachinePointerInfo(SV), MVT::i8);
3374   uint64_t nextOffset = FPROffset;
3375   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3376                                   ConstFPROffset);
3377 
3378   // Store second byte : number of float regs
3379   SDValue secondStore =
3380       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3381                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3382   nextOffset += StackOffset;
3383   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3384 
3385   // Store second word : arguments given on stack
3386   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3387                                     MachinePointerInfo(SV, nextOffset));
3388   nextOffset += FrameOffset;
3389   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3390 
3391   // Store third word : arguments given in registers
3392   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3393                       MachinePointerInfo(SV, nextOffset));
3394 }
3395 
3396 /// FPR - The set of FP registers that should be allocated for arguments
3397 /// on Darwin and AIX.
3398 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3399                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3400                                 PPC::F11, PPC::F12, PPC::F13};
3401 
3402 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3403 /// the stack.
3404 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3405                                        unsigned PtrByteSize) {
3406   unsigned ArgSize = ArgVT.getStoreSize();
3407   if (Flags.isByVal())
3408     ArgSize = Flags.getByValSize();
3409 
3410   // Round up to multiples of the pointer size, except for array members,
3411   // which are always packed.
3412   if (!Flags.isInConsecutiveRegs())
3413     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3414 
3415   return ArgSize;
3416 }
3417 
3418 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3419 /// on the stack.
3420 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3421                                          ISD::ArgFlagsTy Flags,
3422                                          unsigned PtrByteSize) {
3423   Align Alignment(PtrByteSize);
3424 
3425   // Altivec parameters are padded to a 16 byte boundary.
3426   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3427       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3428       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3429       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3430     Alignment = Align(16);
3431 
3432   // ByVal parameters are aligned as requested.
3433   if (Flags.isByVal()) {
3434     auto BVAlign = Flags.getNonZeroByValAlign();
3435     if (BVAlign > PtrByteSize) {
3436       if (BVAlign.value() % PtrByteSize != 0)
3437         llvm_unreachable(
3438             "ByVal alignment is not a multiple of the pointer size");
3439 
3440       Alignment = BVAlign;
3441     }
3442   }
3443 
3444   // Array members are always packed to their original alignment.
3445   if (Flags.isInConsecutiveRegs()) {
3446     // If the array member was split into multiple registers, the first
3447     // needs to be aligned to the size of the full type.  (Except for
3448     // ppcf128, which is only aligned as its f64 components.)
3449     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3450       Alignment = Align(OrigVT.getStoreSize());
3451     else
3452       Alignment = Align(ArgVT.getStoreSize());
3453   }
3454 
3455   return Alignment;
3456 }
3457 
3458 /// CalculateStackSlotUsed - Return whether this argument will use its
3459 /// stack slot (instead of being passed in registers).  ArgOffset,
3460 /// AvailableFPRs, and AvailableVRs must hold the current argument
3461 /// position, and will be updated to account for this argument.
3462 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT, ISD::ArgFlagsTy Flags,
3463                                    unsigned PtrByteSize, unsigned LinkageSize,
3464                                    unsigned ParamAreaSize, unsigned &ArgOffset,
3465                                    unsigned &AvailableFPRs,
3466                                    unsigned &AvailableVRs) {
3467   bool UseMemory = false;
3468 
3469   // Respect alignment of argument on the stack.
3470   Align Alignment =
3471       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3472   ArgOffset = alignTo(ArgOffset, Alignment);
3473   // If there's no space left in the argument save area, we must
3474   // use memory (this check also catches zero-sized arguments).
3475   if (ArgOffset >= LinkageSize + ParamAreaSize)
3476     UseMemory = true;
3477 
3478   // Allocate argument on the stack.
3479   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3480   if (Flags.isInConsecutiveRegsLast())
3481     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3482   // If we overran the argument save area, we must use memory
3483   // (this check catches arguments passed partially in memory)
3484   if (ArgOffset > LinkageSize + ParamAreaSize)
3485     UseMemory = true;
3486 
3487   // However, if the argument is actually passed in an FPR or a VR,
3488   // we don't use memory after all.
3489   if (!Flags.isByVal()) {
3490     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
3491       if (AvailableFPRs > 0) {
3492         --AvailableFPRs;
3493         return false;
3494       }
3495     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3496         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3497         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3498         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3499       if (AvailableVRs > 0) {
3500         --AvailableVRs;
3501         return false;
3502       }
3503   }
3504 
3505   return UseMemory;
3506 }
3507 
3508 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3509 /// ensure minimum alignment required for target.
3510 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3511                                      unsigned NumBytes) {
3512   return alignTo(NumBytes, Lowering->getStackAlign());
3513 }
3514 
3515 SDValue PPCTargetLowering::LowerFormalArguments(
3516     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3517     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3518     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3519   if (Subtarget.isAIXABI())
3520     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3521                                     InVals);
3522   if (Subtarget.is64BitELFABI())
3523     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3524                                        InVals);
3525   if (Subtarget.is32BitELFABI())
3526     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3527                                        InVals);
3528 
3529   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3530                                      InVals);
3531 }
3532 
3533 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3534     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3535     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3536     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3537 
3538   // 32-bit SVR4 ABI Stack Frame Layout:
3539   //              +-----------------------------------+
3540   //        +-->  |            Back chain             |
3541   //        |     +-----------------------------------+
3542   //        |     | Floating-point register save area |
3543   //        |     +-----------------------------------+
3544   //        |     |    General register save area     |
3545   //        |     +-----------------------------------+
3546   //        |     |          CR save word             |
3547   //        |     +-----------------------------------+
3548   //        |     |         VRSAVE save word          |
3549   //        |     +-----------------------------------+
3550   //        |     |         Alignment padding         |
3551   //        |     +-----------------------------------+
3552   //        |     |     Vector register save area     |
3553   //        |     +-----------------------------------+
3554   //        |     |       Local variable space        |
3555   //        |     +-----------------------------------+
3556   //        |     |        Parameter list area        |
3557   //        |     +-----------------------------------+
3558   //        |     |           LR save word            |
3559   //        |     +-----------------------------------+
3560   // SP-->  +---  |            Back chain             |
3561   //              +-----------------------------------+
3562   //
3563   // Specifications:
3564   //   System V Application Binary Interface PowerPC Processor Supplement
3565   //   AltiVec Technology Programming Interface Manual
3566 
3567   MachineFunction &MF = DAG.getMachineFunction();
3568   MachineFrameInfo &MFI = MF.getFrameInfo();
3569   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3570 
3571   EVT PtrVT = getPointerTy(MF.getDataLayout());
3572   // Potential tail calls could cause overwriting of argument stack slots.
3573   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3574                        (CallConv == CallingConv::Fast));
3575   const Align PtrAlign(4);
3576 
3577   // Assign locations to all of the incoming arguments.
3578   SmallVector<CCValAssign, 16> ArgLocs;
3579   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3580                  *DAG.getContext());
3581 
3582   // Reserve space for the linkage area on the stack.
3583   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3584   CCInfo.AllocateStack(LinkageSize, PtrAlign);
3585   if (useSoftFloat())
3586     CCInfo.PreAnalyzeFormalArguments(Ins);
3587 
3588   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3589   CCInfo.clearWasPPCF128();
3590 
3591   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3592     CCValAssign &VA = ArgLocs[i];
3593 
3594     // Arguments stored in registers.
3595     if (VA.isRegLoc()) {
3596       const TargetRegisterClass *RC;
3597       EVT ValVT = VA.getValVT();
3598 
3599       switch (ValVT.getSimpleVT().SimpleTy) {
3600         default:
3601           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3602         case MVT::i1:
3603         case MVT::i32:
3604           RC = &PPC::GPRCRegClass;
3605           break;
3606         case MVT::f32:
3607           if (Subtarget.hasP8Vector())
3608             RC = &PPC::VSSRCRegClass;
3609           else if (Subtarget.hasSPE())
3610             RC = &PPC::GPRCRegClass;
3611           else
3612             RC = &PPC::F4RCRegClass;
3613           break;
3614         case MVT::f64:
3615           if (Subtarget.hasVSX())
3616             RC = &PPC::VSFRCRegClass;
3617           else if (Subtarget.hasSPE())
3618             // SPE passes doubles in GPR pairs.
3619             RC = &PPC::GPRCRegClass;
3620           else
3621             RC = &PPC::F8RCRegClass;
3622           break;
3623         case MVT::v16i8:
3624         case MVT::v8i16:
3625         case MVT::v4i32:
3626           RC = &PPC::VRRCRegClass;
3627           break;
3628         case MVT::v4f32:
3629           RC = &PPC::VRRCRegClass;
3630           break;
3631         case MVT::v2f64:
3632         case MVT::v2i64:
3633           RC = &PPC::VRRCRegClass;
3634           break;
3635       }
3636 
3637       SDValue ArgValue;
3638       // Transform the arguments stored in physical registers into
3639       // virtual ones.
3640       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3641         assert(i + 1 < e && "No second half of double precision argument");
3642         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3643         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3644         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3645         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3646         if (!Subtarget.isLittleEndian())
3647           std::swap (ArgValueLo, ArgValueHi);
3648         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3649                                ArgValueHi);
3650       } else {
3651         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3652         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3653                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3654         if (ValVT == MVT::i1)
3655           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3656       }
3657 
3658       InVals.push_back(ArgValue);
3659     } else {
3660       // Argument stored in memory.
3661       assert(VA.isMemLoc());
3662 
3663       // Get the extended size of the argument type in stack
3664       unsigned ArgSize = VA.getLocVT().getStoreSize();
3665       // Get the actual size of the argument type
3666       unsigned ObjSize = VA.getValVT().getStoreSize();
3667       unsigned ArgOffset = VA.getLocMemOffset();
3668       // Stack objects in PPC32 are right justified.
3669       ArgOffset += ArgSize - ObjSize;
3670       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3671 
3672       // Create load nodes to retrieve arguments from the stack.
3673       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3674       InVals.push_back(
3675           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3676     }
3677   }
3678 
3679   // Assign locations to all of the incoming aggregate by value arguments.
3680   // Aggregates passed by value are stored in the local variable space of the
3681   // caller's stack frame, right above the parameter list area.
3682   SmallVector<CCValAssign, 16> ByValArgLocs;
3683   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3684                       ByValArgLocs, *DAG.getContext());
3685 
3686   // Reserve stack space for the allocations in CCInfo.
3687   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
3688 
3689   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3690 
3691   // Area that is at least reserved in the caller of this function.
3692   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3693   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3694 
3695   // Set the size that is at least reserved in caller of this function.  Tail
3696   // call optimized function's reserved stack space needs to be aligned so that
3697   // taking the difference between two stack areas will result in an aligned
3698   // stack.
3699   MinReservedArea =
3700       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3701   FuncInfo->setMinReservedArea(MinReservedArea);
3702 
3703   SmallVector<SDValue, 8> MemOps;
3704 
3705   // If the function takes variable number of arguments, make a frame index for
3706   // the start of the first vararg value... for expansion of llvm.va_start.
3707   if (isVarArg) {
3708     static const MCPhysReg GPArgRegs[] = {
3709       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3710       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3711     };
3712     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3713 
3714     static const MCPhysReg FPArgRegs[] = {
3715       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3716       PPC::F8
3717     };
3718     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3719 
3720     if (useSoftFloat() || hasSPE())
3721        NumFPArgRegs = 0;
3722 
3723     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3724     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3725 
3726     // Make room for NumGPArgRegs and NumFPArgRegs.
3727     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3728                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3729 
3730     FuncInfo->setVarArgsStackOffset(
3731       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3732                             CCInfo.getNextStackOffset(), true));
3733 
3734     FuncInfo->setVarArgsFrameIndex(
3735         MFI.CreateStackObject(Depth, Align(8), false));
3736     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3737 
3738     // The fixed integer arguments of a variadic function are stored to the
3739     // VarArgsFrameIndex on the stack so that they may be loaded by
3740     // dereferencing the result of va_next.
3741     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3742       // Get an existing live-in vreg, or add a new one.
3743       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3744       if (!VReg)
3745         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3746 
3747       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3748       SDValue Store =
3749           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3750       MemOps.push_back(Store);
3751       // Increment the address by four for the next argument to store
3752       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3753       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3754     }
3755 
3756     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3757     // is set.
3758     // The double arguments are stored to the VarArgsFrameIndex
3759     // on the stack.
3760     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3761       // Get an existing live-in vreg, or add a new one.
3762       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3763       if (!VReg)
3764         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3765 
3766       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3767       SDValue Store =
3768           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3769       MemOps.push_back(Store);
3770       // Increment the address by eight for the next argument to store
3771       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3772                                          PtrVT);
3773       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3774     }
3775   }
3776 
3777   if (!MemOps.empty())
3778     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3779 
3780   return Chain;
3781 }
3782 
3783 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3784 // value to MVT::i64 and then truncate to the correct register size.
3785 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3786                                              EVT ObjectVT, SelectionDAG &DAG,
3787                                              SDValue ArgVal,
3788                                              const SDLoc &dl) const {
3789   if (Flags.isSExt())
3790     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3791                          DAG.getValueType(ObjectVT));
3792   else if (Flags.isZExt())
3793     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3794                          DAG.getValueType(ObjectVT));
3795 
3796   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3797 }
3798 
3799 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3800     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3801     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3802     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3803   // TODO: add description of PPC stack frame format, or at least some docs.
3804   //
3805   bool isELFv2ABI = Subtarget.isELFv2ABI();
3806   bool isLittleEndian = Subtarget.isLittleEndian();
3807   MachineFunction &MF = DAG.getMachineFunction();
3808   MachineFrameInfo &MFI = MF.getFrameInfo();
3809   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3810 
3811   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3812          "fastcc not supported on varargs functions");
3813 
3814   EVT PtrVT = getPointerTy(MF.getDataLayout());
3815   // Potential tail calls could cause overwriting of argument stack slots.
3816   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3817                        (CallConv == CallingConv::Fast));
3818   unsigned PtrByteSize = 8;
3819   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3820 
3821   static const MCPhysReg GPR[] = {
3822     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3823     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3824   };
3825   static const MCPhysReg VR[] = {
3826     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3827     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3828   };
3829 
3830   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3831   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3832   const unsigned Num_VR_Regs  = array_lengthof(VR);
3833 
3834   // Do a first pass over the arguments to determine whether the ABI
3835   // guarantees that our caller has allocated the parameter save area
3836   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3837   // in the ELFv2 ABI, it is true if this is a vararg function or if
3838   // any parameter is located in a stack slot.
3839 
3840   bool HasParameterArea = !isELFv2ABI || isVarArg;
3841   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3842   unsigned NumBytes = LinkageSize;
3843   unsigned AvailableFPRs = Num_FPR_Regs;
3844   unsigned AvailableVRs = Num_VR_Regs;
3845   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3846     if (Ins[i].Flags.isNest())
3847       continue;
3848 
3849     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3850                                PtrByteSize, LinkageSize, ParamAreaSize,
3851                                NumBytes, AvailableFPRs, AvailableVRs))
3852       HasParameterArea = true;
3853   }
3854 
3855   // Add DAG nodes to load the arguments or copy them out of registers.  On
3856   // entry to a function on PPC, the arguments start after the linkage area,
3857   // although the first ones are often in registers.
3858 
3859   unsigned ArgOffset = LinkageSize;
3860   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3861   SmallVector<SDValue, 8> MemOps;
3862   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3863   unsigned CurArgIdx = 0;
3864   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3865     SDValue ArgVal;
3866     bool needsLoad = false;
3867     EVT ObjectVT = Ins[ArgNo].VT;
3868     EVT OrigVT = Ins[ArgNo].ArgVT;
3869     unsigned ObjSize = ObjectVT.getStoreSize();
3870     unsigned ArgSize = ObjSize;
3871     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3872     if (Ins[ArgNo].isOrigArg()) {
3873       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3874       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3875     }
3876     // We re-align the argument offset for each argument, except when using the
3877     // fast calling convention, when we need to make sure we do that only when
3878     // we'll actually use a stack slot.
3879     unsigned CurArgOffset;
3880     Align Alignment;
3881     auto ComputeArgOffset = [&]() {
3882       /* Respect alignment of argument on the stack.  */
3883       Alignment =
3884           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3885       ArgOffset = alignTo(ArgOffset, Alignment);
3886       CurArgOffset = ArgOffset;
3887     };
3888 
3889     if (CallConv != CallingConv::Fast) {
3890       ComputeArgOffset();
3891 
3892       /* Compute GPR index associated with argument offset.  */
3893       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3894       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3895     }
3896 
3897     // FIXME the codegen can be much improved in some cases.
3898     // We do not have to keep everything in memory.
3899     if (Flags.isByVal()) {
3900       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3901 
3902       if (CallConv == CallingConv::Fast)
3903         ComputeArgOffset();
3904 
3905       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3906       ObjSize = Flags.getByValSize();
3907       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3908       // Empty aggregate parameters do not take up registers.  Examples:
3909       //   struct { } a;
3910       //   union  { } b;
3911       //   int c[0];
3912       // etc.  However, we have to provide a place-holder in InVals, so
3913       // pretend we have an 8-byte item at the current address for that
3914       // purpose.
3915       if (!ObjSize) {
3916         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3917         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3918         InVals.push_back(FIN);
3919         continue;
3920       }
3921 
3922       // Create a stack object covering all stack doublewords occupied
3923       // by the argument.  If the argument is (fully or partially) on
3924       // the stack, or if the argument is fully in registers but the
3925       // caller has allocated the parameter save anyway, we can refer
3926       // directly to the caller's stack frame.  Otherwise, create a
3927       // local copy in our own frame.
3928       int FI;
3929       if (HasParameterArea ||
3930           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3931         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3932       else
3933         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3934       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3935 
3936       // Handle aggregates smaller than 8 bytes.
3937       if (ObjSize < PtrByteSize) {
3938         // The value of the object is its address, which differs from the
3939         // address of the enclosing doubleword on big-endian systems.
3940         SDValue Arg = FIN;
3941         if (!isLittleEndian) {
3942           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3943           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3944         }
3945         InVals.push_back(Arg);
3946 
3947         if (GPR_idx != Num_GPR_Regs) {
3948           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3949           FuncInfo->addLiveInAttr(VReg, Flags);
3950           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3951           SDValue Store;
3952 
3953           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3954             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3955                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3956             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3957                                       MachinePointerInfo(&*FuncArg), ObjType);
3958           } else {
3959             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3960             // store the whole register as-is to the parameter save area
3961             // slot.
3962             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3963                                  MachinePointerInfo(&*FuncArg));
3964           }
3965 
3966           MemOps.push_back(Store);
3967         }
3968         // Whether we copied from a register or not, advance the offset
3969         // into the parameter save area by a full doubleword.
3970         ArgOffset += PtrByteSize;
3971         continue;
3972       }
3973 
3974       // The value of the object is its address, which is the address of
3975       // its first stack doubleword.
3976       InVals.push_back(FIN);
3977 
3978       // Store whatever pieces of the object are in registers to memory.
3979       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3980         if (GPR_idx == Num_GPR_Regs)
3981           break;
3982 
3983         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3984         FuncInfo->addLiveInAttr(VReg, Flags);
3985         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3986         SDValue Addr = FIN;
3987         if (j) {
3988           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3989           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3990         }
3991         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3992                                      MachinePointerInfo(&*FuncArg, j));
3993         MemOps.push_back(Store);
3994         ++GPR_idx;
3995       }
3996       ArgOffset += ArgSize;
3997       continue;
3998     }
3999 
4000     switch (ObjectVT.getSimpleVT().SimpleTy) {
4001     default: llvm_unreachable("Unhandled argument type!");
4002     case MVT::i1:
4003     case MVT::i32:
4004     case MVT::i64:
4005       if (Flags.isNest()) {
4006         // The 'nest' parameter, if any, is passed in R11.
4007         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
4008         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4009 
4010         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4011           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4012 
4013         break;
4014       }
4015 
4016       // These can be scalar arguments or elements of an integer array type
4017       // passed directly.  Clang may use those instead of "byval" aggregate
4018       // types to avoid forcing arguments to memory unnecessarily.
4019       if (GPR_idx != Num_GPR_Regs) {
4020         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4021         FuncInfo->addLiveInAttr(VReg, Flags);
4022         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4023 
4024         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4025           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4026           // value to MVT::i64 and then truncate to the correct register size.
4027           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4028       } else {
4029         if (CallConv == CallingConv::Fast)
4030           ComputeArgOffset();
4031 
4032         needsLoad = true;
4033         ArgSize = PtrByteSize;
4034       }
4035       if (CallConv != CallingConv::Fast || needsLoad)
4036         ArgOffset += 8;
4037       break;
4038 
4039     case MVT::f32:
4040     case MVT::f64:
4041       // These can be scalar arguments or elements of a float array type
4042       // passed directly.  The latter are used to implement ELFv2 homogenous
4043       // float aggregates.
4044       if (FPR_idx != Num_FPR_Regs) {
4045         unsigned VReg;
4046 
4047         if (ObjectVT == MVT::f32)
4048           VReg = MF.addLiveIn(FPR[FPR_idx],
4049                               Subtarget.hasP8Vector()
4050                                   ? &PPC::VSSRCRegClass
4051                                   : &PPC::F4RCRegClass);
4052         else
4053           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
4054                                                 ? &PPC::VSFRCRegClass
4055                                                 : &PPC::F8RCRegClass);
4056 
4057         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4058         ++FPR_idx;
4059       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
4060         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
4061         // once we support fp <-> gpr moves.
4062 
4063         // This can only ever happen in the presence of f32 array types,
4064         // since otherwise we never run out of FPRs before running out
4065         // of GPRs.
4066         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
4067         FuncInfo->addLiveInAttr(VReg, Flags);
4068         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4069 
4070         if (ObjectVT == MVT::f32) {
4071           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
4072             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
4073                                  DAG.getConstant(32, dl, MVT::i32));
4074           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4075         }
4076 
4077         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4078       } else {
4079         if (CallConv == CallingConv::Fast)
4080           ComputeArgOffset();
4081 
4082         needsLoad = true;
4083       }
4084 
4085       // When passing an array of floats, the array occupies consecutive
4086       // space in the argument area; only round up to the next doubleword
4087       // at the end of the array.  Otherwise, each float takes 8 bytes.
4088       if (CallConv != CallingConv::Fast || needsLoad) {
4089         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4090         ArgOffset += ArgSize;
4091         if (Flags.isInConsecutiveRegsLast())
4092           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4093       }
4094       break;
4095     case MVT::v4f32:
4096     case MVT::v4i32:
4097     case MVT::v8i16:
4098     case MVT::v16i8:
4099     case MVT::v2f64:
4100     case MVT::v2i64:
4101     case MVT::v1i128:
4102     case MVT::f128:
4103       // These can be scalar arguments or elements of a vector array type
4104       // passed directly.  The latter are used to implement ELFv2 homogenous
4105       // vector aggregates.
4106       if (VR_idx != Num_VR_Regs) {
4107         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4108         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4109         ++VR_idx;
4110       } else {
4111         if (CallConv == CallingConv::Fast)
4112           ComputeArgOffset();
4113         needsLoad = true;
4114       }
4115       if (CallConv != CallingConv::Fast || needsLoad)
4116         ArgOffset += 16;
4117       break;
4118     }
4119 
4120     // We need to load the argument to a virtual register if we determined
4121     // above that we ran out of physical registers of the appropriate type.
4122     if (needsLoad) {
4123       if (ObjSize < ArgSize && !isLittleEndian)
4124         CurArgOffset += ArgSize - ObjSize;
4125       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4126       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4127       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4128     }
4129 
4130     InVals.push_back(ArgVal);
4131   }
4132 
4133   // Area that is at least reserved in the caller of this function.
4134   unsigned MinReservedArea;
4135   if (HasParameterArea)
4136     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4137   else
4138     MinReservedArea = LinkageSize;
4139 
4140   // Set the size that is at least reserved in caller of this function.  Tail
4141   // call optimized functions' reserved stack space needs to be aligned so that
4142   // taking the difference between two stack areas will result in an aligned
4143   // stack.
4144   MinReservedArea =
4145       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4146   FuncInfo->setMinReservedArea(MinReservedArea);
4147 
4148   // If the function takes variable number of arguments, make a frame index for
4149   // the start of the first vararg value... for expansion of llvm.va_start.
4150   // On ELFv2ABI spec, it writes:
4151   // C programs that are intended to be *portable* across different compilers
4152   // and architectures must use the header file <stdarg.h> to deal with variable
4153   // argument lists.
4154   if (isVarArg && MFI.hasVAStart()) {
4155     int Depth = ArgOffset;
4156 
4157     FuncInfo->setVarArgsFrameIndex(
4158       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4159     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4160 
4161     // If this function is vararg, store any remaining integer argument regs
4162     // to their spots on the stack so that they may be loaded by dereferencing
4163     // the result of va_next.
4164     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4165          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4166       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4167       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4168       SDValue Store =
4169           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4170       MemOps.push_back(Store);
4171       // Increment the address by four for the next argument to store
4172       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4173       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4174     }
4175   }
4176 
4177   if (!MemOps.empty())
4178     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4179 
4180   return Chain;
4181 }
4182 
4183 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4184     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4185     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4186     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4187   // TODO: add description of PPC stack frame format, or at least some docs.
4188   //
4189   MachineFunction &MF = DAG.getMachineFunction();
4190   MachineFrameInfo &MFI = MF.getFrameInfo();
4191   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4192 
4193   EVT PtrVT = getPointerTy(MF.getDataLayout());
4194   bool isPPC64 = PtrVT == MVT::i64;
4195   // Potential tail calls could cause overwriting of argument stack slots.
4196   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4197                        (CallConv == CallingConv::Fast));
4198   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4199   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4200   unsigned ArgOffset = LinkageSize;
4201   // Area that is at least reserved in caller of this function.
4202   unsigned MinReservedArea = ArgOffset;
4203 
4204   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4205     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4206     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4207   };
4208   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4209     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4210     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4211   };
4212   static const MCPhysReg VR[] = {
4213     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4214     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4215   };
4216 
4217   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4218   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4219   const unsigned Num_VR_Regs  = array_lengthof( VR);
4220 
4221   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4222 
4223   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4224 
4225   // In 32-bit non-varargs functions, the stack space for vectors is after the
4226   // stack space for non-vectors.  We do not use this space unless we have
4227   // too many vectors to fit in registers, something that only occurs in
4228   // constructed examples:), but we have to walk the arglist to figure
4229   // that out...for the pathological case, compute VecArgOffset as the
4230   // start of the vector parameter area.  Computing VecArgOffset is the
4231   // entire point of the following loop.
4232   unsigned VecArgOffset = ArgOffset;
4233   if (!isVarArg && !isPPC64) {
4234     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4235          ++ArgNo) {
4236       EVT ObjectVT = Ins[ArgNo].VT;
4237       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4238 
4239       if (Flags.isByVal()) {
4240         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4241         unsigned ObjSize = Flags.getByValSize();
4242         unsigned ArgSize =
4243                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4244         VecArgOffset += ArgSize;
4245         continue;
4246       }
4247 
4248       switch(ObjectVT.getSimpleVT().SimpleTy) {
4249       default: llvm_unreachable("Unhandled argument type!");
4250       case MVT::i1:
4251       case MVT::i32:
4252       case MVT::f32:
4253         VecArgOffset += 4;
4254         break;
4255       case MVT::i64:  // PPC64
4256       case MVT::f64:
4257         // FIXME: We are guaranteed to be !isPPC64 at this point.
4258         // Does MVT::i64 apply?
4259         VecArgOffset += 8;
4260         break;
4261       case MVT::v4f32:
4262       case MVT::v4i32:
4263       case MVT::v8i16:
4264       case MVT::v16i8:
4265         // Nothing to do, we're only looking at Nonvector args here.
4266         break;
4267       }
4268     }
4269   }
4270   // We've found where the vector parameter area in memory is.  Skip the
4271   // first 12 parameters; these don't use that memory.
4272   VecArgOffset = ((VecArgOffset+15)/16)*16;
4273   VecArgOffset += 12*16;
4274 
4275   // Add DAG nodes to load the arguments or copy them out of registers.  On
4276   // entry to a function on PPC, the arguments start after the linkage area,
4277   // although the first ones are often in registers.
4278 
4279   SmallVector<SDValue, 8> MemOps;
4280   unsigned nAltivecParamsAtEnd = 0;
4281   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4282   unsigned CurArgIdx = 0;
4283   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4284     SDValue ArgVal;
4285     bool needsLoad = false;
4286     EVT ObjectVT = Ins[ArgNo].VT;
4287     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4288     unsigned ArgSize = ObjSize;
4289     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4290     if (Ins[ArgNo].isOrigArg()) {
4291       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4292       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4293     }
4294     unsigned CurArgOffset = ArgOffset;
4295 
4296     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4297     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4298         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4299       if (isVarArg || isPPC64) {
4300         MinReservedArea = ((MinReservedArea+15)/16)*16;
4301         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4302                                                   Flags,
4303                                                   PtrByteSize);
4304       } else  nAltivecParamsAtEnd++;
4305     } else
4306       // Calculate min reserved area.
4307       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4308                                                 Flags,
4309                                                 PtrByteSize);
4310 
4311     // FIXME the codegen can be much improved in some cases.
4312     // We do not have to keep everything in memory.
4313     if (Flags.isByVal()) {
4314       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4315 
4316       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4317       ObjSize = Flags.getByValSize();
4318       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4319       // Objects of size 1 and 2 are right justified, everything else is
4320       // left justified.  This means the memory address is adjusted forwards.
4321       if (ObjSize==1 || ObjSize==2) {
4322         CurArgOffset = CurArgOffset + (4 - ObjSize);
4323       }
4324       // The value of the object is its address.
4325       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4326       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4327       InVals.push_back(FIN);
4328       if (ObjSize==1 || ObjSize==2) {
4329         if (GPR_idx != Num_GPR_Regs) {
4330           unsigned VReg;
4331           if (isPPC64)
4332             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4333           else
4334             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4335           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4336           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4337           SDValue Store =
4338               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4339                                 MachinePointerInfo(&*FuncArg), ObjType);
4340           MemOps.push_back(Store);
4341           ++GPR_idx;
4342         }
4343 
4344         ArgOffset += PtrByteSize;
4345 
4346         continue;
4347       }
4348       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4349         // Store whatever pieces of the object are in registers
4350         // to memory.  ArgOffset will be the address of the beginning
4351         // of the object.
4352         if (GPR_idx != Num_GPR_Regs) {
4353           unsigned VReg;
4354           if (isPPC64)
4355             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4356           else
4357             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4358           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4359           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4360           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4361           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4362                                        MachinePointerInfo(&*FuncArg, j));
4363           MemOps.push_back(Store);
4364           ++GPR_idx;
4365           ArgOffset += PtrByteSize;
4366         } else {
4367           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4368           break;
4369         }
4370       }
4371       continue;
4372     }
4373 
4374     switch (ObjectVT.getSimpleVT().SimpleTy) {
4375     default: llvm_unreachable("Unhandled argument type!");
4376     case MVT::i1:
4377     case MVT::i32:
4378       if (!isPPC64) {
4379         if (GPR_idx != Num_GPR_Regs) {
4380           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4381           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4382 
4383           if (ObjectVT == MVT::i1)
4384             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4385 
4386           ++GPR_idx;
4387         } else {
4388           needsLoad = true;
4389           ArgSize = PtrByteSize;
4390         }
4391         // All int arguments reserve stack space in the Darwin ABI.
4392         ArgOffset += PtrByteSize;
4393         break;
4394       }
4395       LLVM_FALLTHROUGH;
4396     case MVT::i64:  // PPC64
4397       if (GPR_idx != Num_GPR_Regs) {
4398         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4399         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4400 
4401         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4402           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4403           // value to MVT::i64 and then truncate to the correct register size.
4404           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4405 
4406         ++GPR_idx;
4407       } else {
4408         needsLoad = true;
4409         ArgSize = PtrByteSize;
4410       }
4411       // All int arguments reserve stack space in the Darwin ABI.
4412       ArgOffset += 8;
4413       break;
4414 
4415     case MVT::f32:
4416     case MVT::f64:
4417       // Every 4 bytes of argument space consumes one of the GPRs available for
4418       // argument passing.
4419       if (GPR_idx != Num_GPR_Regs) {
4420         ++GPR_idx;
4421         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4422           ++GPR_idx;
4423       }
4424       if (FPR_idx != Num_FPR_Regs) {
4425         unsigned VReg;
4426 
4427         if (ObjectVT == MVT::f32)
4428           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4429         else
4430           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4431 
4432         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4433         ++FPR_idx;
4434       } else {
4435         needsLoad = true;
4436       }
4437 
4438       // All FP arguments reserve stack space in the Darwin ABI.
4439       ArgOffset += isPPC64 ? 8 : ObjSize;
4440       break;
4441     case MVT::v4f32:
4442     case MVT::v4i32:
4443     case MVT::v8i16:
4444     case MVT::v16i8:
4445       // Note that vector arguments in registers don't reserve stack space,
4446       // except in varargs functions.
4447       if (VR_idx != Num_VR_Regs) {
4448         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4449         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4450         if (isVarArg) {
4451           while ((ArgOffset % 16) != 0) {
4452             ArgOffset += PtrByteSize;
4453             if (GPR_idx != Num_GPR_Regs)
4454               GPR_idx++;
4455           }
4456           ArgOffset += 16;
4457           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4458         }
4459         ++VR_idx;
4460       } else {
4461         if (!isVarArg && !isPPC64) {
4462           // Vectors go after all the nonvectors.
4463           CurArgOffset = VecArgOffset;
4464           VecArgOffset += 16;
4465         } else {
4466           // Vectors are aligned.
4467           ArgOffset = ((ArgOffset+15)/16)*16;
4468           CurArgOffset = ArgOffset;
4469           ArgOffset += 16;
4470         }
4471         needsLoad = true;
4472       }
4473       break;
4474     }
4475 
4476     // We need to load the argument to a virtual register if we determined above
4477     // that we ran out of physical registers of the appropriate type.
4478     if (needsLoad) {
4479       int FI = MFI.CreateFixedObject(ObjSize,
4480                                      CurArgOffset + (ArgSize - ObjSize),
4481                                      isImmutable);
4482       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4483       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4484     }
4485 
4486     InVals.push_back(ArgVal);
4487   }
4488 
4489   // Allow for Altivec parameters at the end, if needed.
4490   if (nAltivecParamsAtEnd) {
4491     MinReservedArea = ((MinReservedArea+15)/16)*16;
4492     MinReservedArea += 16*nAltivecParamsAtEnd;
4493   }
4494 
4495   // Area that is at least reserved in the caller of this function.
4496   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4497 
4498   // Set the size that is at least reserved in caller of this function.  Tail
4499   // call optimized functions' reserved stack space needs to be aligned so that
4500   // taking the difference between two stack areas will result in an aligned
4501   // stack.
4502   MinReservedArea =
4503       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4504   FuncInfo->setMinReservedArea(MinReservedArea);
4505 
4506   // If the function takes variable number of arguments, make a frame index for
4507   // the start of the first vararg value... for expansion of llvm.va_start.
4508   if (isVarArg) {
4509     int Depth = ArgOffset;
4510 
4511     FuncInfo->setVarArgsFrameIndex(
4512       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4513                             Depth, true));
4514     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4515 
4516     // If this function is vararg, store any remaining integer argument regs
4517     // to their spots on the stack so that they may be loaded by dereferencing
4518     // the result of va_next.
4519     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4520       unsigned VReg;
4521 
4522       if (isPPC64)
4523         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4524       else
4525         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4526 
4527       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4528       SDValue Store =
4529           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4530       MemOps.push_back(Store);
4531       // Increment the address by four for the next argument to store
4532       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4533       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4534     }
4535   }
4536 
4537   if (!MemOps.empty())
4538     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4539 
4540   return Chain;
4541 }
4542 
4543 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4544 /// adjusted to accommodate the arguments for the tailcall.
4545 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4546                                    unsigned ParamSize) {
4547 
4548   if (!isTailCall) return 0;
4549 
4550   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4551   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4552   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4553   // Remember only if the new adjustment is bigger.
4554   if (SPDiff < FI->getTailCallSPDelta())
4555     FI->setTailCallSPDelta(SPDiff);
4556 
4557   return SPDiff;
4558 }
4559 
4560 static bool isFunctionGlobalAddress(SDValue Callee);
4561 
4562 static bool callsShareTOCBase(const Function *Caller, SDValue Callee,
4563                               const TargetMachine &TM) {
4564   // It does not make sense to call callsShareTOCBase() with a caller that
4565   // is PC Relative since PC Relative callers do not have a TOC.
4566 #ifndef NDEBUG
4567   const PPCSubtarget *STICaller = &TM.getSubtarget<PPCSubtarget>(*Caller);
4568   assert(!STICaller->isUsingPCRelativeCalls() &&
4569          "PC Relative callers do not have a TOC and cannot share a TOC Base");
4570 #endif
4571 
4572   // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4573   // don't have enough information to determine if the caller and callee share
4574   // the same  TOC base, so we have to pessimistically assume they don't for
4575   // correctness.
4576   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4577   if (!G)
4578     return false;
4579 
4580   const GlobalValue *GV = G->getGlobal();
4581 
4582   // If the callee is preemptable, then the static linker will use a plt-stub
4583   // which saves the toc to the stack, and needs a nop after the call
4584   // instruction to convert to a toc-restore.
4585   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4586     return false;
4587 
4588   // Functions with PC Relative enabled may clobber the TOC in the same DSO.
4589   // We may need a TOC restore in the situation where the caller requires a
4590   // valid TOC but the callee is PC Relative and does not.
4591   const Function *F = dyn_cast<Function>(GV);
4592   const GlobalAlias *Alias = dyn_cast<GlobalAlias>(GV);
4593 
4594   // If we have an Alias we can try to get the function from there.
4595   if (Alias) {
4596     const GlobalObject *GlobalObj = Alias->getBaseObject();
4597     F = dyn_cast<Function>(GlobalObj);
4598   }
4599 
4600   // If we still have no valid function pointer we do not have enough
4601   // information to determine if the callee uses PC Relative calls so we must
4602   // assume that it does.
4603   if (!F)
4604     return false;
4605 
4606   // If the callee uses PC Relative we cannot guarantee that the callee won't
4607   // clobber the TOC of the caller and so we must assume that the two
4608   // functions do not share a TOC base.
4609   const PPCSubtarget *STICallee = &TM.getSubtarget<PPCSubtarget>(*F);
4610   if (STICallee->isUsingPCRelativeCalls())
4611     return false;
4612 
4613   // The medium and large code models are expected to provide a sufficiently
4614   // large TOC to provide all data addressing needs of a module with a
4615   // single TOC.
4616   if (CodeModel::Medium == TM.getCodeModel() ||
4617       CodeModel::Large == TM.getCodeModel())
4618     return true;
4619 
4620   // Otherwise we need to ensure callee and caller are in the same section,
4621   // since the linker may allocate multiple TOCs, and we don't know which
4622   // sections will belong to the same TOC base.
4623   if (!GV->isStrongDefinitionForLinker())
4624     return false;
4625 
4626   // Any explicitly-specified sections and section prefixes must also match.
4627   // Also, if we're using -ffunction-sections, then each function is always in
4628   // a different section (the same is true for COMDAT functions).
4629   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4630       GV->getSection() != Caller->getSection())
4631     return false;
4632   if (const auto *F = dyn_cast<Function>(GV)) {
4633     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4634       return false;
4635   }
4636 
4637   return true;
4638 }
4639 
4640 static bool
4641 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4642                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4643   assert(Subtarget.is64BitELFABI());
4644 
4645   const unsigned PtrByteSize = 8;
4646   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4647 
4648   static const MCPhysReg GPR[] = {
4649     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4650     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4651   };
4652   static const MCPhysReg VR[] = {
4653     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4654     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4655   };
4656 
4657   const unsigned NumGPRs = array_lengthof(GPR);
4658   const unsigned NumFPRs = 13;
4659   const unsigned NumVRs = array_lengthof(VR);
4660   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4661 
4662   unsigned NumBytes = LinkageSize;
4663   unsigned AvailableFPRs = NumFPRs;
4664   unsigned AvailableVRs = NumVRs;
4665 
4666   for (const ISD::OutputArg& Param : Outs) {
4667     if (Param.Flags.isNest()) continue;
4668 
4669     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags, PtrByteSize,
4670                                LinkageSize, ParamAreaSize, NumBytes,
4671                                AvailableFPRs, AvailableVRs))
4672       return true;
4673   }
4674   return false;
4675 }
4676 
4677 static bool hasSameArgumentList(const Function *CallerFn, const CallBase &CB) {
4678   if (CB.arg_size() != CallerFn->arg_size())
4679     return false;
4680 
4681   auto CalleeArgIter = CB.arg_begin();
4682   auto CalleeArgEnd = CB.arg_end();
4683   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4684 
4685   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4686     const Value* CalleeArg = *CalleeArgIter;
4687     const Value* CallerArg = &(*CallerArgIter);
4688     if (CalleeArg == CallerArg)
4689       continue;
4690 
4691     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4692     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4693     //      }
4694     // 1st argument of callee is undef and has the same type as caller.
4695     if (CalleeArg->getType() == CallerArg->getType() &&
4696         isa<UndefValue>(CalleeArg))
4697       continue;
4698 
4699     return false;
4700   }
4701 
4702   return true;
4703 }
4704 
4705 // Returns true if TCO is possible between the callers and callees
4706 // calling conventions.
4707 static bool
4708 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4709                                     CallingConv::ID CalleeCC) {
4710   // Tail calls are possible with fastcc and ccc.
4711   auto isTailCallableCC  = [] (CallingConv::ID CC){
4712       return  CC == CallingConv::C || CC == CallingConv::Fast;
4713   };
4714   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4715     return false;
4716 
4717   // We can safely tail call both fastcc and ccc callees from a c calling
4718   // convention caller. If the caller is fastcc, we may have less stack space
4719   // than a non-fastcc caller with the same signature so disable tail-calls in
4720   // that case.
4721   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4722 }
4723 
4724 bool PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4725     SDValue Callee, CallingConv::ID CalleeCC, const CallBase *CB, bool isVarArg,
4726     const SmallVectorImpl<ISD::OutputArg> &Outs,
4727     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
4728   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4729 
4730   if (DisableSCO && !TailCallOpt) return false;
4731 
4732   // Variadic argument functions are not supported.
4733   if (isVarArg) return false;
4734 
4735   auto &Caller = DAG.getMachineFunction().getFunction();
4736   // Check that the calling conventions are compatible for tco.
4737   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4738     return false;
4739 
4740   // Caller contains any byval parameter is not supported.
4741   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4742     return false;
4743 
4744   // Callee contains any byval parameter is not supported, too.
4745   // Note: This is a quick work around, because in some cases, e.g.
4746   // caller's stack size > callee's stack size, we are still able to apply
4747   // sibling call optimization. For example, gcc is able to do SCO for caller1
4748   // in the following example, but not for caller2.
4749   //   struct test {
4750   //     long int a;
4751   //     char ary[56];
4752   //   } gTest;
4753   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4754   //     b->a = v.a;
4755   //     return 0;
4756   //   }
4757   //   void caller1(struct test a, struct test c, struct test *b) {
4758   //     callee(gTest, b); }
4759   //   void caller2(struct test *b) { callee(gTest, b); }
4760   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4761     return false;
4762 
4763   // If callee and caller use different calling conventions, we cannot pass
4764   // parameters on stack since offsets for the parameter area may be different.
4765   if (Caller.getCallingConv() != CalleeCC &&
4766       needStackSlotPassParameters(Subtarget, Outs))
4767     return false;
4768 
4769   // All variants of 64-bit ELF ABIs without PC-Relative addressing require that
4770   // the caller and callee share the same TOC for TCO/SCO. If the caller and
4771   // callee potentially have different TOC bases then we cannot tail call since
4772   // we need to restore the TOC pointer after the call.
4773   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4774   // We cannot guarantee this for indirect calls or calls to external functions.
4775   // When PC-Relative addressing is used, the concept of the TOC is no longer
4776   // applicable so this check is not required.
4777   // Check first for indirect calls.
4778   if (!Subtarget.isUsingPCRelativeCalls() &&
4779       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
4780     return false;
4781 
4782   // Check if we share the TOC base.
4783   if (!Subtarget.isUsingPCRelativeCalls() &&
4784       !callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4785     return false;
4786 
4787   // TCO allows altering callee ABI, so we don't have to check further.
4788   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4789     return true;
4790 
4791   if (DisableSCO) return false;
4792 
4793   // If callee use the same argument list that caller is using, then we can
4794   // apply SCO on this case. If it is not, then we need to check if callee needs
4795   // stack for passing arguments.
4796   // PC Relative tail calls may not have a CallBase.
4797   // If there is no CallBase we cannot verify if we have the same argument
4798   // list so assume that we don't have the same argument list.
4799   if (CB && !hasSameArgumentList(&Caller, *CB) &&
4800       needStackSlotPassParameters(Subtarget, Outs))
4801     return false;
4802   else if (!CB && needStackSlotPassParameters(Subtarget, Outs))
4803     return false;
4804 
4805   return true;
4806 }
4807 
4808 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4809 /// for tail call optimization. Targets which want to do tail call
4810 /// optimization should implement this function.
4811 bool
4812 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4813                                                      CallingConv::ID CalleeCC,
4814                                                      bool isVarArg,
4815                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4816                                                      SelectionDAG& DAG) const {
4817   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4818     return false;
4819 
4820   // Variable argument functions are not supported.
4821   if (isVarArg)
4822     return false;
4823 
4824   MachineFunction &MF = DAG.getMachineFunction();
4825   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4826   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4827     // Functions containing by val parameters are not supported.
4828     for (unsigned i = 0; i != Ins.size(); i++) {
4829        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4830        if (Flags.isByVal()) return false;
4831     }
4832 
4833     // Non-PIC/GOT tail calls are supported.
4834     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4835       return true;
4836 
4837     // At the moment we can only do local tail calls (in same module, hidden
4838     // or protected) if we are generating PIC.
4839     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4840       return G->getGlobal()->hasHiddenVisibility()
4841           || G->getGlobal()->hasProtectedVisibility();
4842   }
4843 
4844   return false;
4845 }
4846 
4847 /// isCallCompatibleAddress - Return the immediate to use if the specified
4848 /// 32-bit value is representable in the immediate field of a BxA instruction.
4849 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4850   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4851   if (!C) return nullptr;
4852 
4853   int Addr = C->getZExtValue();
4854   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4855       SignExtend32<26>(Addr) != Addr)
4856     return nullptr;  // Top 6 bits have to be sext of immediate.
4857 
4858   return DAG
4859       .getConstant(
4860           (int)C->getZExtValue() >> 2, SDLoc(Op),
4861           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4862       .getNode();
4863 }
4864 
4865 namespace {
4866 
4867 struct TailCallArgumentInfo {
4868   SDValue Arg;
4869   SDValue FrameIdxOp;
4870   int FrameIdx = 0;
4871 
4872   TailCallArgumentInfo() = default;
4873 };
4874 
4875 } // end anonymous namespace
4876 
4877 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4878 static void StoreTailCallArgumentsToStackSlot(
4879     SelectionDAG &DAG, SDValue Chain,
4880     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4881     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4882   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4883     SDValue Arg = TailCallArgs[i].Arg;
4884     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4885     int FI = TailCallArgs[i].FrameIdx;
4886     // Store relative to framepointer.
4887     MemOpChains.push_back(DAG.getStore(
4888         Chain, dl, Arg, FIN,
4889         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4890   }
4891 }
4892 
4893 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4894 /// the appropriate stack slot for the tail call optimized function call.
4895 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4896                                              SDValue OldRetAddr, SDValue OldFP,
4897                                              int SPDiff, const SDLoc &dl) {
4898   if (SPDiff) {
4899     // Calculate the new stack slot for the return address.
4900     MachineFunction &MF = DAG.getMachineFunction();
4901     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4902     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4903     bool isPPC64 = Subtarget.isPPC64();
4904     int SlotSize = isPPC64 ? 8 : 4;
4905     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4906     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4907                                                          NewRetAddrLoc, true);
4908     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4909     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4910     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4911                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4912   }
4913   return Chain;
4914 }
4915 
4916 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4917 /// the position of the argument.
4918 static void
4919 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4920                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4921                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4922   int Offset = ArgOffset + SPDiff;
4923   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4924   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4925   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4926   SDValue FIN = DAG.getFrameIndex(FI, VT);
4927   TailCallArgumentInfo Info;
4928   Info.Arg = Arg;
4929   Info.FrameIdxOp = FIN;
4930   Info.FrameIdx = FI;
4931   TailCallArguments.push_back(Info);
4932 }
4933 
4934 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4935 /// stack slot. Returns the chain as result and the loaded frame pointers in
4936 /// LROpOut/FPOpout. Used when tail calling.
4937 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4938     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4939     SDValue &FPOpOut, const SDLoc &dl) const {
4940   if (SPDiff) {
4941     // Load the LR and FP stack slot for later adjusting.
4942     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4943     LROpOut = getReturnAddrFrameIndex(DAG);
4944     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4945     Chain = SDValue(LROpOut.getNode(), 1);
4946   }
4947   return Chain;
4948 }
4949 
4950 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4951 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4952 /// specified by the specific parameter attribute. The copy will be passed as
4953 /// a byval function parameter.
4954 /// Sometimes what we are copying is the end of a larger object, the part that
4955 /// does not fit in registers.
4956 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4957                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4958                                          SelectionDAG &DAG, const SDLoc &dl) {
4959   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4960   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4961                        Flags.getNonZeroByValAlign(), false, false, false,
4962                        MachinePointerInfo(), MachinePointerInfo());
4963 }
4964 
4965 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4966 /// tail calls.
4967 static void LowerMemOpCallTo(
4968     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4969     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4970     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4971     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4972   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4973   if (!isTailCall) {
4974     if (isVector) {
4975       SDValue StackPtr;
4976       if (isPPC64)
4977         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4978       else
4979         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4980       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4981                            DAG.getConstant(ArgOffset, dl, PtrVT));
4982     }
4983     MemOpChains.push_back(
4984         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4985     // Calculate and remember argument location.
4986   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4987                                   TailCallArguments);
4988 }
4989 
4990 static void
4991 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4992                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4993                 SDValue FPOp,
4994                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4995   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4996   // might overwrite each other in case of tail call optimization.
4997   SmallVector<SDValue, 8> MemOpChains2;
4998   // Do not flag preceding copytoreg stuff together with the following stuff.
4999   InFlag = SDValue();
5000   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
5001                                     MemOpChains2, dl);
5002   if (!MemOpChains2.empty())
5003     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
5004 
5005   // Store the return address to the appropriate stack slot.
5006   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
5007 
5008   // Emit callseq_end just before tailcall node.
5009   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5010                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
5011   InFlag = Chain.getValue(1);
5012 }
5013 
5014 // Is this global address that of a function that can be called by name? (as
5015 // opposed to something that must hold a descriptor for an indirect call).
5016 static bool isFunctionGlobalAddress(SDValue Callee) {
5017   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
5018     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
5019         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
5020       return false;
5021 
5022     return G->getGlobal()->getValueType()->isFunctionTy();
5023   }
5024 
5025   return false;
5026 }
5027 
5028 SDValue PPCTargetLowering::LowerCallResult(
5029     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
5030     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5031     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
5032   SmallVector<CCValAssign, 16> RVLocs;
5033   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5034                     *DAG.getContext());
5035 
5036   CCRetInfo.AnalyzeCallResult(
5037       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
5038                ? RetCC_PPC_Cold
5039                : RetCC_PPC);
5040 
5041   // Copy all of the result registers out of their specified physreg.
5042   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
5043     CCValAssign &VA = RVLocs[i];
5044     assert(VA.isRegLoc() && "Can only return in registers!");
5045 
5046     SDValue Val;
5047 
5048     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5049       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5050                                       InFlag);
5051       Chain = Lo.getValue(1);
5052       InFlag = Lo.getValue(2);
5053       VA = RVLocs[++i]; // skip ahead to next loc
5054       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5055                                       InFlag);
5056       Chain = Hi.getValue(1);
5057       InFlag = Hi.getValue(2);
5058       if (!Subtarget.isLittleEndian())
5059         std::swap (Lo, Hi);
5060       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5061     } else {
5062       Val = DAG.getCopyFromReg(Chain, dl,
5063                                VA.getLocReg(), VA.getLocVT(), InFlag);
5064       Chain = Val.getValue(1);
5065       InFlag = Val.getValue(2);
5066     }
5067 
5068     switch (VA.getLocInfo()) {
5069     default: llvm_unreachable("Unknown loc info!");
5070     case CCValAssign::Full: break;
5071     case CCValAssign::AExt:
5072       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5073       break;
5074     case CCValAssign::ZExt:
5075       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5076                         DAG.getValueType(VA.getValVT()));
5077       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5078       break;
5079     case CCValAssign::SExt:
5080       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5081                         DAG.getValueType(VA.getValVT()));
5082       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5083       break;
5084     }
5085 
5086     InVals.push_back(Val);
5087   }
5088 
5089   return Chain;
5090 }
5091 
5092 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5093                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5094   // PatchPoint calls are not indirect.
5095   if (isPatchPoint)
5096     return false;
5097 
5098   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5099     return false;
5100 
5101   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5102   // becuase the immediate function pointer points to a descriptor instead of
5103   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5104   // pointer immediate points to the global entry point, while the BLA would
5105   // need to jump to the local entry point (see rL211174).
5106   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5107       isBLACompatibleAddress(Callee, DAG))
5108     return false;
5109 
5110   return true;
5111 }
5112 
5113 // AIX and 64-bit ELF ABIs w/o PCRel require a TOC save/restore around calls.
5114 static inline bool isTOCSaveRestoreRequired(const PPCSubtarget &Subtarget) {
5115   return Subtarget.isAIXABI() ||
5116          (Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls());
5117 }
5118 
5119 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5120                               const Function &Caller,
5121                               const SDValue &Callee,
5122                               const PPCSubtarget &Subtarget,
5123                               const TargetMachine &TM) {
5124   if (CFlags.IsTailCall)
5125     return PPCISD::TC_RETURN;
5126 
5127   // This is a call through a function pointer.
5128   if (CFlags.IsIndirect) {
5129     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5130     // indirect calls. The save of the caller's TOC pointer to the stack will be
5131     // inserted into the DAG as part of call lowering. The restore of the TOC
5132     // pointer is modeled by using a pseudo instruction for the call opcode that
5133     // represents the 2 instruction sequence of an indirect branch and link,
5134     // immediately followed by a load of the TOC pointer from the the stack save
5135     // slot into gpr2. For 64-bit ELFv2 ABI with PCRel, do not restore the TOC
5136     // as it is not saved or used.
5137     return isTOCSaveRestoreRequired(Subtarget) ? PPCISD::BCTRL_LOAD_TOC
5138                                                : PPCISD::BCTRL;
5139   }
5140 
5141   if (Subtarget.isUsingPCRelativeCalls()) {
5142     assert(Subtarget.is64BitELFABI() && "PC Relative is only on ELF ABI.");
5143     return PPCISD::CALL_NOTOC;
5144   }
5145 
5146   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5147   // immediately following the call instruction if the caller and callee may
5148   // have different TOC bases. At link time if the linker determines the calls
5149   // may not share a TOC base, the call is redirected to a trampoline inserted
5150   // by the linker. The trampoline will (among other things) save the callers
5151   // TOC pointer at an ABI designated offset in the linkage area and the linker
5152   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5153   // into gpr2.
5154   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5155     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5156                                                   : PPCISD::CALL_NOP;
5157 
5158   return PPCISD::CALL;
5159 }
5160 
5161 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5162                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5163   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5164     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5165       return SDValue(Dest, 0);
5166 
5167   // Returns true if the callee is local, and false otherwise.
5168   auto isLocalCallee = [&]() {
5169     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5170     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5171     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5172 
5173     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5174            !dyn_cast_or_null<GlobalIFunc>(GV);
5175   };
5176 
5177   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5178   // a static relocation model causes some versions of GNU LD (2.17.50, at
5179   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5180   // built with secure-PLT.
5181   bool UsePlt =
5182       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5183       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5184 
5185   const auto getAIXFuncEntryPointSymbolSDNode = [&](const GlobalValue *GV) {
5186     const TargetMachine &TM = Subtarget.getTargetMachine();
5187     const TargetLoweringObjectFile *TLOF = TM.getObjFileLowering();
5188     MCSymbolXCOFF *S =
5189         cast<MCSymbolXCOFF>(TLOF->getFunctionEntryPointSymbol(GV, TM));
5190 
5191     MVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5192     return DAG.getMCSymbol(S, PtrVT);
5193   };
5194 
5195   if (isFunctionGlobalAddress(Callee)) {
5196     const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
5197 
5198     if (Subtarget.isAIXABI()) {
5199       assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5200       return getAIXFuncEntryPointSymbolSDNode(GV);
5201     }
5202     return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5203                                       UsePlt ? PPCII::MO_PLT : 0);
5204   }
5205 
5206   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5207     const char *SymName = S->getSymbol();
5208     if (Subtarget.isAIXABI()) {
5209       // If there exists a user-declared function whose name is the same as the
5210       // ExternalSymbol's, then we pick up the user-declared version.
5211       const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5212       if (const Function *F =
5213               dyn_cast_or_null<Function>(Mod->getNamedValue(SymName)))
5214         return getAIXFuncEntryPointSymbolSDNode(F);
5215 
5216       // On AIX, direct function calls reference the symbol for the function's
5217       // entry point, which is named by prepending a "." before the function's
5218       // C-linkage name. A Qualname is returned here because an external
5219       // function entry point is a csect with XTY_ER property.
5220       const auto getExternalFunctionEntryPointSymbol = [&](StringRef SymName) {
5221         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5222         MCSectionXCOFF *Sec = Context.getXCOFFSection(
5223             (Twine(".") + Twine(SymName)).str(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5224             SectionKind::getMetadata());
5225         return Sec->getQualNameSymbol();
5226       };
5227 
5228       SymName = getExternalFunctionEntryPointSymbol(SymName)->getName().data();
5229     }
5230     return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5231                                        UsePlt ? PPCII::MO_PLT : 0);
5232   }
5233 
5234   // No transformation needed.
5235   assert(Callee.getNode() && "What no callee?");
5236   return Callee;
5237 }
5238 
5239 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5240   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5241          "Expected a CALLSEQ_STARTSDNode.");
5242 
5243   // The last operand is the chain, except when the node has glue. If the node
5244   // has glue, then the last operand is the glue, and the chain is the second
5245   // last operand.
5246   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5247   if (LastValue.getValueType() != MVT::Glue)
5248     return LastValue;
5249 
5250   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5251 }
5252 
5253 // Creates the node that moves a functions address into the count register
5254 // to prepare for an indirect call instruction.
5255 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5256                                 SDValue &Glue, SDValue &Chain,
5257                                 const SDLoc &dl) {
5258   SDValue MTCTROps[] = {Chain, Callee, Glue};
5259   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5260   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5261                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5262   // The glue is the second value produced.
5263   Glue = Chain.getValue(1);
5264 }
5265 
5266 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5267                                           SDValue &Glue, SDValue &Chain,
5268                                           SDValue CallSeqStart,
5269                                           const CallBase *CB, const SDLoc &dl,
5270                                           bool hasNest,
5271                                           const PPCSubtarget &Subtarget) {
5272   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5273   // entry point, but to the function descriptor (the function entry point
5274   // address is part of the function descriptor though).
5275   // The function descriptor is a three doubleword structure with the
5276   // following fields: function entry point, TOC base address and
5277   // environment pointer.
5278   // Thus for a call through a function pointer, the following actions need
5279   // to be performed:
5280   //   1. Save the TOC of the caller in the TOC save area of its stack
5281   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5282   //   2. Load the address of the function entry point from the function
5283   //      descriptor.
5284   //   3. Load the TOC of the callee from the function descriptor into r2.
5285   //   4. Load the environment pointer from the function descriptor into
5286   //      r11.
5287   //   5. Branch to the function entry point address.
5288   //   6. On return of the callee, the TOC of the caller needs to be
5289   //      restored (this is done in FinishCall()).
5290   //
5291   // The loads are scheduled at the beginning of the call sequence, and the
5292   // register copies are flagged together to ensure that no other
5293   // operations can be scheduled in between. E.g. without flagging the
5294   // copies together, a TOC access in the caller could be scheduled between
5295   // the assignment of the callee TOC and the branch to the callee, which leads
5296   // to incorrect code.
5297 
5298   // Start by loading the function address from the descriptor.
5299   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5300   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5301                       ? (MachineMemOperand::MODereferenceable |
5302                          MachineMemOperand::MOInvariant)
5303                       : MachineMemOperand::MONone;
5304 
5305   MachinePointerInfo MPI(CB ? CB->getCalledOperand() : nullptr);
5306 
5307   // Registers used in building the DAG.
5308   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5309   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5310 
5311   // Offsets of descriptor members.
5312   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5313   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5314 
5315   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5316   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5317 
5318   // One load for the functions entry point address.
5319   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5320                                     Alignment, MMOFlags);
5321 
5322   // One for loading the TOC anchor for the module that contains the called
5323   // function.
5324   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5325   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5326   SDValue TOCPtr =
5327       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5328                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5329 
5330   // One for loading the environment pointer.
5331   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5332   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5333   SDValue LoadEnvPtr =
5334       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5335                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5336 
5337 
5338   // Then copy the newly loaded TOC anchor to the TOC pointer.
5339   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5340   Chain = TOCVal.getValue(0);
5341   Glue = TOCVal.getValue(1);
5342 
5343   // If the function call has an explicit 'nest' parameter, it takes the
5344   // place of the environment pointer.
5345   assert((!hasNest || !Subtarget.isAIXABI()) &&
5346          "Nest parameter is not supported on AIX.");
5347   if (!hasNest) {
5348     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5349     Chain = EnvVal.getValue(0);
5350     Glue = EnvVal.getValue(1);
5351   }
5352 
5353   // The rest of the indirect call sequence is the same as the non-descriptor
5354   // DAG.
5355   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5356 }
5357 
5358 static void
5359 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5360                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5361                   SelectionDAG &DAG,
5362                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5363                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5364                   const PPCSubtarget &Subtarget) {
5365   const bool IsPPC64 = Subtarget.isPPC64();
5366   // MVT for a general purpose register.
5367   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5368 
5369   // First operand is always the chain.
5370   Ops.push_back(Chain);
5371 
5372   // If it's a direct call pass the callee as the second operand.
5373   if (!CFlags.IsIndirect)
5374     Ops.push_back(Callee);
5375   else {
5376     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5377 
5378     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5379     // on the stack (this would have been done in `LowerCall_64SVR4` or
5380     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5381     // represents both the indirect branch and a load that restores the TOC
5382     // pointer from the linkage area. The operand for the TOC restore is an add
5383     // of the TOC save offset to the stack pointer. This must be the second
5384     // operand: after the chain input but before any other variadic arguments.
5385     // For 64-bit ELFv2 ABI with PCRel, do not restore the TOC as it is not
5386     // saved or used.
5387     if (isTOCSaveRestoreRequired(Subtarget)) {
5388       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5389 
5390       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5391       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5392       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5393       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5394       Ops.push_back(AddTOC);
5395     }
5396 
5397     // Add the register used for the environment pointer.
5398     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5399       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5400                                     RegVT));
5401 
5402 
5403     // Add CTR register as callee so a bctr can be emitted later.
5404     if (CFlags.IsTailCall)
5405       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5406   }
5407 
5408   // If this is a tail call add stack pointer delta.
5409   if (CFlags.IsTailCall)
5410     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5411 
5412   // Add argument registers to the end of the list so that they are known live
5413   // into the call.
5414   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5415     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5416                                   RegsToPass[i].second.getValueType()));
5417 
5418   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5419   // no way to mark dependencies as implicit here.
5420   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5421   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5422        !CFlags.IsPatchPoint && !Subtarget.isUsingPCRelativeCalls())
5423     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5424 
5425   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5426   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5427     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5428 
5429   // Add a register mask operand representing the call-preserved registers.
5430   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5431   const uint32_t *Mask =
5432       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5433   assert(Mask && "Missing call preserved mask for calling convention");
5434   Ops.push_back(DAG.getRegisterMask(Mask));
5435 
5436   // If the glue is valid, it is the last operand.
5437   if (Glue.getNode())
5438     Ops.push_back(Glue);
5439 }
5440 
5441 SDValue PPCTargetLowering::FinishCall(
5442     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5443     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5444     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5445     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5446     SmallVectorImpl<SDValue> &InVals, const CallBase *CB) const {
5447 
5448   if ((Subtarget.is64BitELFABI() && !Subtarget.isUsingPCRelativeCalls()) ||
5449       Subtarget.isAIXABI())
5450     setUsesTOCBasePtr(DAG);
5451 
5452   unsigned CallOpc =
5453       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5454                     Subtarget, DAG.getTarget());
5455 
5456   if (!CFlags.IsIndirect)
5457     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5458   else if (Subtarget.usesFunctionDescriptors())
5459     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CB,
5460                                   dl, CFlags.HasNest, Subtarget);
5461   else
5462     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5463 
5464   // Build the operand list for the call instruction.
5465   SmallVector<SDValue, 8> Ops;
5466   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5467                     SPDiff, Subtarget);
5468 
5469   // Emit tail call.
5470   if (CFlags.IsTailCall) {
5471     // Indirect tail call when using PC Relative calls do not have the same
5472     // constraints.
5473     assert(((Callee.getOpcode() == ISD::Register &&
5474              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5475             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5476             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5477             isa<ConstantSDNode>(Callee) ||
5478             (CFlags.IsIndirect && Subtarget.isUsingPCRelativeCalls())) &&
5479            "Expecting a global address, external symbol, absolute value, "
5480            "register or an indirect tail call when PC Relative calls are "
5481            "used.");
5482     // PC Relative calls also use TC_RETURN as the way to mark tail calls.
5483     assert(CallOpc == PPCISD::TC_RETURN &&
5484            "Unexpected call opcode for a tail call.");
5485     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5486     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5487   }
5488 
5489   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5490   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5491   DAG.addNoMergeSiteInfo(Chain.getNode(), CFlags.NoMerge);
5492   Glue = Chain.getValue(1);
5493 
5494   // When performing tail call optimization the callee pops its arguments off
5495   // the stack. Account for this here so these bytes can be pushed back on in
5496   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5497   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5498                          getTargetMachine().Options.GuaranteedTailCallOpt)
5499                             ? NumBytes
5500                             : 0;
5501 
5502   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5503                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5504                              Glue, dl);
5505   Glue = Chain.getValue(1);
5506 
5507   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5508                          DAG, InVals);
5509 }
5510 
5511 SDValue
5512 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5513                              SmallVectorImpl<SDValue> &InVals) const {
5514   SelectionDAG &DAG                     = CLI.DAG;
5515   SDLoc &dl                             = CLI.DL;
5516   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5517   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5518   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5519   SDValue Chain                         = CLI.Chain;
5520   SDValue Callee                        = CLI.Callee;
5521   bool &isTailCall                      = CLI.IsTailCall;
5522   CallingConv::ID CallConv              = CLI.CallConv;
5523   bool isVarArg                         = CLI.IsVarArg;
5524   bool isPatchPoint                     = CLI.IsPatchPoint;
5525   const CallBase *CB                    = CLI.CB;
5526 
5527   if (isTailCall) {
5528     if (Subtarget.useLongCalls() && !(CB && CB->isMustTailCall()))
5529       isTailCall = false;
5530     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5531       isTailCall = IsEligibleForTailCallOptimization_64SVR4(
5532           Callee, CallConv, CB, isVarArg, Outs, Ins, DAG);
5533     else
5534       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5535                                                      Ins, DAG);
5536     if (isTailCall) {
5537       ++NumTailCalls;
5538       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5539         ++NumSiblingCalls;
5540 
5541       // PC Relative calls no longer guarantee that the callee is a Global
5542       // Address Node. The callee could be an indirect tail call in which
5543       // case the SDValue for the callee could be a load (to load the address
5544       // of a function pointer) or it may be a register copy (to move the
5545       // address of the callee from a function parameter into a virtual
5546       // register). It may also be an ExternalSymbolSDNode (ex memcopy).
5547       assert((Subtarget.isUsingPCRelativeCalls() ||
5548               isa<GlobalAddressSDNode>(Callee)) &&
5549              "Callee should be an llvm::Function object.");
5550 
5551       LLVM_DEBUG(dbgs() << "TCO caller: " << DAG.getMachineFunction().getName()
5552                         << "\nTCO callee: ");
5553       LLVM_DEBUG(Callee.dump());
5554     }
5555   }
5556 
5557   if (!isTailCall && CB && CB->isMustTailCall())
5558     report_fatal_error("failed to perform tail call elimination on a call "
5559                        "site marked musttail");
5560 
5561   // When long calls (i.e. indirect calls) are always used, calls are always
5562   // made via function pointer. If we have a function name, first translate it
5563   // into a pointer.
5564   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5565       !isTailCall)
5566     Callee = LowerGlobalAddress(Callee, DAG);
5567 
5568   CallFlags CFlags(
5569       CallConv, isTailCall, isVarArg, isPatchPoint,
5570       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5571       // hasNest
5572       Subtarget.is64BitELFABI() &&
5573           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }),
5574       CLI.NoMerge);
5575 
5576   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5577     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5578                             InVals, CB);
5579 
5580   if (Subtarget.isSVR4ABI())
5581     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5582                             InVals, CB);
5583 
5584   if (Subtarget.isAIXABI())
5585     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5586                          InVals, CB);
5587 
5588   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5589                           InVals, CB);
5590 }
5591 
5592 SDValue PPCTargetLowering::LowerCall_32SVR4(
5593     SDValue Chain, SDValue Callee, CallFlags CFlags,
5594     const SmallVectorImpl<ISD::OutputArg> &Outs,
5595     const SmallVectorImpl<SDValue> &OutVals,
5596     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5597     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5598     const CallBase *CB) const {
5599   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5600   // of the 32-bit SVR4 ABI stack frame layout.
5601 
5602   const CallingConv::ID CallConv = CFlags.CallConv;
5603   const bool IsVarArg = CFlags.IsVarArg;
5604   const bool IsTailCall = CFlags.IsTailCall;
5605 
5606   assert((CallConv == CallingConv::C ||
5607           CallConv == CallingConv::Cold ||
5608           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5609 
5610   const Align PtrAlign(4);
5611 
5612   MachineFunction &MF = DAG.getMachineFunction();
5613 
5614   // Mark this function as potentially containing a function that contains a
5615   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5616   // and restoring the callers stack pointer in this functions epilog. This is
5617   // done because by tail calling the called function might overwrite the value
5618   // in this function's (MF) stack pointer stack slot 0(SP).
5619   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5620       CallConv == CallingConv::Fast)
5621     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5622 
5623   // Count how many bytes are to be pushed on the stack, including the linkage
5624   // area, parameter list area and the part of the local variable space which
5625   // contains copies of aggregates which are passed by value.
5626 
5627   // Assign locations to all of the outgoing arguments.
5628   SmallVector<CCValAssign, 16> ArgLocs;
5629   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5630 
5631   // Reserve space for the linkage area on the stack.
5632   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5633                        PtrAlign);
5634   if (useSoftFloat())
5635     CCInfo.PreAnalyzeCallOperands(Outs);
5636 
5637   if (IsVarArg) {
5638     // Handle fixed and variable vector arguments differently.
5639     // Fixed vector arguments go into registers as long as registers are
5640     // available. Variable vector arguments always go into memory.
5641     unsigned NumArgs = Outs.size();
5642 
5643     for (unsigned i = 0; i != NumArgs; ++i) {
5644       MVT ArgVT = Outs[i].VT;
5645       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5646       bool Result;
5647 
5648       if (Outs[i].IsFixed) {
5649         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5650                                CCInfo);
5651       } else {
5652         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5653                                       ArgFlags, CCInfo);
5654       }
5655 
5656       if (Result) {
5657 #ifndef NDEBUG
5658         errs() << "Call operand #" << i << " has unhandled type "
5659              << EVT(ArgVT).getEVTString() << "\n";
5660 #endif
5661         llvm_unreachable(nullptr);
5662       }
5663     }
5664   } else {
5665     // All arguments are treated the same.
5666     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5667   }
5668   CCInfo.clearWasPPCF128();
5669 
5670   // Assign locations to all of the outgoing aggregate by value arguments.
5671   SmallVector<CCValAssign, 16> ByValArgLocs;
5672   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5673 
5674   // Reserve stack space for the allocations in CCInfo.
5675   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrAlign);
5676 
5677   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5678 
5679   // Size of the linkage area, parameter list area and the part of the local
5680   // space variable where copies of aggregates which are passed by value are
5681   // stored.
5682   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5683 
5684   // Calculate by how many bytes the stack has to be adjusted in case of tail
5685   // call optimization.
5686   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5687 
5688   // Adjust the stack pointer for the new arguments...
5689   // These operations are automatically eliminated by the prolog/epilog pass
5690   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5691   SDValue CallSeqStart = Chain;
5692 
5693   // Load the return address and frame pointer so it can be moved somewhere else
5694   // later.
5695   SDValue LROp, FPOp;
5696   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5697 
5698   // Set up a copy of the stack pointer for use loading and storing any
5699   // arguments that may not fit in the registers available for argument
5700   // passing.
5701   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5702 
5703   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5704   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5705   SmallVector<SDValue, 8> MemOpChains;
5706 
5707   bool seenFloatArg = false;
5708   // Walk the register/memloc assignments, inserting copies/loads.
5709   // i - Tracks the index into the list of registers allocated for the call
5710   // RealArgIdx - Tracks the index into the list of actual function arguments
5711   // j - Tracks the index into the list of byval arguments
5712   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5713        i != e;
5714        ++i, ++RealArgIdx) {
5715     CCValAssign &VA = ArgLocs[i];
5716     SDValue Arg = OutVals[RealArgIdx];
5717     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5718 
5719     if (Flags.isByVal()) {
5720       // Argument is an aggregate which is passed by value, thus we need to
5721       // create a copy of it in the local variable space of the current stack
5722       // frame (which is the stack frame of the caller) and pass the address of
5723       // this copy to the callee.
5724       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5725       CCValAssign &ByValVA = ByValArgLocs[j++];
5726       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5727 
5728       // Memory reserved in the local variable space of the callers stack frame.
5729       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5730 
5731       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5732       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5733                            StackPtr, PtrOff);
5734 
5735       // Create a copy of the argument in the local area of the current
5736       // stack frame.
5737       SDValue MemcpyCall =
5738         CreateCopyOfByValArgument(Arg, PtrOff,
5739                                   CallSeqStart.getNode()->getOperand(0),
5740                                   Flags, DAG, dl);
5741 
5742       // This must go outside the CALLSEQ_START..END.
5743       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5744                                                      SDLoc(MemcpyCall));
5745       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5746                              NewCallSeqStart.getNode());
5747       Chain = CallSeqStart = NewCallSeqStart;
5748 
5749       // Pass the address of the aggregate copy on the stack either in a
5750       // physical register or in the parameter list area of the current stack
5751       // frame to the callee.
5752       Arg = PtrOff;
5753     }
5754 
5755     // When useCRBits() is true, there can be i1 arguments.
5756     // It is because getRegisterType(MVT::i1) => MVT::i1,
5757     // and for other integer types getRegisterType() => MVT::i32.
5758     // Extend i1 and ensure callee will get i32.
5759     if (Arg.getValueType() == MVT::i1)
5760       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5761                         dl, MVT::i32, Arg);
5762 
5763     if (VA.isRegLoc()) {
5764       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5765       // Put argument in a physical register.
5766       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5767         bool IsLE = Subtarget.isLittleEndian();
5768         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5769                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5770         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5771         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5772                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5773         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5774                              SVal.getValue(0)));
5775       } else
5776         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5777     } else {
5778       // Put argument in the parameter list area of the current stack frame.
5779       assert(VA.isMemLoc());
5780       unsigned LocMemOffset = VA.getLocMemOffset();
5781 
5782       if (!IsTailCall) {
5783         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5784         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5785                              StackPtr, PtrOff);
5786 
5787         MemOpChains.push_back(
5788             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5789       } else {
5790         // Calculate and remember argument location.
5791         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5792                                  TailCallArguments);
5793       }
5794     }
5795   }
5796 
5797   if (!MemOpChains.empty())
5798     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5799 
5800   // Build a sequence of copy-to-reg nodes chained together with token chain
5801   // and flag operands which copy the outgoing args into the appropriate regs.
5802   SDValue InFlag;
5803   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5804     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5805                              RegsToPass[i].second, InFlag);
5806     InFlag = Chain.getValue(1);
5807   }
5808 
5809   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5810   // registers.
5811   if (IsVarArg) {
5812     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5813     SDValue Ops[] = { Chain, InFlag };
5814 
5815     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5816                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5817 
5818     InFlag = Chain.getValue(1);
5819   }
5820 
5821   if (IsTailCall)
5822     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5823                     TailCallArguments);
5824 
5825   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5826                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
5827 }
5828 
5829 // Copy an argument into memory, being careful to do this outside the
5830 // call sequence for the call to which the argument belongs.
5831 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5832     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5833     SelectionDAG &DAG, const SDLoc &dl) const {
5834   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5835                         CallSeqStart.getNode()->getOperand(0),
5836                         Flags, DAG, dl);
5837   // The MEMCPY must go outside the CALLSEQ_START..END.
5838   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5839   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5840                                                  SDLoc(MemcpyCall));
5841   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5842                          NewCallSeqStart.getNode());
5843   return NewCallSeqStart;
5844 }
5845 
5846 SDValue PPCTargetLowering::LowerCall_64SVR4(
5847     SDValue Chain, SDValue Callee, CallFlags CFlags,
5848     const SmallVectorImpl<ISD::OutputArg> &Outs,
5849     const SmallVectorImpl<SDValue> &OutVals,
5850     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5851     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5852     const CallBase *CB) const {
5853   bool isELFv2ABI = Subtarget.isELFv2ABI();
5854   bool isLittleEndian = Subtarget.isLittleEndian();
5855   unsigned NumOps = Outs.size();
5856   bool IsSibCall = false;
5857   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5858 
5859   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5860   unsigned PtrByteSize = 8;
5861 
5862   MachineFunction &MF = DAG.getMachineFunction();
5863 
5864   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5865     IsSibCall = true;
5866 
5867   // Mark this function as potentially containing a function that contains a
5868   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5869   // and restoring the callers stack pointer in this functions epilog. This is
5870   // done because by tail calling the called function might overwrite the value
5871   // in this function's (MF) stack pointer stack slot 0(SP).
5872   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5873     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5874 
5875   assert(!(IsFastCall && CFlags.IsVarArg) &&
5876          "fastcc not supported on varargs functions");
5877 
5878   // Count how many bytes are to be pushed on the stack, including the linkage
5879   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5880   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5881   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5882   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5883   unsigned NumBytes = LinkageSize;
5884   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5885 
5886   static const MCPhysReg GPR[] = {
5887     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5888     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5889   };
5890   static const MCPhysReg VR[] = {
5891     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5892     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5893   };
5894 
5895   const unsigned NumGPRs = array_lengthof(GPR);
5896   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5897   const unsigned NumVRs  = array_lengthof(VR);
5898 
5899   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5900   // can be passed to the callee in registers.
5901   // For the fast calling convention, there is another check below.
5902   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5903   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5904   if (!HasParameterArea) {
5905     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5906     unsigned AvailableFPRs = NumFPRs;
5907     unsigned AvailableVRs = NumVRs;
5908     unsigned NumBytesTmp = NumBytes;
5909     for (unsigned i = 0; i != NumOps; ++i) {
5910       if (Outs[i].Flags.isNest()) continue;
5911       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5912                                  PtrByteSize, LinkageSize, ParamAreaSize,
5913                                  NumBytesTmp, AvailableFPRs, AvailableVRs))
5914         HasParameterArea = true;
5915     }
5916   }
5917 
5918   // When using the fast calling convention, we don't provide backing for
5919   // arguments that will be in registers.
5920   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5921 
5922   // Avoid allocating parameter area for fastcc functions if all the arguments
5923   // can be passed in the registers.
5924   if (IsFastCall)
5925     HasParameterArea = false;
5926 
5927   // Add up all the space actually used.
5928   for (unsigned i = 0; i != NumOps; ++i) {
5929     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5930     EVT ArgVT = Outs[i].VT;
5931     EVT OrigVT = Outs[i].ArgVT;
5932 
5933     if (Flags.isNest())
5934       continue;
5935 
5936     if (IsFastCall) {
5937       if (Flags.isByVal()) {
5938         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5939         if (NumGPRsUsed > NumGPRs)
5940           HasParameterArea = true;
5941       } else {
5942         switch (ArgVT.getSimpleVT().SimpleTy) {
5943         default: llvm_unreachable("Unexpected ValueType for argument!");
5944         case MVT::i1:
5945         case MVT::i32:
5946         case MVT::i64:
5947           if (++NumGPRsUsed <= NumGPRs)
5948             continue;
5949           break;
5950         case MVT::v4i32:
5951         case MVT::v8i16:
5952         case MVT::v16i8:
5953         case MVT::v2f64:
5954         case MVT::v2i64:
5955         case MVT::v1i128:
5956         case MVT::f128:
5957           if (++NumVRsUsed <= NumVRs)
5958             continue;
5959           break;
5960         case MVT::v4f32:
5961           if (++NumVRsUsed <= NumVRs)
5962             continue;
5963           break;
5964         case MVT::f32:
5965         case MVT::f64:
5966           if (++NumFPRsUsed <= NumFPRs)
5967             continue;
5968           break;
5969         }
5970         HasParameterArea = true;
5971       }
5972     }
5973 
5974     /* Respect alignment of argument on the stack.  */
5975     auto Alignement =
5976         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5977     NumBytes = alignTo(NumBytes, Alignement);
5978 
5979     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5980     if (Flags.isInConsecutiveRegsLast())
5981       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5982   }
5983 
5984   unsigned NumBytesActuallyUsed = NumBytes;
5985 
5986   // In the old ELFv1 ABI,
5987   // the prolog code of the callee may store up to 8 GPR argument registers to
5988   // the stack, allowing va_start to index over them in memory if its varargs.
5989   // Because we cannot tell if this is needed on the caller side, we have to
5990   // conservatively assume that it is needed.  As such, make sure we have at
5991   // least enough stack space for the caller to store the 8 GPRs.
5992   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5993   // really requires memory operands, e.g. a vararg function.
5994   if (HasParameterArea)
5995     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5996   else
5997     NumBytes = LinkageSize;
5998 
5999   // Tail call needs the stack to be aligned.
6000   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
6001     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6002 
6003   int SPDiff = 0;
6004 
6005   // Calculate by how many bytes the stack has to be adjusted in case of tail
6006   // call optimization.
6007   if (!IsSibCall)
6008     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6009 
6010   // To protect arguments on the stack from being clobbered in a tail call,
6011   // force all the loads to happen before doing any other lowering.
6012   if (CFlags.IsTailCall)
6013     Chain = DAG.getStackArgumentTokenFactor(Chain);
6014 
6015   // Adjust the stack pointer for the new arguments...
6016   // These operations are automatically eliminated by the prolog/epilog pass
6017   if (!IsSibCall)
6018     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6019   SDValue CallSeqStart = Chain;
6020 
6021   // Load the return address and frame pointer so it can be move somewhere else
6022   // later.
6023   SDValue LROp, FPOp;
6024   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6025 
6026   // Set up a copy of the stack pointer for use loading and storing any
6027   // arguments that may not fit in the registers available for argument
6028   // passing.
6029   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6030 
6031   // Figure out which arguments are going to go in registers, and which in
6032   // memory.  Also, if this is a vararg function, floating point operations
6033   // must be stored to our stack, and loaded into integer regs as well, if
6034   // any integer regs are available for argument passing.
6035   unsigned ArgOffset = LinkageSize;
6036 
6037   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6038   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6039 
6040   SmallVector<SDValue, 8> MemOpChains;
6041   for (unsigned i = 0; i != NumOps; ++i) {
6042     SDValue Arg = OutVals[i];
6043     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6044     EVT ArgVT = Outs[i].VT;
6045     EVT OrigVT = Outs[i].ArgVT;
6046 
6047     // PtrOff will be used to store the current argument to the stack if a
6048     // register cannot be found for it.
6049     SDValue PtrOff;
6050 
6051     // We re-align the argument offset for each argument, except when using the
6052     // fast calling convention, when we need to make sure we do that only when
6053     // we'll actually use a stack slot.
6054     auto ComputePtrOff = [&]() {
6055       /* Respect alignment of argument on the stack.  */
6056       auto Alignment =
6057           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
6058       ArgOffset = alignTo(ArgOffset, Alignment);
6059 
6060       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6061 
6062       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6063     };
6064 
6065     if (!IsFastCall) {
6066       ComputePtrOff();
6067 
6068       /* Compute GPR index associated with argument offset.  */
6069       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6070       GPR_idx = std::min(GPR_idx, NumGPRs);
6071     }
6072 
6073     // Promote integers to 64-bit values.
6074     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6075       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6076       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6077       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6078     }
6079 
6080     // FIXME memcpy is used way more than necessary.  Correctness first.
6081     // Note: "by value" is code for passing a structure by value, not
6082     // basic types.
6083     if (Flags.isByVal()) {
6084       // Note: Size includes alignment padding, so
6085       //   struct x { short a; char b; }
6086       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6087       // These are the proper values we need for right-justifying the
6088       // aggregate in a parameter register.
6089       unsigned Size = Flags.getByValSize();
6090 
6091       // An empty aggregate parameter takes up no storage and no
6092       // registers.
6093       if (Size == 0)
6094         continue;
6095 
6096       if (IsFastCall)
6097         ComputePtrOff();
6098 
6099       // All aggregates smaller than 8 bytes must be passed right-justified.
6100       if (Size==1 || Size==2 || Size==4) {
6101         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6102         if (GPR_idx != NumGPRs) {
6103           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6104                                         MachinePointerInfo(), VT);
6105           MemOpChains.push_back(Load.getValue(1));
6106           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6107 
6108           ArgOffset += PtrByteSize;
6109           continue;
6110         }
6111       }
6112 
6113       if (GPR_idx == NumGPRs && Size < 8) {
6114         SDValue AddPtr = PtrOff;
6115         if (!isLittleEndian) {
6116           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6117                                           PtrOff.getValueType());
6118           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6119         }
6120         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6121                                                           CallSeqStart,
6122                                                           Flags, DAG, dl);
6123         ArgOffset += PtrByteSize;
6124         continue;
6125       }
6126       // Copy entire object into memory.  There are cases where gcc-generated
6127       // code assumes it is there, even if it could be put entirely into
6128       // registers.  (This is not what the doc says.)
6129 
6130       // FIXME: The above statement is likely due to a misunderstanding of the
6131       // documents.  All arguments must be copied into the parameter area BY
6132       // THE CALLEE in the event that the callee takes the address of any
6133       // formal argument.  That has not yet been implemented.  However, it is
6134       // reasonable to use the stack area as a staging area for the register
6135       // load.
6136 
6137       // Skip this for small aggregates, as we will use the same slot for a
6138       // right-justified copy, below.
6139       if (Size >= 8)
6140         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6141                                                           CallSeqStart,
6142                                                           Flags, DAG, dl);
6143 
6144       // When a register is available, pass a small aggregate right-justified.
6145       if (Size < 8 && GPR_idx != NumGPRs) {
6146         // The easiest way to get this right-justified in a register
6147         // is to copy the structure into the rightmost portion of a
6148         // local variable slot, then load the whole slot into the
6149         // register.
6150         // FIXME: The memcpy seems to produce pretty awful code for
6151         // small aggregates, particularly for packed ones.
6152         // FIXME: It would be preferable to use the slot in the
6153         // parameter save area instead of a new local variable.
6154         SDValue AddPtr = PtrOff;
6155         if (!isLittleEndian) {
6156           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6157           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6158         }
6159         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6160                                                           CallSeqStart,
6161                                                           Flags, DAG, dl);
6162 
6163         // Load the slot into the register.
6164         SDValue Load =
6165             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6166         MemOpChains.push_back(Load.getValue(1));
6167         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6168 
6169         // Done with this argument.
6170         ArgOffset += PtrByteSize;
6171         continue;
6172       }
6173 
6174       // For aggregates larger than PtrByteSize, copy the pieces of the
6175       // object that fit into registers from the parameter save area.
6176       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6177         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6178         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6179         if (GPR_idx != NumGPRs) {
6180           SDValue Load =
6181               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6182           MemOpChains.push_back(Load.getValue(1));
6183           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6184           ArgOffset += PtrByteSize;
6185         } else {
6186           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6187           break;
6188         }
6189       }
6190       continue;
6191     }
6192 
6193     switch (Arg.getSimpleValueType().SimpleTy) {
6194     default: llvm_unreachable("Unexpected ValueType for argument!");
6195     case MVT::i1:
6196     case MVT::i32:
6197     case MVT::i64:
6198       if (Flags.isNest()) {
6199         // The 'nest' parameter, if any, is passed in R11.
6200         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6201         break;
6202       }
6203 
6204       // These can be scalar arguments or elements of an integer array type
6205       // passed directly.  Clang may use those instead of "byval" aggregate
6206       // types to avoid forcing arguments to memory unnecessarily.
6207       if (GPR_idx != NumGPRs) {
6208         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6209       } else {
6210         if (IsFastCall)
6211           ComputePtrOff();
6212 
6213         assert(HasParameterArea &&
6214                "Parameter area must exist to pass an argument in memory.");
6215         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6216                          true, CFlags.IsTailCall, false, MemOpChains,
6217                          TailCallArguments, dl);
6218         if (IsFastCall)
6219           ArgOffset += PtrByteSize;
6220       }
6221       if (!IsFastCall)
6222         ArgOffset += PtrByteSize;
6223       break;
6224     case MVT::f32:
6225     case MVT::f64: {
6226       // These can be scalar arguments or elements of a float array type
6227       // passed directly.  The latter are used to implement ELFv2 homogenous
6228       // float aggregates.
6229 
6230       // Named arguments go into FPRs first, and once they overflow, the
6231       // remaining arguments go into GPRs and then the parameter save area.
6232       // Unnamed arguments for vararg functions always go to GPRs and
6233       // then the parameter save area.  For now, put all arguments to vararg
6234       // routines always in both locations (FPR *and* GPR or stack slot).
6235       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6236       bool NeededLoad = false;
6237 
6238       // First load the argument into the next available FPR.
6239       if (FPR_idx != NumFPRs)
6240         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6241 
6242       // Next, load the argument into GPR or stack slot if needed.
6243       if (!NeedGPROrStack)
6244         ;
6245       else if (GPR_idx != NumGPRs && !IsFastCall) {
6246         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6247         // once we support fp <-> gpr moves.
6248 
6249         // In the non-vararg case, this can only ever happen in the
6250         // presence of f32 array types, since otherwise we never run
6251         // out of FPRs before running out of GPRs.
6252         SDValue ArgVal;
6253 
6254         // Double values are always passed in a single GPR.
6255         if (Arg.getValueType() != MVT::f32) {
6256           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6257 
6258         // Non-array float values are extended and passed in a GPR.
6259         } else if (!Flags.isInConsecutiveRegs()) {
6260           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6261           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6262 
6263         // If we have an array of floats, we collect every odd element
6264         // together with its predecessor into one GPR.
6265         } else if (ArgOffset % PtrByteSize != 0) {
6266           SDValue Lo, Hi;
6267           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6268           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6269           if (!isLittleEndian)
6270             std::swap(Lo, Hi);
6271           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6272 
6273         // The final element, if even, goes into the first half of a GPR.
6274         } else if (Flags.isInConsecutiveRegsLast()) {
6275           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6276           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6277           if (!isLittleEndian)
6278             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6279                                  DAG.getConstant(32, dl, MVT::i32));
6280 
6281         // Non-final even elements are skipped; they will be handled
6282         // together the with subsequent argument on the next go-around.
6283         } else
6284           ArgVal = SDValue();
6285 
6286         if (ArgVal.getNode())
6287           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6288       } else {
6289         if (IsFastCall)
6290           ComputePtrOff();
6291 
6292         // Single-precision floating-point values are mapped to the
6293         // second (rightmost) word of the stack doubleword.
6294         if (Arg.getValueType() == MVT::f32 &&
6295             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6296           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6297           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6298         }
6299 
6300         assert(HasParameterArea &&
6301                "Parameter area must exist to pass an argument in memory.");
6302         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6303                          true, CFlags.IsTailCall, false, MemOpChains,
6304                          TailCallArguments, dl);
6305 
6306         NeededLoad = true;
6307       }
6308       // When passing an array of floats, the array occupies consecutive
6309       // space in the argument area; only round up to the next doubleword
6310       // at the end of the array.  Otherwise, each float takes 8 bytes.
6311       if (!IsFastCall || NeededLoad) {
6312         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6313                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6314         if (Flags.isInConsecutiveRegsLast())
6315           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6316       }
6317       break;
6318     }
6319     case MVT::v4f32:
6320     case MVT::v4i32:
6321     case MVT::v8i16:
6322     case MVT::v16i8:
6323     case MVT::v2f64:
6324     case MVT::v2i64:
6325     case MVT::v1i128:
6326     case MVT::f128:
6327       // These can be scalar arguments or elements of a vector array type
6328       // passed directly.  The latter are used to implement ELFv2 homogenous
6329       // vector aggregates.
6330 
6331       // For a varargs call, named arguments go into VRs or on the stack as
6332       // usual; unnamed arguments always go to the stack or the corresponding
6333       // GPRs when within range.  For now, we always put the value in both
6334       // locations (or even all three).
6335       if (CFlags.IsVarArg) {
6336         assert(HasParameterArea &&
6337                "Parameter area must exist if we have a varargs call.");
6338         // We could elide this store in the case where the object fits
6339         // entirely in R registers.  Maybe later.
6340         SDValue Store =
6341             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6342         MemOpChains.push_back(Store);
6343         if (VR_idx != NumVRs) {
6344           SDValue Load =
6345               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6346           MemOpChains.push_back(Load.getValue(1));
6347           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6348         }
6349         ArgOffset += 16;
6350         for (unsigned i=0; i<16; i+=PtrByteSize) {
6351           if (GPR_idx == NumGPRs)
6352             break;
6353           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6354                                    DAG.getConstant(i, dl, PtrVT));
6355           SDValue Load =
6356               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6357           MemOpChains.push_back(Load.getValue(1));
6358           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6359         }
6360         break;
6361       }
6362 
6363       // Non-varargs Altivec params go into VRs or on the stack.
6364       if (VR_idx != NumVRs) {
6365         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6366       } else {
6367         if (IsFastCall)
6368           ComputePtrOff();
6369 
6370         assert(HasParameterArea &&
6371                "Parameter area must exist to pass an argument in memory.");
6372         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6373                          true, CFlags.IsTailCall, true, MemOpChains,
6374                          TailCallArguments, dl);
6375         if (IsFastCall)
6376           ArgOffset += 16;
6377       }
6378 
6379       if (!IsFastCall)
6380         ArgOffset += 16;
6381       break;
6382     }
6383   }
6384 
6385   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6386          "mismatch in size of parameter area");
6387   (void)NumBytesActuallyUsed;
6388 
6389   if (!MemOpChains.empty())
6390     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6391 
6392   // Check if this is an indirect call (MTCTR/BCTRL).
6393   // See prepareDescriptorIndirectCall and buildCallOperands for more
6394   // information about calls through function pointers in the 64-bit SVR4 ABI.
6395   if (CFlags.IsIndirect) {
6396     // For 64-bit ELFv2 ABI with PCRel, do not save the TOC of the
6397     // caller in the TOC save area.
6398     if (isTOCSaveRestoreRequired(Subtarget)) {
6399       assert(!CFlags.IsTailCall && "Indirect tails calls not supported");
6400       // Load r2 into a virtual register and store it to the TOC save area.
6401       setUsesTOCBasePtr(DAG);
6402       SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6403       // TOC save area offset.
6404       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6405       SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6406       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6407       Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr,
6408                            MachinePointerInfo::getStack(
6409                                DAG.getMachineFunction(), TOCSaveOffset));
6410     }
6411     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6412     // This does not mean the MTCTR instruction must use R12; it's easier
6413     // to model this as an extra parameter, so do that.
6414     if (isELFv2ABI && !CFlags.IsPatchPoint)
6415       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6416   }
6417 
6418   // Build a sequence of copy-to-reg nodes chained together with token chain
6419   // and flag operands which copy the outgoing args into the appropriate regs.
6420   SDValue InFlag;
6421   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6422     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6423                              RegsToPass[i].second, InFlag);
6424     InFlag = Chain.getValue(1);
6425   }
6426 
6427   if (CFlags.IsTailCall && !IsSibCall)
6428     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6429                     TailCallArguments);
6430 
6431   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6432                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6433 }
6434 
6435 SDValue PPCTargetLowering::LowerCall_Darwin(
6436     SDValue Chain, SDValue Callee, CallFlags CFlags,
6437     const SmallVectorImpl<ISD::OutputArg> &Outs,
6438     const SmallVectorImpl<SDValue> &OutVals,
6439     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6440     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6441     const CallBase *CB) const {
6442   unsigned NumOps = Outs.size();
6443 
6444   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6445   bool isPPC64 = PtrVT == MVT::i64;
6446   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6447 
6448   MachineFunction &MF = DAG.getMachineFunction();
6449 
6450   // Mark this function as potentially containing a function that contains a
6451   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6452   // and restoring the callers stack pointer in this functions epilog. This is
6453   // done because by tail calling the called function might overwrite the value
6454   // in this function's (MF) stack pointer stack slot 0(SP).
6455   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6456       CFlags.CallConv == CallingConv::Fast)
6457     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6458 
6459   // Count how many bytes are to be pushed on the stack, including the linkage
6460   // area, and parameter passing area.  We start with 24/48 bytes, which is
6461   // prereserved space for [SP][CR][LR][3 x unused].
6462   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6463   unsigned NumBytes = LinkageSize;
6464 
6465   // Add up all the space actually used.
6466   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6467   // they all go in registers, but we must reserve stack space for them for
6468   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6469   // assigned stack space in order, with padding so Altivec parameters are
6470   // 16-byte aligned.
6471   unsigned nAltivecParamsAtEnd = 0;
6472   for (unsigned i = 0; i != NumOps; ++i) {
6473     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6474     EVT ArgVT = Outs[i].VT;
6475     // Varargs Altivec parameters are padded to a 16 byte boundary.
6476     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6477         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6478         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6479       if (!CFlags.IsVarArg && !isPPC64) {
6480         // Non-varargs Altivec parameters go after all the non-Altivec
6481         // parameters; handle those later so we know how much padding we need.
6482         nAltivecParamsAtEnd++;
6483         continue;
6484       }
6485       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6486       NumBytes = ((NumBytes+15)/16)*16;
6487     }
6488     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6489   }
6490 
6491   // Allow for Altivec parameters at the end, if needed.
6492   if (nAltivecParamsAtEnd) {
6493     NumBytes = ((NumBytes+15)/16)*16;
6494     NumBytes += 16*nAltivecParamsAtEnd;
6495   }
6496 
6497   // The prolog code of the callee may store up to 8 GPR argument registers to
6498   // the stack, allowing va_start to index over them in memory if its varargs.
6499   // Because we cannot tell if this is needed on the caller side, we have to
6500   // conservatively assume that it is needed.  As such, make sure we have at
6501   // least enough stack space for the caller to store the 8 GPRs.
6502   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6503 
6504   // Tail call needs the stack to be aligned.
6505   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6506       CFlags.CallConv == CallingConv::Fast)
6507     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6508 
6509   // Calculate by how many bytes the stack has to be adjusted in case of tail
6510   // call optimization.
6511   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6512 
6513   // To protect arguments on the stack from being clobbered in a tail call,
6514   // force all the loads to happen before doing any other lowering.
6515   if (CFlags.IsTailCall)
6516     Chain = DAG.getStackArgumentTokenFactor(Chain);
6517 
6518   // Adjust the stack pointer for the new arguments...
6519   // These operations are automatically eliminated by the prolog/epilog pass
6520   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6521   SDValue CallSeqStart = Chain;
6522 
6523   // Load the return address and frame pointer so it can be move somewhere else
6524   // later.
6525   SDValue LROp, FPOp;
6526   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6527 
6528   // Set up a copy of the stack pointer for use loading and storing any
6529   // arguments that may not fit in the registers available for argument
6530   // passing.
6531   SDValue StackPtr;
6532   if (isPPC64)
6533     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6534   else
6535     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6536 
6537   // Figure out which arguments are going to go in registers, and which in
6538   // memory.  Also, if this is a vararg function, floating point operations
6539   // must be stored to our stack, and loaded into integer regs as well, if
6540   // any integer regs are available for argument passing.
6541   unsigned ArgOffset = LinkageSize;
6542   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6543 
6544   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6545     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6546     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6547   };
6548   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6549     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6550     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6551   };
6552   static const MCPhysReg VR[] = {
6553     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6554     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6555   };
6556   const unsigned NumGPRs = array_lengthof(GPR_32);
6557   const unsigned NumFPRs = 13;
6558   const unsigned NumVRs  = array_lengthof(VR);
6559 
6560   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6561 
6562   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6563   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6564 
6565   SmallVector<SDValue, 8> MemOpChains;
6566   for (unsigned i = 0; i != NumOps; ++i) {
6567     SDValue Arg = OutVals[i];
6568     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6569 
6570     // PtrOff will be used to store the current argument to the stack if a
6571     // register cannot be found for it.
6572     SDValue PtrOff;
6573 
6574     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6575 
6576     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6577 
6578     // On PPC64, promote integers to 64-bit values.
6579     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6580       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6581       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6582       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6583     }
6584 
6585     // FIXME memcpy is used way more than necessary.  Correctness first.
6586     // Note: "by value" is code for passing a structure by value, not
6587     // basic types.
6588     if (Flags.isByVal()) {
6589       unsigned Size = Flags.getByValSize();
6590       // Very small objects are passed right-justified.  Everything else is
6591       // passed left-justified.
6592       if (Size==1 || Size==2) {
6593         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6594         if (GPR_idx != NumGPRs) {
6595           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6596                                         MachinePointerInfo(), VT);
6597           MemOpChains.push_back(Load.getValue(1));
6598           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6599 
6600           ArgOffset += PtrByteSize;
6601         } else {
6602           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6603                                           PtrOff.getValueType());
6604           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6605           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6606                                                             CallSeqStart,
6607                                                             Flags, DAG, dl);
6608           ArgOffset += PtrByteSize;
6609         }
6610         continue;
6611       }
6612       // Copy entire object into memory.  There are cases where gcc-generated
6613       // code assumes it is there, even if it could be put entirely into
6614       // registers.  (This is not what the doc says.)
6615       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6616                                                         CallSeqStart,
6617                                                         Flags, DAG, dl);
6618 
6619       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6620       // copy the pieces of the object that fit into registers from the
6621       // parameter save area.
6622       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6623         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6624         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6625         if (GPR_idx != NumGPRs) {
6626           SDValue Load =
6627               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6628           MemOpChains.push_back(Load.getValue(1));
6629           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6630           ArgOffset += PtrByteSize;
6631         } else {
6632           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6633           break;
6634         }
6635       }
6636       continue;
6637     }
6638 
6639     switch (Arg.getSimpleValueType().SimpleTy) {
6640     default: llvm_unreachable("Unexpected ValueType for argument!");
6641     case MVT::i1:
6642     case MVT::i32:
6643     case MVT::i64:
6644       if (GPR_idx != NumGPRs) {
6645         if (Arg.getValueType() == MVT::i1)
6646           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6647 
6648         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6649       } else {
6650         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6651                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6652                          TailCallArguments, dl);
6653       }
6654       ArgOffset += PtrByteSize;
6655       break;
6656     case MVT::f32:
6657     case MVT::f64:
6658       if (FPR_idx != NumFPRs) {
6659         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6660 
6661         if (CFlags.IsVarArg) {
6662           SDValue Store =
6663               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6664           MemOpChains.push_back(Store);
6665 
6666           // Float varargs are always shadowed in available integer registers
6667           if (GPR_idx != NumGPRs) {
6668             SDValue Load =
6669                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6670             MemOpChains.push_back(Load.getValue(1));
6671             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6672           }
6673           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6674             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6675             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6676             SDValue Load =
6677                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6678             MemOpChains.push_back(Load.getValue(1));
6679             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6680           }
6681         } else {
6682           // If we have any FPRs remaining, we may also have GPRs remaining.
6683           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6684           // GPRs.
6685           if (GPR_idx != NumGPRs)
6686             ++GPR_idx;
6687           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6688               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6689             ++GPR_idx;
6690         }
6691       } else
6692         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6693                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6694                          TailCallArguments, dl);
6695       if (isPPC64)
6696         ArgOffset += 8;
6697       else
6698         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6699       break;
6700     case MVT::v4f32:
6701     case MVT::v4i32:
6702     case MVT::v8i16:
6703     case MVT::v16i8:
6704       if (CFlags.IsVarArg) {
6705         // These go aligned on the stack, or in the corresponding R registers
6706         // when within range.  The Darwin PPC ABI doc claims they also go in
6707         // V registers; in fact gcc does this only for arguments that are
6708         // prototyped, not for those that match the ...  We do it for all
6709         // arguments, seems to work.
6710         while (ArgOffset % 16 !=0) {
6711           ArgOffset += PtrByteSize;
6712           if (GPR_idx != NumGPRs)
6713             GPR_idx++;
6714         }
6715         // We could elide this store in the case where the object fits
6716         // entirely in R registers.  Maybe later.
6717         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6718                              DAG.getConstant(ArgOffset, dl, PtrVT));
6719         SDValue Store =
6720             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6721         MemOpChains.push_back(Store);
6722         if (VR_idx != NumVRs) {
6723           SDValue Load =
6724               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6725           MemOpChains.push_back(Load.getValue(1));
6726           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6727         }
6728         ArgOffset += 16;
6729         for (unsigned i=0; i<16; i+=PtrByteSize) {
6730           if (GPR_idx == NumGPRs)
6731             break;
6732           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6733                                    DAG.getConstant(i, dl, PtrVT));
6734           SDValue Load =
6735               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6736           MemOpChains.push_back(Load.getValue(1));
6737           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6738         }
6739         break;
6740       }
6741 
6742       // Non-varargs Altivec params generally go in registers, but have
6743       // stack space allocated at the end.
6744       if (VR_idx != NumVRs) {
6745         // Doesn't have GPR space allocated.
6746         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6747       } else if (nAltivecParamsAtEnd==0) {
6748         // We are emitting Altivec params in order.
6749         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6750                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6751                          TailCallArguments, dl);
6752         ArgOffset += 16;
6753       }
6754       break;
6755     }
6756   }
6757   // If all Altivec parameters fit in registers, as they usually do,
6758   // they get stack space following the non-Altivec parameters.  We
6759   // don't track this here because nobody below needs it.
6760   // If there are more Altivec parameters than fit in registers emit
6761   // the stores here.
6762   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6763     unsigned j = 0;
6764     // Offset is aligned; skip 1st 12 params which go in V registers.
6765     ArgOffset = ((ArgOffset+15)/16)*16;
6766     ArgOffset += 12*16;
6767     for (unsigned i = 0; i != NumOps; ++i) {
6768       SDValue Arg = OutVals[i];
6769       EVT ArgType = Outs[i].VT;
6770       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6771           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6772         if (++j > NumVRs) {
6773           SDValue PtrOff;
6774           // We are emitting Altivec params in order.
6775           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6776                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6777                            TailCallArguments, dl);
6778           ArgOffset += 16;
6779         }
6780       }
6781     }
6782   }
6783 
6784   if (!MemOpChains.empty())
6785     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6786 
6787   // On Darwin, R12 must contain the address of an indirect callee.  This does
6788   // not mean the MTCTR instruction must use R12; it's easier to model this as
6789   // an extra parameter, so do that.
6790   if (CFlags.IsIndirect) {
6791     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6792     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6793                                                    PPC::R12), Callee));
6794   }
6795 
6796   // Build a sequence of copy-to-reg nodes chained together with token chain
6797   // and flag operands which copy the outgoing args into the appropriate regs.
6798   SDValue InFlag;
6799   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6800     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6801                              RegsToPass[i].second, InFlag);
6802     InFlag = Chain.getValue(1);
6803   }
6804 
6805   if (CFlags.IsTailCall)
6806     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6807                     TailCallArguments);
6808 
6809   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6810                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
6811 }
6812 
6813 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6814                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6815                    CCState &State) {
6816 
6817   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6818       State.getMachineFunction().getSubtarget());
6819   const bool IsPPC64 = Subtarget.isPPC64();
6820   const Align PtrAlign = IsPPC64 ? Align(8) : Align(4);
6821   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6822 
6823   assert((!ValVT.isInteger() ||
6824           (ValVT.getSizeInBits() <= RegVT.getSizeInBits())) &&
6825          "Integer argument exceeds register size: should have been legalized");
6826 
6827   if (ValVT == MVT::f128)
6828     report_fatal_error("f128 is unimplemented on AIX.");
6829 
6830   if (ArgFlags.isNest())
6831     report_fatal_error("Nest arguments are unimplemented.");
6832 
6833   if (ValVT.isVector() || LocVT.isVector())
6834     report_fatal_error("Vector arguments are unimplemented on AIX.");
6835 
6836   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6837                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6838                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6839   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6840                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6841                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6842 
6843   if (ArgFlags.isByVal()) {
6844     if (ArgFlags.getNonZeroByValAlign() > PtrAlign)
6845       report_fatal_error("Pass-by-value arguments with alignment greater than "
6846                          "register width are not supported.");
6847 
6848     const unsigned ByValSize = ArgFlags.getByValSize();
6849 
6850     // An empty aggregate parameter takes up no storage and no registers,
6851     // but needs a MemLoc for a stack slot for the formal arguments side.
6852     if (ByValSize == 0) {
6853       State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6854                                        State.getNextStackOffset(), RegVT,
6855                                        LocInfo));
6856       return false;
6857     }
6858 
6859     const unsigned StackSize = alignTo(ByValSize, PtrAlign);
6860     unsigned Offset = State.AllocateStack(StackSize, PtrAlign);
6861     for (const unsigned E = Offset + StackSize; Offset < E;
6862          Offset += PtrAlign.value()) {
6863       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6864         State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6865       else {
6866         State.addLoc(CCValAssign::getMem(ValNo, MVT::INVALID_SIMPLE_VALUE_TYPE,
6867                                          Offset, MVT::INVALID_SIMPLE_VALUE_TYPE,
6868                                          LocInfo));
6869         break;
6870       }
6871     }
6872     return false;
6873   }
6874 
6875   // Arguments always reserve parameter save area.
6876   switch (ValVT.SimpleTy) {
6877   default:
6878     report_fatal_error("Unhandled value type for argument.");
6879   case MVT::i64:
6880     // i64 arguments should have been split to i32 for PPC32.
6881     assert(IsPPC64 && "PPC32 should have split i64 values.");
6882     LLVM_FALLTHROUGH;
6883   case MVT::i1:
6884   case MVT::i32: {
6885     const unsigned Offset = State.AllocateStack(PtrAlign.value(), PtrAlign);
6886     // AIX integer arguments are always passed in register width.
6887     if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6888       LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6889                                   : CCValAssign::LocInfo::ZExt;
6890     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32))
6891       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6892     else
6893       State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, RegVT, LocInfo));
6894 
6895     return false;
6896   }
6897   case MVT::f32:
6898   case MVT::f64: {
6899     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6900     const unsigned StoreSize = LocVT.getStoreSize();
6901     // Floats are always 4-byte aligned in the PSA on AIX.
6902     // This includes f64 in 64-bit mode for ABI compatibility.
6903     const unsigned Offset =
6904         State.AllocateStack(IsPPC64 ? 8 : StoreSize, Align(4));
6905     unsigned FReg = State.AllocateReg(FPR);
6906     if (FReg)
6907       State.addLoc(CCValAssign::getReg(ValNo, ValVT, FReg, LocVT, LocInfo));
6908 
6909     // Reserve and initialize GPRs or initialize the PSA as required.
6910     for (unsigned I = 0; I < StoreSize; I += PtrAlign.value()) {
6911       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6912         assert(FReg && "An FPR should be available when a GPR is reserved.");
6913         if (State.isVarArg()) {
6914           // Successfully reserved GPRs are only initialized for vararg calls.
6915           // Custom handling is required for:
6916           //   f64 in PPC32 needs to be split into 2 GPRs.
6917           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6918           State.addLoc(
6919               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6920         }
6921       } else {
6922         // If there are insufficient GPRs, the PSA needs to be initialized.
6923         // Initialization occurs even if an FPR was initialized for
6924         // compatibility with the AIX XL compiler. The full memory for the
6925         // argument will be initialized even if a prior word is saved in GPR.
6926         // A custom memLoc is used when the argument also passes in FPR so
6927         // that the callee handling can skip over it easily.
6928         State.addLoc(
6929             FReg ? CCValAssign::getCustomMem(ValNo, ValVT, Offset, LocVT,
6930                                              LocInfo)
6931                  : CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
6932         break;
6933       }
6934     }
6935 
6936     return false;
6937   }
6938   }
6939   return true;
6940 }
6941 
6942 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6943                                                     bool IsPPC64) {
6944   assert((IsPPC64 || SVT != MVT::i64) &&
6945          "i64 should have been split for 32-bit codegen.");
6946 
6947   switch (SVT) {
6948   default:
6949     report_fatal_error("Unexpected value type for formal argument");
6950   case MVT::i1:
6951   case MVT::i32:
6952   case MVT::i64:
6953     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6954   case MVT::f32:
6955     return &PPC::F4RCRegClass;
6956   case MVT::f64:
6957     return &PPC::F8RCRegClass;
6958   }
6959 }
6960 
6961 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6962                                         SelectionDAG &DAG, SDValue ArgValue,
6963                                         MVT LocVT, const SDLoc &dl) {
6964   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6965   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6966 
6967   if (Flags.isSExt())
6968     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6969                            DAG.getValueType(ValVT));
6970   else if (Flags.isZExt())
6971     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6972                            DAG.getValueType(ValVT));
6973 
6974   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6975 }
6976 
6977 static unsigned mapArgRegToOffsetAIX(unsigned Reg, const PPCFrameLowering *FL) {
6978   const unsigned LASize = FL->getLinkageSize();
6979 
6980   if (PPC::GPRCRegClass.contains(Reg)) {
6981     assert(Reg >= PPC::R3 && Reg <= PPC::R10 &&
6982            "Reg must be a valid argument register!");
6983     return LASize + 4 * (Reg - PPC::R3);
6984   }
6985 
6986   if (PPC::G8RCRegClass.contains(Reg)) {
6987     assert(Reg >= PPC::X3 && Reg <= PPC::X10 &&
6988            "Reg must be a valid argument register!");
6989     return LASize + 8 * (Reg - PPC::X3);
6990   }
6991 
6992   llvm_unreachable("Only general purpose registers expected.");
6993 }
6994 
6995 //   AIX ABI Stack Frame Layout:
6996 //
6997 //   Low Memory +--------------------------------------------+
6998 //   SP   +---> | Back chain                                 | ---+
6999 //        |     +--------------------------------------------+    |
7000 //        |     | Saved Condition Register                   |    |
7001 //        |     +--------------------------------------------+    |
7002 //        |     | Saved Linkage Register                     |    |
7003 //        |     +--------------------------------------------+    | Linkage Area
7004 //        |     | Reserved for compilers                     |    |
7005 //        |     +--------------------------------------------+    |
7006 //        |     | Reserved for binders                       |    |
7007 //        |     +--------------------------------------------+    |
7008 //        |     | Saved TOC pointer                          | ---+
7009 //        |     +--------------------------------------------+
7010 //        |     | Parameter save area                        |
7011 //        |     +--------------------------------------------+
7012 //        |     | Alloca space                               |
7013 //        |     +--------------------------------------------+
7014 //        |     | Local variable space                       |
7015 //        |     +--------------------------------------------+
7016 //        |     | Float/int conversion temporary             |
7017 //        |     +--------------------------------------------+
7018 //        |     | Save area for AltiVec registers            |
7019 //        |     +--------------------------------------------+
7020 //        |     | AltiVec alignment padding                  |
7021 //        |     +--------------------------------------------+
7022 //        |     | Save area for VRSAVE register              |
7023 //        |     +--------------------------------------------+
7024 //        |     | Save area for General Purpose registers    |
7025 //        |     +--------------------------------------------+
7026 //        |     | Save area for Floating Point registers     |
7027 //        |     +--------------------------------------------+
7028 //        +---- | Back chain                                 |
7029 // High Memory  +--------------------------------------------+
7030 //
7031 //  Specifications:
7032 //  AIX 7.2 Assembler Language Reference
7033 //  Subroutine linkage convention
7034 
7035 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
7036     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
7037     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7038     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
7039 
7040   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
7041           CallConv == CallingConv::Fast) &&
7042          "Unexpected calling convention!");
7043 
7044   if (getTargetMachine().Options.GuaranteedTailCallOpt)
7045     report_fatal_error("Tail call support is unimplemented on AIX.");
7046 
7047   if (useSoftFloat())
7048     report_fatal_error("Soft float support is unimplemented on AIX.");
7049 
7050   const PPCSubtarget &Subtarget =
7051       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
7052 
7053   const bool IsPPC64 = Subtarget.isPPC64();
7054   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7055 
7056   // Assign locations to all of the incoming arguments.
7057   SmallVector<CCValAssign, 16> ArgLocs;
7058   MachineFunction &MF = DAG.getMachineFunction();
7059   MachineFrameInfo &MFI = MF.getFrameInfo();
7060   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7061 
7062   const EVT PtrVT = getPointerTy(MF.getDataLayout());
7063   // Reserve space for the linkage area on the stack.
7064   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7065   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7066   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
7067 
7068   SmallVector<SDValue, 8> MemOps;
7069 
7070   for (size_t I = 0, End = ArgLocs.size(); I != End; /* No increment here */) {
7071     CCValAssign &VA = ArgLocs[I++];
7072     MVT LocVT = VA.getLocVT();
7073     ISD::ArgFlagsTy Flags = Ins[VA.getValNo()].Flags;
7074 
7075     // For compatibility with the AIX XL compiler, the float args in the
7076     // parameter save area are initialized even if the argument is available
7077     // in register.  The caller is required to initialize both the register
7078     // and memory, however, the callee can choose to expect it in either.
7079     // The memloc is dismissed here because the argument is retrieved from
7080     // the register.
7081     if (VA.isMemLoc() && VA.needsCustom())
7082       continue;
7083 
7084     if (Flags.isByVal() && VA.isMemLoc()) {
7085       const unsigned Size =
7086           alignTo(Flags.getByValSize() ? Flags.getByValSize() : PtrByteSize,
7087                   PtrByteSize);
7088       const int FI = MF.getFrameInfo().CreateFixedObject(
7089           Size, VA.getLocMemOffset(), /* IsImmutable */ false,
7090           /* IsAliased */ true);
7091       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7092       InVals.push_back(FIN);
7093 
7094       continue;
7095     }
7096 
7097     if (Flags.isByVal()) {
7098       assert(VA.isRegLoc() && "MemLocs should already be handled.");
7099 
7100       const MCPhysReg ArgReg = VA.getLocReg();
7101       const PPCFrameLowering *FL = Subtarget.getFrameLowering();
7102 
7103       if (Flags.getNonZeroByValAlign() > PtrByteSize)
7104         report_fatal_error("Over aligned byvals not supported yet.");
7105 
7106       const unsigned StackSize = alignTo(Flags.getByValSize(), PtrByteSize);
7107       const int FI = MF.getFrameInfo().CreateFixedObject(
7108           StackSize, mapArgRegToOffsetAIX(ArgReg, FL), /* IsImmutable */ false,
7109           /* IsAliased */ true);
7110       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7111       InVals.push_back(FIN);
7112 
7113       // Add live ins for all the RegLocs for the same ByVal.
7114       const TargetRegisterClass *RegClass =
7115           IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7116 
7117       auto HandleRegLoc = [&, RegClass, LocVT](const MCPhysReg PhysReg,
7118                                                unsigned Offset) {
7119         const unsigned VReg = MF.addLiveIn(PhysReg, RegClass);
7120         // Since the callers side has left justified the aggregate in the
7121         // register, we can simply store the entire register into the stack
7122         // slot.
7123         SDValue CopyFrom = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7124         // The store to the fixedstack object is needed becuase accessing a
7125         // field of the ByVal will use a gep and load. Ideally we will optimize
7126         // to extracting the value from the register directly, and elide the
7127         // stores when the arguments address is not taken, but that will need to
7128         // be future work.
7129         SDValue Store = DAG.getStore(
7130             CopyFrom.getValue(1), dl, CopyFrom,
7131             DAG.getObjectPtrOffset(dl, FIN, TypeSize::Fixed(Offset)),
7132             MachinePointerInfo::getFixedStack(MF, FI, Offset));
7133 
7134         MemOps.push_back(Store);
7135       };
7136 
7137       unsigned Offset = 0;
7138       HandleRegLoc(VA.getLocReg(), Offset);
7139       Offset += PtrByteSize;
7140       for (; Offset != StackSize && ArgLocs[I].isRegLoc();
7141            Offset += PtrByteSize) {
7142         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7143                "RegLocs should be for ByVal argument.");
7144 
7145         const CCValAssign RL = ArgLocs[I++];
7146         HandleRegLoc(RL.getLocReg(), Offset);
7147       }
7148 
7149       if (Offset != StackSize) {
7150         assert(ArgLocs[I].getValNo() == VA.getValNo() &&
7151                "Expected MemLoc for remaining bytes.");
7152         assert(ArgLocs[I].isMemLoc() && "Expected MemLoc for remaining bytes.");
7153         // Consume the MemLoc.The InVal has already been emitted, so nothing
7154         // more needs to be done.
7155         ++I;
7156       }
7157 
7158       continue;
7159     }
7160 
7161     EVT ValVT = VA.getValVT();
7162     if (VA.isRegLoc() && !VA.needsCustom()) {
7163       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
7164       unsigned VReg =
7165           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
7166       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
7167       if (ValVT.isScalarInteger() &&
7168           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
7169         ArgValue =
7170             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
7171       }
7172       InVals.push_back(ArgValue);
7173       continue;
7174     }
7175     if (VA.isMemLoc()) {
7176       const unsigned LocSize = LocVT.getStoreSize();
7177       const unsigned ValSize = ValVT.getStoreSize();
7178       assert((ValSize <= LocSize) &&
7179              "Object size is larger than size of MemLoc");
7180       int CurArgOffset = VA.getLocMemOffset();
7181       // Objects are right-justified because AIX is big-endian.
7182       if (LocSize > ValSize)
7183         CurArgOffset += LocSize - ValSize;
7184       // Potential tail calls could cause overwriting of argument stack slots.
7185       const bool IsImmutable =
7186           !(getTargetMachine().Options.GuaranteedTailCallOpt &&
7187             (CallConv == CallingConv::Fast));
7188       int FI = MFI.CreateFixedObject(ValSize, CurArgOffset, IsImmutable);
7189       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
7190       SDValue ArgValue =
7191           DAG.getLoad(ValVT, dl, Chain, FIN, MachinePointerInfo());
7192       InVals.push_back(ArgValue);
7193       continue;
7194     }
7195   }
7196 
7197   // On AIX a minimum of 8 words is saved to the parameter save area.
7198   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
7199   // Area that is at least reserved in the caller of this function.
7200   unsigned CallerReservedArea =
7201       std::max(CCInfo.getNextStackOffset(), LinkageSize + MinParameterSaveArea);
7202 
7203   // Set the size that is at least reserved in caller of this function. Tail
7204   // call optimized function's reserved stack space needs to be aligned so
7205   // that taking the difference between two stack areas will result in an
7206   // aligned stack.
7207   CallerReservedArea =
7208       EnsureStackAlignment(Subtarget.getFrameLowering(), CallerReservedArea);
7209   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7210   FuncInfo->setMinReservedArea(CallerReservedArea);
7211 
7212   if (isVarArg) {
7213     FuncInfo->setVarArgsFrameIndex(
7214         MFI.CreateFixedObject(PtrByteSize, CCInfo.getNextStackOffset(), true));
7215     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
7216 
7217     static const MCPhysReg GPR_32[] = {PPC::R3, PPC::R4, PPC::R5, PPC::R6,
7218                                        PPC::R7, PPC::R8, PPC::R9, PPC::R10};
7219 
7220     static const MCPhysReg GPR_64[] = {PPC::X3, PPC::X4, PPC::X5, PPC::X6,
7221                                        PPC::X7, PPC::X8, PPC::X9, PPC::X10};
7222     const unsigned NumGPArgRegs = array_lengthof(IsPPC64 ? GPR_64 : GPR_32);
7223 
7224     // The fixed integer arguments of a variadic function are stored to the
7225     // VarArgsFrameIndex on the stack so that they may be loaded by
7226     // dereferencing the result of va_next.
7227     for (unsigned GPRIndex =
7228              (CCInfo.getNextStackOffset() - LinkageSize) / PtrByteSize;
7229          GPRIndex < NumGPArgRegs; ++GPRIndex) {
7230 
7231       const unsigned VReg =
7232           IsPPC64 ? MF.addLiveIn(GPR_64[GPRIndex], &PPC::G8RCRegClass)
7233                   : MF.addLiveIn(GPR_32[GPRIndex], &PPC::GPRCRegClass);
7234 
7235       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
7236       SDValue Store =
7237           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
7238       MemOps.push_back(Store);
7239       // Increment the address for the next argument to store.
7240       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
7241       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
7242     }
7243   }
7244 
7245   if (!MemOps.empty())
7246     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
7247 
7248   return Chain;
7249 }
7250 
7251 SDValue PPCTargetLowering::LowerCall_AIX(
7252     SDValue Chain, SDValue Callee, CallFlags CFlags,
7253     const SmallVectorImpl<ISD::OutputArg> &Outs,
7254     const SmallVectorImpl<SDValue> &OutVals,
7255     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7256     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7257     const CallBase *CB) const {
7258   // See PPCTargetLowering::LowerFormalArguments_AIX() for a description of the
7259   // AIX ABI stack frame layout.
7260 
7261   assert((CFlags.CallConv == CallingConv::C ||
7262           CFlags.CallConv == CallingConv::Cold ||
7263           CFlags.CallConv == CallingConv::Fast) &&
7264          "Unexpected calling convention!");
7265 
7266   if (CFlags.IsPatchPoint)
7267     report_fatal_error("This call type is unimplemented on AIX.");
7268 
7269   const PPCSubtarget& Subtarget =
7270       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7271   if (Subtarget.hasAltivec())
7272     report_fatal_error("Altivec support is unimplemented on AIX.");
7273 
7274   MachineFunction &MF = DAG.getMachineFunction();
7275   SmallVector<CCValAssign, 16> ArgLocs;
7276   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7277                  *DAG.getContext());
7278 
7279   // Reserve space for the linkage save area (LSA) on the stack.
7280   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7281   //   [SP][CR][LR][2 x reserved][TOC].
7282   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7283   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7284   const bool IsPPC64 = Subtarget.isPPC64();
7285   const EVT PtrVT = getPointerTy(DAG.getDataLayout());
7286   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7287   CCInfo.AllocateStack(LinkageSize, Align(PtrByteSize));
7288   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7289 
7290   // The prolog code of the callee may store up to 8 GPR argument registers to
7291   // the stack, allowing va_start to index over them in memory if the callee
7292   // is variadic.
7293   // Because we cannot tell if this is needed on the caller side, we have to
7294   // conservatively assume that it is needed.  As such, make sure we have at
7295   // least enough stack space for the caller to store the 8 GPRs.
7296   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7297   const unsigned NumBytes = std::max(LinkageSize + MinParameterSaveAreaSize,
7298                                      CCInfo.getNextStackOffset());
7299 
7300   // Adjust the stack pointer for the new arguments...
7301   // These operations are automatically eliminated by the prolog/epilog pass.
7302   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7303   SDValue CallSeqStart = Chain;
7304 
7305   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7306   SmallVector<SDValue, 8> MemOpChains;
7307 
7308   // Set up a copy of the stack pointer for loading and storing any
7309   // arguments that may not fit in the registers available for argument
7310   // passing.
7311   const SDValue StackPtr = IsPPC64 ? DAG.getRegister(PPC::X1, MVT::i64)
7312                                    : DAG.getRegister(PPC::R1, MVT::i32);
7313 
7314   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7315     const unsigned ValNo = ArgLocs[I].getValNo();
7316     SDValue Arg = OutVals[ValNo];
7317     ISD::ArgFlagsTy Flags = Outs[ValNo].Flags;
7318 
7319     if (Flags.isByVal()) {
7320       const unsigned ByValSize = Flags.getByValSize();
7321 
7322       // Nothing to do for zero-sized ByVals on the caller side.
7323       if (!ByValSize) {
7324         ++I;
7325         continue;
7326       }
7327 
7328       auto GetLoad = [&](EVT VT, unsigned LoadOffset) {
7329         return DAG.getExtLoad(
7330             ISD::ZEXTLOAD, dl, PtrVT, Chain,
7331             (LoadOffset != 0)
7332                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7333                 : Arg,
7334             MachinePointerInfo(), VT);
7335       };
7336 
7337       unsigned LoadOffset = 0;
7338 
7339       // Initialize registers, which are fully occupied by the by-val argument.
7340       while (LoadOffset + PtrByteSize <= ByValSize && ArgLocs[I].isRegLoc()) {
7341         SDValue Load = GetLoad(PtrVT, LoadOffset);
7342         MemOpChains.push_back(Load.getValue(1));
7343         LoadOffset += PtrByteSize;
7344         const CCValAssign &ByValVA = ArgLocs[I++];
7345         assert(ByValVA.getValNo() == ValNo &&
7346                "Unexpected location for pass-by-value argument.");
7347         RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), Load));
7348       }
7349 
7350       if (LoadOffset == ByValSize)
7351         continue;
7352 
7353       // There must be one more loc to handle the remainder.
7354       assert(ArgLocs[I].getValNo() == ValNo &&
7355              "Expected additional location for by-value argument.");
7356 
7357       if (ArgLocs[I].isMemLoc()) {
7358         assert(LoadOffset < ByValSize && "Unexpected memloc for by-val arg.");
7359         const CCValAssign &ByValVA = ArgLocs[I++];
7360         ISD::ArgFlagsTy MemcpyFlags = Flags;
7361         // Only memcpy the bytes that don't pass in register.
7362         MemcpyFlags.setByValSize(ByValSize - LoadOffset);
7363         Chain = CallSeqStart = createMemcpyOutsideCallSeq(
7364             (LoadOffset != 0)
7365                 ? DAG.getObjectPtrOffset(dl, Arg, TypeSize::Fixed(LoadOffset))
7366                 : Arg,
7367             DAG.getObjectPtrOffset(dl, StackPtr,
7368                                    TypeSize::Fixed(ByValVA.getLocMemOffset())),
7369             CallSeqStart, MemcpyFlags, DAG, dl);
7370         continue;
7371       }
7372 
7373       // Initialize the final register residue.
7374       // Any residue that occupies the final by-val arg register must be
7375       // left-justified on AIX. Loads must be a power-of-2 size and cannot be
7376       // larger than the ByValSize. For example: a 7 byte by-val arg requires 4,
7377       // 2 and 1 byte loads.
7378       const unsigned ResidueBytes = ByValSize % PtrByteSize;
7379       assert(ResidueBytes != 0 && LoadOffset + PtrByteSize > ByValSize &&
7380              "Unexpected register residue for by-value argument.");
7381       SDValue ResidueVal;
7382       for (unsigned Bytes = 0; Bytes != ResidueBytes;) {
7383         const unsigned N = PowerOf2Floor(ResidueBytes - Bytes);
7384         const MVT VT =
7385             N == 1 ? MVT::i8
7386                    : ((N == 2) ? MVT::i16 : (N == 4 ? MVT::i32 : MVT::i64));
7387         SDValue Load = GetLoad(VT, LoadOffset);
7388         MemOpChains.push_back(Load.getValue(1));
7389         LoadOffset += N;
7390         Bytes += N;
7391 
7392         // By-val arguments are passed left-justfied in register.
7393         // Every load here needs to be shifted, otherwise a full register load
7394         // should have been used.
7395         assert(PtrVT.getSimpleVT().getSizeInBits() > (Bytes * 8) &&
7396                "Unexpected load emitted during handling of pass-by-value "
7397                "argument.");
7398         unsigned NumSHLBits = PtrVT.getSimpleVT().getSizeInBits() - (Bytes * 8);
7399         EVT ShiftAmountTy =
7400             getShiftAmountTy(Load->getValueType(0), DAG.getDataLayout());
7401         SDValue SHLAmt = DAG.getConstant(NumSHLBits, dl, ShiftAmountTy);
7402         SDValue ShiftedLoad =
7403             DAG.getNode(ISD::SHL, dl, Load.getValueType(), Load, SHLAmt);
7404         ResidueVal = ResidueVal ? DAG.getNode(ISD::OR, dl, PtrVT, ResidueVal,
7405                                               ShiftedLoad)
7406                                 : ShiftedLoad;
7407       }
7408 
7409       const CCValAssign &ByValVA = ArgLocs[I++];
7410       RegsToPass.push_back(std::make_pair(ByValVA.getLocReg(), ResidueVal));
7411       continue;
7412     }
7413 
7414     CCValAssign &VA = ArgLocs[I++];
7415     const MVT LocVT = VA.getLocVT();
7416     const MVT ValVT = VA.getValVT();
7417 
7418     switch (VA.getLocInfo()) {
7419     default:
7420       report_fatal_error("Unexpected argument extension type.");
7421     case CCValAssign::Full:
7422       break;
7423     case CCValAssign::ZExt:
7424       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7425       break;
7426     case CCValAssign::SExt:
7427       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7428       break;
7429     }
7430 
7431     if (VA.isRegLoc() && !VA.needsCustom()) {
7432       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7433       continue;
7434     }
7435 
7436     if (VA.isMemLoc()) {
7437       SDValue PtrOff =
7438           DAG.getConstant(VA.getLocMemOffset(), dl, StackPtr.getValueType());
7439       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7440       MemOpChains.push_back(
7441           DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
7442 
7443       continue;
7444     }
7445 
7446     // Custom handling is used for GPR initializations for vararg float
7447     // arguments.
7448     assert(VA.isRegLoc() && VA.needsCustom() && CFlags.IsVarArg &&
7449            ValVT.isFloatingPoint() && LocVT.isInteger() &&
7450            "Unexpected register handling for calling convention.");
7451 
7452     SDValue ArgAsInt =
7453         DAG.getBitcast(MVT::getIntegerVT(ValVT.getSizeInBits()), Arg);
7454 
7455     if (Arg.getValueType().getStoreSize() == LocVT.getStoreSize())
7456       // f32 in 32-bit GPR
7457       // f64 in 64-bit GPR
7458       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7459     else if (Arg.getValueType().getSizeInBits() < LocVT.getSizeInBits())
7460       // f32 in 64-bit GPR.
7461       RegsToPass.push_back(std::make_pair(
7462           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, LocVT)));
7463     else {
7464       // f64 in two 32-bit GPRs
7465       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7466       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7467              "Unexpected custom register for argument!");
7468       CCValAssign &GPR1 = VA;
7469       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7470                                      DAG.getConstant(32, dl, MVT::i8));
7471       RegsToPass.push_back(std::make_pair(
7472           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7473 
7474       if (I != E) {
7475         // If only 1 GPR was available, there will only be one custom GPR and
7476         // the argument will also pass in memory.
7477         CCValAssign &PeekArg = ArgLocs[I];
7478         if (PeekArg.isRegLoc() && PeekArg.getValNo() == PeekArg.getValNo()) {
7479           assert(PeekArg.needsCustom() && "A second custom GPR is expected.");
7480           CCValAssign &GPR2 = ArgLocs[I++];
7481           RegsToPass.push_back(std::make_pair(
7482               GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7483         }
7484       }
7485     }
7486   }
7487 
7488   if (!MemOpChains.empty())
7489     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
7490 
7491   // For indirect calls, we need to save the TOC base to the stack for
7492   // restoration after the call.
7493   if (CFlags.IsIndirect) {
7494     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7495     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7496     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7497     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7498     const unsigned TOCSaveOffset =
7499         Subtarget.getFrameLowering()->getTOCSaveOffset();
7500 
7501     setUsesTOCBasePtr(DAG);
7502     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7503     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7504     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7505     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7506     Chain = DAG.getStore(
7507         Val.getValue(1), dl, Val, AddPtr,
7508         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7509   }
7510 
7511   // Build a sequence of copy-to-reg nodes chained together with token chain
7512   // and flag operands which copy the outgoing args into the appropriate regs.
7513   SDValue InFlag;
7514   for (auto Reg : RegsToPass) {
7515     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7516     InFlag = Chain.getValue(1);
7517   }
7518 
7519   const int SPDiff = 0;
7520   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7521                     Callee, SPDiff, NumBytes, Ins, InVals, CB);
7522 }
7523 
7524 bool
7525 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7526                                   MachineFunction &MF, bool isVarArg,
7527                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7528                                   LLVMContext &Context) const {
7529   SmallVector<CCValAssign, 16> RVLocs;
7530   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7531   return CCInfo.CheckReturn(
7532       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7533                 ? RetCC_PPC_Cold
7534                 : RetCC_PPC);
7535 }
7536 
7537 SDValue
7538 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7539                                bool isVarArg,
7540                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7541                                const SmallVectorImpl<SDValue> &OutVals,
7542                                const SDLoc &dl, SelectionDAG &DAG) const {
7543   SmallVector<CCValAssign, 16> RVLocs;
7544   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7545                  *DAG.getContext());
7546   CCInfo.AnalyzeReturn(Outs,
7547                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7548                            ? RetCC_PPC_Cold
7549                            : RetCC_PPC);
7550 
7551   SDValue Flag;
7552   SmallVector<SDValue, 4> RetOps(1, Chain);
7553 
7554   // Copy the result values into the output registers.
7555   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7556     CCValAssign &VA = RVLocs[i];
7557     assert(VA.isRegLoc() && "Can only return in registers!");
7558 
7559     SDValue Arg = OutVals[RealResIdx];
7560 
7561     switch (VA.getLocInfo()) {
7562     default: llvm_unreachable("Unknown loc info!");
7563     case CCValAssign::Full: break;
7564     case CCValAssign::AExt:
7565       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7566       break;
7567     case CCValAssign::ZExt:
7568       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7569       break;
7570     case CCValAssign::SExt:
7571       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7572       break;
7573     }
7574     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7575       bool isLittleEndian = Subtarget.isLittleEndian();
7576       // Legalize ret f64 -> ret 2 x i32.
7577       SDValue SVal =
7578           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7579                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7580       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7581       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7582       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7583                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7584       Flag = Chain.getValue(1);
7585       VA = RVLocs[++i]; // skip ahead to next loc
7586       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7587     } else
7588       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7589     Flag = Chain.getValue(1);
7590     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7591   }
7592 
7593   RetOps[0] = Chain;  // Update chain.
7594 
7595   // Add the flag if we have it.
7596   if (Flag.getNode())
7597     RetOps.push_back(Flag);
7598 
7599   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7600 }
7601 
7602 SDValue
7603 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7604                                                 SelectionDAG &DAG) const {
7605   SDLoc dl(Op);
7606 
7607   // Get the correct type for integers.
7608   EVT IntVT = Op.getValueType();
7609 
7610   // Get the inputs.
7611   SDValue Chain = Op.getOperand(0);
7612   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7613   // Build a DYNAREAOFFSET node.
7614   SDValue Ops[2] = {Chain, FPSIdx};
7615   SDVTList VTs = DAG.getVTList(IntVT);
7616   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7617 }
7618 
7619 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7620                                              SelectionDAG &DAG) const {
7621   // When we pop the dynamic allocation we need to restore the SP link.
7622   SDLoc dl(Op);
7623 
7624   // Get the correct type for pointers.
7625   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7626 
7627   // Construct the stack pointer operand.
7628   bool isPPC64 = Subtarget.isPPC64();
7629   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7630   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7631 
7632   // Get the operands for the STACKRESTORE.
7633   SDValue Chain = Op.getOperand(0);
7634   SDValue SaveSP = Op.getOperand(1);
7635 
7636   // Load the old link SP.
7637   SDValue LoadLinkSP =
7638       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7639 
7640   // Restore the stack pointer.
7641   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7642 
7643   // Store the old link SP.
7644   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7645 }
7646 
7647 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7648   MachineFunction &MF = DAG.getMachineFunction();
7649   bool isPPC64 = Subtarget.isPPC64();
7650   EVT PtrVT = getPointerTy(MF.getDataLayout());
7651 
7652   // Get current frame pointer save index.  The users of this index will be
7653   // primarily DYNALLOC instructions.
7654   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7655   int RASI = FI->getReturnAddrSaveIndex();
7656 
7657   // If the frame pointer save index hasn't been defined yet.
7658   if (!RASI) {
7659     // Find out what the fix offset of the frame pointer save area.
7660     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7661     // Allocate the frame index for frame pointer save area.
7662     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7663     // Save the result.
7664     FI->setReturnAddrSaveIndex(RASI);
7665   }
7666   return DAG.getFrameIndex(RASI, PtrVT);
7667 }
7668 
7669 SDValue
7670 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7671   MachineFunction &MF = DAG.getMachineFunction();
7672   bool isPPC64 = Subtarget.isPPC64();
7673   EVT PtrVT = getPointerTy(MF.getDataLayout());
7674 
7675   // Get current frame pointer save index.  The users of this index will be
7676   // primarily DYNALLOC instructions.
7677   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7678   int FPSI = FI->getFramePointerSaveIndex();
7679 
7680   // If the frame pointer save index hasn't been defined yet.
7681   if (!FPSI) {
7682     // Find out what the fix offset of the frame pointer save area.
7683     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7684     // Allocate the frame index for frame pointer save area.
7685     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7686     // Save the result.
7687     FI->setFramePointerSaveIndex(FPSI);
7688   }
7689   return DAG.getFrameIndex(FPSI, PtrVT);
7690 }
7691 
7692 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7693                                                    SelectionDAG &DAG) const {
7694   MachineFunction &MF = DAG.getMachineFunction();
7695   // Get the inputs.
7696   SDValue Chain = Op.getOperand(0);
7697   SDValue Size  = Op.getOperand(1);
7698   SDLoc dl(Op);
7699 
7700   // Get the correct type for pointers.
7701   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7702   // Negate the size.
7703   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7704                                 DAG.getConstant(0, dl, PtrVT), Size);
7705   // Construct a node for the frame pointer save index.
7706   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7707   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7708   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7709   if (hasInlineStackProbe(MF))
7710     return DAG.getNode(PPCISD::PROBED_ALLOCA, dl, VTs, Ops);
7711   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7712 }
7713 
7714 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7715                                                      SelectionDAG &DAG) const {
7716   MachineFunction &MF = DAG.getMachineFunction();
7717 
7718   bool isPPC64 = Subtarget.isPPC64();
7719   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7720 
7721   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7722   return DAG.getFrameIndex(FI, PtrVT);
7723 }
7724 
7725 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7726                                                SelectionDAG &DAG) const {
7727   SDLoc DL(Op);
7728   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7729                      DAG.getVTList(MVT::i32, MVT::Other),
7730                      Op.getOperand(0), Op.getOperand(1));
7731 }
7732 
7733 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7734                                                 SelectionDAG &DAG) const {
7735   SDLoc DL(Op);
7736   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7737                      Op.getOperand(0), Op.getOperand(1));
7738 }
7739 
7740 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7741 
7742   assert(Op.getValueType() == MVT::i1 &&
7743          "Custom lowering only for i1 loads");
7744 
7745   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7746 
7747   SDLoc dl(Op);
7748   LoadSDNode *LD = cast<LoadSDNode>(Op);
7749 
7750   SDValue Chain = LD->getChain();
7751   SDValue BasePtr = LD->getBasePtr();
7752   MachineMemOperand *MMO = LD->getMemOperand();
7753 
7754   SDValue NewLD =
7755       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7756                      BasePtr, MVT::i8, MMO);
7757   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7758 
7759   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7760   return DAG.getMergeValues(Ops, dl);
7761 }
7762 
7763 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7764   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7765          "Custom lowering only for i1 stores");
7766 
7767   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7768 
7769   SDLoc dl(Op);
7770   StoreSDNode *ST = cast<StoreSDNode>(Op);
7771 
7772   SDValue Chain = ST->getChain();
7773   SDValue BasePtr = ST->getBasePtr();
7774   SDValue Value = ST->getValue();
7775   MachineMemOperand *MMO = ST->getMemOperand();
7776 
7777   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7778                       Value);
7779   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7780 }
7781 
7782 // FIXME: Remove this once the ANDI glue bug is fixed:
7783 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7784   assert(Op.getValueType() == MVT::i1 &&
7785          "Custom lowering only for i1 results");
7786 
7787   SDLoc DL(Op);
7788   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7789 }
7790 
7791 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7792                                                SelectionDAG &DAG) const {
7793 
7794   // Implements a vector truncate that fits in a vector register as a shuffle.
7795   // We want to legalize vector truncates down to where the source fits in
7796   // a vector register (and target is therefore smaller than vector register
7797   // size).  At that point legalization will try to custom lower the sub-legal
7798   // result and get here - where we can contain the truncate as a single target
7799   // operation.
7800 
7801   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7802   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7803   //
7804   // We will implement it for big-endian ordering as this (where x denotes
7805   // undefined):
7806   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7807   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7808   //
7809   // The same operation in little-endian ordering will be:
7810   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7811   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7812 
7813   assert(Op.getValueType().isVector() && "Vector type expected.");
7814 
7815   SDLoc DL(Op);
7816   SDValue N1 = Op.getOperand(0);
7817   unsigned SrcSize = N1.getValueType().getSizeInBits();
7818   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7819   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7820 
7821   EVT TrgVT = Op.getValueType();
7822   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7823   EVT EltVT = TrgVT.getVectorElementType();
7824   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7825   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7826 
7827   // First list the elements we want to keep.
7828   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7829   SmallVector<int, 16> ShuffV;
7830   if (Subtarget.isLittleEndian())
7831     for (unsigned i = 0; i < TrgNumElts; ++i)
7832       ShuffV.push_back(i * SizeMult);
7833   else
7834     for (unsigned i = 1; i <= TrgNumElts; ++i)
7835       ShuffV.push_back(i * SizeMult - 1);
7836 
7837   // Populate the remaining elements with undefs.
7838   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7839     // ShuffV.push_back(i + WideNumElts);
7840     ShuffV.push_back(WideNumElts + 1);
7841 
7842   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7843   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7844 }
7845 
7846 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7847 /// possible.
7848 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7849   // Not FP, or using SPE? Not a fsel.
7850   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7851       !Op.getOperand(2).getValueType().isFloatingPoint() || Subtarget.hasSPE())
7852     return Op;
7853 
7854   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7855 
7856   EVT ResVT = Op.getValueType();
7857   EVT CmpVT = Op.getOperand(0).getValueType();
7858   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7859   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7860   SDLoc dl(Op);
7861   SDNodeFlags Flags = Op.getNode()->getFlags();
7862 
7863   // We have xsmaxcdp/xsmincdp which are OK to emit even in the
7864   // presence of infinities.
7865   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7866     switch (CC) {
7867     default:
7868       break;
7869     case ISD::SETOGT:
7870     case ISD::SETGT:
7871       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7872     case ISD::SETOLT:
7873     case ISD::SETLT:
7874       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7875     }
7876   }
7877 
7878   // We might be able to do better than this under some circumstances, but in
7879   // general, fsel-based lowering of select is a finite-math-only optimization.
7880   // For more information, see section F.3 of the 2.06 ISA specification.
7881   // With ISA 3.0
7882   if ((!DAG.getTarget().Options.NoInfsFPMath && !Flags.hasNoInfs()) ||
7883       (!DAG.getTarget().Options.NoNaNsFPMath && !Flags.hasNoNaNs()))
7884     return Op;
7885 
7886   // If the RHS of the comparison is a 0.0, we don't need to do the
7887   // subtraction at all.
7888   SDValue Sel1;
7889   if (isFloatingPointZero(RHS))
7890     switch (CC) {
7891     default: break;       // SETUO etc aren't handled by fsel.
7892     case ISD::SETNE:
7893       std::swap(TV, FV);
7894       LLVM_FALLTHROUGH;
7895     case ISD::SETEQ:
7896       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7897         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7898       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7899       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7900         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7901       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7902                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7903     case ISD::SETULT:
7904     case ISD::SETLT:
7905       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7906       LLVM_FALLTHROUGH;
7907     case ISD::SETOGE:
7908     case ISD::SETGE:
7909       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7910         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7911       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7912     case ISD::SETUGT:
7913     case ISD::SETGT:
7914       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7915       LLVM_FALLTHROUGH;
7916     case ISD::SETOLE:
7917     case ISD::SETLE:
7918       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7919         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7920       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7921                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7922     }
7923 
7924   SDValue Cmp;
7925   switch (CC) {
7926   default: break;       // SETUO etc aren't handled by fsel.
7927   case ISD::SETNE:
7928     std::swap(TV, FV);
7929     LLVM_FALLTHROUGH;
7930   case ISD::SETEQ:
7931     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7932     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7933       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7934     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7935     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7936       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7937     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7938                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7939   case ISD::SETULT:
7940   case ISD::SETLT:
7941     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7942     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7943       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7944     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7945   case ISD::SETOGE:
7946   case ISD::SETGE:
7947     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7948     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7949       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7950     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7951   case ISD::SETUGT:
7952   case ISD::SETGT:
7953     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7954     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7955       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7956     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7957   case ISD::SETOLE:
7958   case ISD::SETLE:
7959     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7960     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7961       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7962     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7963   }
7964   return Op;
7965 }
7966 
7967 static unsigned getPPCStrictOpcode(unsigned Opc) {
7968   switch (Opc) {
7969   default:
7970     llvm_unreachable("No strict version of this opcode!");
7971   case PPCISD::FCTIDZ:
7972     return PPCISD::STRICT_FCTIDZ;
7973   case PPCISD::FCTIWZ:
7974     return PPCISD::STRICT_FCTIWZ;
7975   case PPCISD::FCTIDUZ:
7976     return PPCISD::STRICT_FCTIDUZ;
7977   case PPCISD::FCTIWUZ:
7978     return PPCISD::STRICT_FCTIWUZ;
7979   }
7980 }
7981 
7982 static SDValue convertFPToInt(SDValue Op, SelectionDAG &DAG,
7983                               const PPCSubtarget &Subtarget) {
7984   SDLoc dl(Op);
7985   bool IsStrict = Op->isStrictFPOpcode();
7986   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
7987                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
7988   // For strict nodes, source is the second operand.
7989   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
7990   SDValue Chain = IsStrict ? Op.getOperand(0) : SDValue();
7991   assert(Src.getValueType().isFloatingPoint());
7992   if (Src.getValueType() == MVT::f32) {
7993     if (IsStrict) {
7994       Src = DAG.getNode(ISD::STRICT_FP_EXTEND, dl, {MVT::f64, MVT::Other},
7995                         {Chain, Src});
7996       Chain = Src.getValue(1);
7997     } else
7998       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7999   }
8000   SDValue Conv;
8001   unsigned Opc = ISD::DELETED_NODE;
8002   switch (Op.getSimpleValueType().SimpleTy) {
8003   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
8004   case MVT::i32:
8005     Opc = IsSigned ? PPCISD::FCTIWZ
8006                    : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ);
8007     break;
8008   case MVT::i64:
8009     assert((IsSigned || Subtarget.hasFPCVT()) &&
8010            "i64 FP_TO_UINT is supported only with FPCVT");
8011     Opc = IsSigned ? PPCISD::FCTIDZ : PPCISD::FCTIDUZ;
8012   }
8013   if (IsStrict) {
8014     Opc = getPPCStrictOpcode(Opc);
8015     Conv = DAG.getNode(Opc, dl, {MVT::f64, MVT::Other}, {Chain, Src});
8016   } else {
8017     Conv = DAG.getNode(Opc, dl, MVT::f64, Src);
8018   }
8019   return Conv;
8020 }
8021 
8022 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
8023                                                SelectionDAG &DAG,
8024                                                const SDLoc &dl) const {
8025   SDValue Tmp = convertFPToInt(Op, DAG, Subtarget);
8026   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8027                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8028   bool IsStrict = Op->isStrictFPOpcode();
8029 
8030   // Convert the FP value to an int value through memory.
8031   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
8032                   (IsSigned || Subtarget.hasFPCVT());
8033   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
8034   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
8035   MachinePointerInfo MPI =
8036       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
8037 
8038   // Emit a store to the stack slot.
8039   SDValue Chain = IsStrict ? Tmp.getValue(1) : DAG.getEntryNode();
8040   Align Alignment(DAG.getEVTAlign(Tmp.getValueType()));
8041   if (i32Stack) {
8042     MachineFunction &MF = DAG.getMachineFunction();
8043     Alignment = Align(4);
8044     MachineMemOperand *MMO =
8045         MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Alignment);
8046     SDValue Ops[] = { Chain, Tmp, FIPtr };
8047     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8048               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
8049   } else
8050     Chain = DAG.getStore(Chain, dl, Tmp, FIPtr, MPI, Alignment);
8051 
8052   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
8053   // add in a bias on big endian.
8054   if (Op.getValueType() == MVT::i32 && !i32Stack) {
8055     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
8056                         DAG.getConstant(4, dl, FIPtr.getValueType()));
8057     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
8058   }
8059 
8060   RLI.Chain = Chain;
8061   RLI.Ptr = FIPtr;
8062   RLI.MPI = MPI;
8063   RLI.Alignment = Alignment;
8064 }
8065 
8066 /// Custom lowers floating point to integer conversions to use
8067 /// the direct move instructions available in ISA 2.07 to avoid the
8068 /// need for load/store combinations.
8069 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
8070                                                     SelectionDAG &DAG,
8071                                                     const SDLoc &dl) const {
8072   SDValue Conv = convertFPToInt(Op, DAG, Subtarget);
8073   SDValue Mov = DAG.getNode(PPCISD::MFVSR, dl, Op.getValueType(), Conv);
8074   if (Op->isStrictFPOpcode())
8075     return DAG.getMergeValues({Mov, Conv.getValue(1)}, dl);
8076   else
8077     return Mov;
8078 }
8079 
8080 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
8081                                           const SDLoc &dl) const {
8082   bool IsStrict = Op->isStrictFPOpcode();
8083   bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT ||
8084                   Op.getOpcode() == ISD::STRICT_FP_TO_SINT;
8085   SDValue Src = Op.getOperand(IsStrict ? 1 : 0);
8086   // FP to INT conversions are legal for f128.
8087   if (Src.getValueType() == MVT::f128)
8088     return Op;
8089 
8090   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
8091   // PPC (the libcall is not available).
8092   if (Src.getValueType() == MVT::ppcf128 && !IsStrict) {
8093     if (Op.getValueType() == MVT::i32) {
8094       if (IsSigned) {
8095         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8096                                  DAG.getIntPtrConstant(0, dl));
8097         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::f64, Src,
8098                                  DAG.getIntPtrConstant(1, dl));
8099 
8100         // Add the two halves of the long double in round-to-zero mode.
8101         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8102 
8103         // Now use a smaller FP_TO_SINT.
8104         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
8105       } else {
8106         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
8107         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
8108         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
8109         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
8110         // FIXME: generated code sucks.
8111         // TODO: Are there fast-math-flags to propagate to this FSUB?
8112         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128, Src, Tmp);
8113         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
8114         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
8115                            DAG.getConstant(0x80000000, dl, MVT::i32));
8116         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Src);
8117         return DAG.getSelectCC(dl, Src, Tmp, True, False, ISD::SETGE);
8118       }
8119     }
8120 
8121     return SDValue();
8122   }
8123 
8124   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
8125     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
8126 
8127   ReuseLoadInfo RLI;
8128   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8129 
8130   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8131                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8132 }
8133 
8134 // We're trying to insert a regular store, S, and then a load, L. If the
8135 // incoming value, O, is a load, we might just be able to have our load use the
8136 // address used by O. However, we don't know if anything else will store to
8137 // that address before we can load from it. To prevent this situation, we need
8138 // to insert our load, L, into the chain as a peer of O. To do this, we give L
8139 // the same chain operand as O, we create a token factor from the chain results
8140 // of O and L, and we replace all uses of O's chain result with that token
8141 // factor (see spliceIntoChain below for this last part).
8142 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
8143                                             ReuseLoadInfo &RLI,
8144                                             SelectionDAG &DAG,
8145                                             ISD::LoadExtType ET) const {
8146   SDLoc dl(Op);
8147   bool ValidFPToUint = Op.getOpcode() == ISD::FP_TO_UINT &&
8148                        (Subtarget.hasFPCVT() || Op.getValueType() == MVT::i32);
8149   if (ET == ISD::NON_EXTLOAD &&
8150       (ValidFPToUint || Op.getOpcode() == ISD::FP_TO_SINT) &&
8151       isOperationLegalOrCustom(Op.getOpcode(),
8152                                Op.getOperand(0).getValueType())) {
8153 
8154     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
8155     return true;
8156   }
8157 
8158   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
8159   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
8160       LD->isNonTemporal())
8161     return false;
8162   if (LD->getMemoryVT() != MemVT)
8163     return false;
8164 
8165   RLI.Ptr = LD->getBasePtr();
8166   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
8167     assert(LD->getAddressingMode() == ISD::PRE_INC &&
8168            "Non-pre-inc AM on PPC?");
8169     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
8170                           LD->getOffset());
8171   }
8172 
8173   RLI.Chain = LD->getChain();
8174   RLI.MPI = LD->getPointerInfo();
8175   RLI.IsDereferenceable = LD->isDereferenceable();
8176   RLI.IsInvariant = LD->isInvariant();
8177   RLI.Alignment = LD->getAlign();
8178   RLI.AAInfo = LD->getAAInfo();
8179   RLI.Ranges = LD->getRanges();
8180 
8181   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
8182   return true;
8183 }
8184 
8185 // Given the head of the old chain, ResChain, insert a token factor containing
8186 // it and NewResChain, and make users of ResChain now be users of that token
8187 // factor.
8188 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
8189 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
8190                                         SDValue NewResChain,
8191                                         SelectionDAG &DAG) const {
8192   if (!ResChain)
8193     return;
8194 
8195   SDLoc dl(NewResChain);
8196 
8197   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8198                            NewResChain, DAG.getUNDEF(MVT::Other));
8199   assert(TF.getNode() != NewResChain.getNode() &&
8200          "A new TF really is required here");
8201 
8202   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
8203   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
8204 }
8205 
8206 /// Analyze profitability of direct move
8207 /// prefer float load to int load plus direct move
8208 /// when there is no integer use of int load
8209 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
8210   SDNode *Origin = Op.getOperand(0).getNode();
8211   if (Origin->getOpcode() != ISD::LOAD)
8212     return true;
8213 
8214   // If there is no LXSIBZX/LXSIHZX, like Power8,
8215   // prefer direct move if the memory size is 1 or 2 bytes.
8216   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
8217   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
8218     return true;
8219 
8220   for (SDNode::use_iterator UI = Origin->use_begin(),
8221                             UE = Origin->use_end();
8222        UI != UE; ++UI) {
8223 
8224     // Only look at the users of the loaded value.
8225     if (UI.getUse().get().getResNo() != 0)
8226       continue;
8227 
8228     if (UI->getOpcode() != ISD::SINT_TO_FP &&
8229         UI->getOpcode() != ISD::UINT_TO_FP)
8230       return true;
8231   }
8232 
8233   return false;
8234 }
8235 
8236 static SDValue convertIntToFP(SDValue Op, SDValue Src, SelectionDAG &DAG,
8237                               const PPCSubtarget &Subtarget) {
8238   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8239   SDLoc dl(Op);
8240   // If we have FCFIDS, then use it when converting to single-precision.
8241   // Otherwise, convert to double-precision and then round.
8242   bool IsSingle = Op.getValueType() == MVT::f32 && Subtarget.hasFPCVT();
8243   unsigned ConvOpc = IsSingle ? (IsSigned ? PPCISD::FCFIDS : PPCISD::FCFIDUS)
8244                               : (IsSigned ? PPCISD::FCFID : PPCISD::FCFIDU);
8245   EVT ConvTy = IsSingle ? MVT::f32 : MVT::f64;
8246   return DAG.getNode(ConvOpc, dl, ConvTy, Src);
8247 }
8248 
8249 /// Custom lowers integer to floating point conversions to use
8250 /// the direct move instructions available in ISA 2.07 to avoid the
8251 /// need for load/store combinations.
8252 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
8253                                                     SelectionDAG &DAG,
8254                                                     const SDLoc &dl) const {
8255   assert((Op.getValueType() == MVT::f32 ||
8256           Op.getValueType() == MVT::f64) &&
8257          "Invalid floating point type as target of conversion");
8258   assert(Subtarget.hasFPCVT() &&
8259          "Int to FP conversions with direct moves require FPCVT");
8260   SDValue Src = Op.getOperand(0);
8261   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
8262   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
8263   unsigned MovOpc = (WordInt && !Signed) ? PPCISD::MTVSRZ : PPCISD::MTVSRA;
8264   SDValue Mov = DAG.getNode(MovOpc, dl, MVT::f64, Src);
8265   return convertIntToFP(Op, Mov, DAG, Subtarget);
8266 }
8267 
8268 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
8269 
8270   EVT VecVT = Vec.getValueType();
8271   assert(VecVT.isVector() && "Expected a vector type.");
8272   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
8273 
8274   EVT EltVT = VecVT.getVectorElementType();
8275   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
8276   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
8277 
8278   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
8279   SmallVector<SDValue, 16> Ops(NumConcat);
8280   Ops[0] = Vec;
8281   SDValue UndefVec = DAG.getUNDEF(VecVT);
8282   for (unsigned i = 1; i < NumConcat; ++i)
8283     Ops[i] = UndefVec;
8284 
8285   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
8286 }
8287 
8288 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
8289                                                 const SDLoc &dl) const {
8290 
8291   unsigned Opc = Op.getOpcode();
8292   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
8293          "Unexpected conversion type");
8294   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
8295          "Supports conversions to v2f64/v4f32 only.");
8296 
8297   bool SignedConv = Opc == ISD::SINT_TO_FP;
8298   bool FourEltRes = Op.getValueType() == MVT::v4f32;
8299 
8300   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
8301   EVT WideVT = Wide.getValueType();
8302   unsigned WideNumElts = WideVT.getVectorNumElements();
8303   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
8304 
8305   SmallVector<int, 16> ShuffV;
8306   for (unsigned i = 0; i < WideNumElts; ++i)
8307     ShuffV.push_back(i + WideNumElts);
8308 
8309   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
8310   int SaveElts = FourEltRes ? 4 : 2;
8311   if (Subtarget.isLittleEndian())
8312     for (int i = 0; i < SaveElts; i++)
8313       ShuffV[i * Stride] = i;
8314   else
8315     for (int i = 1; i <= SaveElts; i++)
8316       ShuffV[i * Stride - 1] = i - 1;
8317 
8318   SDValue ShuffleSrc2 =
8319       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
8320   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
8321 
8322   SDValue Extend;
8323   if (SignedConv) {
8324     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
8325     EVT ExtVT = Op.getOperand(0).getValueType();
8326     if (Subtarget.hasP9Altivec())
8327       ExtVT = EVT::getVectorVT(*DAG.getContext(), WideVT.getVectorElementType(),
8328                                IntermediateVT.getVectorNumElements());
8329 
8330     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
8331                          DAG.getValueType(ExtVT));
8332   } else
8333     Extend = DAG.getNode(ISD::BITCAST, dl, IntermediateVT, Arrange);
8334 
8335   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
8336 }
8337 
8338 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
8339                                           SelectionDAG &DAG) const {
8340   SDLoc dl(Op);
8341   SDValue Src = Op.getOperand(0);
8342   bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
8343 
8344   EVT InVT = Src.getValueType();
8345   EVT OutVT = Op.getValueType();
8346   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
8347       isOperationCustom(Op.getOpcode(), InVT))
8348     return LowerINT_TO_FPVector(Op, DAG, dl);
8349 
8350   // Conversions to f128 are legal.
8351   if (Op.getValueType() == MVT::f128)
8352     return Op;
8353 
8354   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8355   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8356     return SDValue();
8357 
8358   if (Src.getValueType() == MVT::i1)
8359     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Src,
8360                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8361                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8362 
8363   // If we have direct moves, we can do all the conversion, skip the store/load
8364   // however, without FPCVT we can't do most conversions.
8365   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8366       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8367     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8368 
8369   assert((IsSigned || Subtarget.hasFPCVT()) &&
8370          "UINT_TO_FP is supported only with FPCVT");
8371 
8372   if (Src.getValueType() == MVT::i64) {
8373     SDValue SINT = Src;
8374     // When converting to single-precision, we actually need to convert
8375     // to double-precision first and then round to single-precision.
8376     // To avoid double-rounding effects during that operation, we have
8377     // to prepare the input operand.  Bits that might be truncated when
8378     // converting to double-precision are replaced by a bit that won't
8379     // be lost at this stage, but is below the single-precision rounding
8380     // position.
8381     //
8382     // However, if -enable-unsafe-fp-math is in effect, accept double
8383     // rounding to avoid the extra overhead.
8384     if (Op.getValueType() == MVT::f32 &&
8385         !Subtarget.hasFPCVT() &&
8386         !DAG.getTarget().Options.UnsafeFPMath) {
8387 
8388       // Twiddle input to make sure the low 11 bits are zero.  (If this
8389       // is the case, we are guaranteed the value will fit into the 53 bit
8390       // mantissa of an IEEE double-precision value without rounding.)
8391       // If any of those low 11 bits were not zero originally, make sure
8392       // bit 12 (value 2048) is set instead, so that the final rounding
8393       // to single-precision gets the correct result.
8394       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8395                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8396       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8397                           Round, DAG.getConstant(2047, dl, MVT::i64));
8398       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8399       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8400                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8401 
8402       // However, we cannot use that value unconditionally: if the magnitude
8403       // of the input value is small, the bit-twiddling we did above might
8404       // end up visibly changing the output.  Fortunately, in that case, we
8405       // don't need to twiddle bits since the original input will convert
8406       // exactly to double-precision floating-point already.  Therefore,
8407       // construct a conditional to use the original value if the top 11
8408       // bits are all sign-bit copies, and use the rounded value computed
8409       // above otherwise.
8410       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8411                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8412       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8413                          Cond, DAG.getConstant(1, dl, MVT::i64));
8414       Cond = DAG.getSetCC(
8415           dl,
8416           getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
8417           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8418 
8419       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8420     }
8421 
8422     ReuseLoadInfo RLI;
8423     SDValue Bits;
8424 
8425     MachineFunction &MF = DAG.getMachineFunction();
8426     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8427       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8428                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8429       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8430     } else if (Subtarget.hasLFIWAX() &&
8431                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8432       MachineMemOperand *MMO =
8433         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8434                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8435       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8436       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8437                                      DAG.getVTList(MVT::f64, MVT::Other),
8438                                      Ops, MVT::i32, MMO);
8439       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8440     } else if (Subtarget.hasFPCVT() &&
8441                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8442       MachineMemOperand *MMO =
8443         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8444                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8445       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8446       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8447                                      DAG.getVTList(MVT::f64, MVT::Other),
8448                                      Ops, MVT::i32, MMO);
8449       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8450     } else if (((Subtarget.hasLFIWAX() &&
8451                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8452                 (Subtarget.hasFPCVT() &&
8453                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8454                SINT.getOperand(0).getValueType() == MVT::i32) {
8455       MachineFrameInfo &MFI = MF.getFrameInfo();
8456       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8457 
8458       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8459       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8460 
8461       SDValue Store =
8462           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8463                        MachinePointerInfo::getFixedStack(
8464                            DAG.getMachineFunction(), FrameIdx));
8465 
8466       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8467              "Expected an i32 store");
8468 
8469       RLI.Ptr = FIdx;
8470       RLI.Chain = Store;
8471       RLI.MPI =
8472           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8473       RLI.Alignment = Align(4);
8474 
8475       MachineMemOperand *MMO =
8476         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8477                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8478       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8479       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8480                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8481                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8482                                      Ops, MVT::i32, MMO);
8483     } else
8484       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8485 
8486     SDValue FP = convertIntToFP(Op, Bits, DAG, Subtarget);
8487 
8488     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8489       FP = DAG.getNode(ISD::FP_ROUND, dl,
8490                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8491     return FP;
8492   }
8493 
8494   assert(Src.getValueType() == MVT::i32 &&
8495          "Unhandled INT_TO_FP type in custom expander!");
8496   // Since we only generate this in 64-bit mode, we can take advantage of
8497   // 64-bit registers.  In particular, sign extend the input value into the
8498   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8499   // then lfd it and fcfid it.
8500   MachineFunction &MF = DAG.getMachineFunction();
8501   MachineFrameInfo &MFI = MF.getFrameInfo();
8502   EVT PtrVT = getPointerTy(MF.getDataLayout());
8503 
8504   SDValue Ld;
8505   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8506     ReuseLoadInfo RLI;
8507     bool ReusingLoad;
8508     if (!(ReusingLoad = canReuseLoadAddress(Src, MVT::i32, RLI, DAG))) {
8509       int FrameIdx = MFI.CreateStackObject(4, Align(4), false);
8510       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8511 
8512       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Src, FIdx,
8513                                    MachinePointerInfo::getFixedStack(
8514                                        DAG.getMachineFunction(), FrameIdx));
8515 
8516       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8517              "Expected an i32 store");
8518 
8519       RLI.Ptr = FIdx;
8520       RLI.Chain = Store;
8521       RLI.MPI =
8522           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8523       RLI.Alignment = Align(4);
8524     }
8525 
8526     MachineMemOperand *MMO =
8527       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8528                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8529     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8530     Ld = DAG.getMemIntrinsicNode(IsSigned ? PPCISD::LFIWAX : PPCISD::LFIWZX, dl,
8531                                  DAG.getVTList(MVT::f64, MVT::Other), Ops,
8532                                  MVT::i32, MMO);
8533     if (ReusingLoad)
8534       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8535   } else {
8536     assert(Subtarget.isPPC64() &&
8537            "i32->FP without LFIWAX supported only on PPC64");
8538 
8539     int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
8540     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8541 
8542     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64, Src);
8543 
8544     // STD the extended value into the stack slot.
8545     SDValue Store = DAG.getStore(
8546         DAG.getEntryNode(), dl, Ext64, FIdx,
8547         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8548 
8549     // Load the value as a double.
8550     Ld = DAG.getLoad(
8551         MVT::f64, dl, Store, FIdx,
8552         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8553   }
8554 
8555   // FCFID it and return it.
8556   SDValue FP = convertIntToFP(Op, Ld, DAG, Subtarget);
8557   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8558     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8559                      DAG.getIntPtrConstant(0, dl));
8560   return FP;
8561 }
8562 
8563 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8564                                             SelectionDAG &DAG) const {
8565   SDLoc dl(Op);
8566   /*
8567    The rounding mode is in bits 30:31 of FPSR, and has the following
8568    settings:
8569      00 Round to nearest
8570      01 Round to 0
8571      10 Round to +inf
8572      11 Round to -inf
8573 
8574   FLT_ROUNDS, on the other hand, expects the following:
8575     -1 Undefined
8576      0 Round to 0
8577      1 Round to nearest
8578      2 Round to +inf
8579      3 Round to -inf
8580 
8581   To perform the conversion, we do:
8582     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8583   */
8584 
8585   MachineFunction &MF = DAG.getMachineFunction();
8586   EVT VT = Op.getValueType();
8587   EVT PtrVT = getPointerTy(MF.getDataLayout());
8588 
8589   // Save FP Control Word to register
8590   SDValue Chain = Op.getOperand(0);
8591   SDValue MFFS = DAG.getNode(PPCISD::MFFS, dl, {MVT::f64, MVT::Other}, Chain);
8592   Chain = MFFS.getValue(1);
8593 
8594   // Save FP register to stack slot
8595   int SSFI = MF.getFrameInfo().CreateStackObject(8, Align(8), false);
8596   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8597   Chain = DAG.getStore(Chain, dl, MFFS, StackSlot, MachinePointerInfo());
8598 
8599   // Load FP Control Word from low 32 bits of stack slot.
8600   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8601   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8602   SDValue CWD = DAG.getLoad(MVT::i32, dl, Chain, Addr, MachinePointerInfo());
8603   Chain = CWD.getValue(1);
8604 
8605   // Transform as necessary
8606   SDValue CWD1 =
8607     DAG.getNode(ISD::AND, dl, MVT::i32,
8608                 CWD, DAG.getConstant(3, dl, MVT::i32));
8609   SDValue CWD2 =
8610     DAG.getNode(ISD::SRL, dl, MVT::i32,
8611                 DAG.getNode(ISD::AND, dl, MVT::i32,
8612                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8613                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8614                             DAG.getConstant(3, dl, MVT::i32)),
8615                 DAG.getConstant(1, dl, MVT::i32));
8616 
8617   SDValue RetVal =
8618     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8619 
8620   RetVal =
8621       DAG.getNode((VT.getSizeInBits() < 16 ? ISD::TRUNCATE : ISD::ZERO_EXTEND),
8622                   dl, VT, RetVal);
8623 
8624   return DAG.getMergeValues({RetVal, Chain}, dl);
8625 }
8626 
8627 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8628   EVT VT = Op.getValueType();
8629   unsigned BitWidth = VT.getSizeInBits();
8630   SDLoc dl(Op);
8631   assert(Op.getNumOperands() == 3 &&
8632          VT == Op.getOperand(1).getValueType() &&
8633          "Unexpected SHL!");
8634 
8635   // Expand into a bunch of logical ops.  Note that these ops
8636   // depend on the PPC behavior for oversized shift amounts.
8637   SDValue Lo = Op.getOperand(0);
8638   SDValue Hi = Op.getOperand(1);
8639   SDValue Amt = Op.getOperand(2);
8640   EVT AmtVT = Amt.getValueType();
8641 
8642   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8643                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8644   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8645   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8646   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8647   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8648                              DAG.getConstant(-BitWidth, dl, AmtVT));
8649   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8650   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8651   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8652   SDValue OutOps[] = { OutLo, OutHi };
8653   return DAG.getMergeValues(OutOps, dl);
8654 }
8655 
8656 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8657   EVT VT = Op.getValueType();
8658   SDLoc dl(Op);
8659   unsigned BitWidth = VT.getSizeInBits();
8660   assert(Op.getNumOperands() == 3 &&
8661          VT == Op.getOperand(1).getValueType() &&
8662          "Unexpected SRL!");
8663 
8664   // Expand into a bunch of logical ops.  Note that these ops
8665   // depend on the PPC behavior for oversized shift amounts.
8666   SDValue Lo = Op.getOperand(0);
8667   SDValue Hi = Op.getOperand(1);
8668   SDValue Amt = Op.getOperand(2);
8669   EVT AmtVT = Amt.getValueType();
8670 
8671   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8672                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8673   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8674   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8675   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8676   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8677                              DAG.getConstant(-BitWidth, dl, AmtVT));
8678   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8679   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8680   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8681   SDValue OutOps[] = { OutLo, OutHi };
8682   return DAG.getMergeValues(OutOps, dl);
8683 }
8684 
8685 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8686   SDLoc dl(Op);
8687   EVT VT = Op.getValueType();
8688   unsigned BitWidth = VT.getSizeInBits();
8689   assert(Op.getNumOperands() == 3 &&
8690          VT == Op.getOperand(1).getValueType() &&
8691          "Unexpected SRA!");
8692 
8693   // Expand into a bunch of logical ops, followed by a select_cc.
8694   SDValue Lo = Op.getOperand(0);
8695   SDValue Hi = Op.getOperand(1);
8696   SDValue Amt = Op.getOperand(2);
8697   EVT AmtVT = Amt.getValueType();
8698 
8699   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8700                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8701   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8702   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8703   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8704   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8705                              DAG.getConstant(-BitWidth, dl, AmtVT));
8706   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8707   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8708   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8709                                   Tmp4, Tmp6, ISD::SETLE);
8710   SDValue OutOps[] = { OutLo, OutHi };
8711   return DAG.getMergeValues(OutOps, dl);
8712 }
8713 
8714 SDValue PPCTargetLowering::LowerFunnelShift(SDValue Op,
8715                                             SelectionDAG &DAG) const {
8716   SDLoc dl(Op);
8717   EVT VT = Op.getValueType();
8718   unsigned BitWidth = VT.getSizeInBits();
8719 
8720   bool IsFSHL = Op.getOpcode() == ISD::FSHL;
8721   SDValue X = Op.getOperand(0);
8722   SDValue Y = Op.getOperand(1);
8723   SDValue Z = Op.getOperand(2);
8724   EVT AmtVT = Z.getValueType();
8725 
8726   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
8727   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
8728   // This is simpler than TargetLowering::expandFunnelShift because we can rely
8729   // on PowerPC shift by BW being well defined.
8730   Z = DAG.getNode(ISD::AND, dl, AmtVT, Z,
8731                   DAG.getConstant(BitWidth - 1, dl, AmtVT));
8732   SDValue SubZ =
8733       DAG.getNode(ISD::SUB, dl, AmtVT, DAG.getConstant(BitWidth, dl, AmtVT), Z);
8734   X = DAG.getNode(PPCISD::SHL, dl, VT, X, IsFSHL ? Z : SubZ);
8735   Y = DAG.getNode(PPCISD::SRL, dl, VT, Y, IsFSHL ? SubZ : Z);
8736   return DAG.getNode(ISD::OR, dl, VT, X, Y);
8737 }
8738 
8739 //===----------------------------------------------------------------------===//
8740 // Vector related lowering.
8741 //
8742 
8743 /// getCanonicalConstSplat - Build a canonical splat immediate of Val with an
8744 /// element size of SplatSize. Cast the result to VT.
8745 static SDValue getCanonicalConstSplat(uint64_t Val, unsigned SplatSize, EVT VT,
8746                                       SelectionDAG &DAG, const SDLoc &dl) {
8747   static const MVT VTys[] = { // canonical VT to use for each size.
8748     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8749   };
8750 
8751   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8752 
8753   // For a splat with all ones, turn it to vspltisb 0xFF to canonicalize.
8754   if (Val == ((1LU << (SplatSize * 8)) - 1)) {
8755     SplatSize = 1;
8756     Val = 0xFF;
8757   }
8758 
8759   EVT CanonicalVT = VTys[SplatSize-1];
8760 
8761   // Build a canonical splat for this value.
8762   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8763 }
8764 
8765 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8766 /// specified intrinsic ID.
8767 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8768                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8769   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8770   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8771                      DAG.getConstant(IID, dl, MVT::i32), Op);
8772 }
8773 
8774 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8775 /// specified intrinsic ID.
8776 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8777                                 SelectionDAG &DAG, const SDLoc &dl,
8778                                 EVT DestVT = MVT::Other) {
8779   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8780   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8781                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8782 }
8783 
8784 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8785 /// specified intrinsic ID.
8786 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8787                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8788                                 EVT DestVT = MVT::Other) {
8789   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8790   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8791                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8792 }
8793 
8794 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8795 /// amount.  The result has the specified value type.
8796 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8797                            SelectionDAG &DAG, const SDLoc &dl) {
8798   // Force LHS/RHS to be the right type.
8799   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8800   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8801 
8802   int Ops[16];
8803   for (unsigned i = 0; i != 16; ++i)
8804     Ops[i] = i + Amt;
8805   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8806   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8807 }
8808 
8809 /// Do we have an efficient pattern in a .td file for this node?
8810 ///
8811 /// \param V - pointer to the BuildVectorSDNode being matched
8812 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8813 ///
8814 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8815 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8816 /// the opposite is true (expansion is beneficial) are:
8817 /// - The node builds a vector out of integers that are not 32 or 64-bits
8818 /// - The node builds a vector out of constants
8819 /// - The node is a "load-and-splat"
8820 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8821 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8822                                             bool HasDirectMove,
8823                                             bool HasP8Vector) {
8824   EVT VecVT = V->getValueType(0);
8825   bool RightType = VecVT == MVT::v2f64 ||
8826     (HasP8Vector && VecVT == MVT::v4f32) ||
8827     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8828   if (!RightType)
8829     return false;
8830 
8831   bool IsSplat = true;
8832   bool IsLoad = false;
8833   SDValue Op0 = V->getOperand(0);
8834 
8835   // This function is called in a block that confirms the node is not a constant
8836   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8837   // different constants.
8838   if (V->isConstant())
8839     return false;
8840   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8841     if (V->getOperand(i).isUndef())
8842       return false;
8843     // We want to expand nodes that represent load-and-splat even if the
8844     // loaded value is a floating point truncation or conversion to int.
8845     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8846         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8847          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8848         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8849          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8850         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8851          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8852       IsLoad = true;
8853     // If the operands are different or the input is not a load and has more
8854     // uses than just this BV node, then it isn't a splat.
8855     if (V->getOperand(i) != Op0 ||
8856         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8857       IsSplat = false;
8858   }
8859   return !(IsSplat && IsLoad);
8860 }
8861 
8862 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8863 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8864 
8865   SDLoc dl(Op);
8866   SDValue Op0 = Op->getOperand(0);
8867 
8868   if ((Op.getValueType() != MVT::f128) ||
8869       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8870       (Op0.getOperand(0).getValueType() != MVT::i64) ||
8871       (Op0.getOperand(1).getValueType() != MVT::i64))
8872     return SDValue();
8873 
8874   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8875                      Op0.getOperand(1));
8876 }
8877 
8878 static const SDValue *getNormalLoadInput(const SDValue &Op, bool &IsPermuted) {
8879   const SDValue *InputLoad = &Op;
8880   if (InputLoad->getOpcode() == ISD::BITCAST)
8881     InputLoad = &InputLoad->getOperand(0);
8882   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR ||
8883       InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED) {
8884     IsPermuted = InputLoad->getOpcode() == PPCISD::SCALAR_TO_VECTOR_PERMUTED;
8885     InputLoad = &InputLoad->getOperand(0);
8886   }
8887   if (InputLoad->getOpcode() != ISD::LOAD)
8888     return nullptr;
8889   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8890   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8891 }
8892 
8893 // Convert the argument APFloat to a single precision APFloat if there is no
8894 // loss in information during the conversion to single precision APFloat and the
8895 // resulting number is not a denormal number. Return true if successful.
8896 bool llvm::convertToNonDenormSingle(APFloat &ArgAPFloat) {
8897   APFloat APFloatToConvert = ArgAPFloat;
8898   bool LosesInfo = true;
8899   APFloatToConvert.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
8900                            &LosesInfo);
8901   bool Success = (!LosesInfo && !APFloatToConvert.isDenormal());
8902   if (Success)
8903     ArgAPFloat = APFloatToConvert;
8904   return Success;
8905 }
8906 
8907 // Bitcast the argument APInt to a double and convert it to a single precision
8908 // APFloat, bitcast the APFloat to an APInt and assign it to the original
8909 // argument if there is no loss in information during the conversion from
8910 // double to single precision APFloat and the resulting number is not a denormal
8911 // number. Return true if successful.
8912 bool llvm::convertToNonDenormSingle(APInt &ArgAPInt) {
8913   double DpValue = ArgAPInt.bitsToDouble();
8914   APFloat APFloatDp(DpValue);
8915   bool Success = convertToNonDenormSingle(APFloatDp);
8916   if (Success)
8917     ArgAPInt = APFloatDp.bitcastToAPInt();
8918   return Success;
8919 }
8920 
8921 // If this is a case we can't handle, return null and let the default
8922 // expansion code take care of it.  If we CAN select this case, and if it
8923 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8924 // this case more efficiently than a constant pool load, lower it to the
8925 // sequence of ops that should be used.
8926 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8927                                              SelectionDAG &DAG) const {
8928   SDLoc dl(Op);
8929   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8930   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8931 
8932   // Check if this is a splat of a constant value.
8933   APInt APSplatBits, APSplatUndef;
8934   unsigned SplatBitSize;
8935   bool HasAnyUndefs;
8936   bool BVNIsConstantSplat =
8937       BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8938                            HasAnyUndefs, 0, !Subtarget.isLittleEndian());
8939 
8940   // If it is a splat of a double, check if we can shrink it to a 32 bit
8941   // non-denormal float which when converted back to double gives us the same
8942   // double. This is to exploit the XXSPLTIDP instruction.
8943   if (BVNIsConstantSplat && Subtarget.hasPrefixInstrs() &&
8944       (SplatBitSize == 64) && (Op->getValueType(0) == MVT::v2f64) &&
8945       convertToNonDenormSingle(APSplatBits)) {
8946     SDValue SplatNode = DAG.getNode(
8947         PPCISD::XXSPLTI_SP_TO_DP, dl, MVT::v2f64,
8948         DAG.getTargetConstant(APSplatBits.getZExtValue(), dl, MVT::i32));
8949     return DAG.getBitcast(Op.getValueType(), SplatNode);
8950   }
8951 
8952   if (!BVNIsConstantSplat || SplatBitSize > 32) {
8953 
8954     bool IsPermutedLoad = false;
8955     const SDValue *InputLoad =
8956         getNormalLoadInput(Op.getOperand(0), IsPermutedLoad);
8957     // Handle load-and-splat patterns as we have instructions that will do this
8958     // in one go.
8959     if (InputLoad && DAG.isSplatValue(Op, true)) {
8960       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8961 
8962       // We have handling for 4 and 8 byte elements.
8963       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8964 
8965       // Checking for a single use of this load, we have to check for vector
8966       // width (128 bits) / ElementSize uses (since each operand of the
8967       // BUILD_VECTOR is a separate use of the value.
8968       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8969           ((Subtarget.hasVSX() && ElementSize == 64) ||
8970            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8971         SDValue Ops[] = {
8972           LD->getChain(),    // Chain
8973           LD->getBasePtr(),  // Ptr
8974           DAG.getValueType(Op.getValueType()) // VT
8975         };
8976         return
8977           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8978                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8979                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8980       }
8981     }
8982 
8983     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8984     // lowered to VSX instructions under certain conditions.
8985     // Without VSX, there is no pattern more efficient than expanding the node.
8986     if (Subtarget.hasVSX() &&
8987         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8988                                         Subtarget.hasP8Vector()))
8989       return Op;
8990     return SDValue();
8991   }
8992 
8993   uint64_t SplatBits = APSplatBits.getZExtValue();
8994   uint64_t SplatUndef = APSplatUndef.getZExtValue();
8995   unsigned SplatSize = SplatBitSize / 8;
8996 
8997   // First, handle single instruction cases.
8998 
8999   // All zeros?
9000   if (SplatBits == 0) {
9001     // Canonicalize all zero vectors to be v4i32.
9002     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
9003       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
9004       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
9005     }
9006     return Op;
9007   }
9008 
9009   // We have XXSPLTIW for constant splats four bytes wide.
9010   // Given vector length is a multiple of 4, 2-byte splats can be replaced
9011   // with 4-byte splats. We replicate the SplatBits in case of 2-byte splat to
9012   // make a 4-byte splat element. For example: 2-byte splat of 0xABAB can be
9013   // turned into a 4-byte splat of 0xABABABAB.
9014   if (Subtarget.hasPrefixInstrs() && SplatSize == 2)
9015     return getCanonicalConstSplat((SplatBits |= SplatBits << 16), SplatSize * 2,
9016                                   Op.getValueType(), DAG, dl);
9017 
9018   if (Subtarget.hasPrefixInstrs() && SplatSize == 4)
9019     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9020                                   dl);
9021 
9022   // We have XXSPLTIB for constant splats one byte wide.
9023   if (Subtarget.hasP9Vector() && SplatSize == 1)
9024     return getCanonicalConstSplat(SplatBits, SplatSize, Op.getValueType(), DAG,
9025                                   dl);
9026 
9027   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
9028   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
9029                     (32-SplatBitSize));
9030   if (SextVal >= -16 && SextVal <= 15)
9031     return getCanonicalConstSplat(SextVal, SplatSize, Op.getValueType(), DAG,
9032                                   dl);
9033 
9034   // Two instruction sequences.
9035 
9036   // If this value is in the range [-32,30] and is even, use:
9037   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
9038   // If this value is in the range [17,31] and is odd, use:
9039   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
9040   // If this value is in the range [-31,-17] and is odd, use:
9041   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
9042   // Note the last two are three-instruction sequences.
9043   if (SextVal >= -32 && SextVal <= 31) {
9044     // To avoid having these optimizations undone by constant folding,
9045     // we convert to a pseudo that will be expanded later into one of
9046     // the above forms.
9047     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
9048     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
9049               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
9050     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
9051     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
9052     if (VT == Op.getValueType())
9053       return RetVal;
9054     else
9055       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
9056   }
9057 
9058   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
9059   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
9060   // for fneg/fabs.
9061   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
9062     // Make -1 and vspltisw -1:
9063     SDValue OnesV = getCanonicalConstSplat(-1, 4, MVT::v4i32, DAG, dl);
9064 
9065     // Make the VSLW intrinsic, computing 0x8000_0000.
9066     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
9067                                    OnesV, DAG, dl);
9068 
9069     // xor by OnesV to invert it.
9070     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
9071     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9072   }
9073 
9074   // Check to see if this is a wide variety of vsplti*, binop self cases.
9075   static const signed char SplatCsts[] = {
9076     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
9077     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
9078   };
9079 
9080   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
9081     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
9082     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
9083     int i = SplatCsts[idx];
9084 
9085     // Figure out what shift amount will be used by altivec if shifted by i in
9086     // this splat size.
9087     unsigned TypeShiftAmt = i & (SplatBitSize-1);
9088 
9089     // vsplti + shl self.
9090     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
9091       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9092       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9093         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
9094         Intrinsic::ppc_altivec_vslw
9095       };
9096       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9097       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9098     }
9099 
9100     // vsplti + srl self.
9101     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9102       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9103       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9104         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
9105         Intrinsic::ppc_altivec_vsrw
9106       };
9107       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9108       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9109     }
9110 
9111     // vsplti + sra self.
9112     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
9113       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9114       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9115         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
9116         Intrinsic::ppc_altivec_vsraw
9117       };
9118       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9119       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9120     }
9121 
9122     // vsplti + rol self.
9123     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
9124                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
9125       SDValue Res = getCanonicalConstSplat(i, SplatSize, MVT::Other, DAG, dl);
9126       static const unsigned IIDs[] = { // Intrinsic to use for each size.
9127         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
9128         Intrinsic::ppc_altivec_vrlw
9129       };
9130       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
9131       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
9132     }
9133 
9134     // t = vsplti c, result = vsldoi t, t, 1
9135     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
9136       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9137       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
9138       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9139     }
9140     // t = vsplti c, result = vsldoi t, t, 2
9141     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
9142       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9143       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
9144       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9145     }
9146     // t = vsplti c, result = vsldoi t, t, 3
9147     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
9148       SDValue T = getCanonicalConstSplat(i, SplatSize, MVT::v16i8, DAG, dl);
9149       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
9150       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
9151     }
9152   }
9153 
9154   return SDValue();
9155 }
9156 
9157 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
9158 /// the specified operations to build the shuffle.
9159 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
9160                                       SDValue RHS, SelectionDAG &DAG,
9161                                       const SDLoc &dl) {
9162   unsigned OpNum = (PFEntry >> 26) & 0x0F;
9163   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
9164   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
9165 
9166   enum {
9167     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
9168     OP_VMRGHW,
9169     OP_VMRGLW,
9170     OP_VSPLTISW0,
9171     OP_VSPLTISW1,
9172     OP_VSPLTISW2,
9173     OP_VSPLTISW3,
9174     OP_VSLDOI4,
9175     OP_VSLDOI8,
9176     OP_VSLDOI12
9177   };
9178 
9179   if (OpNum == OP_COPY) {
9180     if (LHSID == (1*9+2)*9+3) return LHS;
9181     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
9182     return RHS;
9183   }
9184 
9185   SDValue OpLHS, OpRHS;
9186   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
9187   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
9188 
9189   int ShufIdxs[16];
9190   switch (OpNum) {
9191   default: llvm_unreachable("Unknown i32 permute!");
9192   case OP_VMRGHW:
9193     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
9194     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
9195     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
9196     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
9197     break;
9198   case OP_VMRGLW:
9199     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
9200     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
9201     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
9202     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
9203     break;
9204   case OP_VSPLTISW0:
9205     for (unsigned i = 0; i != 16; ++i)
9206       ShufIdxs[i] = (i&3)+0;
9207     break;
9208   case OP_VSPLTISW1:
9209     for (unsigned i = 0; i != 16; ++i)
9210       ShufIdxs[i] = (i&3)+4;
9211     break;
9212   case OP_VSPLTISW2:
9213     for (unsigned i = 0; i != 16; ++i)
9214       ShufIdxs[i] = (i&3)+8;
9215     break;
9216   case OP_VSPLTISW3:
9217     for (unsigned i = 0; i != 16; ++i)
9218       ShufIdxs[i] = (i&3)+12;
9219     break;
9220   case OP_VSLDOI4:
9221     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
9222   case OP_VSLDOI8:
9223     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
9224   case OP_VSLDOI12:
9225     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
9226   }
9227   EVT VT = OpLHS.getValueType();
9228   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
9229   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
9230   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
9231   return DAG.getNode(ISD::BITCAST, dl, VT, T);
9232 }
9233 
9234 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
9235 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
9236 /// SDValue.
9237 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
9238                                            SelectionDAG &DAG) const {
9239   const unsigned BytesInVector = 16;
9240   bool IsLE = Subtarget.isLittleEndian();
9241   SDLoc dl(N);
9242   SDValue V1 = N->getOperand(0);
9243   SDValue V2 = N->getOperand(1);
9244   unsigned ShiftElts = 0, InsertAtByte = 0;
9245   bool Swap = false;
9246 
9247   // Shifts required to get the byte we want at element 7.
9248   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
9249                                    0, 15, 14, 13, 12, 11, 10, 9};
9250   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
9251                                 1, 2,  3,  4,  5,  6,  7,  8};
9252 
9253   ArrayRef<int> Mask = N->getMask();
9254   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
9255 
9256   // For each mask element, find out if we're just inserting something
9257   // from V2 into V1 or vice versa.
9258   // Possible permutations inserting an element from V2 into V1:
9259   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9260   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
9261   //   ...
9262   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
9263   // Inserting from V1 into V2 will be similar, except mask range will be
9264   // [16,31].
9265 
9266   bool FoundCandidate = false;
9267   // If both vector operands for the shuffle are the same vector, the mask
9268   // will contain only elements from the first one and the second one will be
9269   // undef.
9270   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
9271   // Go through the mask of half-words to find an element that's being moved
9272   // from one vector to the other.
9273   for (unsigned i = 0; i < BytesInVector; ++i) {
9274     unsigned CurrentElement = Mask[i];
9275     // If 2nd operand is undefined, we should only look for element 7 in the
9276     // Mask.
9277     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
9278       continue;
9279 
9280     bool OtherElementsInOrder = true;
9281     // Examine the other elements in the Mask to see if they're in original
9282     // order.
9283     for (unsigned j = 0; j < BytesInVector; ++j) {
9284       if (j == i)
9285         continue;
9286       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
9287       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
9288       // in which we always assume we're always picking from the 1st operand.
9289       int MaskOffset =
9290           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
9291       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
9292         OtherElementsInOrder = false;
9293         break;
9294       }
9295     }
9296     // If other elements are in original order, we record the number of shifts
9297     // we need to get the element we want into element 7. Also record which byte
9298     // in the vector we should insert into.
9299     if (OtherElementsInOrder) {
9300       // If 2nd operand is undefined, we assume no shifts and no swapping.
9301       if (V2.isUndef()) {
9302         ShiftElts = 0;
9303         Swap = false;
9304       } else {
9305         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
9306         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
9307                          : BigEndianShifts[CurrentElement & 0xF];
9308         Swap = CurrentElement < BytesInVector;
9309       }
9310       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9311       FoundCandidate = true;
9312       break;
9313     }
9314   }
9315 
9316   if (!FoundCandidate)
9317     return SDValue();
9318 
9319   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9320   // optionally with VECSHL if shift is required.
9321   if (Swap)
9322     std::swap(V1, V2);
9323   if (V2.isUndef())
9324     V2 = V1;
9325   if (ShiftElts) {
9326     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9327                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9328     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9329                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9330   }
9331   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9332                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9333 }
9334 
9335 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9336 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9337 /// SDValue.
9338 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9339                                            SelectionDAG &DAG) const {
9340   const unsigned NumHalfWords = 8;
9341   const unsigned BytesInVector = NumHalfWords * 2;
9342   // Check that the shuffle is on half-words.
9343   if (!isNByteElemShuffleMask(N, 2, 1))
9344     return SDValue();
9345 
9346   bool IsLE = Subtarget.isLittleEndian();
9347   SDLoc dl(N);
9348   SDValue V1 = N->getOperand(0);
9349   SDValue V2 = N->getOperand(1);
9350   unsigned ShiftElts = 0, InsertAtByte = 0;
9351   bool Swap = false;
9352 
9353   // Shifts required to get the half-word we want at element 3.
9354   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9355   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9356 
9357   uint32_t Mask = 0;
9358   uint32_t OriginalOrderLow = 0x1234567;
9359   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9360   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9361   // 32-bit space, only need 4-bit nibbles per element.
9362   for (unsigned i = 0; i < NumHalfWords; ++i) {
9363     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9364     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9365   }
9366 
9367   // For each mask element, find out if we're just inserting something
9368   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9369   // from V2 into V1:
9370   //   X, 1, 2, 3, 4, 5, 6, 7
9371   //   0, X, 2, 3, 4, 5, 6, 7
9372   //   0, 1, X, 3, 4, 5, 6, 7
9373   //   0, 1, 2, X, 4, 5, 6, 7
9374   //   0, 1, 2, 3, X, 5, 6, 7
9375   //   0, 1, 2, 3, 4, X, 6, 7
9376   //   0, 1, 2, 3, 4, 5, X, 7
9377   //   0, 1, 2, 3, 4, 5, 6, X
9378   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9379 
9380   bool FoundCandidate = false;
9381   // Go through the mask of half-words to find an element that's being moved
9382   // from one vector to the other.
9383   for (unsigned i = 0; i < NumHalfWords; ++i) {
9384     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9385     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9386     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9387     uint32_t TargetOrder = 0x0;
9388 
9389     // If both vector operands for the shuffle are the same vector, the mask
9390     // will contain only elements from the first one and the second one will be
9391     // undef.
9392     if (V2.isUndef()) {
9393       ShiftElts = 0;
9394       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9395       TargetOrder = OriginalOrderLow;
9396       Swap = false;
9397       // Skip if not the correct element or mask of other elements don't equal
9398       // to our expected order.
9399       if (MaskOneElt == VINSERTHSrcElem &&
9400           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9401         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9402         FoundCandidate = true;
9403         break;
9404       }
9405     } else { // If both operands are defined.
9406       // Target order is [8,15] if the current mask is between [0,7].
9407       TargetOrder =
9408           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9409       // Skip if mask of other elements don't equal our expected order.
9410       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9411         // We only need the last 3 bits for the number of shifts.
9412         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9413                          : BigEndianShifts[MaskOneElt & 0x7];
9414         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9415         Swap = MaskOneElt < NumHalfWords;
9416         FoundCandidate = true;
9417         break;
9418       }
9419     }
9420   }
9421 
9422   if (!FoundCandidate)
9423     return SDValue();
9424 
9425   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9426   // optionally with VECSHL if shift is required.
9427   if (Swap)
9428     std::swap(V1, V2);
9429   if (V2.isUndef())
9430     V2 = V1;
9431   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9432   if (ShiftElts) {
9433     // Double ShiftElts because we're left shifting on v16i8 type.
9434     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9435                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9436     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9437     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9438                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9439     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9440   }
9441   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9442   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9443                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9444   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9445 }
9446 
9447 /// lowerToXXSPLTI32DX - Return the SDValue if this VECTOR_SHUFFLE can be
9448 /// handled by the XXSPLTI32DX instruction introduced in ISA 3.1, otherwise
9449 /// return the default SDValue.
9450 SDValue PPCTargetLowering::lowerToXXSPLTI32DX(ShuffleVectorSDNode *SVN,
9451                                               SelectionDAG &DAG) const {
9452   // The LHS and RHS may be bitcasts to v16i8 as we canonicalize shuffles
9453   // to v16i8. Peek through the bitcasts to get the actual operands.
9454   SDValue LHS = peekThroughBitcasts(SVN->getOperand(0));
9455   SDValue RHS = peekThroughBitcasts(SVN->getOperand(1));
9456 
9457   auto ShuffleMask = SVN->getMask();
9458   SDValue VecShuffle(SVN, 0);
9459   SDLoc DL(SVN);
9460 
9461   // Check that we have a four byte shuffle.
9462   if (!isNByteElemShuffleMask(SVN, 4, 1))
9463     return SDValue();
9464 
9465   // Canonicalize the RHS being a BUILD_VECTOR when lowering to xxsplti32dx.
9466   if (RHS->getOpcode() != ISD::BUILD_VECTOR) {
9467     std::swap(LHS, RHS);
9468     VecShuffle = DAG.getCommutedVectorShuffle(*SVN);
9469     ShuffleMask = cast<ShuffleVectorSDNode>(VecShuffle)->getMask();
9470   }
9471 
9472   // Ensure that the RHS is a vector of constants.
9473   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
9474   if (!BVN)
9475     return SDValue();
9476 
9477   // Check if RHS is a splat of 4-bytes (or smaller).
9478   APInt APSplatValue, APSplatUndef;
9479   unsigned SplatBitSize;
9480   bool HasAnyUndefs;
9481   if (!BVN->isConstantSplat(APSplatValue, APSplatUndef, SplatBitSize,
9482                             HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
9483       SplatBitSize > 32)
9484     return SDValue();
9485 
9486   // Check that the shuffle mask matches the semantics of XXSPLTI32DX.
9487   // The instruction splats a constant C into two words of the source vector
9488   // producing { C, Unchanged, C, Unchanged } or { Unchanged, C, Unchanged, C }.
9489   // Thus we check that the shuffle mask is the equivalent  of
9490   // <0, [4-7], 2, [4-7]> or <[4-7], 1, [4-7], 3> respectively.
9491   // Note: the check above of isNByteElemShuffleMask() ensures that the bytes
9492   // within each word are consecutive, so we only need to check the first byte.
9493   SDValue Index;
9494   bool IsLE = Subtarget.isLittleEndian();
9495   if ((ShuffleMask[0] == 0 && ShuffleMask[8] == 8) &&
9496       (ShuffleMask[4] % 4 == 0 && ShuffleMask[12] % 4 == 0 &&
9497        ShuffleMask[4] > 15 && ShuffleMask[12] > 15))
9498     Index = DAG.getTargetConstant(IsLE ? 0 : 1, DL, MVT::i32);
9499   else if ((ShuffleMask[4] == 4 && ShuffleMask[12] == 12) &&
9500            (ShuffleMask[0] % 4 == 0 && ShuffleMask[8] % 4 == 0 &&
9501             ShuffleMask[0] > 15 && ShuffleMask[8] > 15))
9502     Index = DAG.getTargetConstant(IsLE ? 1 : 0, DL, MVT::i32);
9503   else
9504     return SDValue();
9505 
9506   // If the splat is narrower than 32-bits, we need to get the 32-bit value
9507   // for XXSPLTI32DX.
9508   unsigned SplatVal = APSplatValue.getZExtValue();
9509   for (; SplatBitSize < 32; SplatBitSize <<= 1)
9510     SplatVal |= (SplatVal << SplatBitSize);
9511 
9512   SDValue SplatNode = DAG.getNode(
9513       PPCISD::XXSPLTI32DX, DL, MVT::v2i64, DAG.getBitcast(MVT::v2i64, LHS),
9514       Index, DAG.getTargetConstant(SplatVal, DL, MVT::i32));
9515   return DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, SplatNode);
9516 }
9517 
9518 /// LowerROTL - Custom lowering for ROTL(v1i128) to vector_shuffle(v16i8).
9519 /// We lower ROTL(v1i128) to vector_shuffle(v16i8) only if shift amount is
9520 /// a multiple of 8. Otherwise convert it to a scalar rotation(i128)
9521 /// i.e (or (shl x, C1), (srl x, 128-C1)).
9522 SDValue PPCTargetLowering::LowerROTL(SDValue Op, SelectionDAG &DAG) const {
9523   assert(Op.getOpcode() == ISD::ROTL && "Should only be called for ISD::ROTL");
9524   assert(Op.getValueType() == MVT::v1i128 &&
9525          "Only set v1i128 as custom, other type shouldn't reach here!");
9526   SDLoc dl(Op);
9527   SDValue N0 = peekThroughBitcasts(Op.getOperand(0));
9528   SDValue N1 = peekThroughBitcasts(Op.getOperand(1));
9529   unsigned SHLAmt = N1.getConstantOperandVal(0);
9530   if (SHLAmt % 8 == 0) {
9531     SmallVector<int, 16> Mask(16, 0);
9532     std::iota(Mask.begin(), Mask.end(), 0);
9533     std::rotate(Mask.begin(), Mask.begin() + SHLAmt / 8, Mask.end());
9534     if (SDValue Shuffle =
9535             DAG.getVectorShuffle(MVT::v16i8, dl, DAG.getBitcast(MVT::v16i8, N0),
9536                                  DAG.getUNDEF(MVT::v16i8), Mask))
9537       return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, Shuffle);
9538   }
9539   SDValue ArgVal = DAG.getBitcast(MVT::i128, N0);
9540   SDValue SHLOp = DAG.getNode(ISD::SHL, dl, MVT::i128, ArgVal,
9541                               DAG.getConstant(SHLAmt, dl, MVT::i32));
9542   SDValue SRLOp = DAG.getNode(ISD::SRL, dl, MVT::i128, ArgVal,
9543                               DAG.getConstant(128 - SHLAmt, dl, MVT::i32));
9544   SDValue OROp = DAG.getNode(ISD::OR, dl, MVT::i128, SHLOp, SRLOp);
9545   return DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, OROp);
9546 }
9547 
9548 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9549 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9550 /// return the code it can be lowered into.  Worst case, it can always be
9551 /// lowered into a vperm.
9552 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9553                                                SelectionDAG &DAG) const {
9554   SDLoc dl(Op);
9555   SDValue V1 = Op.getOperand(0);
9556   SDValue V2 = Op.getOperand(1);
9557   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9558 
9559   // Any nodes that were combined in the target-independent combiner prior
9560   // to vector legalization will not be sent to the target combine. Try to
9561   // combine it here.
9562   if (SDValue NewShuffle = combineVectorShuffle(SVOp, DAG)) {
9563     if (!isa<ShuffleVectorSDNode>(NewShuffle))
9564       return NewShuffle;
9565     Op = NewShuffle;
9566     SVOp = cast<ShuffleVectorSDNode>(Op);
9567     V1 = Op.getOperand(0);
9568     V2 = Op.getOperand(1);
9569   }
9570   EVT VT = Op.getValueType();
9571   bool isLittleEndian = Subtarget.isLittleEndian();
9572 
9573   unsigned ShiftElts, InsertAtByte;
9574   bool Swap = false;
9575 
9576   // If this is a load-and-splat, we can do that with a single instruction
9577   // in some cases. However if the load has multiple uses, we don't want to
9578   // combine it because that will just produce multiple loads.
9579   bool IsPermutedLoad = false;
9580   const SDValue *InputLoad = getNormalLoadInput(V1, IsPermutedLoad);
9581   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9582       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9583       InputLoad->hasOneUse()) {
9584     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9585     int SplatIdx =
9586       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9587 
9588     // The splat index for permuted loads will be in the left half of the vector
9589     // which is strictly wider than the loaded value by 8 bytes. So we need to
9590     // adjust the splat index to point to the correct address in memory.
9591     if (IsPermutedLoad) {
9592       assert(isLittleEndian && "Unexpected permuted load on big endian target");
9593       SplatIdx += IsFourByte ? 2 : 1;
9594       assert((SplatIdx < (IsFourByte ? 4 : 2)) &&
9595              "Splat of a value outside of the loaded memory");
9596     }
9597 
9598     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9599     // For 4-byte load-and-splat, we need Power9.
9600     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9601       uint64_t Offset = 0;
9602       if (IsFourByte)
9603         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9604       else
9605         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9606 
9607       SDValue BasePtr = LD->getBasePtr();
9608       if (Offset != 0)
9609         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9610                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9611       SDValue Ops[] = {
9612         LD->getChain(),    // Chain
9613         BasePtr,           // BasePtr
9614         DAG.getValueType(Op.getValueType()) // VT
9615       };
9616       SDVTList VTL =
9617         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9618       SDValue LdSplt =
9619         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9620                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9621       if (LdSplt.getValueType() != SVOp->getValueType(0))
9622         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9623       return LdSplt;
9624     }
9625   }
9626   if (Subtarget.hasP9Vector() &&
9627       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9628                            isLittleEndian)) {
9629     if (Swap)
9630       std::swap(V1, V2);
9631     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9632     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9633     if (ShiftElts) {
9634       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9635                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9636       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9637                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9638       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9639     }
9640     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9641                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9642     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9643   }
9644 
9645   if (Subtarget.hasPrefixInstrs()) {
9646     SDValue SplatInsertNode;
9647     if ((SplatInsertNode = lowerToXXSPLTI32DX(SVOp, DAG)))
9648       return SplatInsertNode;
9649   }
9650 
9651   if (Subtarget.hasP9Altivec()) {
9652     SDValue NewISDNode;
9653     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9654       return NewISDNode;
9655 
9656     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9657       return NewISDNode;
9658   }
9659 
9660   if (Subtarget.hasVSX() &&
9661       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9662     if (Swap)
9663       std::swap(V1, V2);
9664     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9665     SDValue Conv2 =
9666         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9667 
9668     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9669                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9670     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9671   }
9672 
9673   if (Subtarget.hasVSX() &&
9674     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9675     if (Swap)
9676       std::swap(V1, V2);
9677     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9678     SDValue Conv2 =
9679         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9680 
9681     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9682                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9683     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9684   }
9685 
9686   if (Subtarget.hasP9Vector()) {
9687      if (PPC::isXXBRHShuffleMask(SVOp)) {
9688       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9689       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9690       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9691     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9692       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9693       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9694       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9695     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9696       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9697       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9698       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9699     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9700       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9701       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9702       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9703     }
9704   }
9705 
9706   if (Subtarget.hasVSX()) {
9707     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9708       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9709 
9710       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9711       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9712                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9713       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9714     }
9715 
9716     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9717     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9718       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9719       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9720       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9721     }
9722   }
9723 
9724   // Cases that are handled by instructions that take permute immediates
9725   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9726   // selected by the instruction selector.
9727   if (V2.isUndef()) {
9728     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9729         PPC::isSplatShuffleMask(SVOp, 2) ||
9730         PPC::isSplatShuffleMask(SVOp, 4) ||
9731         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9732         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9733         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9734         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9735         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9736         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9737         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9738         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9739         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9740         (Subtarget.hasP8Altivec() && (
9741          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9742          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9743          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9744       return Op;
9745     }
9746   }
9747 
9748   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9749   // and produce a fixed permutation.  If any of these match, do not lower to
9750   // VPERM.
9751   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9752   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9753       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9754       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9755       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9756       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9757       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9758       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9759       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9760       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9761       (Subtarget.hasP8Altivec() && (
9762        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9763        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9764        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9765     return Op;
9766 
9767   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9768   // perfect shuffle table to emit an optimal matching sequence.
9769   ArrayRef<int> PermMask = SVOp->getMask();
9770 
9771   unsigned PFIndexes[4];
9772   bool isFourElementShuffle = true;
9773   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9774     unsigned EltNo = 8;   // Start out undef.
9775     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9776       if (PermMask[i*4+j] < 0)
9777         continue;   // Undef, ignore it.
9778 
9779       unsigned ByteSource = PermMask[i*4+j];
9780       if ((ByteSource & 3) != j) {
9781         isFourElementShuffle = false;
9782         break;
9783       }
9784 
9785       if (EltNo == 8) {
9786         EltNo = ByteSource/4;
9787       } else if (EltNo != ByteSource/4) {
9788         isFourElementShuffle = false;
9789         break;
9790       }
9791     }
9792     PFIndexes[i] = EltNo;
9793   }
9794 
9795   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9796   // perfect shuffle vector to determine if it is cost effective to do this as
9797   // discrete instructions, or whether we should use a vperm.
9798   // For now, we skip this for little endian until such time as we have a
9799   // little-endian perfect shuffle table.
9800   if (isFourElementShuffle && !isLittleEndian) {
9801     // Compute the index in the perfect shuffle table.
9802     unsigned PFTableIndex =
9803       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9804 
9805     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9806     unsigned Cost  = (PFEntry >> 30);
9807 
9808     // Determining when to avoid vperm is tricky.  Many things affect the cost
9809     // of vperm, particularly how many times the perm mask needs to be computed.
9810     // For example, if the perm mask can be hoisted out of a loop or is already
9811     // used (perhaps because there are multiple permutes with the same shuffle
9812     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9813     // the loop requires an extra register.
9814     //
9815     // As a compromise, we only emit discrete instructions if the shuffle can be
9816     // generated in 3 or fewer operations.  When we have loop information
9817     // available, if this block is within a loop, we should avoid using vperm
9818     // for 3-operation perms and use a constant pool load instead.
9819     if (Cost < 3)
9820       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9821   }
9822 
9823   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9824   // vector that will get spilled to the constant pool.
9825   if (V2.isUndef()) V2 = V1;
9826 
9827   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9828   // that it is in input element units, not in bytes.  Convert now.
9829 
9830   // For little endian, the order of the input vectors is reversed, and
9831   // the permutation mask is complemented with respect to 31.  This is
9832   // necessary to produce proper semantics with the big-endian-biased vperm
9833   // instruction.
9834   EVT EltVT = V1.getValueType().getVectorElementType();
9835   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9836 
9837   SmallVector<SDValue, 16> ResultMask;
9838   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9839     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9840 
9841     for (unsigned j = 0; j != BytesPerElement; ++j)
9842       if (isLittleEndian)
9843         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9844                                              dl, MVT::i32));
9845       else
9846         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9847                                              MVT::i32));
9848   }
9849 
9850   ShufflesHandledWithVPERM++;
9851   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9852   LLVM_DEBUG(dbgs() << "Emitting a VPERM for the following shuffle:\n");
9853   LLVM_DEBUG(SVOp->dump());
9854   LLVM_DEBUG(dbgs() << "With the following permute control vector:\n");
9855   LLVM_DEBUG(VPermMask.dump());
9856 
9857   if (isLittleEndian)
9858     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9859                        V2, V1, VPermMask);
9860   else
9861     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9862                        V1, V2, VPermMask);
9863 }
9864 
9865 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9866 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9867 /// information about the intrinsic.
9868 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9869                                  bool &isDot, const PPCSubtarget &Subtarget) {
9870   unsigned IntrinsicID =
9871       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9872   CompareOpc = -1;
9873   isDot = false;
9874   switch (IntrinsicID) {
9875   default:
9876     return false;
9877   // Comparison predicates.
9878   case Intrinsic::ppc_altivec_vcmpbfp_p:
9879     CompareOpc = 966;
9880     isDot = true;
9881     break;
9882   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9883     CompareOpc = 198;
9884     isDot = true;
9885     break;
9886   case Intrinsic::ppc_altivec_vcmpequb_p:
9887     CompareOpc = 6;
9888     isDot = true;
9889     break;
9890   case Intrinsic::ppc_altivec_vcmpequh_p:
9891     CompareOpc = 70;
9892     isDot = true;
9893     break;
9894   case Intrinsic::ppc_altivec_vcmpequw_p:
9895     CompareOpc = 134;
9896     isDot = true;
9897     break;
9898   case Intrinsic::ppc_altivec_vcmpequd_p:
9899     if (Subtarget.hasP8Altivec()) {
9900       CompareOpc = 199;
9901       isDot = true;
9902     } else
9903       return false;
9904     break;
9905   case Intrinsic::ppc_altivec_vcmpneb_p:
9906   case Intrinsic::ppc_altivec_vcmpneh_p:
9907   case Intrinsic::ppc_altivec_vcmpnew_p:
9908   case Intrinsic::ppc_altivec_vcmpnezb_p:
9909   case Intrinsic::ppc_altivec_vcmpnezh_p:
9910   case Intrinsic::ppc_altivec_vcmpnezw_p:
9911     if (Subtarget.hasP9Altivec()) {
9912       switch (IntrinsicID) {
9913       default:
9914         llvm_unreachable("Unknown comparison intrinsic.");
9915       case Intrinsic::ppc_altivec_vcmpneb_p:
9916         CompareOpc = 7;
9917         break;
9918       case Intrinsic::ppc_altivec_vcmpneh_p:
9919         CompareOpc = 71;
9920         break;
9921       case Intrinsic::ppc_altivec_vcmpnew_p:
9922         CompareOpc = 135;
9923         break;
9924       case Intrinsic::ppc_altivec_vcmpnezb_p:
9925         CompareOpc = 263;
9926         break;
9927       case Intrinsic::ppc_altivec_vcmpnezh_p:
9928         CompareOpc = 327;
9929         break;
9930       case Intrinsic::ppc_altivec_vcmpnezw_p:
9931         CompareOpc = 391;
9932         break;
9933       }
9934       isDot = true;
9935     } else
9936       return false;
9937     break;
9938   case Intrinsic::ppc_altivec_vcmpgefp_p:
9939     CompareOpc = 454;
9940     isDot = true;
9941     break;
9942   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9943     CompareOpc = 710;
9944     isDot = true;
9945     break;
9946   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9947     CompareOpc = 774;
9948     isDot = true;
9949     break;
9950   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9951     CompareOpc = 838;
9952     isDot = true;
9953     break;
9954   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9955     CompareOpc = 902;
9956     isDot = true;
9957     break;
9958   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9959     if (Subtarget.hasP8Altivec()) {
9960       CompareOpc = 967;
9961       isDot = true;
9962     } else
9963       return false;
9964     break;
9965   case Intrinsic::ppc_altivec_vcmpgtub_p:
9966     CompareOpc = 518;
9967     isDot = true;
9968     break;
9969   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9970     CompareOpc = 582;
9971     isDot = true;
9972     break;
9973   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9974     CompareOpc = 646;
9975     isDot = true;
9976     break;
9977   case Intrinsic::ppc_altivec_vcmpgtud_p:
9978     if (Subtarget.hasP8Altivec()) {
9979       CompareOpc = 711;
9980       isDot = true;
9981     } else
9982       return false;
9983     break;
9984 
9985   // VSX predicate comparisons use the same infrastructure
9986   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9987   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9988   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9989   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9990   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9991   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9992     if (Subtarget.hasVSX()) {
9993       switch (IntrinsicID) {
9994       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9995         CompareOpc = 99;
9996         break;
9997       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9998         CompareOpc = 115;
9999         break;
10000       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
10001         CompareOpc = 107;
10002         break;
10003       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
10004         CompareOpc = 67;
10005         break;
10006       case Intrinsic::ppc_vsx_xvcmpgesp_p:
10007         CompareOpc = 83;
10008         break;
10009       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
10010         CompareOpc = 75;
10011         break;
10012       }
10013       isDot = true;
10014     } else
10015       return false;
10016     break;
10017 
10018   // Normal Comparisons.
10019   case Intrinsic::ppc_altivec_vcmpbfp:
10020     CompareOpc = 966;
10021     break;
10022   case Intrinsic::ppc_altivec_vcmpeqfp:
10023     CompareOpc = 198;
10024     break;
10025   case Intrinsic::ppc_altivec_vcmpequb:
10026     CompareOpc = 6;
10027     break;
10028   case Intrinsic::ppc_altivec_vcmpequh:
10029     CompareOpc = 70;
10030     break;
10031   case Intrinsic::ppc_altivec_vcmpequw:
10032     CompareOpc = 134;
10033     break;
10034   case Intrinsic::ppc_altivec_vcmpequd:
10035     if (Subtarget.hasP8Altivec())
10036       CompareOpc = 199;
10037     else
10038       return false;
10039     break;
10040   case Intrinsic::ppc_altivec_vcmpneb:
10041   case Intrinsic::ppc_altivec_vcmpneh:
10042   case Intrinsic::ppc_altivec_vcmpnew:
10043   case Intrinsic::ppc_altivec_vcmpnezb:
10044   case Intrinsic::ppc_altivec_vcmpnezh:
10045   case Intrinsic::ppc_altivec_vcmpnezw:
10046     if (Subtarget.hasP9Altivec())
10047       switch (IntrinsicID) {
10048       default:
10049         llvm_unreachable("Unknown comparison intrinsic.");
10050       case Intrinsic::ppc_altivec_vcmpneb:
10051         CompareOpc = 7;
10052         break;
10053       case Intrinsic::ppc_altivec_vcmpneh:
10054         CompareOpc = 71;
10055         break;
10056       case Intrinsic::ppc_altivec_vcmpnew:
10057         CompareOpc = 135;
10058         break;
10059       case Intrinsic::ppc_altivec_vcmpnezb:
10060         CompareOpc = 263;
10061         break;
10062       case Intrinsic::ppc_altivec_vcmpnezh:
10063         CompareOpc = 327;
10064         break;
10065       case Intrinsic::ppc_altivec_vcmpnezw:
10066         CompareOpc = 391;
10067         break;
10068       }
10069     else
10070       return false;
10071     break;
10072   case Intrinsic::ppc_altivec_vcmpgefp:
10073     CompareOpc = 454;
10074     break;
10075   case Intrinsic::ppc_altivec_vcmpgtfp:
10076     CompareOpc = 710;
10077     break;
10078   case Intrinsic::ppc_altivec_vcmpgtsb:
10079     CompareOpc = 774;
10080     break;
10081   case Intrinsic::ppc_altivec_vcmpgtsh:
10082     CompareOpc = 838;
10083     break;
10084   case Intrinsic::ppc_altivec_vcmpgtsw:
10085     CompareOpc = 902;
10086     break;
10087   case Intrinsic::ppc_altivec_vcmpgtsd:
10088     if (Subtarget.hasP8Altivec())
10089       CompareOpc = 967;
10090     else
10091       return false;
10092     break;
10093   case Intrinsic::ppc_altivec_vcmpgtub:
10094     CompareOpc = 518;
10095     break;
10096   case Intrinsic::ppc_altivec_vcmpgtuh:
10097     CompareOpc = 582;
10098     break;
10099   case Intrinsic::ppc_altivec_vcmpgtuw:
10100     CompareOpc = 646;
10101     break;
10102   case Intrinsic::ppc_altivec_vcmpgtud:
10103     if (Subtarget.hasP8Altivec())
10104       CompareOpc = 711;
10105     else
10106       return false;
10107     break;
10108   }
10109   return true;
10110 }
10111 
10112 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
10113 /// lower, do it, otherwise return null.
10114 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
10115                                                    SelectionDAG &DAG) const {
10116   unsigned IntrinsicID =
10117     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
10118 
10119   SDLoc dl(Op);
10120 
10121   if (IntrinsicID == Intrinsic::thread_pointer) {
10122     // Reads the thread pointer register, used for __builtin_thread_pointer.
10123     if (Subtarget.isPPC64())
10124       return DAG.getRegister(PPC::X13, MVT::i64);
10125     return DAG.getRegister(PPC::R2, MVT::i32);
10126   }
10127 
10128   // If this is a lowered altivec predicate compare, CompareOpc is set to the
10129   // opcode number of the comparison.
10130   int CompareOpc;
10131   bool isDot;
10132   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
10133     return SDValue();    // Don't custom lower most intrinsics.
10134 
10135   // If this is a non-dot comparison, make the VCMP node and we are done.
10136   if (!isDot) {
10137     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
10138                               Op.getOperand(1), Op.getOperand(2),
10139                               DAG.getConstant(CompareOpc, dl, MVT::i32));
10140     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
10141   }
10142 
10143   // Create the PPCISD altivec 'dot' comparison node.
10144   SDValue Ops[] = {
10145     Op.getOperand(2),  // LHS
10146     Op.getOperand(3),  // RHS
10147     DAG.getConstant(CompareOpc, dl, MVT::i32)
10148   };
10149   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
10150   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
10151 
10152   // Now that we have the comparison, emit a copy from the CR to a GPR.
10153   // This is flagged to the above dot comparison.
10154   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
10155                                 DAG.getRegister(PPC::CR6, MVT::i32),
10156                                 CompNode.getValue(1));
10157 
10158   // Unpack the result based on how the target uses it.
10159   unsigned BitNo;   // Bit # of CR6.
10160   bool InvertBit;   // Invert result?
10161   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
10162   default:  // Can't happen, don't crash on invalid number though.
10163   case 0:   // Return the value of the EQ bit of CR6.
10164     BitNo = 0; InvertBit = false;
10165     break;
10166   case 1:   // Return the inverted value of the EQ bit of CR6.
10167     BitNo = 0; InvertBit = true;
10168     break;
10169   case 2:   // Return the value of the LT bit of CR6.
10170     BitNo = 2; InvertBit = false;
10171     break;
10172   case 3:   // Return the inverted value of the LT bit of CR6.
10173     BitNo = 2; InvertBit = true;
10174     break;
10175   }
10176 
10177   // Shift the bit into the low position.
10178   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
10179                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
10180   // Isolate the bit.
10181   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
10182                       DAG.getConstant(1, dl, MVT::i32));
10183 
10184   // If we are supposed to, toggle the bit.
10185   if (InvertBit)
10186     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
10187                         DAG.getConstant(1, dl, MVT::i32));
10188   return Flags;
10189 }
10190 
10191 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
10192                                                SelectionDAG &DAG) const {
10193   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
10194   // the beginning of the argument list.
10195   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
10196   SDLoc DL(Op);
10197   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
10198   case Intrinsic::ppc_cfence: {
10199     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
10200     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
10201     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
10202                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
10203                                                   Op.getOperand(ArgStart + 1)),
10204                                       Op.getOperand(0)),
10205                    0);
10206   }
10207   default:
10208     break;
10209   }
10210   return SDValue();
10211 }
10212 
10213 // Lower scalar BSWAP64 to xxbrd.
10214 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
10215   SDLoc dl(Op);
10216   // MTVSRDD
10217   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
10218                    Op.getOperand(0));
10219   // XXBRD
10220   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
10221   // MFVSRD
10222   int VectorIndex = 0;
10223   if (Subtarget.isLittleEndian())
10224     VectorIndex = 1;
10225   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
10226                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
10227   return Op;
10228 }
10229 
10230 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
10231 // compared to a value that is atomically loaded (atomic loads zero-extend).
10232 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
10233                                                 SelectionDAG &DAG) const {
10234   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
10235          "Expecting an atomic compare-and-swap here.");
10236   SDLoc dl(Op);
10237   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
10238   EVT MemVT = AtomicNode->getMemoryVT();
10239   if (MemVT.getSizeInBits() >= 32)
10240     return Op;
10241 
10242   SDValue CmpOp = Op.getOperand(2);
10243   // If this is already correctly zero-extended, leave it alone.
10244   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
10245   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
10246     return Op;
10247 
10248   // Clear the high bits of the compare operand.
10249   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
10250   SDValue NewCmpOp =
10251     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
10252                 DAG.getConstant(MaskVal, dl, MVT::i32));
10253 
10254   // Replace the existing compare operand with the properly zero-extended one.
10255   SmallVector<SDValue, 4> Ops;
10256   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
10257     Ops.push_back(AtomicNode->getOperand(i));
10258   Ops[2] = NewCmpOp;
10259   MachineMemOperand *MMO = AtomicNode->getMemOperand();
10260   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
10261   auto NodeTy =
10262     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
10263   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
10264 }
10265 
10266 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
10267                                                  SelectionDAG &DAG) const {
10268   SDLoc dl(Op);
10269   // Create a stack slot that is 16-byte aligned.
10270   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10271   int FrameIdx = MFI.CreateStackObject(16, Align(16), false);
10272   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10273   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10274 
10275   // Store the input value into Value#0 of the stack slot.
10276   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
10277                                MachinePointerInfo());
10278   // Load it out.
10279   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
10280 }
10281 
10282 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10283                                                   SelectionDAG &DAG) const {
10284   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
10285          "Should only be called for ISD::INSERT_VECTOR_ELT");
10286 
10287   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
10288   // We have legal lowering for constant indices but not for variable ones.
10289   if (!C)
10290     return SDValue();
10291 
10292   EVT VT = Op.getValueType();
10293   SDLoc dl(Op);
10294   SDValue V1 = Op.getOperand(0);
10295   SDValue V2 = Op.getOperand(1);
10296   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
10297   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
10298     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
10299     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
10300     unsigned InsertAtElement = C->getZExtValue();
10301     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
10302     if (Subtarget.isLittleEndian()) {
10303       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
10304     }
10305     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
10306                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
10307   }
10308   return Op;
10309 }
10310 
10311 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10312   SDLoc dl(Op);
10313   if (Op.getValueType() == MVT::v4i32) {
10314     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10315 
10316     SDValue Zero = getCanonicalConstSplat(0, 1, MVT::v4i32, DAG, dl);
10317     // +16 as shift amt.
10318     SDValue Neg16 = getCanonicalConstSplat(-16, 4, MVT::v4i32, DAG, dl);
10319     SDValue RHSSwap =   // = vrlw RHS, 16
10320       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10321 
10322     // Shrinkify inputs to v8i16.
10323     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10324     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10325     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10326 
10327     // Low parts multiplied together, generating 32-bit results (we ignore the
10328     // top parts).
10329     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10330                                         LHS, RHS, DAG, dl, MVT::v4i32);
10331 
10332     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10333                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10334     // Shift the high parts up 16 bits.
10335     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10336                               Neg16, DAG, dl);
10337     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10338   } else if (Op.getValueType() == MVT::v16i8) {
10339     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10340     bool isLittleEndian = Subtarget.isLittleEndian();
10341 
10342     // Multiply the even 8-bit parts, producing 16-bit sums.
10343     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10344                                            LHS, RHS, DAG, dl, MVT::v8i16);
10345     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10346 
10347     // Multiply the odd 8-bit parts, producing 16-bit sums.
10348     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10349                                           LHS, RHS, DAG, dl, MVT::v8i16);
10350     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10351 
10352     // Merge the results together.  Because vmuleub and vmuloub are
10353     // instructions with a big-endian bias, we must reverse the
10354     // element numbering and reverse the meaning of "odd" and "even"
10355     // when generating little endian code.
10356     int Ops[16];
10357     for (unsigned i = 0; i != 8; ++i) {
10358       if (isLittleEndian) {
10359         Ops[i*2  ] = 2*i;
10360         Ops[i*2+1] = 2*i+16;
10361       } else {
10362         Ops[i*2  ] = 2*i+1;
10363         Ops[i*2+1] = 2*i+1+16;
10364       }
10365     }
10366     if (isLittleEndian)
10367       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10368     else
10369       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10370   } else {
10371     llvm_unreachable("Unknown mul to lower!");
10372   }
10373 }
10374 
10375 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10376 
10377   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10378 
10379   EVT VT = Op.getValueType();
10380   assert(VT.isVector() &&
10381          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10382   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10383           VT == MVT::v16i8) &&
10384          "Unexpected vector element type!");
10385   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10386          "Current subtarget doesn't support smax v2i64!");
10387 
10388   // For vector abs, it can be lowered to:
10389   // abs x
10390   // ==>
10391   // y = -x
10392   // smax(x, y)
10393 
10394   SDLoc dl(Op);
10395   SDValue X = Op.getOperand(0);
10396   SDValue Zero = DAG.getConstant(0, dl, VT);
10397   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10398 
10399   // SMAX patch https://reviews.llvm.org/D47332
10400   // hasn't landed yet, so use intrinsic first here.
10401   // TODO: Should use SMAX directly once SMAX patch landed
10402   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10403   if (VT == MVT::v2i64)
10404     BifID = Intrinsic::ppc_altivec_vmaxsd;
10405   else if (VT == MVT::v8i16)
10406     BifID = Intrinsic::ppc_altivec_vmaxsh;
10407   else if (VT == MVT::v16i8)
10408     BifID = Intrinsic::ppc_altivec_vmaxsb;
10409 
10410   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10411 }
10412 
10413 // Custom lowering for fpext vf32 to v2f64
10414 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10415 
10416   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10417          "Should only be called for ISD::FP_EXTEND");
10418 
10419   // FIXME: handle extends from half precision float vectors on P9.
10420   // We only want to custom lower an extend from v2f32 to v2f64.
10421   if (Op.getValueType() != MVT::v2f64 ||
10422       Op.getOperand(0).getValueType() != MVT::v2f32)
10423     return SDValue();
10424 
10425   SDLoc dl(Op);
10426   SDValue Op0 = Op.getOperand(0);
10427 
10428   switch (Op0.getOpcode()) {
10429   default:
10430     return SDValue();
10431   case ISD::EXTRACT_SUBVECTOR: {
10432     assert(Op0.getNumOperands() == 2 &&
10433            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10434            "Node should have 2 operands with second one being a constant!");
10435 
10436     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10437       return SDValue();
10438 
10439     // Custom lower is only done for high or low doubleword.
10440     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10441     if (Idx % 2 != 0)
10442       return SDValue();
10443 
10444     // Since input is v4f32, at this point Idx is either 0 or 2.
10445     // Shift to get the doubleword position we want.
10446     int DWord = Idx >> 1;
10447 
10448     // High and low word positions are different on little endian.
10449     if (Subtarget.isLittleEndian())
10450       DWord ^= 0x1;
10451 
10452     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10453                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10454   }
10455   case ISD::FADD:
10456   case ISD::FMUL:
10457   case ISD::FSUB: {
10458     SDValue NewLoad[2];
10459     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10460       // Ensure both input are loads.
10461       SDValue LdOp = Op0.getOperand(i);
10462       if (LdOp.getOpcode() != ISD::LOAD)
10463         return SDValue();
10464       // Generate new load node.
10465       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10466       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10467       NewLoad[i] = DAG.getMemIntrinsicNode(
10468           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10469           LD->getMemoryVT(), LD->getMemOperand());
10470     }
10471     SDValue NewOp =
10472         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10473                     NewLoad[1], Op0.getNode()->getFlags());
10474     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10475                        DAG.getConstant(0, dl, MVT::i32));
10476   }
10477   case ISD::LOAD: {
10478     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10479     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10480     SDValue NewLd = DAG.getMemIntrinsicNode(
10481         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10482         LD->getMemoryVT(), LD->getMemOperand());
10483     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10484                        DAG.getConstant(0, dl, MVT::i32));
10485   }
10486   }
10487   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10488 }
10489 
10490 /// LowerOperation - Provide custom lowering hooks for some operations.
10491 ///
10492 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10493   switch (Op.getOpcode()) {
10494   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10495   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10496   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10497   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10498   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10499   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10500   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10501   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10502   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10503 
10504   // Variable argument lowering.
10505   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10506   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10507   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10508 
10509   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10510   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10511   case ISD::GET_DYNAMIC_AREA_OFFSET:
10512     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10513 
10514   // Exception handling lowering.
10515   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10516   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10517   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10518 
10519   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10520   case ISD::STORE:              return LowerSTORE(Op, DAG);
10521   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10522   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10523   case ISD::STRICT_FP_TO_UINT:
10524   case ISD::STRICT_FP_TO_SINT:
10525   case ISD::FP_TO_UINT:
10526   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10527   case ISD::UINT_TO_FP:
10528   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10529   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10530 
10531   // Lower 64-bit shifts.
10532   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10533   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10534   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10535 
10536   case ISD::FSHL:               return LowerFunnelShift(Op, DAG);
10537   case ISD::FSHR:               return LowerFunnelShift(Op, DAG);
10538 
10539   // Vector-related lowering.
10540   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10541   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10542   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10543   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10544   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10545   case ISD::MUL:                return LowerMUL(Op, DAG);
10546   case ISD::ABS:                return LowerABS(Op, DAG);
10547   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10548   case ISD::ROTL:               return LowerROTL(Op, DAG);
10549 
10550   // For counter-based loop handling.
10551   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10552 
10553   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10554 
10555   // Frame & Return address.
10556   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10557   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10558 
10559   case ISD::INTRINSIC_VOID:
10560     return LowerINTRINSIC_VOID(Op, DAG);
10561   case ISD::BSWAP:
10562     return LowerBSWAP(Op, DAG);
10563   case ISD::ATOMIC_CMP_SWAP:
10564     return LowerATOMIC_CMP_SWAP(Op, DAG);
10565   }
10566 }
10567 
10568 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10569                                            SmallVectorImpl<SDValue>&Results,
10570                                            SelectionDAG &DAG) const {
10571   SDLoc dl(N);
10572   switch (N->getOpcode()) {
10573   default:
10574     llvm_unreachable("Do not know how to custom type legalize this operation!");
10575   case ISD::READCYCLECOUNTER: {
10576     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10577     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10578 
10579     Results.push_back(
10580         DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, RTB, RTB.getValue(1)));
10581     Results.push_back(RTB.getValue(2));
10582     break;
10583   }
10584   case ISD::INTRINSIC_W_CHAIN: {
10585     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10586         Intrinsic::loop_decrement)
10587       break;
10588 
10589     assert(N->getValueType(0) == MVT::i1 &&
10590            "Unexpected result type for CTR decrement intrinsic");
10591     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10592                                  N->getValueType(0));
10593     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10594     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10595                                  N->getOperand(1));
10596 
10597     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10598     Results.push_back(NewInt.getValue(1));
10599     break;
10600   }
10601   case ISD::VAARG: {
10602     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10603       return;
10604 
10605     EVT VT = N->getValueType(0);
10606 
10607     if (VT == MVT::i64) {
10608       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10609 
10610       Results.push_back(NewNode);
10611       Results.push_back(NewNode.getValue(1));
10612     }
10613     return;
10614   }
10615   case ISD::STRICT_FP_TO_SINT:
10616   case ISD::STRICT_FP_TO_UINT:
10617   case ISD::FP_TO_SINT:
10618   case ISD::FP_TO_UINT:
10619     // LowerFP_TO_INT() can only handle f32 and f64.
10620     if (N->getOperand(N->isStrictFPOpcode() ? 1 : 0).getValueType() ==
10621         MVT::ppcf128)
10622       return;
10623     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10624     return;
10625   case ISD::TRUNCATE: {
10626     EVT TrgVT = N->getValueType(0);
10627     EVT OpVT = N->getOperand(0).getValueType();
10628     if (TrgVT.isVector() &&
10629         isOperationCustom(N->getOpcode(), TrgVT) &&
10630         OpVT.getSizeInBits() <= 128 &&
10631         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10632       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10633     return;
10634   }
10635   case ISD::BITCAST:
10636     // Don't handle bitcast here.
10637     return;
10638   case ISD::FP_EXTEND:
10639     SDValue Lowered = LowerFP_EXTEND(SDValue(N, 0), DAG);
10640     if (Lowered)
10641       Results.push_back(Lowered);
10642     return;
10643   }
10644 }
10645 
10646 //===----------------------------------------------------------------------===//
10647 //  Other Lowering Code
10648 //===----------------------------------------------------------------------===//
10649 
10650 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10651   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10652   Function *Func = Intrinsic::getDeclaration(M, Id);
10653   return Builder.CreateCall(Func, {});
10654 }
10655 
10656 // The mappings for emitLeading/TrailingFence is taken from
10657 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10658 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10659                                                  Instruction *Inst,
10660                                                  AtomicOrdering Ord) const {
10661   if (Ord == AtomicOrdering::SequentiallyConsistent)
10662     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10663   if (isReleaseOrStronger(Ord))
10664     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10665   return nullptr;
10666 }
10667 
10668 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10669                                                   Instruction *Inst,
10670                                                   AtomicOrdering Ord) const {
10671   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10672     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10673     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10674     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10675     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10676       return Builder.CreateCall(
10677           Intrinsic::getDeclaration(
10678               Builder.GetInsertBlock()->getParent()->getParent(),
10679               Intrinsic::ppc_cfence, {Inst->getType()}),
10680           {Inst});
10681     // FIXME: Can use isync for rmw operation.
10682     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10683   }
10684   return nullptr;
10685 }
10686 
10687 MachineBasicBlock *
10688 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10689                                     unsigned AtomicSize,
10690                                     unsigned BinOpcode,
10691                                     unsigned CmpOpcode,
10692                                     unsigned CmpPred) const {
10693   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10694   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10695 
10696   auto LoadMnemonic = PPC::LDARX;
10697   auto StoreMnemonic = PPC::STDCX;
10698   switch (AtomicSize) {
10699   default:
10700     llvm_unreachable("Unexpected size of atomic entity");
10701   case 1:
10702     LoadMnemonic = PPC::LBARX;
10703     StoreMnemonic = PPC::STBCX;
10704     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10705     break;
10706   case 2:
10707     LoadMnemonic = PPC::LHARX;
10708     StoreMnemonic = PPC::STHCX;
10709     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10710     break;
10711   case 4:
10712     LoadMnemonic = PPC::LWARX;
10713     StoreMnemonic = PPC::STWCX;
10714     break;
10715   case 8:
10716     LoadMnemonic = PPC::LDARX;
10717     StoreMnemonic = PPC::STDCX;
10718     break;
10719   }
10720 
10721   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10722   MachineFunction *F = BB->getParent();
10723   MachineFunction::iterator It = ++BB->getIterator();
10724 
10725   Register dest = MI.getOperand(0).getReg();
10726   Register ptrA = MI.getOperand(1).getReg();
10727   Register ptrB = MI.getOperand(2).getReg();
10728   Register incr = MI.getOperand(3).getReg();
10729   DebugLoc dl = MI.getDebugLoc();
10730 
10731   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10732   MachineBasicBlock *loop2MBB =
10733     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10734   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10735   F->insert(It, loopMBB);
10736   if (CmpOpcode)
10737     F->insert(It, loop2MBB);
10738   F->insert(It, exitMBB);
10739   exitMBB->splice(exitMBB->begin(), BB,
10740                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10741   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10742 
10743   MachineRegisterInfo &RegInfo = F->getRegInfo();
10744   Register TmpReg = (!BinOpcode) ? incr :
10745     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10746                                            : &PPC::GPRCRegClass);
10747 
10748   //  thisMBB:
10749   //   ...
10750   //   fallthrough --> loopMBB
10751   BB->addSuccessor(loopMBB);
10752 
10753   //  loopMBB:
10754   //   l[wd]arx dest, ptr
10755   //   add r0, dest, incr
10756   //   st[wd]cx. r0, ptr
10757   //   bne- loopMBB
10758   //   fallthrough --> exitMBB
10759 
10760   // For max/min...
10761   //  loopMBB:
10762   //   l[wd]arx dest, ptr
10763   //   cmpl?[wd] incr, dest
10764   //   bgt exitMBB
10765   //  loop2MBB:
10766   //   st[wd]cx. dest, ptr
10767   //   bne- loopMBB
10768   //   fallthrough --> exitMBB
10769 
10770   BB = loopMBB;
10771   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10772     .addReg(ptrA).addReg(ptrB);
10773   if (BinOpcode)
10774     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10775   if (CmpOpcode) {
10776     // Signed comparisons of byte or halfword values must be sign-extended.
10777     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10778       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10779       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10780               ExtReg).addReg(dest);
10781       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10782         .addReg(incr).addReg(ExtReg);
10783     } else
10784       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10785         .addReg(incr).addReg(dest);
10786 
10787     BuildMI(BB, dl, TII->get(PPC::BCC))
10788       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10789     BB->addSuccessor(loop2MBB);
10790     BB->addSuccessor(exitMBB);
10791     BB = loop2MBB;
10792   }
10793   BuildMI(BB, dl, TII->get(StoreMnemonic))
10794     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10795   BuildMI(BB, dl, TII->get(PPC::BCC))
10796     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10797   BB->addSuccessor(loopMBB);
10798   BB->addSuccessor(exitMBB);
10799 
10800   //  exitMBB:
10801   //   ...
10802   BB = exitMBB;
10803   return BB;
10804 }
10805 
10806 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10807     MachineInstr &MI, MachineBasicBlock *BB,
10808     bool is8bit, // operation
10809     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10810   // If we support part-word atomic mnemonics, just use them
10811   if (Subtarget.hasPartwordAtomics())
10812     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10813                             CmpPred);
10814 
10815   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10816   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10817   // In 64 bit mode we have to use 64 bits for addresses, even though the
10818   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10819   // registers without caring whether they're 32 or 64, but here we're
10820   // doing actual arithmetic on the addresses.
10821   bool is64bit = Subtarget.isPPC64();
10822   bool isLittleEndian = Subtarget.isLittleEndian();
10823   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10824 
10825   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10826   MachineFunction *F = BB->getParent();
10827   MachineFunction::iterator It = ++BB->getIterator();
10828 
10829   Register dest = MI.getOperand(0).getReg();
10830   Register ptrA = MI.getOperand(1).getReg();
10831   Register ptrB = MI.getOperand(2).getReg();
10832   Register incr = MI.getOperand(3).getReg();
10833   DebugLoc dl = MI.getDebugLoc();
10834 
10835   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10836   MachineBasicBlock *loop2MBB =
10837       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10838   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10839   F->insert(It, loopMBB);
10840   if (CmpOpcode)
10841     F->insert(It, loop2MBB);
10842   F->insert(It, exitMBB);
10843   exitMBB->splice(exitMBB->begin(), BB,
10844                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10845   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10846 
10847   MachineRegisterInfo &RegInfo = F->getRegInfo();
10848   const TargetRegisterClass *RC =
10849       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10850   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10851 
10852   Register PtrReg = RegInfo.createVirtualRegister(RC);
10853   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10854   Register ShiftReg =
10855       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10856   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10857   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10858   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10859   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10860   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10861   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10862   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10863   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10864   Register Ptr1Reg;
10865   Register TmpReg =
10866       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10867 
10868   //  thisMBB:
10869   //   ...
10870   //   fallthrough --> loopMBB
10871   BB->addSuccessor(loopMBB);
10872 
10873   // The 4-byte load must be aligned, while a char or short may be
10874   // anywhere in the word.  Hence all this nasty bookkeeping code.
10875   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10876   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10877   //   xori shift, shift1, 24 [16]
10878   //   rlwinm ptr, ptr1, 0, 0, 29
10879   //   slw incr2, incr, shift
10880   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10881   //   slw mask, mask2, shift
10882   //  loopMBB:
10883   //   lwarx tmpDest, ptr
10884   //   add tmp, tmpDest, incr2
10885   //   andc tmp2, tmpDest, mask
10886   //   and tmp3, tmp, mask
10887   //   or tmp4, tmp3, tmp2
10888   //   stwcx. tmp4, ptr
10889   //   bne- loopMBB
10890   //   fallthrough --> exitMBB
10891   //   srw dest, tmpDest, shift
10892   if (ptrA != ZeroReg) {
10893     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10894     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10895         .addReg(ptrA)
10896         .addReg(ptrB);
10897   } else {
10898     Ptr1Reg = ptrB;
10899   }
10900   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10901   // mode.
10902   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10903       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10904       .addImm(3)
10905       .addImm(27)
10906       .addImm(is8bit ? 28 : 27);
10907   if (!isLittleEndian)
10908     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10909         .addReg(Shift1Reg)
10910         .addImm(is8bit ? 24 : 16);
10911   if (is64bit)
10912     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10913         .addReg(Ptr1Reg)
10914         .addImm(0)
10915         .addImm(61);
10916   else
10917     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10918         .addReg(Ptr1Reg)
10919         .addImm(0)
10920         .addImm(0)
10921         .addImm(29);
10922   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10923   if (is8bit)
10924     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10925   else {
10926     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10927     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10928         .addReg(Mask3Reg)
10929         .addImm(65535);
10930   }
10931   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10932       .addReg(Mask2Reg)
10933       .addReg(ShiftReg);
10934 
10935   BB = loopMBB;
10936   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10937       .addReg(ZeroReg)
10938       .addReg(PtrReg);
10939   if (BinOpcode)
10940     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10941         .addReg(Incr2Reg)
10942         .addReg(TmpDestReg);
10943   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10944       .addReg(TmpDestReg)
10945       .addReg(MaskReg);
10946   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10947   if (CmpOpcode) {
10948     // For unsigned comparisons, we can directly compare the shifted values.
10949     // For signed comparisons we shift and sign extend.
10950     Register SReg = RegInfo.createVirtualRegister(GPRC);
10951     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10952         .addReg(TmpDestReg)
10953         .addReg(MaskReg);
10954     unsigned ValueReg = SReg;
10955     unsigned CmpReg = Incr2Reg;
10956     if (CmpOpcode == PPC::CMPW) {
10957       ValueReg = RegInfo.createVirtualRegister(GPRC);
10958       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10959           .addReg(SReg)
10960           .addReg(ShiftReg);
10961       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10962       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10963           .addReg(ValueReg);
10964       ValueReg = ValueSReg;
10965       CmpReg = incr;
10966     }
10967     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10968         .addReg(CmpReg)
10969         .addReg(ValueReg);
10970     BuildMI(BB, dl, TII->get(PPC::BCC))
10971         .addImm(CmpPred)
10972         .addReg(PPC::CR0)
10973         .addMBB(exitMBB);
10974     BB->addSuccessor(loop2MBB);
10975     BB->addSuccessor(exitMBB);
10976     BB = loop2MBB;
10977   }
10978   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10979   BuildMI(BB, dl, TII->get(PPC::STWCX))
10980       .addReg(Tmp4Reg)
10981       .addReg(ZeroReg)
10982       .addReg(PtrReg);
10983   BuildMI(BB, dl, TII->get(PPC::BCC))
10984       .addImm(PPC::PRED_NE)
10985       .addReg(PPC::CR0)
10986       .addMBB(loopMBB);
10987   BB->addSuccessor(loopMBB);
10988   BB->addSuccessor(exitMBB);
10989 
10990   //  exitMBB:
10991   //   ...
10992   BB = exitMBB;
10993   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10994       .addReg(TmpDestReg)
10995       .addReg(ShiftReg);
10996   return BB;
10997 }
10998 
10999 llvm::MachineBasicBlock *
11000 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
11001                                     MachineBasicBlock *MBB) const {
11002   DebugLoc DL = MI.getDebugLoc();
11003   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11004   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
11005 
11006   MachineFunction *MF = MBB->getParent();
11007   MachineRegisterInfo &MRI = MF->getRegInfo();
11008 
11009   const BasicBlock *BB = MBB->getBasicBlock();
11010   MachineFunction::iterator I = ++MBB->getIterator();
11011 
11012   Register DstReg = MI.getOperand(0).getReg();
11013   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
11014   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
11015   Register mainDstReg = MRI.createVirtualRegister(RC);
11016   Register restoreDstReg = MRI.createVirtualRegister(RC);
11017 
11018   MVT PVT = getPointerTy(MF->getDataLayout());
11019   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11020          "Invalid Pointer Size!");
11021   // For v = setjmp(buf), we generate
11022   //
11023   // thisMBB:
11024   //  SjLjSetup mainMBB
11025   //  bl mainMBB
11026   //  v_restore = 1
11027   //  b sinkMBB
11028   //
11029   // mainMBB:
11030   //  buf[LabelOffset] = LR
11031   //  v_main = 0
11032   //
11033   // sinkMBB:
11034   //  v = phi(main, restore)
11035   //
11036 
11037   MachineBasicBlock *thisMBB = MBB;
11038   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
11039   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
11040   MF->insert(I, mainMBB);
11041   MF->insert(I, sinkMBB);
11042 
11043   MachineInstrBuilder MIB;
11044 
11045   // Transfer the remainder of BB and its successor edges to sinkMBB.
11046   sinkMBB->splice(sinkMBB->begin(), MBB,
11047                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11048   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
11049 
11050   // Note that the structure of the jmp_buf used here is not compatible
11051   // with that used by libc, and is not designed to be. Specifically, it
11052   // stores only those 'reserved' registers that LLVM does not otherwise
11053   // understand how to spill. Also, by convention, by the time this
11054   // intrinsic is called, Clang has already stored the frame address in the
11055   // first slot of the buffer and stack address in the third. Following the
11056   // X86 target code, we'll store the jump address in the second slot. We also
11057   // need to save the TOC pointer (R2) to handle jumps between shared
11058   // libraries, and that will be stored in the fourth slot. The thread
11059   // identifier (R13) is not affected.
11060 
11061   // thisMBB:
11062   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11063   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11064   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11065 
11066   // Prepare IP either in reg.
11067   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
11068   Register LabelReg = MRI.createVirtualRegister(PtrRC);
11069   Register BufReg = MI.getOperand(1).getReg();
11070 
11071   if (Subtarget.is64BitELFABI()) {
11072     setUsesTOCBasePtr(*MBB->getParent());
11073     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
11074               .addReg(PPC::X2)
11075               .addImm(TOCOffset)
11076               .addReg(BufReg)
11077               .cloneMemRefs(MI);
11078   }
11079 
11080   // Naked functions never have a base pointer, and so we use r1. For all
11081   // other functions, this decision must be delayed until during PEI.
11082   unsigned BaseReg;
11083   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
11084     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
11085   else
11086     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
11087 
11088   MIB = BuildMI(*thisMBB, MI, DL,
11089                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
11090             .addReg(BaseReg)
11091             .addImm(BPOffset)
11092             .addReg(BufReg)
11093             .cloneMemRefs(MI);
11094 
11095   // Setup
11096   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
11097   MIB.addRegMask(TRI->getNoPreservedMask());
11098 
11099   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
11100 
11101   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
11102           .addMBB(mainMBB);
11103   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
11104 
11105   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
11106   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
11107 
11108   // mainMBB:
11109   //  mainDstReg = 0
11110   MIB =
11111       BuildMI(mainMBB, DL,
11112               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
11113 
11114   // Store IP
11115   if (Subtarget.isPPC64()) {
11116     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
11117             .addReg(LabelReg)
11118             .addImm(LabelOffset)
11119             .addReg(BufReg);
11120   } else {
11121     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
11122             .addReg(LabelReg)
11123             .addImm(LabelOffset)
11124             .addReg(BufReg);
11125   }
11126   MIB.cloneMemRefs(MI);
11127 
11128   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11129   mainMBB->addSuccessor(sinkMBB);
11130 
11131   // sinkMBB:
11132   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11133           TII->get(PPC::PHI), DstReg)
11134     .addReg(mainDstReg).addMBB(mainMBB)
11135     .addReg(restoreDstReg).addMBB(thisMBB);
11136 
11137   MI.eraseFromParent();
11138   return sinkMBB;
11139 }
11140 
11141 MachineBasicBlock *
11142 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11143                                      MachineBasicBlock *MBB) const {
11144   DebugLoc DL = MI.getDebugLoc();
11145   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11146 
11147   MachineFunction *MF = MBB->getParent();
11148   MachineRegisterInfo &MRI = MF->getRegInfo();
11149 
11150   MVT PVT = getPointerTy(MF->getDataLayout());
11151   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11152          "Invalid Pointer Size!");
11153 
11154   const TargetRegisterClass *RC =
11155     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11156   Register Tmp = MRI.createVirtualRegister(RC);
11157   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11158   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11159   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11160   unsigned BP =
11161       (PVT == MVT::i64)
11162           ? PPC::X30
11163           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11164                                                               : PPC::R30);
11165 
11166   MachineInstrBuilder MIB;
11167 
11168   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11169   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11170   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11171   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11172 
11173   Register BufReg = MI.getOperand(0).getReg();
11174 
11175   // Reload FP (the jumped-to function may not have had a
11176   // frame pointer, and if so, then its r31 will be restored
11177   // as necessary).
11178   if (PVT == MVT::i64) {
11179     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11180             .addImm(0)
11181             .addReg(BufReg);
11182   } else {
11183     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11184             .addImm(0)
11185             .addReg(BufReg);
11186   }
11187   MIB.cloneMemRefs(MI);
11188 
11189   // Reload IP
11190   if (PVT == MVT::i64) {
11191     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11192             .addImm(LabelOffset)
11193             .addReg(BufReg);
11194   } else {
11195     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11196             .addImm(LabelOffset)
11197             .addReg(BufReg);
11198   }
11199   MIB.cloneMemRefs(MI);
11200 
11201   // Reload SP
11202   if (PVT == MVT::i64) {
11203     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11204             .addImm(SPOffset)
11205             .addReg(BufReg);
11206   } else {
11207     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11208             .addImm(SPOffset)
11209             .addReg(BufReg);
11210   }
11211   MIB.cloneMemRefs(MI);
11212 
11213   // Reload BP
11214   if (PVT == MVT::i64) {
11215     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11216             .addImm(BPOffset)
11217             .addReg(BufReg);
11218   } else {
11219     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11220             .addImm(BPOffset)
11221             .addReg(BufReg);
11222   }
11223   MIB.cloneMemRefs(MI);
11224 
11225   // Reload TOC
11226   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11227     setUsesTOCBasePtr(*MBB->getParent());
11228     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11229               .addImm(TOCOffset)
11230               .addReg(BufReg)
11231               .cloneMemRefs(MI);
11232   }
11233 
11234   // Jump
11235   BuildMI(*MBB, MI, DL,
11236           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11237   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11238 
11239   MI.eraseFromParent();
11240   return MBB;
11241 }
11242 
11243 bool PPCTargetLowering::hasInlineStackProbe(MachineFunction &MF) const {
11244   // If the function specifically requests inline stack probes, emit them.
11245   if (MF.getFunction().hasFnAttribute("probe-stack"))
11246     return MF.getFunction().getFnAttribute("probe-stack").getValueAsString() ==
11247            "inline-asm";
11248   return false;
11249 }
11250 
11251 unsigned PPCTargetLowering::getStackProbeSize(MachineFunction &MF) const {
11252   const TargetFrameLowering *TFI = Subtarget.getFrameLowering();
11253   unsigned StackAlign = TFI->getStackAlignment();
11254   assert(StackAlign >= 1 && isPowerOf2_32(StackAlign) &&
11255          "Unexpected stack alignment");
11256   // The default stack probe size is 4096 if the function has no
11257   // stack-probe-size attribute.
11258   unsigned StackProbeSize = 4096;
11259   const Function &Fn = MF.getFunction();
11260   if (Fn.hasFnAttribute("stack-probe-size"))
11261     Fn.getFnAttribute("stack-probe-size")
11262         .getValueAsString()
11263         .getAsInteger(0, StackProbeSize);
11264   // Round down to the stack alignment.
11265   StackProbeSize &= ~(StackAlign - 1);
11266   return StackProbeSize ? StackProbeSize : StackAlign;
11267 }
11268 
11269 // Lower dynamic stack allocation with probing. `emitProbedAlloca` is splitted
11270 // into three phases. In the first phase, it uses pseudo instruction
11271 // PREPARE_PROBED_ALLOCA to get the future result of actual FramePointer and
11272 // FinalStackPtr. In the second phase, it generates a loop for probing blocks.
11273 // At last, it uses pseudo instruction DYNAREAOFFSET to get the future result of
11274 // MaxCallFrameSize so that it can calculate correct data area pointer.
11275 MachineBasicBlock *
11276 PPCTargetLowering::emitProbedAlloca(MachineInstr &MI,
11277                                     MachineBasicBlock *MBB) const {
11278   const bool isPPC64 = Subtarget.isPPC64();
11279   MachineFunction *MF = MBB->getParent();
11280   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11281   DebugLoc DL = MI.getDebugLoc();
11282   const unsigned ProbeSize = getStackProbeSize(*MF);
11283   const BasicBlock *ProbedBB = MBB->getBasicBlock();
11284   MachineRegisterInfo &MRI = MF->getRegInfo();
11285   // The CFG of probing stack looks as
11286   //         +-----+
11287   //         | MBB |
11288   //         +--+--+
11289   //            |
11290   //       +----v----+
11291   //  +--->+ TestMBB +---+
11292   //  |    +----+----+   |
11293   //  |         |        |
11294   //  |   +-----v----+   |
11295   //  +---+ BlockMBB |   |
11296   //      +----------+   |
11297   //                     |
11298   //       +---------+   |
11299   //       | TailMBB +<--+
11300   //       +---------+
11301   // In MBB, calculate previous frame pointer and final stack pointer.
11302   // In TestMBB, test if sp is equal to final stack pointer, if so, jump to
11303   // TailMBB. In BlockMBB, update the sp atomically and jump back to TestMBB.
11304   // TailMBB is spliced via \p MI.
11305   MachineBasicBlock *TestMBB = MF->CreateMachineBasicBlock(ProbedBB);
11306   MachineBasicBlock *TailMBB = MF->CreateMachineBasicBlock(ProbedBB);
11307   MachineBasicBlock *BlockMBB = MF->CreateMachineBasicBlock(ProbedBB);
11308 
11309   MachineFunction::iterator MBBIter = ++MBB->getIterator();
11310   MF->insert(MBBIter, TestMBB);
11311   MF->insert(MBBIter, BlockMBB);
11312   MF->insert(MBBIter, TailMBB);
11313 
11314   const TargetRegisterClass *G8RC = &PPC::G8RCRegClass;
11315   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11316 
11317   Register DstReg = MI.getOperand(0).getReg();
11318   Register NegSizeReg = MI.getOperand(1).getReg();
11319   Register SPReg = isPPC64 ? PPC::X1 : PPC::R1;
11320   Register FinalStackPtr = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11321   Register FramePointer = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11322   Register ActualNegSizeReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11323 
11324   // Since value of NegSizeReg might be realigned in prologepilog, insert a
11325   // PREPARE_PROBED_ALLOCA pseudo instruction to get actual FramePointer and
11326   // NegSize.
11327   unsigned ProbeOpc;
11328   if (!MRI.hasOneNonDBGUse(NegSizeReg))
11329     ProbeOpc =
11330         isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_64 : PPC::PREPARE_PROBED_ALLOCA_32;
11331   else
11332     // By introducing PREPARE_PROBED_ALLOCA_NEGSIZE_OPT, ActualNegSizeReg
11333     // and NegSizeReg will be allocated in the same phyreg to avoid
11334     // redundant copy when NegSizeReg has only one use which is current MI and
11335     // will be replaced by PREPARE_PROBED_ALLOCA then.
11336     ProbeOpc = isPPC64 ? PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_64
11337                        : PPC::PREPARE_PROBED_ALLOCA_NEGSIZE_SAME_REG_32;
11338   BuildMI(*MBB, {MI}, DL, TII->get(ProbeOpc), FramePointer)
11339       .addDef(ActualNegSizeReg)
11340       .addReg(NegSizeReg)
11341       .add(MI.getOperand(2))
11342       .add(MI.getOperand(3));
11343 
11344   // Calculate final stack pointer, which equals to SP + ActualNegSize.
11345   BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4),
11346           FinalStackPtr)
11347       .addReg(SPReg)
11348       .addReg(ActualNegSizeReg);
11349 
11350   // Materialize a scratch register for update.
11351   int64_t NegProbeSize = -(int64_t)ProbeSize;
11352   assert(isInt<32>(NegProbeSize) && "Unhandled probe size!");
11353   Register ScratchReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11354   if (!isInt<16>(NegProbeSize)) {
11355     Register TempReg = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11356     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LIS8 : PPC::LIS), TempReg)
11357         .addImm(NegProbeSize >> 16);
11358     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::ORI8 : PPC::ORI),
11359             ScratchReg)
11360         .addReg(TempReg)
11361         .addImm(NegProbeSize & 0xFFFF);
11362   } else
11363     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::LI8 : PPC::LI), ScratchReg)
11364         .addImm(NegProbeSize);
11365 
11366   {
11367     // Probing leading residual part.
11368     Register Div = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11369     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::DIVD : PPC::DIVW), Div)
11370         .addReg(ActualNegSizeReg)
11371         .addReg(ScratchReg);
11372     Register Mul = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11373     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::MULLD : PPC::MULLW), Mul)
11374         .addReg(Div)
11375         .addReg(ScratchReg);
11376     Register NegMod = MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11377     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::SUBF8 : PPC::SUBF), NegMod)
11378         .addReg(Mul)
11379         .addReg(ActualNegSizeReg);
11380     BuildMI(*MBB, {MI}, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11381         .addReg(FramePointer)
11382         .addReg(SPReg)
11383         .addReg(NegMod);
11384   }
11385 
11386   {
11387     // Remaining part should be multiple of ProbeSize.
11388     Register CmpResult = MRI.createVirtualRegister(&PPC::CRRCRegClass);
11389     BuildMI(TestMBB, DL, TII->get(isPPC64 ? PPC::CMPD : PPC::CMPW), CmpResult)
11390         .addReg(SPReg)
11391         .addReg(FinalStackPtr);
11392     BuildMI(TestMBB, DL, TII->get(PPC::BCC))
11393         .addImm(PPC::PRED_EQ)
11394         .addReg(CmpResult)
11395         .addMBB(TailMBB);
11396     TestMBB->addSuccessor(BlockMBB);
11397     TestMBB->addSuccessor(TailMBB);
11398   }
11399 
11400   {
11401     // Touch the block.
11402     // |P...|P...|P...
11403     BuildMI(BlockMBB, DL, TII->get(isPPC64 ? PPC::STDUX : PPC::STWUX), SPReg)
11404         .addReg(FramePointer)
11405         .addReg(SPReg)
11406         .addReg(ScratchReg);
11407     BuildMI(BlockMBB, DL, TII->get(PPC::B)).addMBB(TestMBB);
11408     BlockMBB->addSuccessor(TestMBB);
11409   }
11410 
11411   // Calculation of MaxCallFrameSize is deferred to prologepilog, use
11412   // DYNAREAOFFSET pseudo instruction to get the future result.
11413   Register MaxCallFrameSizeReg =
11414       MRI.createVirtualRegister(isPPC64 ? G8RC : GPRC);
11415   BuildMI(TailMBB, DL,
11416           TII->get(isPPC64 ? PPC::DYNAREAOFFSET8 : PPC::DYNAREAOFFSET),
11417           MaxCallFrameSizeReg)
11418       .add(MI.getOperand(2))
11419       .add(MI.getOperand(3));
11420   BuildMI(TailMBB, DL, TII->get(isPPC64 ? PPC::ADD8 : PPC::ADD4), DstReg)
11421       .addReg(SPReg)
11422       .addReg(MaxCallFrameSizeReg);
11423 
11424   // Splice instructions after MI to TailMBB.
11425   TailMBB->splice(TailMBB->end(), MBB,
11426                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
11427   TailMBB->transferSuccessorsAndUpdatePHIs(MBB);
11428   MBB->addSuccessor(TestMBB);
11429 
11430   // Delete the pseudo instruction.
11431   MI.eraseFromParent();
11432 
11433   ++NumDynamicAllocaProbed;
11434   return TailMBB;
11435 }
11436 
11437 MachineBasicBlock *
11438 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11439                                                MachineBasicBlock *BB) const {
11440   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11441       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11442     if (Subtarget.is64BitELFABI() &&
11443         MI.getOpcode() == TargetOpcode::PATCHPOINT &&
11444         !Subtarget.isUsingPCRelativeCalls()) {
11445       // Call lowering should have added an r2 operand to indicate a dependence
11446       // on the TOC base pointer value. It can't however, because there is no
11447       // way to mark the dependence as implicit there, and so the stackmap code
11448       // will confuse it with a regular operand. Instead, add the dependence
11449       // here.
11450       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11451     }
11452 
11453     return emitPatchPoint(MI, BB);
11454   }
11455 
11456   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11457       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11458     return emitEHSjLjSetJmp(MI, BB);
11459   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11460              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11461     return emitEHSjLjLongJmp(MI, BB);
11462   }
11463 
11464   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11465 
11466   // To "insert" these instructions we actually have to insert their
11467   // control-flow patterns.
11468   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11469   MachineFunction::iterator It = ++BB->getIterator();
11470 
11471   MachineFunction *F = BB->getParent();
11472 
11473   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11474       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11475       MI.getOpcode() == PPC::SELECT_I8) {
11476     SmallVector<MachineOperand, 2> Cond;
11477     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11478         MI.getOpcode() == PPC::SELECT_CC_I8)
11479       Cond.push_back(MI.getOperand(4));
11480     else
11481       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11482     Cond.push_back(MI.getOperand(1));
11483 
11484     DebugLoc dl = MI.getDebugLoc();
11485     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11486                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11487   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11488              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11489              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11490              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11491              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11492              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11493              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11494              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11495              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11496              MI.getOpcode() == PPC::SELECT_F4 ||
11497              MI.getOpcode() == PPC::SELECT_F8 ||
11498              MI.getOpcode() == PPC::SELECT_F16 ||
11499              MI.getOpcode() == PPC::SELECT_SPE ||
11500              MI.getOpcode() == PPC::SELECT_SPE4 ||
11501              MI.getOpcode() == PPC::SELECT_VRRC ||
11502              MI.getOpcode() == PPC::SELECT_VSFRC ||
11503              MI.getOpcode() == PPC::SELECT_VSSRC ||
11504              MI.getOpcode() == PPC::SELECT_VSRC) {
11505     // The incoming instruction knows the destination vreg to set, the
11506     // condition code register to branch on, the true/false values to
11507     // select between, and a branch opcode to use.
11508 
11509     //  thisMBB:
11510     //  ...
11511     //   TrueVal = ...
11512     //   cmpTY ccX, r1, r2
11513     //   bCC copy1MBB
11514     //   fallthrough --> copy0MBB
11515     MachineBasicBlock *thisMBB = BB;
11516     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11517     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11518     DebugLoc dl = MI.getDebugLoc();
11519     F->insert(It, copy0MBB);
11520     F->insert(It, sinkMBB);
11521 
11522     // Transfer the remainder of BB and its successor edges to sinkMBB.
11523     sinkMBB->splice(sinkMBB->begin(), BB,
11524                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11525     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11526 
11527     // Next, add the true and fallthrough blocks as its successors.
11528     BB->addSuccessor(copy0MBB);
11529     BB->addSuccessor(sinkMBB);
11530 
11531     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11532         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11533         MI.getOpcode() == PPC::SELECT_F16 ||
11534         MI.getOpcode() == PPC::SELECT_SPE4 ||
11535         MI.getOpcode() == PPC::SELECT_SPE ||
11536         MI.getOpcode() == PPC::SELECT_VRRC ||
11537         MI.getOpcode() == PPC::SELECT_VSFRC ||
11538         MI.getOpcode() == PPC::SELECT_VSSRC ||
11539         MI.getOpcode() == PPC::SELECT_VSRC) {
11540       BuildMI(BB, dl, TII->get(PPC::BC))
11541           .addReg(MI.getOperand(1).getReg())
11542           .addMBB(sinkMBB);
11543     } else {
11544       unsigned SelectPred = MI.getOperand(4).getImm();
11545       BuildMI(BB, dl, TII->get(PPC::BCC))
11546           .addImm(SelectPred)
11547           .addReg(MI.getOperand(1).getReg())
11548           .addMBB(sinkMBB);
11549     }
11550 
11551     //  copy0MBB:
11552     //   %FalseValue = ...
11553     //   # fallthrough to sinkMBB
11554     BB = copy0MBB;
11555 
11556     // Update machine-CFG edges
11557     BB->addSuccessor(sinkMBB);
11558 
11559     //  sinkMBB:
11560     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11561     //  ...
11562     BB = sinkMBB;
11563     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11564         .addReg(MI.getOperand(3).getReg())
11565         .addMBB(copy0MBB)
11566         .addReg(MI.getOperand(2).getReg())
11567         .addMBB(thisMBB);
11568   } else if (MI.getOpcode() == PPC::ReadTB) {
11569     // To read the 64-bit time-base register on a 32-bit target, we read the
11570     // two halves. Should the counter have wrapped while it was being read, we
11571     // need to try again.
11572     // ...
11573     // readLoop:
11574     // mfspr Rx,TBU # load from TBU
11575     // mfspr Ry,TB  # load from TB
11576     // mfspr Rz,TBU # load from TBU
11577     // cmpw crX,Rx,Rz # check if 'old'='new'
11578     // bne readLoop   # branch if they're not equal
11579     // ...
11580 
11581     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11582     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11583     DebugLoc dl = MI.getDebugLoc();
11584     F->insert(It, readMBB);
11585     F->insert(It, sinkMBB);
11586 
11587     // Transfer the remainder of BB and its successor edges to sinkMBB.
11588     sinkMBB->splice(sinkMBB->begin(), BB,
11589                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11590     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11591 
11592     BB->addSuccessor(readMBB);
11593     BB = readMBB;
11594 
11595     MachineRegisterInfo &RegInfo = F->getRegInfo();
11596     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11597     Register LoReg = MI.getOperand(0).getReg();
11598     Register HiReg = MI.getOperand(1).getReg();
11599 
11600     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11601     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11602     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11603 
11604     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11605 
11606     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11607         .addReg(HiReg)
11608         .addReg(ReadAgainReg);
11609     BuildMI(BB, dl, TII->get(PPC::BCC))
11610         .addImm(PPC::PRED_NE)
11611         .addReg(CmpReg)
11612         .addMBB(readMBB);
11613 
11614     BB->addSuccessor(readMBB);
11615     BB->addSuccessor(sinkMBB);
11616   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11617     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11618   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11619     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11620   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11621     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11622   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11623     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11624 
11625   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11626     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11627   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11628     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11629   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11630     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11631   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11632     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11633 
11634   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11635     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11636   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11637     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11638   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11639     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11640   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11641     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11642 
11643   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11644     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11645   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11646     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11647   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11648     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11649   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11650     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11651 
11652   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11653     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11654   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11655     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11656   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11657     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11658   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11659     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11660 
11661   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11662     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11663   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11664     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11665   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11666     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11667   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11668     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11669 
11670   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11671     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11672   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11673     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11674   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11675     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11676   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11677     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11678 
11679   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11680     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11681   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11682     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11683   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11684     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11685   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11686     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11687 
11688   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11689     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11690   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11691     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11692   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11693     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11694   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11695     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11696 
11697   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11698     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11699   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11700     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11701   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11702     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11703   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11704     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11705 
11706   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11707     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11708   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11709     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11710   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11711     BB = EmitAtomicBinary(MI, BB, 4, 0);
11712   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11713     BB = EmitAtomicBinary(MI, BB, 8, 0);
11714   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11715            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11716            (Subtarget.hasPartwordAtomics() &&
11717             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11718            (Subtarget.hasPartwordAtomics() &&
11719             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11720     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11721 
11722     auto LoadMnemonic = PPC::LDARX;
11723     auto StoreMnemonic = PPC::STDCX;
11724     switch (MI.getOpcode()) {
11725     default:
11726       llvm_unreachable("Compare and swap of unknown size");
11727     case PPC::ATOMIC_CMP_SWAP_I8:
11728       LoadMnemonic = PPC::LBARX;
11729       StoreMnemonic = PPC::STBCX;
11730       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11731       break;
11732     case PPC::ATOMIC_CMP_SWAP_I16:
11733       LoadMnemonic = PPC::LHARX;
11734       StoreMnemonic = PPC::STHCX;
11735       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11736       break;
11737     case PPC::ATOMIC_CMP_SWAP_I32:
11738       LoadMnemonic = PPC::LWARX;
11739       StoreMnemonic = PPC::STWCX;
11740       break;
11741     case PPC::ATOMIC_CMP_SWAP_I64:
11742       LoadMnemonic = PPC::LDARX;
11743       StoreMnemonic = PPC::STDCX;
11744       break;
11745     }
11746     Register dest = MI.getOperand(0).getReg();
11747     Register ptrA = MI.getOperand(1).getReg();
11748     Register ptrB = MI.getOperand(2).getReg();
11749     Register oldval = MI.getOperand(3).getReg();
11750     Register newval = MI.getOperand(4).getReg();
11751     DebugLoc dl = MI.getDebugLoc();
11752 
11753     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11754     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11755     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11756     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11757     F->insert(It, loop1MBB);
11758     F->insert(It, loop2MBB);
11759     F->insert(It, midMBB);
11760     F->insert(It, exitMBB);
11761     exitMBB->splice(exitMBB->begin(), BB,
11762                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11763     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11764 
11765     //  thisMBB:
11766     //   ...
11767     //   fallthrough --> loopMBB
11768     BB->addSuccessor(loop1MBB);
11769 
11770     // loop1MBB:
11771     //   l[bhwd]arx dest, ptr
11772     //   cmp[wd] dest, oldval
11773     //   bne- midMBB
11774     // loop2MBB:
11775     //   st[bhwd]cx. newval, ptr
11776     //   bne- loopMBB
11777     //   b exitBB
11778     // midMBB:
11779     //   st[bhwd]cx. dest, ptr
11780     // exitBB:
11781     BB = loop1MBB;
11782     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11783     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11784         .addReg(oldval)
11785         .addReg(dest);
11786     BuildMI(BB, dl, TII->get(PPC::BCC))
11787         .addImm(PPC::PRED_NE)
11788         .addReg(PPC::CR0)
11789         .addMBB(midMBB);
11790     BB->addSuccessor(loop2MBB);
11791     BB->addSuccessor(midMBB);
11792 
11793     BB = loop2MBB;
11794     BuildMI(BB, dl, TII->get(StoreMnemonic))
11795         .addReg(newval)
11796         .addReg(ptrA)
11797         .addReg(ptrB);
11798     BuildMI(BB, dl, TII->get(PPC::BCC))
11799         .addImm(PPC::PRED_NE)
11800         .addReg(PPC::CR0)
11801         .addMBB(loop1MBB);
11802     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11803     BB->addSuccessor(loop1MBB);
11804     BB->addSuccessor(exitMBB);
11805 
11806     BB = midMBB;
11807     BuildMI(BB, dl, TII->get(StoreMnemonic))
11808         .addReg(dest)
11809         .addReg(ptrA)
11810         .addReg(ptrB);
11811     BB->addSuccessor(exitMBB);
11812 
11813     //  exitMBB:
11814     //   ...
11815     BB = exitMBB;
11816   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11817              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11818     // We must use 64-bit registers for addresses when targeting 64-bit,
11819     // since we're actually doing arithmetic on them.  Other registers
11820     // can be 32-bit.
11821     bool is64bit = Subtarget.isPPC64();
11822     bool isLittleEndian = Subtarget.isLittleEndian();
11823     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11824 
11825     Register dest = MI.getOperand(0).getReg();
11826     Register ptrA = MI.getOperand(1).getReg();
11827     Register ptrB = MI.getOperand(2).getReg();
11828     Register oldval = MI.getOperand(3).getReg();
11829     Register newval = MI.getOperand(4).getReg();
11830     DebugLoc dl = MI.getDebugLoc();
11831 
11832     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11833     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11834     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11835     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11836     F->insert(It, loop1MBB);
11837     F->insert(It, loop2MBB);
11838     F->insert(It, midMBB);
11839     F->insert(It, exitMBB);
11840     exitMBB->splice(exitMBB->begin(), BB,
11841                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11842     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11843 
11844     MachineRegisterInfo &RegInfo = F->getRegInfo();
11845     const TargetRegisterClass *RC =
11846         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11847     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11848 
11849     Register PtrReg = RegInfo.createVirtualRegister(RC);
11850     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11851     Register ShiftReg =
11852         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11853     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11854     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11855     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11856     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11857     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11858     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11859     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11860     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11861     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11862     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11863     Register Ptr1Reg;
11864     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11865     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11866     //  thisMBB:
11867     //   ...
11868     //   fallthrough --> loopMBB
11869     BB->addSuccessor(loop1MBB);
11870 
11871     // The 4-byte load must be aligned, while a char or short may be
11872     // anywhere in the word.  Hence all this nasty bookkeeping code.
11873     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11874     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11875     //   xori shift, shift1, 24 [16]
11876     //   rlwinm ptr, ptr1, 0, 0, 29
11877     //   slw newval2, newval, shift
11878     //   slw oldval2, oldval,shift
11879     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11880     //   slw mask, mask2, shift
11881     //   and newval3, newval2, mask
11882     //   and oldval3, oldval2, mask
11883     // loop1MBB:
11884     //   lwarx tmpDest, ptr
11885     //   and tmp, tmpDest, mask
11886     //   cmpw tmp, oldval3
11887     //   bne- midMBB
11888     // loop2MBB:
11889     //   andc tmp2, tmpDest, mask
11890     //   or tmp4, tmp2, newval3
11891     //   stwcx. tmp4, ptr
11892     //   bne- loop1MBB
11893     //   b exitBB
11894     // midMBB:
11895     //   stwcx. tmpDest, ptr
11896     // exitBB:
11897     //   srw dest, tmpDest, shift
11898     if (ptrA != ZeroReg) {
11899       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11900       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11901           .addReg(ptrA)
11902           .addReg(ptrB);
11903     } else {
11904       Ptr1Reg = ptrB;
11905     }
11906 
11907     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11908     // mode.
11909     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11910         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11911         .addImm(3)
11912         .addImm(27)
11913         .addImm(is8bit ? 28 : 27);
11914     if (!isLittleEndian)
11915       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11916           .addReg(Shift1Reg)
11917           .addImm(is8bit ? 24 : 16);
11918     if (is64bit)
11919       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11920           .addReg(Ptr1Reg)
11921           .addImm(0)
11922           .addImm(61);
11923     else
11924       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11925           .addReg(Ptr1Reg)
11926           .addImm(0)
11927           .addImm(0)
11928           .addImm(29);
11929     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11930         .addReg(newval)
11931         .addReg(ShiftReg);
11932     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11933         .addReg(oldval)
11934         .addReg(ShiftReg);
11935     if (is8bit)
11936       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11937     else {
11938       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11939       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11940           .addReg(Mask3Reg)
11941           .addImm(65535);
11942     }
11943     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11944         .addReg(Mask2Reg)
11945         .addReg(ShiftReg);
11946     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11947         .addReg(NewVal2Reg)
11948         .addReg(MaskReg);
11949     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11950         .addReg(OldVal2Reg)
11951         .addReg(MaskReg);
11952 
11953     BB = loop1MBB;
11954     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11955         .addReg(ZeroReg)
11956         .addReg(PtrReg);
11957     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11958         .addReg(TmpDestReg)
11959         .addReg(MaskReg);
11960     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11961         .addReg(TmpReg)
11962         .addReg(OldVal3Reg);
11963     BuildMI(BB, dl, TII->get(PPC::BCC))
11964         .addImm(PPC::PRED_NE)
11965         .addReg(PPC::CR0)
11966         .addMBB(midMBB);
11967     BB->addSuccessor(loop2MBB);
11968     BB->addSuccessor(midMBB);
11969 
11970     BB = loop2MBB;
11971     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11972         .addReg(TmpDestReg)
11973         .addReg(MaskReg);
11974     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11975         .addReg(Tmp2Reg)
11976         .addReg(NewVal3Reg);
11977     BuildMI(BB, dl, TII->get(PPC::STWCX))
11978         .addReg(Tmp4Reg)
11979         .addReg(ZeroReg)
11980         .addReg(PtrReg);
11981     BuildMI(BB, dl, TII->get(PPC::BCC))
11982         .addImm(PPC::PRED_NE)
11983         .addReg(PPC::CR0)
11984         .addMBB(loop1MBB);
11985     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11986     BB->addSuccessor(loop1MBB);
11987     BB->addSuccessor(exitMBB);
11988 
11989     BB = midMBB;
11990     BuildMI(BB, dl, TII->get(PPC::STWCX))
11991         .addReg(TmpDestReg)
11992         .addReg(ZeroReg)
11993         .addReg(PtrReg);
11994     BB->addSuccessor(exitMBB);
11995 
11996     //  exitMBB:
11997     //   ...
11998     BB = exitMBB;
11999     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
12000         .addReg(TmpReg)
12001         .addReg(ShiftReg);
12002   } else if (MI.getOpcode() == PPC::FADDrtz) {
12003     // This pseudo performs an FADD with rounding mode temporarily forced
12004     // to round-to-zero.  We emit this via custom inserter since the FPSCR
12005     // is not modeled at the SelectionDAG level.
12006     Register Dest = MI.getOperand(0).getReg();
12007     Register Src1 = MI.getOperand(1).getReg();
12008     Register Src2 = MI.getOperand(2).getReg();
12009     DebugLoc dl = MI.getDebugLoc();
12010 
12011     MachineRegisterInfo &RegInfo = F->getRegInfo();
12012     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12013 
12014     // Save FPSCR value.
12015     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
12016 
12017     // Set rounding mode to round-to-zero.
12018     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1))
12019         .addImm(31)
12020         .addReg(PPC::RM, RegState::ImplicitDefine);
12021 
12022     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0))
12023         .addImm(30)
12024         .addReg(PPC::RM, RegState::ImplicitDefine);
12025 
12026     // Perform addition.
12027     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
12028 
12029     // Restore FPSCR value.
12030     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
12031   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12032              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
12033              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12034              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
12035     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
12036                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
12037                           ? PPC::ANDI8_rec
12038                           : PPC::ANDI_rec;
12039     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
12040                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
12041 
12042     MachineRegisterInfo &RegInfo = F->getRegInfo();
12043     Register Dest = RegInfo.createVirtualRegister(
12044         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
12045 
12046     DebugLoc Dl = MI.getDebugLoc();
12047     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
12048         .addReg(MI.getOperand(1).getReg())
12049         .addImm(1);
12050     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12051             MI.getOperand(0).getReg())
12052         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
12053   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
12054     DebugLoc Dl = MI.getDebugLoc();
12055     MachineRegisterInfo &RegInfo = F->getRegInfo();
12056     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
12057     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
12058     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12059             MI.getOperand(0).getReg())
12060         .addReg(CRReg);
12061   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
12062     DebugLoc Dl = MI.getDebugLoc();
12063     unsigned Imm = MI.getOperand(1).getImm();
12064     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
12065     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
12066             MI.getOperand(0).getReg())
12067         .addReg(PPC::CR0EQ);
12068   } else if (MI.getOpcode() == PPC::SETRNDi) {
12069     DebugLoc dl = MI.getDebugLoc();
12070     Register OldFPSCRReg = MI.getOperand(0).getReg();
12071 
12072     // Save FPSCR value.
12073     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12074 
12075     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
12076     // the following settings:
12077     //   00 Round to nearest
12078     //   01 Round to 0
12079     //   10 Round to +inf
12080     //   11 Round to -inf
12081 
12082     // When the operand is immediate, using the two least significant bits of
12083     // the immediate to set the bits 62:63 of FPSCR.
12084     unsigned Mode = MI.getOperand(1).getImm();
12085     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
12086         .addImm(31)
12087         .addReg(PPC::RM, RegState::ImplicitDefine);
12088 
12089     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
12090         .addImm(30)
12091         .addReg(PPC::RM, RegState::ImplicitDefine);
12092   } else if (MI.getOpcode() == PPC::SETRND) {
12093     DebugLoc dl = MI.getDebugLoc();
12094 
12095     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
12096     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
12097     // If the target doesn't have DirectMove, we should use stack to do the
12098     // conversion, because the target doesn't have the instructions like mtvsrd
12099     // or mfvsrd to do this conversion directly.
12100     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
12101       if (Subtarget.hasDirectMove()) {
12102         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
12103           .addReg(SrcReg);
12104       } else {
12105         // Use stack to do the register copy.
12106         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
12107         MachineRegisterInfo &RegInfo = F->getRegInfo();
12108         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
12109         if (RC == &PPC::F8RCRegClass) {
12110           // Copy register from F8RCRegClass to G8RCRegclass.
12111           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
12112                  "Unsupported RegClass.");
12113 
12114           StoreOp = PPC::STFD;
12115           LoadOp = PPC::LD;
12116         } else {
12117           // Copy register from G8RCRegClass to F8RCRegclass.
12118           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
12119                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
12120                  "Unsupported RegClass.");
12121         }
12122 
12123         MachineFrameInfo &MFI = F->getFrameInfo();
12124         int FrameIdx = MFI.CreateStackObject(8, Align(8), false);
12125 
12126         MachineMemOperand *MMOStore = F->getMachineMemOperand(
12127             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12128             MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
12129             MFI.getObjectAlign(FrameIdx));
12130 
12131         // Store the SrcReg into the stack.
12132         BuildMI(*BB, MI, dl, TII->get(StoreOp))
12133           .addReg(SrcReg)
12134           .addImm(0)
12135           .addFrameIndex(FrameIdx)
12136           .addMemOperand(MMOStore);
12137 
12138         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
12139             MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
12140             MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
12141             MFI.getObjectAlign(FrameIdx));
12142 
12143         // Load from the stack where SrcReg is stored, and save to DestReg,
12144         // so we have done the RegClass conversion from RegClass::SrcReg to
12145         // RegClass::DestReg.
12146         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
12147           .addImm(0)
12148           .addFrameIndex(FrameIdx)
12149           .addMemOperand(MMOLoad);
12150       }
12151     };
12152 
12153     Register OldFPSCRReg = MI.getOperand(0).getReg();
12154 
12155     // Save FPSCR value.
12156     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
12157 
12158     // When the operand is gprc register, use two least significant bits of the
12159     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
12160     //
12161     // copy OldFPSCRTmpReg, OldFPSCRReg
12162     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
12163     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
12164     // copy NewFPSCRReg, NewFPSCRTmpReg
12165     // mtfsf 255, NewFPSCRReg
12166     MachineOperand SrcOp = MI.getOperand(1);
12167     MachineRegisterInfo &RegInfo = F->getRegInfo();
12168     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12169 
12170     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
12171 
12172     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12173     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12174 
12175     // The first operand of INSERT_SUBREG should be a register which has
12176     // subregisters, we only care about its RegClass, so we should use an
12177     // IMPLICIT_DEF register.
12178     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
12179     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
12180       .addReg(ImDefReg)
12181       .add(SrcOp)
12182       .addImm(1);
12183 
12184     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
12185     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
12186       .addReg(OldFPSCRTmpReg)
12187       .addReg(ExtSrcReg)
12188       .addImm(0)
12189       .addImm(62);
12190 
12191     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
12192     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
12193 
12194     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
12195     // bits of FPSCR.
12196     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
12197       .addImm(255)
12198       .addReg(NewFPSCRReg)
12199       .addImm(0)
12200       .addImm(0);
12201   } else if (MI.getOpcode() == PPC::SETFLM) {
12202     DebugLoc Dl = MI.getDebugLoc();
12203 
12204     // Result of setflm is previous FPSCR content, so we need to save it first.
12205     Register OldFPSCRReg = MI.getOperand(0).getReg();
12206     BuildMI(*BB, MI, Dl, TII->get(PPC::MFFS), OldFPSCRReg);
12207 
12208     // Put bits in 32:63 to FPSCR.
12209     Register NewFPSCRReg = MI.getOperand(1).getReg();
12210     BuildMI(*BB, MI, Dl, TII->get(PPC::MTFSF))
12211         .addImm(255)
12212         .addReg(NewFPSCRReg)
12213         .addImm(0)
12214         .addImm(0);
12215   } else if (MI.getOpcode() == PPC::PROBED_ALLOCA_32 ||
12216              MI.getOpcode() == PPC::PROBED_ALLOCA_64) {
12217     return emitProbedAlloca(MI, BB);
12218   } else {
12219     llvm_unreachable("Unexpected instr type to insert");
12220   }
12221 
12222   MI.eraseFromParent(); // The pseudo instruction is gone now.
12223   return BB;
12224 }
12225 
12226 //===----------------------------------------------------------------------===//
12227 // Target Optimization Hooks
12228 //===----------------------------------------------------------------------===//
12229 
12230 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
12231   // For the estimates, convergence is quadratic, so we essentially double the
12232   // number of digits correct after every iteration. For both FRE and FRSQRTE,
12233   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
12234   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
12235   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
12236   if (VT.getScalarType() == MVT::f64)
12237     RefinementSteps++;
12238   return RefinementSteps;
12239 }
12240 
12241 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
12242                                            int Enabled, int &RefinementSteps,
12243                                            bool &UseOneConstNR,
12244                                            bool Reciprocal) const {
12245   EVT VT = Operand.getValueType();
12246   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
12247       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
12248       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12249       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12250     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12251       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12252 
12253     // The Newton-Raphson computation with a single constant does not provide
12254     // enough accuracy on some CPUs.
12255     UseOneConstNR = !Subtarget.needsTwoConstNR();
12256     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
12257   }
12258   return SDValue();
12259 }
12260 
12261 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
12262                                             int Enabled,
12263                                             int &RefinementSteps) const {
12264   EVT VT = Operand.getValueType();
12265   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
12266       (VT == MVT::f64 && Subtarget.hasFRE()) ||
12267       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
12268       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
12269     if (RefinementSteps == ReciprocalEstimate::Unspecified)
12270       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
12271     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
12272   }
12273   return SDValue();
12274 }
12275 
12276 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
12277   // Note: This functionality is used only when unsafe-fp-math is enabled, and
12278   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
12279   // enabled for division), this functionality is redundant with the default
12280   // combiner logic (once the division -> reciprocal/multiply transformation
12281   // has taken place). As a result, this matters more for older cores than for
12282   // newer ones.
12283 
12284   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
12285   // reciprocal if there are two or more FDIVs (for embedded cores with only
12286   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
12287   switch (Subtarget.getCPUDirective()) {
12288   default:
12289     return 3;
12290   case PPC::DIR_440:
12291   case PPC::DIR_A2:
12292   case PPC::DIR_E500:
12293   case PPC::DIR_E500mc:
12294   case PPC::DIR_E5500:
12295     return 2;
12296   }
12297 }
12298 
12299 // isConsecutiveLSLoc needs to work even if all adds have not yet been
12300 // collapsed, and so we need to look through chains of them.
12301 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
12302                                      int64_t& Offset, SelectionDAG &DAG) {
12303   if (DAG.isBaseWithConstantOffset(Loc)) {
12304     Base = Loc.getOperand(0);
12305     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
12306 
12307     // The base might itself be a base plus an offset, and if so, accumulate
12308     // that as well.
12309     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
12310   }
12311 }
12312 
12313 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
12314                             unsigned Bytes, int Dist,
12315                             SelectionDAG &DAG) {
12316   if (VT.getSizeInBits() / 8 != Bytes)
12317     return false;
12318 
12319   SDValue BaseLoc = Base->getBasePtr();
12320   if (Loc.getOpcode() == ISD::FrameIndex) {
12321     if (BaseLoc.getOpcode() != ISD::FrameIndex)
12322       return false;
12323     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
12324     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
12325     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
12326     int FS  = MFI.getObjectSize(FI);
12327     int BFS = MFI.getObjectSize(BFI);
12328     if (FS != BFS || FS != (int)Bytes) return false;
12329     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
12330   }
12331 
12332   SDValue Base1 = Loc, Base2 = BaseLoc;
12333   int64_t Offset1 = 0, Offset2 = 0;
12334   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12335   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12336   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12337     return true;
12338 
12339   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12340   const GlobalValue *GV1 = nullptr;
12341   const GlobalValue *GV2 = nullptr;
12342   Offset1 = 0;
12343   Offset2 = 0;
12344   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12345   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12346   if (isGA1 && isGA2 && GV1 == GV2)
12347     return Offset1 == (Offset2 + Dist*Bytes);
12348   return false;
12349 }
12350 
12351 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12352 // not enforce equality of the chain operands.
12353 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12354                             unsigned Bytes, int Dist,
12355                             SelectionDAG &DAG) {
12356   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12357     EVT VT = LS->getMemoryVT();
12358     SDValue Loc = LS->getBasePtr();
12359     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12360   }
12361 
12362   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12363     EVT VT;
12364     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12365     default: return false;
12366     case Intrinsic::ppc_altivec_lvx:
12367     case Intrinsic::ppc_altivec_lvxl:
12368     case Intrinsic::ppc_vsx_lxvw4x:
12369     case Intrinsic::ppc_vsx_lxvw4x_be:
12370       VT = MVT::v4i32;
12371       break;
12372     case Intrinsic::ppc_vsx_lxvd2x:
12373     case Intrinsic::ppc_vsx_lxvd2x_be:
12374       VT = MVT::v2f64;
12375       break;
12376     case Intrinsic::ppc_altivec_lvebx:
12377       VT = MVT::i8;
12378       break;
12379     case Intrinsic::ppc_altivec_lvehx:
12380       VT = MVT::i16;
12381       break;
12382     case Intrinsic::ppc_altivec_lvewx:
12383       VT = MVT::i32;
12384       break;
12385     }
12386 
12387     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12388   }
12389 
12390   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12391     EVT VT;
12392     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12393     default: return false;
12394     case Intrinsic::ppc_altivec_stvx:
12395     case Intrinsic::ppc_altivec_stvxl:
12396     case Intrinsic::ppc_vsx_stxvw4x:
12397       VT = MVT::v4i32;
12398       break;
12399     case Intrinsic::ppc_vsx_stxvd2x:
12400       VT = MVT::v2f64;
12401       break;
12402     case Intrinsic::ppc_vsx_stxvw4x_be:
12403       VT = MVT::v4i32;
12404       break;
12405     case Intrinsic::ppc_vsx_stxvd2x_be:
12406       VT = MVT::v2f64;
12407       break;
12408     case Intrinsic::ppc_altivec_stvebx:
12409       VT = MVT::i8;
12410       break;
12411     case Intrinsic::ppc_altivec_stvehx:
12412       VT = MVT::i16;
12413       break;
12414     case Intrinsic::ppc_altivec_stvewx:
12415       VT = MVT::i32;
12416       break;
12417     }
12418 
12419     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12420   }
12421 
12422   return false;
12423 }
12424 
12425 // Return true is there is a nearyby consecutive load to the one provided
12426 // (regardless of alignment). We search up and down the chain, looking though
12427 // token factors and other loads (but nothing else). As a result, a true result
12428 // indicates that it is safe to create a new consecutive load adjacent to the
12429 // load provided.
12430 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12431   SDValue Chain = LD->getChain();
12432   EVT VT = LD->getMemoryVT();
12433 
12434   SmallSet<SDNode *, 16> LoadRoots;
12435   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12436   SmallSet<SDNode *, 16> Visited;
12437 
12438   // First, search up the chain, branching to follow all token-factor operands.
12439   // If we find a consecutive load, then we're done, otherwise, record all
12440   // nodes just above the top-level loads and token factors.
12441   while (!Queue.empty()) {
12442     SDNode *ChainNext = Queue.pop_back_val();
12443     if (!Visited.insert(ChainNext).second)
12444       continue;
12445 
12446     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12447       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12448         return true;
12449 
12450       if (!Visited.count(ChainLD->getChain().getNode()))
12451         Queue.push_back(ChainLD->getChain().getNode());
12452     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12453       for (const SDUse &O : ChainNext->ops())
12454         if (!Visited.count(O.getNode()))
12455           Queue.push_back(O.getNode());
12456     } else
12457       LoadRoots.insert(ChainNext);
12458   }
12459 
12460   // Second, search down the chain, starting from the top-level nodes recorded
12461   // in the first phase. These top-level nodes are the nodes just above all
12462   // loads and token factors. Starting with their uses, recursively look though
12463   // all loads (just the chain uses) and token factors to find a consecutive
12464   // load.
12465   Visited.clear();
12466   Queue.clear();
12467 
12468   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12469        IE = LoadRoots.end(); I != IE; ++I) {
12470     Queue.push_back(*I);
12471 
12472     while (!Queue.empty()) {
12473       SDNode *LoadRoot = Queue.pop_back_val();
12474       if (!Visited.insert(LoadRoot).second)
12475         continue;
12476 
12477       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12478         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12479           return true;
12480 
12481       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12482            UE = LoadRoot->use_end(); UI != UE; ++UI)
12483         if (((isa<MemSDNode>(*UI) &&
12484             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12485             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12486           Queue.push_back(*UI);
12487     }
12488   }
12489 
12490   return false;
12491 }
12492 
12493 /// This function is called when we have proved that a SETCC node can be replaced
12494 /// by subtraction (and other supporting instructions) so that the result of
12495 /// comparison is kept in a GPR instead of CR. This function is purely for
12496 /// codegen purposes and has some flags to guide the codegen process.
12497 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12498                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12499   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12500 
12501   // Zero extend the operands to the largest legal integer. Originally, they
12502   // must be of a strictly smaller size.
12503   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12504                          DAG.getConstant(Size, DL, MVT::i32));
12505   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12506                          DAG.getConstant(Size, DL, MVT::i32));
12507 
12508   // Swap if needed. Depends on the condition code.
12509   if (Swap)
12510     std::swap(Op0, Op1);
12511 
12512   // Subtract extended integers.
12513   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12514 
12515   // Move the sign bit to the least significant position and zero out the rest.
12516   // Now the least significant bit carries the result of original comparison.
12517   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12518                              DAG.getConstant(Size - 1, DL, MVT::i32));
12519   auto Final = Shifted;
12520 
12521   // Complement the result if needed. Based on the condition code.
12522   if (Complement)
12523     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12524                         DAG.getConstant(1, DL, MVT::i64));
12525 
12526   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12527 }
12528 
12529 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12530                                                   DAGCombinerInfo &DCI) const {
12531   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12532 
12533   SelectionDAG &DAG = DCI.DAG;
12534   SDLoc DL(N);
12535 
12536   // Size of integers being compared has a critical role in the following
12537   // analysis, so we prefer to do this when all types are legal.
12538   if (!DCI.isAfterLegalizeDAG())
12539     return SDValue();
12540 
12541   // If all users of SETCC extend its value to a legal integer type
12542   // then we replace SETCC with a subtraction
12543   for (SDNode::use_iterator UI = N->use_begin(),
12544        UE = N->use_end(); UI != UE; ++UI) {
12545     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12546       return SDValue();
12547   }
12548 
12549   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12550   auto OpSize = N->getOperand(0).getValueSizeInBits();
12551 
12552   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12553 
12554   if (OpSize < Size) {
12555     switch (CC) {
12556     default: break;
12557     case ISD::SETULT:
12558       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12559     case ISD::SETULE:
12560       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12561     case ISD::SETUGT:
12562       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12563     case ISD::SETUGE:
12564       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12565     }
12566   }
12567 
12568   return SDValue();
12569 }
12570 
12571 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12572                                                   DAGCombinerInfo &DCI) const {
12573   SelectionDAG &DAG = DCI.DAG;
12574   SDLoc dl(N);
12575 
12576   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12577   // If we're tracking CR bits, we need to be careful that we don't have:
12578   //   trunc(binary-ops(zext(x), zext(y)))
12579   // or
12580   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12581   // such that we're unnecessarily moving things into GPRs when it would be
12582   // better to keep them in CR bits.
12583 
12584   // Note that trunc here can be an actual i1 trunc, or can be the effective
12585   // truncation that comes from a setcc or select_cc.
12586   if (N->getOpcode() == ISD::TRUNCATE &&
12587       N->getValueType(0) != MVT::i1)
12588     return SDValue();
12589 
12590   if (N->getOperand(0).getValueType() != MVT::i32 &&
12591       N->getOperand(0).getValueType() != MVT::i64)
12592     return SDValue();
12593 
12594   if (N->getOpcode() == ISD::SETCC ||
12595       N->getOpcode() == ISD::SELECT_CC) {
12596     // If we're looking at a comparison, then we need to make sure that the
12597     // high bits (all except for the first) don't matter the result.
12598     ISD::CondCode CC =
12599       cast<CondCodeSDNode>(N->getOperand(
12600         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12601     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12602 
12603     if (ISD::isSignedIntSetCC(CC)) {
12604       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12605           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12606         return SDValue();
12607     } else if (ISD::isUnsignedIntSetCC(CC)) {
12608       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12609                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12610           !DAG.MaskedValueIsZero(N->getOperand(1),
12611                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12612         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12613                                              : SDValue());
12614     } else {
12615       // This is neither a signed nor an unsigned comparison, just make sure
12616       // that the high bits are equal.
12617       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12618       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12619 
12620       // We don't really care about what is known about the first bit (if
12621       // anything), so clear it in all masks prior to comparing them.
12622       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12623       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12624 
12625       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12626         return SDValue();
12627     }
12628   }
12629 
12630   // We now know that the higher-order bits are irrelevant, we just need to
12631   // make sure that all of the intermediate operations are bit operations, and
12632   // all inputs are extensions.
12633   if (N->getOperand(0).getOpcode() != ISD::AND &&
12634       N->getOperand(0).getOpcode() != ISD::OR  &&
12635       N->getOperand(0).getOpcode() != ISD::XOR &&
12636       N->getOperand(0).getOpcode() != ISD::SELECT &&
12637       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12638       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12639       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12640       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12641       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12642     return SDValue();
12643 
12644   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12645       N->getOperand(1).getOpcode() != ISD::AND &&
12646       N->getOperand(1).getOpcode() != ISD::OR  &&
12647       N->getOperand(1).getOpcode() != ISD::XOR &&
12648       N->getOperand(1).getOpcode() != ISD::SELECT &&
12649       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12650       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12651       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12652       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12653       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12654     return SDValue();
12655 
12656   SmallVector<SDValue, 4> Inputs;
12657   SmallVector<SDValue, 8> BinOps, PromOps;
12658   SmallPtrSet<SDNode *, 16> Visited;
12659 
12660   for (unsigned i = 0; i < 2; ++i) {
12661     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12662           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12663           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12664           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12665         isa<ConstantSDNode>(N->getOperand(i)))
12666       Inputs.push_back(N->getOperand(i));
12667     else
12668       BinOps.push_back(N->getOperand(i));
12669 
12670     if (N->getOpcode() == ISD::TRUNCATE)
12671       break;
12672   }
12673 
12674   // Visit all inputs, collect all binary operations (and, or, xor and
12675   // select) that are all fed by extensions.
12676   while (!BinOps.empty()) {
12677     SDValue BinOp = BinOps.back();
12678     BinOps.pop_back();
12679 
12680     if (!Visited.insert(BinOp.getNode()).second)
12681       continue;
12682 
12683     PromOps.push_back(BinOp);
12684 
12685     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12686       // The condition of the select is not promoted.
12687       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12688         continue;
12689       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12690         continue;
12691 
12692       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12693             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12694             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12695            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12696           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12697         Inputs.push_back(BinOp.getOperand(i));
12698       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12699                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12700                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12701                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12702                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12703                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12704                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12705                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12706                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12707         BinOps.push_back(BinOp.getOperand(i));
12708       } else {
12709         // We have an input that is not an extension or another binary
12710         // operation; we'll abort this transformation.
12711         return SDValue();
12712       }
12713     }
12714   }
12715 
12716   // Make sure that this is a self-contained cluster of operations (which
12717   // is not quite the same thing as saying that everything has only one
12718   // use).
12719   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12720     if (isa<ConstantSDNode>(Inputs[i]))
12721       continue;
12722 
12723     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12724                               UE = Inputs[i].getNode()->use_end();
12725          UI != UE; ++UI) {
12726       SDNode *User = *UI;
12727       if (User != N && !Visited.count(User))
12728         return SDValue();
12729 
12730       // Make sure that we're not going to promote the non-output-value
12731       // operand(s) or SELECT or SELECT_CC.
12732       // FIXME: Although we could sometimes handle this, and it does occur in
12733       // practice that one of the condition inputs to the select is also one of
12734       // the outputs, we currently can't deal with this.
12735       if (User->getOpcode() == ISD::SELECT) {
12736         if (User->getOperand(0) == Inputs[i])
12737           return SDValue();
12738       } else if (User->getOpcode() == ISD::SELECT_CC) {
12739         if (User->getOperand(0) == Inputs[i] ||
12740             User->getOperand(1) == Inputs[i])
12741           return SDValue();
12742       }
12743     }
12744   }
12745 
12746   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12747     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12748                               UE = PromOps[i].getNode()->use_end();
12749          UI != UE; ++UI) {
12750       SDNode *User = *UI;
12751       if (User != N && !Visited.count(User))
12752         return SDValue();
12753 
12754       // Make sure that we're not going to promote the non-output-value
12755       // operand(s) or SELECT or SELECT_CC.
12756       // FIXME: Although we could sometimes handle this, and it does occur in
12757       // practice that one of the condition inputs to the select is also one of
12758       // the outputs, we currently can't deal with this.
12759       if (User->getOpcode() == ISD::SELECT) {
12760         if (User->getOperand(0) == PromOps[i])
12761           return SDValue();
12762       } else if (User->getOpcode() == ISD::SELECT_CC) {
12763         if (User->getOperand(0) == PromOps[i] ||
12764             User->getOperand(1) == PromOps[i])
12765           return SDValue();
12766       }
12767     }
12768   }
12769 
12770   // Replace all inputs with the extension operand.
12771   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12772     // Constants may have users outside the cluster of to-be-promoted nodes,
12773     // and so we need to replace those as we do the promotions.
12774     if (isa<ConstantSDNode>(Inputs[i]))
12775       continue;
12776     else
12777       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12778   }
12779 
12780   std::list<HandleSDNode> PromOpHandles;
12781   for (auto &PromOp : PromOps)
12782     PromOpHandles.emplace_back(PromOp);
12783 
12784   // Replace all operations (these are all the same, but have a different
12785   // (i1) return type). DAG.getNode will validate that the types of
12786   // a binary operator match, so go through the list in reverse so that
12787   // we've likely promoted both operands first. Any intermediate truncations or
12788   // extensions disappear.
12789   while (!PromOpHandles.empty()) {
12790     SDValue PromOp = PromOpHandles.back().getValue();
12791     PromOpHandles.pop_back();
12792 
12793     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12794         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12795         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12796         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12797       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12798           PromOp.getOperand(0).getValueType() != MVT::i1) {
12799         // The operand is not yet ready (see comment below).
12800         PromOpHandles.emplace_front(PromOp);
12801         continue;
12802       }
12803 
12804       SDValue RepValue = PromOp.getOperand(0);
12805       if (isa<ConstantSDNode>(RepValue))
12806         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12807 
12808       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12809       continue;
12810     }
12811 
12812     unsigned C;
12813     switch (PromOp.getOpcode()) {
12814     default:             C = 0; break;
12815     case ISD::SELECT:    C = 1; break;
12816     case ISD::SELECT_CC: C = 2; break;
12817     }
12818 
12819     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12820          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12821         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12822          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12823       // The to-be-promoted operands of this node have not yet been
12824       // promoted (this should be rare because we're going through the
12825       // list backward, but if one of the operands has several users in
12826       // this cluster of to-be-promoted nodes, it is possible).
12827       PromOpHandles.emplace_front(PromOp);
12828       continue;
12829     }
12830 
12831     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12832                                 PromOp.getNode()->op_end());
12833 
12834     // If there are any constant inputs, make sure they're replaced now.
12835     for (unsigned i = 0; i < 2; ++i)
12836       if (isa<ConstantSDNode>(Ops[C+i]))
12837         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12838 
12839     DAG.ReplaceAllUsesOfValueWith(PromOp,
12840       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12841   }
12842 
12843   // Now we're left with the initial truncation itself.
12844   if (N->getOpcode() == ISD::TRUNCATE)
12845     return N->getOperand(0);
12846 
12847   // Otherwise, this is a comparison. The operands to be compared have just
12848   // changed type (to i1), but everything else is the same.
12849   return SDValue(N, 0);
12850 }
12851 
12852 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12853                                                   DAGCombinerInfo &DCI) const {
12854   SelectionDAG &DAG = DCI.DAG;
12855   SDLoc dl(N);
12856 
12857   // If we're tracking CR bits, we need to be careful that we don't have:
12858   //   zext(binary-ops(trunc(x), trunc(y)))
12859   // or
12860   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12861   // such that we're unnecessarily moving things into CR bits that can more
12862   // efficiently stay in GPRs. Note that if we're not certain that the high
12863   // bits are set as required by the final extension, we still may need to do
12864   // some masking to get the proper behavior.
12865 
12866   // This same functionality is important on PPC64 when dealing with
12867   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12868   // the return values of functions. Because it is so similar, it is handled
12869   // here as well.
12870 
12871   if (N->getValueType(0) != MVT::i32 &&
12872       N->getValueType(0) != MVT::i64)
12873     return SDValue();
12874 
12875   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12876         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12877     return SDValue();
12878 
12879   if (N->getOperand(0).getOpcode() != ISD::AND &&
12880       N->getOperand(0).getOpcode() != ISD::OR  &&
12881       N->getOperand(0).getOpcode() != ISD::XOR &&
12882       N->getOperand(0).getOpcode() != ISD::SELECT &&
12883       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12884     return SDValue();
12885 
12886   SmallVector<SDValue, 4> Inputs;
12887   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12888   SmallPtrSet<SDNode *, 16> Visited;
12889 
12890   // Visit all inputs, collect all binary operations (and, or, xor and
12891   // select) that are all fed by truncations.
12892   while (!BinOps.empty()) {
12893     SDValue BinOp = BinOps.back();
12894     BinOps.pop_back();
12895 
12896     if (!Visited.insert(BinOp.getNode()).second)
12897       continue;
12898 
12899     PromOps.push_back(BinOp);
12900 
12901     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12902       // The condition of the select is not promoted.
12903       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12904         continue;
12905       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12906         continue;
12907 
12908       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12909           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12910         Inputs.push_back(BinOp.getOperand(i));
12911       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12912                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12913                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12914                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12915                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12916         BinOps.push_back(BinOp.getOperand(i));
12917       } else {
12918         // We have an input that is not a truncation or another binary
12919         // operation; we'll abort this transformation.
12920         return SDValue();
12921       }
12922     }
12923   }
12924 
12925   // The operands of a select that must be truncated when the select is
12926   // promoted because the operand is actually part of the to-be-promoted set.
12927   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12928 
12929   // Make sure that this is a self-contained cluster of operations (which
12930   // is not quite the same thing as saying that everything has only one
12931   // use).
12932   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12933     if (isa<ConstantSDNode>(Inputs[i]))
12934       continue;
12935 
12936     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12937                               UE = Inputs[i].getNode()->use_end();
12938          UI != UE; ++UI) {
12939       SDNode *User = *UI;
12940       if (User != N && !Visited.count(User))
12941         return SDValue();
12942 
12943       // If we're going to promote the non-output-value operand(s) or SELECT or
12944       // SELECT_CC, record them for truncation.
12945       if (User->getOpcode() == ISD::SELECT) {
12946         if (User->getOperand(0) == Inputs[i])
12947           SelectTruncOp[0].insert(std::make_pair(User,
12948                                     User->getOperand(0).getValueType()));
12949       } else if (User->getOpcode() == ISD::SELECT_CC) {
12950         if (User->getOperand(0) == Inputs[i])
12951           SelectTruncOp[0].insert(std::make_pair(User,
12952                                     User->getOperand(0).getValueType()));
12953         if (User->getOperand(1) == Inputs[i])
12954           SelectTruncOp[1].insert(std::make_pair(User,
12955                                     User->getOperand(1).getValueType()));
12956       }
12957     }
12958   }
12959 
12960   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12961     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12962                               UE = PromOps[i].getNode()->use_end();
12963          UI != UE; ++UI) {
12964       SDNode *User = *UI;
12965       if (User != N && !Visited.count(User))
12966         return SDValue();
12967 
12968       // If we're going to promote the non-output-value operand(s) or SELECT or
12969       // SELECT_CC, record them for truncation.
12970       if (User->getOpcode() == ISD::SELECT) {
12971         if (User->getOperand(0) == PromOps[i])
12972           SelectTruncOp[0].insert(std::make_pair(User,
12973                                     User->getOperand(0).getValueType()));
12974       } else if (User->getOpcode() == ISD::SELECT_CC) {
12975         if (User->getOperand(0) == PromOps[i])
12976           SelectTruncOp[0].insert(std::make_pair(User,
12977                                     User->getOperand(0).getValueType()));
12978         if (User->getOperand(1) == PromOps[i])
12979           SelectTruncOp[1].insert(std::make_pair(User,
12980                                     User->getOperand(1).getValueType()));
12981       }
12982     }
12983   }
12984 
12985   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12986   bool ReallyNeedsExt = false;
12987   if (N->getOpcode() != ISD::ANY_EXTEND) {
12988     // If all of the inputs are not already sign/zero extended, then
12989     // we'll still need to do that at the end.
12990     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12991       if (isa<ConstantSDNode>(Inputs[i]))
12992         continue;
12993 
12994       unsigned OpBits =
12995         Inputs[i].getOperand(0).getValueSizeInBits();
12996       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12997 
12998       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12999            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
13000                                   APInt::getHighBitsSet(OpBits,
13001                                                         OpBits-PromBits))) ||
13002           (N->getOpcode() == ISD::SIGN_EXTEND &&
13003            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
13004              (OpBits-(PromBits-1)))) {
13005         ReallyNeedsExt = true;
13006         break;
13007       }
13008     }
13009   }
13010 
13011   // Replace all inputs, either with the truncation operand, or a
13012   // truncation or extension to the final output type.
13013   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
13014     // Constant inputs need to be replaced with the to-be-promoted nodes that
13015     // use them because they might have users outside of the cluster of
13016     // promoted nodes.
13017     if (isa<ConstantSDNode>(Inputs[i]))
13018       continue;
13019 
13020     SDValue InSrc = Inputs[i].getOperand(0);
13021     if (Inputs[i].getValueType() == N->getValueType(0))
13022       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
13023     else if (N->getOpcode() == ISD::SIGN_EXTEND)
13024       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13025         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
13026     else if (N->getOpcode() == ISD::ZERO_EXTEND)
13027       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13028         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
13029     else
13030       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
13031         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
13032   }
13033 
13034   std::list<HandleSDNode> PromOpHandles;
13035   for (auto &PromOp : PromOps)
13036     PromOpHandles.emplace_back(PromOp);
13037 
13038   // Replace all operations (these are all the same, but have a different
13039   // (promoted) return type). DAG.getNode will validate that the types of
13040   // a binary operator match, so go through the list in reverse so that
13041   // we've likely promoted both operands first.
13042   while (!PromOpHandles.empty()) {
13043     SDValue PromOp = PromOpHandles.back().getValue();
13044     PromOpHandles.pop_back();
13045 
13046     unsigned C;
13047     switch (PromOp.getOpcode()) {
13048     default:             C = 0; break;
13049     case ISD::SELECT:    C = 1; break;
13050     case ISD::SELECT_CC: C = 2; break;
13051     }
13052 
13053     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
13054          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
13055         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
13056          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
13057       // The to-be-promoted operands of this node have not yet been
13058       // promoted (this should be rare because we're going through the
13059       // list backward, but if one of the operands has several users in
13060       // this cluster of to-be-promoted nodes, it is possible).
13061       PromOpHandles.emplace_front(PromOp);
13062       continue;
13063     }
13064 
13065     // For SELECT and SELECT_CC nodes, we do a similar check for any
13066     // to-be-promoted comparison inputs.
13067     if (PromOp.getOpcode() == ISD::SELECT ||
13068         PromOp.getOpcode() == ISD::SELECT_CC) {
13069       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
13070            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
13071           (SelectTruncOp[1].count(PromOp.getNode()) &&
13072            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
13073         PromOpHandles.emplace_front(PromOp);
13074         continue;
13075       }
13076     }
13077 
13078     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
13079                                 PromOp.getNode()->op_end());
13080 
13081     // If this node has constant inputs, then they'll need to be promoted here.
13082     for (unsigned i = 0; i < 2; ++i) {
13083       if (!isa<ConstantSDNode>(Ops[C+i]))
13084         continue;
13085       if (Ops[C+i].getValueType() == N->getValueType(0))
13086         continue;
13087 
13088       if (N->getOpcode() == ISD::SIGN_EXTEND)
13089         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13090       else if (N->getOpcode() == ISD::ZERO_EXTEND)
13091         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13092       else
13093         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
13094     }
13095 
13096     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
13097     // truncate them again to the original value type.
13098     if (PromOp.getOpcode() == ISD::SELECT ||
13099         PromOp.getOpcode() == ISD::SELECT_CC) {
13100       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
13101       if (SI0 != SelectTruncOp[0].end())
13102         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
13103       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
13104       if (SI1 != SelectTruncOp[1].end())
13105         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
13106     }
13107 
13108     DAG.ReplaceAllUsesOfValueWith(PromOp,
13109       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
13110   }
13111 
13112   // Now we're left with the initial extension itself.
13113   if (!ReallyNeedsExt)
13114     return N->getOperand(0);
13115 
13116   // To zero extend, just mask off everything except for the first bit (in the
13117   // i1 case).
13118   if (N->getOpcode() == ISD::ZERO_EXTEND)
13119     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
13120                        DAG.getConstant(APInt::getLowBitsSet(
13121                                          N->getValueSizeInBits(0), PromBits),
13122                                        dl, N->getValueType(0)));
13123 
13124   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
13125          "Invalid extension type");
13126   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
13127   SDValue ShiftCst =
13128       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
13129   return DAG.getNode(
13130       ISD::SRA, dl, N->getValueType(0),
13131       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
13132       ShiftCst);
13133 }
13134 
13135 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
13136                                         DAGCombinerInfo &DCI) const {
13137   assert(N->getOpcode() == ISD::SETCC &&
13138          "Should be called with a SETCC node");
13139 
13140   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
13141   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
13142     SDValue LHS = N->getOperand(0);
13143     SDValue RHS = N->getOperand(1);
13144 
13145     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
13146     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
13147         LHS.hasOneUse())
13148       std::swap(LHS, RHS);
13149 
13150     // x == 0-y --> x+y == 0
13151     // x != 0-y --> x+y != 0
13152     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
13153         RHS.hasOneUse()) {
13154       SDLoc DL(N);
13155       SelectionDAG &DAG = DCI.DAG;
13156       EVT VT = N->getValueType(0);
13157       EVT OpVT = LHS.getValueType();
13158       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
13159       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
13160     }
13161   }
13162 
13163   return DAGCombineTruncBoolExt(N, DCI);
13164 }
13165 
13166 // Is this an extending load from an f32 to an f64?
13167 static bool isFPExtLoad(SDValue Op) {
13168   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
13169     return LD->getExtensionType() == ISD::EXTLOAD &&
13170       Op.getValueType() == MVT::f64;
13171   return false;
13172 }
13173 
13174 /// Reduces the number of fp-to-int conversion when building a vector.
13175 ///
13176 /// If this vector is built out of floating to integer conversions,
13177 /// transform it to a vector built out of floating point values followed by a
13178 /// single floating to integer conversion of the vector.
13179 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
13180 /// becomes (fptosi (build_vector ($A, $B, ...)))
13181 SDValue PPCTargetLowering::
13182 combineElementTruncationToVectorTruncation(SDNode *N,
13183                                            DAGCombinerInfo &DCI) const {
13184   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13185          "Should be called with a BUILD_VECTOR node");
13186 
13187   SelectionDAG &DAG = DCI.DAG;
13188   SDLoc dl(N);
13189 
13190   SDValue FirstInput = N->getOperand(0);
13191   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
13192          "The input operand must be an fp-to-int conversion.");
13193 
13194   // This combine happens after legalization so the fp_to_[su]i nodes are
13195   // already converted to PPCSISD nodes.
13196   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
13197   if (FirstConversion == PPCISD::FCTIDZ ||
13198       FirstConversion == PPCISD::FCTIDUZ ||
13199       FirstConversion == PPCISD::FCTIWZ ||
13200       FirstConversion == PPCISD::FCTIWUZ) {
13201     bool IsSplat = true;
13202     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
13203       FirstConversion == PPCISD::FCTIWUZ;
13204     EVT SrcVT = FirstInput.getOperand(0).getValueType();
13205     SmallVector<SDValue, 4> Ops;
13206     EVT TargetVT = N->getValueType(0);
13207     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13208       SDValue NextOp = N->getOperand(i);
13209       if (NextOp.getOpcode() != PPCISD::MFVSR)
13210         return SDValue();
13211       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
13212       if (NextConversion != FirstConversion)
13213         return SDValue();
13214       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
13215       // This is not valid if the input was originally double precision. It is
13216       // also not profitable to do unless this is an extending load in which
13217       // case doing this combine will allow us to combine consecutive loads.
13218       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
13219         return SDValue();
13220       if (N->getOperand(i) != FirstInput)
13221         IsSplat = false;
13222     }
13223 
13224     // If this is a splat, we leave it as-is since there will be only a single
13225     // fp-to-int conversion followed by a splat of the integer. This is better
13226     // for 32-bit and smaller ints and neutral for 64-bit ints.
13227     if (IsSplat)
13228       return SDValue();
13229 
13230     // Now that we know we have the right type of node, get its operands
13231     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
13232       SDValue In = N->getOperand(i).getOperand(0);
13233       if (Is32Bit) {
13234         // For 32-bit values, we need to add an FP_ROUND node (if we made it
13235         // here, we know that all inputs are extending loads so this is safe).
13236         if (In.isUndef())
13237           Ops.push_back(DAG.getUNDEF(SrcVT));
13238         else {
13239           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
13240                                       MVT::f32, In.getOperand(0),
13241                                       DAG.getIntPtrConstant(1, dl));
13242           Ops.push_back(Trunc);
13243         }
13244       } else
13245         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
13246     }
13247 
13248     unsigned Opcode;
13249     if (FirstConversion == PPCISD::FCTIDZ ||
13250         FirstConversion == PPCISD::FCTIWZ)
13251       Opcode = ISD::FP_TO_SINT;
13252     else
13253       Opcode = ISD::FP_TO_UINT;
13254 
13255     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
13256     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
13257     return DAG.getNode(Opcode, dl, TargetVT, BV);
13258   }
13259   return SDValue();
13260 }
13261 
13262 /// Reduce the number of loads when building a vector.
13263 ///
13264 /// Building a vector out of multiple loads can be converted to a load
13265 /// of the vector type if the loads are consecutive. If the loads are
13266 /// consecutive but in descending order, a shuffle is added at the end
13267 /// to reorder the vector.
13268 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
13269   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13270          "Should be called with a BUILD_VECTOR node");
13271 
13272   SDLoc dl(N);
13273 
13274   // Return early for non byte-sized type, as they can't be consecutive.
13275   if (!N->getValueType(0).getVectorElementType().isByteSized())
13276     return SDValue();
13277 
13278   bool InputsAreConsecutiveLoads = true;
13279   bool InputsAreReverseConsecutive = true;
13280   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
13281   SDValue FirstInput = N->getOperand(0);
13282   bool IsRoundOfExtLoad = false;
13283 
13284   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
13285       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
13286     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
13287     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
13288   }
13289   // Not a build vector of (possibly fp_rounded) loads.
13290   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
13291       N->getNumOperands() == 1)
13292     return SDValue();
13293 
13294   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
13295     // If any inputs are fp_round(extload), they all must be.
13296     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
13297       return SDValue();
13298 
13299     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13300       N->getOperand(i);
13301     if (NextInput.getOpcode() != ISD::LOAD)
13302       return SDValue();
13303 
13304     SDValue PreviousInput =
13305       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13306     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13307     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13308 
13309     // If any inputs are fp_round(extload), they all must be.
13310     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13311       return SDValue();
13312 
13313     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13314       InputsAreConsecutiveLoads = false;
13315     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13316       InputsAreReverseConsecutive = false;
13317 
13318     // Exit early if the loads are neither consecutive nor reverse consecutive.
13319     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13320       return SDValue();
13321   }
13322 
13323   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13324          "The loads cannot be both consecutive and reverse consecutive.");
13325 
13326   SDValue FirstLoadOp =
13327     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13328   SDValue LastLoadOp =
13329     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13330                        N->getOperand(N->getNumOperands()-1);
13331 
13332   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13333   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13334   if (InputsAreConsecutiveLoads) {
13335     assert(LD1 && "Input needs to be a LoadSDNode.");
13336     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13337                        LD1->getBasePtr(), LD1->getPointerInfo(),
13338                        LD1->getAlignment());
13339   }
13340   if (InputsAreReverseConsecutive) {
13341     assert(LDL && "Input needs to be a LoadSDNode.");
13342     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13343                                LDL->getBasePtr(), LDL->getPointerInfo(),
13344                                LDL->getAlignment());
13345     SmallVector<int, 16> Ops;
13346     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13347       Ops.push_back(i);
13348 
13349     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13350                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13351   }
13352   return SDValue();
13353 }
13354 
13355 // This function adds the required vector_shuffle needed to get
13356 // the elements of the vector extract in the correct position
13357 // as specified by the CorrectElems encoding.
13358 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13359                                       SDValue Input, uint64_t Elems,
13360                                       uint64_t CorrectElems) {
13361   SDLoc dl(N);
13362 
13363   unsigned NumElems = Input.getValueType().getVectorNumElements();
13364   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13365 
13366   // Knowing the element indices being extracted from the original
13367   // vector and the order in which they're being inserted, just put
13368   // them at element indices required for the instruction.
13369   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13370     if (DAG.getDataLayout().isLittleEndian())
13371       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13372     else
13373       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13374     CorrectElems = CorrectElems >> 8;
13375     Elems = Elems >> 8;
13376   }
13377 
13378   SDValue Shuffle =
13379       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13380                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13381 
13382   EVT VT = N->getValueType(0);
13383   SDValue Conv = DAG.getBitcast(VT, Shuffle);
13384 
13385   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
13386                                Input.getValueType().getVectorElementType(),
13387                                VT.getVectorNumElements());
13388   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT, Conv,
13389                      DAG.getValueType(ExtVT));
13390 }
13391 
13392 // Look for build vector patterns where input operands come from sign
13393 // extended vector_extract elements of specific indices. If the correct indices
13394 // aren't used, add a vector shuffle to fix up the indices and create
13395 // SIGN_EXTEND_INREG node which selects the vector sign extend instructions
13396 // during instruction selection.
13397 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13398   // This array encodes the indices that the vector sign extend instructions
13399   // extract from when extending from one type to another for both BE and LE.
13400   // The right nibble of each byte corresponds to the LE incides.
13401   // and the left nibble of each byte corresponds to the BE incides.
13402   // For example: 0x3074B8FC  byte->word
13403   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13404   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13405   // For example: 0x000070F8  byte->double word
13406   // For LE: the allowed indices are: 0x0,0x8
13407   // For BE: the allowed indices are: 0x7,0xF
13408   uint64_t TargetElems[] = {
13409       0x3074B8FC, // b->w
13410       0x000070F8, // b->d
13411       0x10325476, // h->w
13412       0x00003074, // h->d
13413       0x00001032, // w->d
13414   };
13415 
13416   uint64_t Elems = 0;
13417   int Index;
13418   SDValue Input;
13419 
13420   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13421     if (!Op)
13422       return false;
13423     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13424         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13425       return false;
13426 
13427     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13428     // of the right width.
13429     SDValue Extract = Op.getOperand(0);
13430     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13431       Extract = Extract.getOperand(0);
13432     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13433       return false;
13434 
13435     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13436     if (!ExtOp)
13437       return false;
13438 
13439     Index = ExtOp->getZExtValue();
13440     if (Input && Input != Extract.getOperand(0))
13441       return false;
13442 
13443     if (!Input)
13444       Input = Extract.getOperand(0);
13445 
13446     Elems = Elems << 8;
13447     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13448     Elems |= Index;
13449 
13450     return true;
13451   };
13452 
13453   // If the build vector operands aren't sign extended vector extracts,
13454   // of the same input vector, then return.
13455   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13456     if (!isSExtOfVecExtract(N->getOperand(i))) {
13457       return SDValue();
13458     }
13459   }
13460 
13461   // If the vector extract indicies are not correct, add the appropriate
13462   // vector_shuffle.
13463   int TgtElemArrayIdx;
13464   int InputSize = Input.getValueType().getScalarSizeInBits();
13465   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13466   if (InputSize + OutputSize == 40)
13467     TgtElemArrayIdx = 0;
13468   else if (InputSize + OutputSize == 72)
13469     TgtElemArrayIdx = 1;
13470   else if (InputSize + OutputSize == 48)
13471     TgtElemArrayIdx = 2;
13472   else if (InputSize + OutputSize == 80)
13473     TgtElemArrayIdx = 3;
13474   else if (InputSize + OutputSize == 96)
13475     TgtElemArrayIdx = 4;
13476   else
13477     return SDValue();
13478 
13479   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13480   CorrectElems = DAG.getDataLayout().isLittleEndian()
13481                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13482                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13483   if (Elems != CorrectElems) {
13484     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13485   }
13486 
13487   // Regular lowering will catch cases where a shuffle is not needed.
13488   return SDValue();
13489 }
13490 
13491 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13492                                                  DAGCombinerInfo &DCI) const {
13493   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13494          "Should be called with a BUILD_VECTOR node");
13495 
13496   SelectionDAG &DAG = DCI.DAG;
13497   SDLoc dl(N);
13498 
13499   if (!Subtarget.hasVSX())
13500     return SDValue();
13501 
13502   // The target independent DAG combiner will leave a build_vector of
13503   // float-to-int conversions intact. We can generate MUCH better code for
13504   // a float-to-int conversion of a vector of floats.
13505   SDValue FirstInput = N->getOperand(0);
13506   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13507     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13508     if (Reduced)
13509       return Reduced;
13510   }
13511 
13512   // If we're building a vector out of consecutive loads, just load that
13513   // vector type.
13514   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13515   if (Reduced)
13516     return Reduced;
13517 
13518   // If we're building a vector out of extended elements from another vector
13519   // we have P9 vector integer extend instructions. The code assumes legal
13520   // input types (i.e. it can't handle things like v4i16) so do not run before
13521   // legalization.
13522   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13523     Reduced = combineBVOfVecSExt(N, DAG);
13524     if (Reduced)
13525       return Reduced;
13526   }
13527 
13528 
13529   if (N->getValueType(0) != MVT::v2f64)
13530     return SDValue();
13531 
13532   // Looking for:
13533   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13534   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13535       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13536     return SDValue();
13537   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13538       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13539     return SDValue();
13540   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13541     return SDValue();
13542 
13543   SDValue Ext1 = FirstInput.getOperand(0);
13544   SDValue Ext2 = N->getOperand(1).getOperand(0);
13545   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13546      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13547     return SDValue();
13548 
13549   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13550   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13551   if (!Ext1Op || !Ext2Op)
13552     return SDValue();
13553   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13554       Ext1.getOperand(0) != Ext2.getOperand(0))
13555     return SDValue();
13556 
13557   int FirstElem = Ext1Op->getZExtValue();
13558   int SecondElem = Ext2Op->getZExtValue();
13559   int SubvecIdx;
13560   if (FirstElem == 0 && SecondElem == 1)
13561     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13562   else if (FirstElem == 2 && SecondElem == 3)
13563     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13564   else
13565     return SDValue();
13566 
13567   SDValue SrcVec = Ext1.getOperand(0);
13568   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13569     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13570   return DAG.getNode(NodeType, dl, MVT::v2f64,
13571                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13572 }
13573 
13574 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13575                                               DAGCombinerInfo &DCI) const {
13576   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13577           N->getOpcode() == ISD::UINT_TO_FP) &&
13578          "Need an int -> FP conversion node here");
13579 
13580   if (useSoftFloat() || !Subtarget.has64BitSupport())
13581     return SDValue();
13582 
13583   SelectionDAG &DAG = DCI.DAG;
13584   SDLoc dl(N);
13585   SDValue Op(N, 0);
13586 
13587   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13588   // from the hardware.
13589   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13590     return SDValue();
13591   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13592       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13593     return SDValue();
13594 
13595   SDValue FirstOperand(Op.getOperand(0));
13596   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13597     (FirstOperand.getValueType() == MVT::i8 ||
13598      FirstOperand.getValueType() == MVT::i16);
13599   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13600     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13601     bool DstDouble = Op.getValueType() == MVT::f64;
13602     unsigned ConvOp = Signed ?
13603       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13604       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13605     SDValue WidthConst =
13606       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13607                             dl, false);
13608     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13609     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13610     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13611                                          DAG.getVTList(MVT::f64, MVT::Other),
13612                                          Ops, MVT::i8, LDN->getMemOperand());
13613 
13614     // For signed conversion, we need to sign-extend the value in the VSR
13615     if (Signed) {
13616       SDValue ExtOps[] = { Ld, WidthConst };
13617       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13618       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13619     } else
13620       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13621   }
13622 
13623 
13624   // For i32 intermediate values, unfortunately, the conversion functions
13625   // leave the upper 32 bits of the value are undefined. Within the set of
13626   // scalar instructions, we have no method for zero- or sign-extending the
13627   // value. Thus, we cannot handle i32 intermediate values here.
13628   if (Op.getOperand(0).getValueType() == MVT::i32)
13629     return SDValue();
13630 
13631   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13632          "UINT_TO_FP is supported only with FPCVT");
13633 
13634   // If we have FCFIDS, then use it when converting to single-precision.
13635   // Otherwise, convert to double-precision and then round.
13636   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13637                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13638                                                             : PPCISD::FCFIDS)
13639                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13640                                                             : PPCISD::FCFID);
13641   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13642                   ? MVT::f32
13643                   : MVT::f64;
13644 
13645   // If we're converting from a float, to an int, and back to a float again,
13646   // then we don't need the store/load pair at all.
13647   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13648        Subtarget.hasFPCVT()) ||
13649       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13650     SDValue Src = Op.getOperand(0).getOperand(0);
13651     if (Src.getValueType() == MVT::f32) {
13652       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13653       DCI.AddToWorklist(Src.getNode());
13654     } else if (Src.getValueType() != MVT::f64) {
13655       // Make sure that we don't pick up a ppc_fp128 source value.
13656       return SDValue();
13657     }
13658 
13659     unsigned FCTOp =
13660       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13661                                                         PPCISD::FCTIDUZ;
13662 
13663     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13664     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13665 
13666     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13667       FP = DAG.getNode(ISD::FP_ROUND, dl,
13668                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13669       DCI.AddToWorklist(FP.getNode());
13670     }
13671 
13672     return FP;
13673   }
13674 
13675   return SDValue();
13676 }
13677 
13678 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13679 // builtins) into loads with swaps.
13680 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13681                                               DAGCombinerInfo &DCI) const {
13682   SelectionDAG &DAG = DCI.DAG;
13683   SDLoc dl(N);
13684   SDValue Chain;
13685   SDValue Base;
13686   MachineMemOperand *MMO;
13687 
13688   switch (N->getOpcode()) {
13689   default:
13690     llvm_unreachable("Unexpected opcode for little endian VSX load");
13691   case ISD::LOAD: {
13692     LoadSDNode *LD = cast<LoadSDNode>(N);
13693     Chain = LD->getChain();
13694     Base = LD->getBasePtr();
13695     MMO = LD->getMemOperand();
13696     // If the MMO suggests this isn't a load of a full vector, leave
13697     // things alone.  For a built-in, we have to make the change for
13698     // correctness, so if there is a size problem that will be a bug.
13699     if (MMO->getSize() < 16)
13700       return SDValue();
13701     break;
13702   }
13703   case ISD::INTRINSIC_W_CHAIN: {
13704     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13705     Chain = Intrin->getChain();
13706     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13707     // us what we want. Get operand 2 instead.
13708     Base = Intrin->getOperand(2);
13709     MMO = Intrin->getMemOperand();
13710     break;
13711   }
13712   }
13713 
13714   MVT VecTy = N->getValueType(0).getSimpleVT();
13715 
13716   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13717   // aligned and the type is a vector with elements up to 4 bytes
13718   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13719       VecTy.getScalarSizeInBits() <= 32) {
13720     return SDValue();
13721   }
13722 
13723   SDValue LoadOps[] = { Chain, Base };
13724   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13725                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13726                                          LoadOps, MVT::v2f64, MMO);
13727 
13728   DCI.AddToWorklist(Load.getNode());
13729   Chain = Load.getValue(1);
13730   SDValue Swap = DAG.getNode(
13731       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13732   DCI.AddToWorklist(Swap.getNode());
13733 
13734   // Add a bitcast if the resulting load type doesn't match v2f64.
13735   if (VecTy != MVT::v2f64) {
13736     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13737     DCI.AddToWorklist(N.getNode());
13738     // Package {bitcast value, swap's chain} to match Load's shape.
13739     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13740                        N, Swap.getValue(1));
13741   }
13742 
13743   return Swap;
13744 }
13745 
13746 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13747 // builtins) into stores with swaps.
13748 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13749                                                DAGCombinerInfo &DCI) const {
13750   SelectionDAG &DAG = DCI.DAG;
13751   SDLoc dl(N);
13752   SDValue Chain;
13753   SDValue Base;
13754   unsigned SrcOpnd;
13755   MachineMemOperand *MMO;
13756 
13757   switch (N->getOpcode()) {
13758   default:
13759     llvm_unreachable("Unexpected opcode for little endian VSX store");
13760   case ISD::STORE: {
13761     StoreSDNode *ST = cast<StoreSDNode>(N);
13762     Chain = ST->getChain();
13763     Base = ST->getBasePtr();
13764     MMO = ST->getMemOperand();
13765     SrcOpnd = 1;
13766     // If the MMO suggests this isn't a store of a full vector, leave
13767     // things alone.  For a built-in, we have to make the change for
13768     // correctness, so if there is a size problem that will be a bug.
13769     if (MMO->getSize() < 16)
13770       return SDValue();
13771     break;
13772   }
13773   case ISD::INTRINSIC_VOID: {
13774     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13775     Chain = Intrin->getChain();
13776     // Intrin->getBasePtr() oddly does not get what we want.
13777     Base = Intrin->getOperand(3);
13778     MMO = Intrin->getMemOperand();
13779     SrcOpnd = 2;
13780     break;
13781   }
13782   }
13783 
13784   SDValue Src = N->getOperand(SrcOpnd);
13785   MVT VecTy = Src.getValueType().getSimpleVT();
13786 
13787   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13788   // aligned and the type is a vector with elements up to 4 bytes
13789   if (Subtarget.needsSwapsForVSXMemOps() && MMO->getAlign() >= Align(16) &&
13790       VecTy.getScalarSizeInBits() <= 32) {
13791     return SDValue();
13792   }
13793 
13794   // All stores are done as v2f64 and possible bit cast.
13795   if (VecTy != MVT::v2f64) {
13796     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13797     DCI.AddToWorklist(Src.getNode());
13798   }
13799 
13800   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13801                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13802   DCI.AddToWorklist(Swap.getNode());
13803   Chain = Swap.getValue(1);
13804   SDValue StoreOps[] = { Chain, Swap, Base };
13805   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13806                                           DAG.getVTList(MVT::Other),
13807                                           StoreOps, VecTy, MMO);
13808   DCI.AddToWorklist(Store.getNode());
13809   return Store;
13810 }
13811 
13812 // Handle DAG combine for STORE (FP_TO_INT F).
13813 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13814                                                DAGCombinerInfo &DCI) const {
13815 
13816   SelectionDAG &DAG = DCI.DAG;
13817   SDLoc dl(N);
13818   unsigned Opcode = N->getOperand(1).getOpcode();
13819 
13820   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13821          && "Not a FP_TO_INT Instruction!");
13822 
13823   SDValue Val = N->getOperand(1).getOperand(0);
13824   EVT Op1VT = N->getOperand(1).getValueType();
13825   EVT ResVT = Val.getValueType();
13826 
13827   // Floating point types smaller than 32 bits are not legal on Power.
13828   if (ResVT.getScalarSizeInBits() < 32)
13829     return SDValue();
13830 
13831   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13832   bool ValidTypeForStoreFltAsInt =
13833         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13834          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13835 
13836   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Vector() ||
13837       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13838     return SDValue();
13839 
13840   // Extend f32 values to f64
13841   if (ResVT.getScalarSizeInBits() == 32) {
13842     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13843     DCI.AddToWorklist(Val.getNode());
13844   }
13845 
13846   // Set signed or unsigned conversion opcode.
13847   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13848                           PPCISD::FP_TO_SINT_IN_VSR :
13849                           PPCISD::FP_TO_UINT_IN_VSR;
13850 
13851   Val = DAG.getNode(ConvOpcode,
13852                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13853   DCI.AddToWorklist(Val.getNode());
13854 
13855   // Set number of bytes being converted.
13856   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13857   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13858                     DAG.getIntPtrConstant(ByteSize, dl, false),
13859                     DAG.getValueType(Op1VT) };
13860 
13861   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13862           DAG.getVTList(MVT::Other), Ops,
13863           cast<StoreSDNode>(N)->getMemoryVT(),
13864           cast<StoreSDNode>(N)->getMemOperand());
13865 
13866   DCI.AddToWorklist(Val.getNode());
13867   return Val;
13868 }
13869 
13870 static bool isAlternatingShuffMask(const ArrayRef<int> &Mask, int NumElts) {
13871   // Check that the source of the element keeps flipping
13872   // (i.e. Mask[i] < NumElts -> Mask[i+i] >= NumElts).
13873   bool PrevElemFromFirstVec = Mask[0] < NumElts;
13874   for (int i = 1, e = Mask.size(); i < e; i++) {
13875     if (PrevElemFromFirstVec && Mask[i] < NumElts)
13876       return false;
13877     if (!PrevElemFromFirstVec && Mask[i] >= NumElts)
13878       return false;
13879     PrevElemFromFirstVec = !PrevElemFromFirstVec;
13880   }
13881   return true;
13882 }
13883 
13884 static bool isSplatBV(SDValue Op) {
13885   if (Op.getOpcode() != ISD::BUILD_VECTOR)
13886     return false;
13887   SDValue FirstOp;
13888 
13889   // Find first non-undef input.
13890   for (int i = 0, e = Op.getNumOperands(); i < e; i++) {
13891     FirstOp = Op.getOperand(i);
13892     if (!FirstOp.isUndef())
13893       break;
13894   }
13895 
13896   // All inputs are undef or the same as the first non-undef input.
13897   for (int i = 1, e = Op.getNumOperands(); i < e; i++)
13898     if (Op.getOperand(i) != FirstOp && !Op.getOperand(i).isUndef())
13899       return false;
13900   return true;
13901 }
13902 
13903 static SDValue isScalarToVec(SDValue Op) {
13904   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13905     return Op;
13906   if (Op.getOpcode() != ISD::BITCAST)
13907     return SDValue();
13908   Op = Op.getOperand(0);
13909   if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR)
13910     return Op;
13911   return SDValue();
13912 }
13913 
13914 static void fixupShuffleMaskForPermutedSToV(SmallVectorImpl<int> &ShuffV,
13915                                             int LHSMaxIdx, int RHSMinIdx,
13916                                             int RHSMaxIdx, int HalfVec) {
13917   for (int i = 0, e = ShuffV.size(); i < e; i++) {
13918     int Idx = ShuffV[i];
13919     if ((Idx >= 0 && Idx < LHSMaxIdx) || (Idx >= RHSMinIdx && Idx < RHSMaxIdx))
13920       ShuffV[i] += HalfVec;
13921   }
13922   return;
13923 }
13924 
13925 // Replace a SCALAR_TO_VECTOR with a SCALAR_TO_VECTOR_PERMUTED except if
13926 // the original is:
13927 // (<n x Ty> (scalar_to_vector (Ty (extract_elt <n x Ty> %a, C))))
13928 // In such a case, just change the shuffle mask to extract the element
13929 // from the permuted index.
13930 static SDValue getSToVPermuted(SDValue OrigSToV, SelectionDAG &DAG) {
13931   SDLoc dl(OrigSToV);
13932   EVT VT = OrigSToV.getValueType();
13933   assert(OrigSToV.getOpcode() == ISD::SCALAR_TO_VECTOR &&
13934          "Expecting a SCALAR_TO_VECTOR here");
13935   SDValue Input = OrigSToV.getOperand(0);
13936 
13937   if (Input.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13938     ConstantSDNode *Idx = dyn_cast<ConstantSDNode>(Input.getOperand(1));
13939     SDValue OrigVector = Input.getOperand(0);
13940 
13941     // Can't handle non-const element indices or different vector types
13942     // for the input to the extract and the output of the scalar_to_vector.
13943     if (Idx && VT == OrigVector.getValueType()) {
13944       SmallVector<int, 16> NewMask(VT.getVectorNumElements(), -1);
13945       NewMask[VT.getVectorNumElements() / 2] = Idx->getZExtValue();
13946       return DAG.getVectorShuffle(VT, dl, OrigVector, OrigVector, NewMask);
13947     }
13948   }
13949   return DAG.getNode(PPCISD::SCALAR_TO_VECTOR_PERMUTED, dl, VT,
13950                      OrigSToV.getOperand(0));
13951 }
13952 
13953 // On little endian subtargets, combine shuffles such as:
13954 // vector_shuffle<16,1,17,3,18,5,19,7,20,9,21,11,22,13,23,15>, <zero>, %b
13955 // into:
13956 // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7>, <zero>, %b
13957 // because the latter can be matched to a single instruction merge.
13958 // Furthermore, SCALAR_TO_VECTOR on little endian always involves a permute
13959 // to put the value into element zero. Adjust the shuffle mask so that the
13960 // vector can remain in permuted form (to prevent a swap prior to a shuffle).
13961 SDValue PPCTargetLowering::combineVectorShuffle(ShuffleVectorSDNode *SVN,
13962                                                 SelectionDAG &DAG) const {
13963   SDValue LHS = SVN->getOperand(0);
13964   SDValue RHS = SVN->getOperand(1);
13965   auto Mask = SVN->getMask();
13966   int NumElts = LHS.getValueType().getVectorNumElements();
13967   SDValue Res(SVN, 0);
13968   SDLoc dl(SVN);
13969 
13970   // None of these combines are useful on big endian systems since the ISA
13971   // already has a big endian bias.
13972   if (!Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13973     return Res;
13974 
13975   // If this is not a shuffle of a shuffle and the first element comes from
13976   // the second vector, canonicalize to the commuted form. This will make it
13977   // more likely to match one of the single instruction patterns.
13978   if (Mask[0] >= NumElts && LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
13979       RHS.getOpcode() != ISD::VECTOR_SHUFFLE) {
13980     std::swap(LHS, RHS);
13981     Res = DAG.getCommutedVectorShuffle(*SVN);
13982     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
13983   }
13984 
13985   // Adjust the shuffle mask if either input vector comes from a
13986   // SCALAR_TO_VECTOR and keep the respective input vector in permuted
13987   // form (to prevent the need for a swap).
13988   SmallVector<int, 16> ShuffV(Mask.begin(), Mask.end());
13989   SDValue SToVLHS = isScalarToVec(LHS);
13990   SDValue SToVRHS = isScalarToVec(RHS);
13991   if (SToVLHS || SToVRHS) {
13992     int NumEltsIn = SToVLHS ? SToVLHS.getValueType().getVectorNumElements()
13993                             : SToVRHS.getValueType().getVectorNumElements();
13994     int NumEltsOut = ShuffV.size();
13995 
13996     // Initially assume that neither input is permuted. These will be adjusted
13997     // accordingly if either input is.
13998     int LHSMaxIdx = -1;
13999     int RHSMinIdx = -1;
14000     int RHSMaxIdx = -1;
14001     int HalfVec = LHS.getValueType().getVectorNumElements() / 2;
14002 
14003     // Get the permuted scalar to vector nodes for the source(s) that come from
14004     // ISD::SCALAR_TO_VECTOR.
14005     if (SToVLHS) {
14006       // Set up the values for the shuffle vector fixup.
14007       LHSMaxIdx = NumEltsOut / NumEltsIn;
14008       SToVLHS = getSToVPermuted(SToVLHS, DAG);
14009       if (SToVLHS.getValueType() != LHS.getValueType())
14010         SToVLHS = DAG.getBitcast(LHS.getValueType(), SToVLHS);
14011       LHS = SToVLHS;
14012     }
14013     if (SToVRHS) {
14014       RHSMinIdx = NumEltsOut;
14015       RHSMaxIdx = NumEltsOut / NumEltsIn + RHSMinIdx;
14016       SToVRHS = getSToVPermuted(SToVRHS, DAG);
14017       if (SToVRHS.getValueType() != RHS.getValueType())
14018         SToVRHS = DAG.getBitcast(RHS.getValueType(), SToVRHS);
14019       RHS = SToVRHS;
14020     }
14021 
14022     // Fix up the shuffle mask to reflect where the desired element actually is.
14023     // The minimum and maximum indices that correspond to element zero for both
14024     // the LHS and RHS are computed and will control which shuffle mask entries
14025     // are to be changed. For example, if the RHS is permuted, any shuffle mask
14026     // entries in the range [RHSMinIdx,RHSMaxIdx) will be incremented by
14027     // HalfVec to refer to the corresponding element in the permuted vector.
14028     fixupShuffleMaskForPermutedSToV(ShuffV, LHSMaxIdx, RHSMinIdx, RHSMaxIdx,
14029                                     HalfVec);
14030     Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14031 
14032     // We may have simplified away the shuffle. We won't be able to do anything
14033     // further with it here.
14034     if (!isa<ShuffleVectorSDNode>(Res))
14035       return Res;
14036     Mask = cast<ShuffleVectorSDNode>(Res)->getMask();
14037   }
14038 
14039   // The common case after we commuted the shuffle is that the RHS is a splat
14040   // and we have elements coming in from the splat at indices that are not
14041   // conducive to using a merge.
14042   // Example:
14043   // vector_shuffle<0,17,1,19,2,21,3,23,4,25,5,27,6,29,7,31> t1, <zero>
14044   if (!isSplatBV(RHS))
14045     return Res;
14046 
14047   // We are looking for a mask such that all even elements are from
14048   // one vector and all odd elements from the other.
14049   if (!isAlternatingShuffMask(Mask, NumElts))
14050     return Res;
14051 
14052   // Adjust the mask so we are pulling in the same index from the splat
14053   // as the index from the interesting vector in consecutive elements.
14054   // Example (even elements from first vector):
14055   // vector_shuffle<0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23> t1, <zero>
14056   if (Mask[0] < NumElts)
14057     for (int i = 1, e = Mask.size(); i < e; i += 2)
14058       ShuffV[i] = (ShuffV[i - 1] + NumElts);
14059   // Example (odd elements from first vector):
14060   // vector_shuffle<16,0,17,1,18,2,19,3,20,4,21,5,22,6,23,7> t1, <zero>
14061   else
14062     for (int i = 0, e = Mask.size(); i < e; i += 2)
14063       ShuffV[i] = (ShuffV[i + 1] + NumElts);
14064 
14065   // If the RHS has undefs, we need to remove them since we may have created
14066   // a shuffle that adds those instead of the splat value.
14067   SDValue SplatVal = cast<BuildVectorSDNode>(RHS.getNode())->getSplatValue();
14068   RHS = DAG.getSplatBuildVector(RHS.getValueType(), dl, SplatVal);
14069 
14070   Res = DAG.getVectorShuffle(SVN->getValueType(0), dl, LHS, RHS, ShuffV);
14071   return Res;
14072 }
14073 
14074 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
14075                                                 LSBaseSDNode *LSBase,
14076                                                 DAGCombinerInfo &DCI) const {
14077   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
14078         "Not a reverse memop pattern!");
14079 
14080   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
14081     auto Mask = SVN->getMask();
14082     int i = 0;
14083     auto I = Mask.rbegin();
14084     auto E = Mask.rend();
14085 
14086     for (; I != E; ++I) {
14087       if (*I != i)
14088         return false;
14089       i++;
14090     }
14091     return true;
14092   };
14093 
14094   SelectionDAG &DAG = DCI.DAG;
14095   EVT VT = SVN->getValueType(0);
14096 
14097   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
14098     return SDValue();
14099 
14100   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
14101   // See comment in PPCVSXSwapRemoval.cpp.
14102   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
14103   if (!Subtarget.hasP9Vector())
14104     return SDValue();
14105 
14106   if(!IsElementReverse(SVN))
14107     return SDValue();
14108 
14109   if (LSBase->getOpcode() == ISD::LOAD) {
14110     SDLoc dl(SVN);
14111     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
14112     return DAG.getMemIntrinsicNode(
14113         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
14114         LSBase->getMemoryVT(), LSBase->getMemOperand());
14115   }
14116 
14117   if (LSBase->getOpcode() == ISD::STORE) {
14118     SDLoc dl(LSBase);
14119     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
14120                           LSBase->getBasePtr()};
14121     return DAG.getMemIntrinsicNode(
14122         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
14123         LSBase->getMemoryVT(), LSBase->getMemOperand());
14124   }
14125 
14126   llvm_unreachable("Expected a load or store node here");
14127 }
14128 
14129 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
14130                                              DAGCombinerInfo &DCI) const {
14131   SelectionDAG &DAG = DCI.DAG;
14132   SDLoc dl(N);
14133   switch (N->getOpcode()) {
14134   default: break;
14135   case ISD::ADD:
14136     return combineADD(N, DCI);
14137   case ISD::SHL:
14138     return combineSHL(N, DCI);
14139   case ISD::SRA:
14140     return combineSRA(N, DCI);
14141   case ISD::SRL:
14142     return combineSRL(N, DCI);
14143   case ISD::MUL:
14144     return combineMUL(N, DCI);
14145   case ISD::FMA:
14146   case PPCISD::FNMSUB:
14147     return combineFMALike(N, DCI);
14148   case PPCISD::SHL:
14149     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
14150         return N->getOperand(0);
14151     break;
14152   case PPCISD::SRL:
14153     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
14154         return N->getOperand(0);
14155     break;
14156   case PPCISD::SRA:
14157     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
14158       if (C->isNullValue() ||   //  0 >>s V -> 0.
14159           C->isAllOnesValue())    // -1 >>s V -> -1.
14160         return N->getOperand(0);
14161     }
14162     break;
14163   case ISD::SIGN_EXTEND:
14164   case ISD::ZERO_EXTEND:
14165   case ISD::ANY_EXTEND:
14166     return DAGCombineExtBoolTrunc(N, DCI);
14167   case ISD::TRUNCATE:
14168     return combineTRUNCATE(N, DCI);
14169   case ISD::SETCC:
14170     if (SDValue CSCC = combineSetCC(N, DCI))
14171       return CSCC;
14172     LLVM_FALLTHROUGH;
14173   case ISD::SELECT_CC:
14174     return DAGCombineTruncBoolExt(N, DCI);
14175   case ISD::SINT_TO_FP:
14176   case ISD::UINT_TO_FP:
14177     return combineFPToIntToFP(N, DCI);
14178   case ISD::VECTOR_SHUFFLE:
14179     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
14180       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
14181       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
14182     }
14183     return combineVectorShuffle(cast<ShuffleVectorSDNode>(N), DCI.DAG);
14184   case ISD::STORE: {
14185 
14186     EVT Op1VT = N->getOperand(1).getValueType();
14187     unsigned Opcode = N->getOperand(1).getOpcode();
14188 
14189     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
14190       SDValue Val= combineStoreFPToInt(N, DCI);
14191       if (Val)
14192         return Val;
14193     }
14194 
14195     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
14196       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
14197       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
14198       if (Val)
14199         return Val;
14200     }
14201 
14202     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
14203     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
14204         N->getOperand(1).getNode()->hasOneUse() &&
14205         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
14206          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
14207 
14208       // STBRX can only handle simple types and it makes no sense to store less
14209       // two bytes in byte-reversed order.
14210       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
14211       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
14212         break;
14213 
14214       SDValue BSwapOp = N->getOperand(1).getOperand(0);
14215       // Do an any-extend to 32-bits if this is a half-word input.
14216       if (BSwapOp.getValueType() == MVT::i16)
14217         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
14218 
14219       // If the type of BSWAP operand is wider than stored memory width
14220       // it need to be shifted to the right side before STBRX.
14221       if (Op1VT.bitsGT(mVT)) {
14222         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
14223         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
14224                               DAG.getConstant(Shift, dl, MVT::i32));
14225         // Need to truncate if this is a bswap of i64 stored as i32/i16.
14226         if (Op1VT == MVT::i64)
14227           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
14228       }
14229 
14230       SDValue Ops[] = {
14231         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
14232       };
14233       return
14234         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
14235                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
14236                                 cast<StoreSDNode>(N)->getMemOperand());
14237     }
14238 
14239     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
14240     // So it can increase the chance of CSE constant construction.
14241     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
14242         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
14243       // Need to sign-extended to 64-bits to handle negative values.
14244       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
14245       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
14246                                     MemVT.getSizeInBits());
14247       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
14248 
14249       // DAG.getTruncStore() can't be used here because it doesn't accept
14250       // the general (base + offset) addressing mode.
14251       // So we use UpdateNodeOperands and setTruncatingStore instead.
14252       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
14253                              N->getOperand(3));
14254       cast<StoreSDNode>(N)->setTruncatingStore(true);
14255       return SDValue(N, 0);
14256     }
14257 
14258     // For little endian, VSX stores require generating xxswapd/lxvd2x.
14259     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14260     if (Op1VT.isSimple()) {
14261       MVT StoreVT = Op1VT.getSimpleVT();
14262       if (Subtarget.needsSwapsForVSXMemOps() &&
14263           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
14264            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
14265         return expandVSXStoreForLE(N, DCI);
14266     }
14267     break;
14268   }
14269   case ISD::LOAD: {
14270     LoadSDNode *LD = cast<LoadSDNode>(N);
14271     EVT VT = LD->getValueType(0);
14272 
14273     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14274     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14275     if (VT.isSimple()) {
14276       MVT LoadVT = VT.getSimpleVT();
14277       if (Subtarget.needsSwapsForVSXMemOps() &&
14278           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
14279            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
14280         return expandVSXLoadForLE(N, DCI);
14281     }
14282 
14283     // We sometimes end up with a 64-bit integer load, from which we extract
14284     // two single-precision floating-point numbers. This happens with
14285     // std::complex<float>, and other similar structures, because of the way we
14286     // canonicalize structure copies. However, if we lack direct moves,
14287     // then the final bitcasts from the extracted integer values to the
14288     // floating-point numbers turn into store/load pairs. Even with direct moves,
14289     // just loading the two floating-point numbers is likely better.
14290     auto ReplaceTwoFloatLoad = [&]() {
14291       if (VT != MVT::i64)
14292         return false;
14293 
14294       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
14295           LD->isVolatile())
14296         return false;
14297 
14298       //  We're looking for a sequence like this:
14299       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
14300       //      t16: i64 = srl t13, Constant:i32<32>
14301       //    t17: i32 = truncate t16
14302       //  t18: f32 = bitcast t17
14303       //    t19: i32 = truncate t13
14304       //  t20: f32 = bitcast t19
14305 
14306       if (!LD->hasNUsesOfValue(2, 0))
14307         return false;
14308 
14309       auto UI = LD->use_begin();
14310       while (UI.getUse().getResNo() != 0) ++UI;
14311       SDNode *Trunc = *UI++;
14312       while (UI.getUse().getResNo() != 0) ++UI;
14313       SDNode *RightShift = *UI;
14314       if (Trunc->getOpcode() != ISD::TRUNCATE)
14315         std::swap(Trunc, RightShift);
14316 
14317       if (Trunc->getOpcode() != ISD::TRUNCATE ||
14318           Trunc->getValueType(0) != MVT::i32 ||
14319           !Trunc->hasOneUse())
14320         return false;
14321       if (RightShift->getOpcode() != ISD::SRL ||
14322           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
14323           RightShift->getConstantOperandVal(1) != 32 ||
14324           !RightShift->hasOneUse())
14325         return false;
14326 
14327       SDNode *Trunc2 = *RightShift->use_begin();
14328       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
14329           Trunc2->getValueType(0) != MVT::i32 ||
14330           !Trunc2->hasOneUse())
14331         return false;
14332 
14333       SDNode *Bitcast = *Trunc->use_begin();
14334       SDNode *Bitcast2 = *Trunc2->use_begin();
14335 
14336       if (Bitcast->getOpcode() != ISD::BITCAST ||
14337           Bitcast->getValueType(0) != MVT::f32)
14338         return false;
14339       if (Bitcast2->getOpcode() != ISD::BITCAST ||
14340           Bitcast2->getValueType(0) != MVT::f32)
14341         return false;
14342 
14343       if (Subtarget.isLittleEndian())
14344         std::swap(Bitcast, Bitcast2);
14345 
14346       // Bitcast has the second float (in memory-layout order) and Bitcast2
14347       // has the first one.
14348 
14349       SDValue BasePtr = LD->getBasePtr();
14350       if (LD->isIndexed()) {
14351         assert(LD->getAddressingMode() == ISD::PRE_INC &&
14352                "Non-pre-inc AM on PPC?");
14353         BasePtr =
14354           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
14355                       LD->getOffset());
14356       }
14357 
14358       auto MMOFlags =
14359           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
14360       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
14361                                       LD->getPointerInfo(), LD->getAlignment(),
14362                                       MMOFlags, LD->getAAInfo());
14363       SDValue AddPtr =
14364         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
14365                     BasePtr, DAG.getIntPtrConstant(4, dl));
14366       SDValue FloatLoad2 = DAG.getLoad(
14367           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
14368           LD->getPointerInfo().getWithOffset(4),
14369           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
14370 
14371       if (LD->isIndexed()) {
14372         // Note that DAGCombine should re-form any pre-increment load(s) from
14373         // what is produced here if that makes sense.
14374         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
14375       }
14376 
14377       DCI.CombineTo(Bitcast2, FloatLoad);
14378       DCI.CombineTo(Bitcast, FloatLoad2);
14379 
14380       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
14381                                     SDValue(FloatLoad2.getNode(), 1));
14382       return true;
14383     };
14384 
14385     if (ReplaceTwoFloatLoad())
14386       return SDValue(N, 0);
14387 
14388     EVT MemVT = LD->getMemoryVT();
14389     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
14390     Align ABIAlignment = DAG.getDataLayout().getABITypeAlign(Ty);
14391     if (LD->isUnindexed() && VT.isVector() &&
14392         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
14393           // P8 and later hardware should just use LOAD.
14394           !Subtarget.hasP8Vector() &&
14395           (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
14396            VT == MVT::v4f32))) &&
14397         LD->getAlign() < ABIAlignment) {
14398       // This is a type-legal unaligned Altivec load.
14399       SDValue Chain = LD->getChain();
14400       SDValue Ptr = LD->getBasePtr();
14401       bool isLittleEndian = Subtarget.isLittleEndian();
14402 
14403       // This implements the loading of unaligned vectors as described in
14404       // the venerable Apple Velocity Engine overview. Specifically:
14405       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
14406       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
14407       //
14408       // The general idea is to expand a sequence of one or more unaligned
14409       // loads into an alignment-based permutation-control instruction (lvsl
14410       // or lvsr), a series of regular vector loads (which always truncate
14411       // their input address to an aligned address), and a series of
14412       // permutations.  The results of these permutations are the requested
14413       // loaded values.  The trick is that the last "extra" load is not taken
14414       // from the address you might suspect (sizeof(vector) bytes after the
14415       // last requested load), but rather sizeof(vector) - 1 bytes after the
14416       // last requested vector. The point of this is to avoid a page fault if
14417       // the base address happened to be aligned. This works because if the
14418       // base address is aligned, then adding less than a full vector length
14419       // will cause the last vector in the sequence to be (re)loaded.
14420       // Otherwise, the next vector will be fetched as you might suspect was
14421       // necessary.
14422 
14423       // We might be able to reuse the permutation generation from
14424       // a different base address offset from this one by an aligned amount.
14425       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
14426       // optimization later.
14427       Intrinsic::ID Intr, IntrLD, IntrPerm;
14428       MVT PermCntlTy, PermTy, LDTy;
14429       Intr = isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14430                             : Intrinsic::ppc_altivec_lvsl;
14431       IntrLD = Intrinsic::ppc_altivec_lvx;
14432       IntrPerm = Intrinsic::ppc_altivec_vperm;
14433       PermCntlTy = MVT::v16i8;
14434       PermTy = MVT::v4i32;
14435       LDTy = MVT::v4i32;
14436 
14437       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
14438 
14439       // Create the new MMO for the new base load. It is like the original MMO,
14440       // but represents an area in memory almost twice the vector size centered
14441       // on the original address. If the address is unaligned, we might start
14442       // reading up to (sizeof(vector)-1) bytes below the address of the
14443       // original unaligned load.
14444       MachineFunction &MF = DAG.getMachineFunction();
14445       MachineMemOperand *BaseMMO =
14446         MF.getMachineMemOperand(LD->getMemOperand(),
14447                                 -(long)MemVT.getStoreSize()+1,
14448                                 2*MemVT.getStoreSize()-1);
14449 
14450       // Create the new base load.
14451       SDValue LDXIntID =
14452           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
14453       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
14454       SDValue BaseLoad =
14455         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14456                                 DAG.getVTList(PermTy, MVT::Other),
14457                                 BaseLoadOps, LDTy, BaseMMO);
14458 
14459       // Note that the value of IncOffset (which is provided to the next
14460       // load's pointer info offset value, and thus used to calculate the
14461       // alignment), and the value of IncValue (which is actually used to
14462       // increment the pointer value) are different! This is because we
14463       // require the next load to appear to be aligned, even though it
14464       // is actually offset from the base pointer by a lesser amount.
14465       int IncOffset = VT.getSizeInBits() / 8;
14466       int IncValue = IncOffset;
14467 
14468       // Walk (both up and down) the chain looking for another load at the real
14469       // (aligned) offset (the alignment of the other load does not matter in
14470       // this case). If found, then do not use the offset reduction trick, as
14471       // that will prevent the loads from being later combined (as they would
14472       // otherwise be duplicates).
14473       if (!findConsecutiveLoad(LD, DAG))
14474         --IncValue;
14475 
14476       SDValue Increment =
14477           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
14478       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14479 
14480       MachineMemOperand *ExtraMMO =
14481         MF.getMachineMemOperand(LD->getMemOperand(),
14482                                 1, 2*MemVT.getStoreSize()-1);
14483       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
14484       SDValue ExtraLoad =
14485         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
14486                                 DAG.getVTList(PermTy, MVT::Other),
14487                                 ExtraLoadOps, LDTy, ExtraMMO);
14488 
14489       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
14490         BaseLoad.getValue(1), ExtraLoad.getValue(1));
14491 
14492       // Because vperm has a big-endian bias, we must reverse the order
14493       // of the input vectors and complement the permute control vector
14494       // when generating little endian code.  We have already handled the
14495       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
14496       // and ExtraLoad here.
14497       SDValue Perm;
14498       if (isLittleEndian)
14499         Perm = BuildIntrinsicOp(IntrPerm,
14500                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14501       else
14502         Perm = BuildIntrinsicOp(IntrPerm,
14503                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14504 
14505       if (VT != PermTy)
14506         Perm = Subtarget.hasAltivec()
14507                    ? DAG.getNode(ISD::BITCAST, dl, VT, Perm)
14508                    : DAG.getNode(ISD::FP_ROUND, dl, VT, Perm,
14509                                  DAG.getTargetConstant(1, dl, MVT::i64));
14510                                // second argument is 1 because this rounding
14511                                // is always exact.
14512 
14513       // The output of the permutation is our loaded result, the TokenFactor is
14514       // our new chain.
14515       DCI.CombineTo(N, Perm, TF);
14516       return SDValue(N, 0);
14517     }
14518     }
14519     break;
14520     case ISD::INTRINSIC_WO_CHAIN: {
14521       bool isLittleEndian = Subtarget.isLittleEndian();
14522       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14523       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14524                                            : Intrinsic::ppc_altivec_lvsl);
14525       if (IID == Intr && N->getOperand(1)->getOpcode() == ISD::ADD) {
14526         SDValue Add = N->getOperand(1);
14527 
14528         int Bits = 4 /* 16 byte alignment */;
14529 
14530         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14531                                   APInt::getAllOnesValue(Bits /* alignment */)
14532                                       .zext(Add.getScalarValueSizeInBits()))) {
14533           SDNode *BasePtr = Add->getOperand(0).getNode();
14534           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14535                                     UE = BasePtr->use_end();
14536                UI != UE; ++UI) {
14537             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14538                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
14539                     IID) {
14540               // We've found another LVSL/LVSR, and this address is an aligned
14541               // multiple of that one. The results will be the same, so use the
14542               // one we've just found instead.
14543 
14544               return SDValue(*UI, 0);
14545             }
14546           }
14547         }
14548 
14549         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14550           SDNode *BasePtr = Add->getOperand(0).getNode();
14551           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14552                UE = BasePtr->use_end(); UI != UE; ++UI) {
14553             if (UI->getOpcode() == ISD::ADD &&
14554                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14555                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14556                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14557                 (1ULL << Bits) == 0) {
14558               SDNode *OtherAdd = *UI;
14559               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14560                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14561                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14562                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14563                   return SDValue(*VI, 0);
14564                 }
14565               }
14566             }
14567           }
14568         }
14569       }
14570 
14571       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14572       // Expose the vabsduw/h/b opportunity for down stream
14573       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14574           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14575            IID == Intrinsic::ppc_altivec_vmaxsh ||
14576            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14577         SDValue V1 = N->getOperand(1);
14578         SDValue V2 = N->getOperand(2);
14579         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14580              V1.getSimpleValueType() == MVT::v8i16 ||
14581              V1.getSimpleValueType() == MVT::v16i8) &&
14582             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14583           // (0-a, a)
14584           if (V1.getOpcode() == ISD::SUB &&
14585               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14586               V1.getOperand(1) == V2) {
14587             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14588           }
14589           // (a, 0-a)
14590           if (V2.getOpcode() == ISD::SUB &&
14591               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14592               V2.getOperand(1) == V1) {
14593             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14594           }
14595           // (x-y, y-x)
14596           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14597               V1.getOperand(0) == V2.getOperand(1) &&
14598               V1.getOperand(1) == V2.getOperand(0)) {
14599             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14600           }
14601         }
14602       }
14603     }
14604 
14605     break;
14606   case ISD::INTRINSIC_W_CHAIN:
14607     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14608     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14609     if (Subtarget.needsSwapsForVSXMemOps()) {
14610       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14611       default:
14612         break;
14613       case Intrinsic::ppc_vsx_lxvw4x:
14614       case Intrinsic::ppc_vsx_lxvd2x:
14615         return expandVSXLoadForLE(N, DCI);
14616       }
14617     }
14618     break;
14619   case ISD::INTRINSIC_VOID:
14620     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14621     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14622     if (Subtarget.needsSwapsForVSXMemOps()) {
14623       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14624       default:
14625         break;
14626       case Intrinsic::ppc_vsx_stxvw4x:
14627       case Intrinsic::ppc_vsx_stxvd2x:
14628         return expandVSXStoreForLE(N, DCI);
14629       }
14630     }
14631     break;
14632   case ISD::BSWAP:
14633     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14634     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14635         N->getOperand(0).hasOneUse() &&
14636         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14637          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14638           N->getValueType(0) == MVT::i64))) {
14639       SDValue Load = N->getOperand(0);
14640       LoadSDNode *LD = cast<LoadSDNode>(Load);
14641       // Create the byte-swapping load.
14642       SDValue Ops[] = {
14643         LD->getChain(),    // Chain
14644         LD->getBasePtr(),  // Ptr
14645         DAG.getValueType(N->getValueType(0)) // VT
14646       };
14647       SDValue BSLoad =
14648         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14649                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14650                                               MVT::i64 : MVT::i32, MVT::Other),
14651                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14652 
14653       // If this is an i16 load, insert the truncate.
14654       SDValue ResVal = BSLoad;
14655       if (N->getValueType(0) == MVT::i16)
14656         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14657 
14658       // First, combine the bswap away.  This makes the value produced by the
14659       // load dead.
14660       DCI.CombineTo(N, ResVal);
14661 
14662       // Next, combine the load away, we give it a bogus result value but a real
14663       // chain result.  The result value is dead because the bswap is dead.
14664       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14665 
14666       // Return N so it doesn't get rechecked!
14667       return SDValue(N, 0);
14668     }
14669     break;
14670   case PPCISD::VCMP:
14671     // If a VCMPo node already exists with exactly the same operands as this
14672     // node, use its result instead of this node (VCMPo computes both a CR6 and
14673     // a normal output).
14674     //
14675     if (!N->getOperand(0).hasOneUse() &&
14676         !N->getOperand(1).hasOneUse() &&
14677         !N->getOperand(2).hasOneUse()) {
14678 
14679       // Scan all of the users of the LHS, looking for VCMPo's that match.
14680       SDNode *VCMPoNode = nullptr;
14681 
14682       SDNode *LHSN = N->getOperand(0).getNode();
14683       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14684            UI != E; ++UI)
14685         if (UI->getOpcode() == PPCISD::VCMPo &&
14686             UI->getOperand(1) == N->getOperand(1) &&
14687             UI->getOperand(2) == N->getOperand(2) &&
14688             UI->getOperand(0) == N->getOperand(0)) {
14689           VCMPoNode = *UI;
14690           break;
14691         }
14692 
14693       // If there is no VCMPo node, or if the flag value has a single use, don't
14694       // transform this.
14695       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14696         break;
14697 
14698       // Look at the (necessarily single) use of the flag value.  If it has a
14699       // chain, this transformation is more complex.  Note that multiple things
14700       // could use the value result, which we should ignore.
14701       SDNode *FlagUser = nullptr;
14702       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14703            FlagUser == nullptr; ++UI) {
14704         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14705         SDNode *User = *UI;
14706         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14707           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14708             FlagUser = User;
14709             break;
14710           }
14711         }
14712       }
14713 
14714       // If the user is a MFOCRF instruction, we know this is safe.
14715       // Otherwise we give up for right now.
14716       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14717         return SDValue(VCMPoNode, 0);
14718     }
14719     break;
14720   case ISD::BRCOND: {
14721     SDValue Cond = N->getOperand(1);
14722     SDValue Target = N->getOperand(2);
14723 
14724     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14725         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14726           Intrinsic::loop_decrement) {
14727 
14728       // We now need to make the intrinsic dead (it cannot be instruction
14729       // selected).
14730       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14731       assert(Cond.getNode()->hasOneUse() &&
14732              "Counter decrement has more than one use");
14733 
14734       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14735                          N->getOperand(0), Target);
14736     }
14737   }
14738   break;
14739   case ISD::BR_CC: {
14740     // If this is a branch on an altivec predicate comparison, lower this so
14741     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14742     // lowering is done pre-legalize, because the legalizer lowers the predicate
14743     // compare down to code that is difficult to reassemble.
14744     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14745     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14746 
14747     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14748     // value. If so, pass-through the AND to get to the intrinsic.
14749     if (LHS.getOpcode() == ISD::AND &&
14750         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14751         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14752           Intrinsic::loop_decrement &&
14753         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14754         !isNullConstant(LHS.getOperand(1)))
14755       LHS = LHS.getOperand(0);
14756 
14757     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14758         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14759           Intrinsic::loop_decrement &&
14760         isa<ConstantSDNode>(RHS)) {
14761       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14762              "Counter decrement comparison is not EQ or NE");
14763 
14764       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14765       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14766                     (CC == ISD::SETNE && !Val);
14767 
14768       // We now need to make the intrinsic dead (it cannot be instruction
14769       // selected).
14770       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14771       assert(LHS.getNode()->hasOneUse() &&
14772              "Counter decrement has more than one use");
14773 
14774       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14775                          N->getOperand(0), N->getOperand(4));
14776     }
14777 
14778     int CompareOpc;
14779     bool isDot;
14780 
14781     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14782         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14783         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14784       assert(isDot && "Can't compare against a vector result!");
14785 
14786       // If this is a comparison against something other than 0/1, then we know
14787       // that the condition is never/always true.
14788       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14789       if (Val != 0 && Val != 1) {
14790         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14791           return N->getOperand(0);
14792         // Always !=, turn it into an unconditional branch.
14793         return DAG.getNode(ISD::BR, dl, MVT::Other,
14794                            N->getOperand(0), N->getOperand(4));
14795       }
14796 
14797       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14798 
14799       // Create the PPCISD altivec 'dot' comparison node.
14800       SDValue Ops[] = {
14801         LHS.getOperand(2),  // LHS of compare
14802         LHS.getOperand(3),  // RHS of compare
14803         DAG.getConstant(CompareOpc, dl, MVT::i32)
14804       };
14805       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14806       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14807 
14808       // Unpack the result based on how the target uses it.
14809       PPC::Predicate CompOpc;
14810       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14811       default:  // Can't happen, don't crash on invalid number though.
14812       case 0:   // Branch on the value of the EQ bit of CR6.
14813         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14814         break;
14815       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14816         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14817         break;
14818       case 2:   // Branch on the value of the LT bit of CR6.
14819         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14820         break;
14821       case 3:   // Branch on the inverted value of the LT bit of CR6.
14822         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14823         break;
14824       }
14825 
14826       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14827                          DAG.getConstant(CompOpc, dl, MVT::i32),
14828                          DAG.getRegister(PPC::CR6, MVT::i32),
14829                          N->getOperand(4), CompNode.getValue(1));
14830     }
14831     break;
14832   }
14833   case ISD::BUILD_VECTOR:
14834     return DAGCombineBuildVector(N, DCI);
14835   case ISD::ABS:
14836     return combineABS(N, DCI);
14837   case ISD::VSELECT:
14838     return combineVSelect(N, DCI);
14839   }
14840 
14841   return SDValue();
14842 }
14843 
14844 SDValue
14845 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14846                                  SelectionDAG &DAG,
14847                                  SmallVectorImpl<SDNode *> &Created) const {
14848   // fold (sdiv X, pow2)
14849   EVT VT = N->getValueType(0);
14850   if (VT == MVT::i64 && !Subtarget.isPPC64())
14851     return SDValue();
14852   if ((VT != MVT::i32 && VT != MVT::i64) ||
14853       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14854     return SDValue();
14855 
14856   SDLoc DL(N);
14857   SDValue N0 = N->getOperand(0);
14858 
14859   bool IsNegPow2 = (-Divisor).isPowerOf2();
14860   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14861   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14862 
14863   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14864   Created.push_back(Op.getNode());
14865 
14866   if (IsNegPow2) {
14867     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14868     Created.push_back(Op.getNode());
14869   }
14870 
14871   return Op;
14872 }
14873 
14874 //===----------------------------------------------------------------------===//
14875 // Inline Assembly Support
14876 //===----------------------------------------------------------------------===//
14877 
14878 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14879                                                       KnownBits &Known,
14880                                                       const APInt &DemandedElts,
14881                                                       const SelectionDAG &DAG,
14882                                                       unsigned Depth) const {
14883   Known.resetAll();
14884   switch (Op.getOpcode()) {
14885   default: break;
14886   case PPCISD::LBRX: {
14887     // lhbrx is known to have the top bits cleared out.
14888     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14889       Known.Zero = 0xFFFF0000;
14890     break;
14891   }
14892   case ISD::INTRINSIC_WO_CHAIN: {
14893     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14894     default: break;
14895     case Intrinsic::ppc_altivec_vcmpbfp_p:
14896     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14897     case Intrinsic::ppc_altivec_vcmpequb_p:
14898     case Intrinsic::ppc_altivec_vcmpequh_p:
14899     case Intrinsic::ppc_altivec_vcmpequw_p:
14900     case Intrinsic::ppc_altivec_vcmpequd_p:
14901     case Intrinsic::ppc_altivec_vcmpgefp_p:
14902     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14903     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14904     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14905     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14906     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14907     case Intrinsic::ppc_altivec_vcmpgtub_p:
14908     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14909     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14910     case Intrinsic::ppc_altivec_vcmpgtud_p:
14911       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14912       break;
14913     }
14914   }
14915   }
14916 }
14917 
14918 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14919   switch (Subtarget.getCPUDirective()) {
14920   default: break;
14921   case PPC::DIR_970:
14922   case PPC::DIR_PWR4:
14923   case PPC::DIR_PWR5:
14924   case PPC::DIR_PWR5X:
14925   case PPC::DIR_PWR6:
14926   case PPC::DIR_PWR6X:
14927   case PPC::DIR_PWR7:
14928   case PPC::DIR_PWR8:
14929   case PPC::DIR_PWR9:
14930   case PPC::DIR_PWR10:
14931   case PPC::DIR_PWR_FUTURE: {
14932     if (!ML)
14933       break;
14934 
14935     if (!DisableInnermostLoopAlign32) {
14936       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14937       // so that we can decrease cache misses and branch-prediction misses.
14938       // Actual alignment of the loop will depend on the hotness check and other
14939       // logic in alignBlocks.
14940       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14941         return Align(32);
14942     }
14943 
14944     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14945 
14946     // For small loops (between 5 and 8 instructions), align to a 32-byte
14947     // boundary so that the entire loop fits in one instruction-cache line.
14948     uint64_t LoopSize = 0;
14949     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14950       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14951         LoopSize += TII->getInstSizeInBytes(*J);
14952         if (LoopSize > 32)
14953           break;
14954       }
14955 
14956     if (LoopSize > 16 && LoopSize <= 32)
14957       return Align(32);
14958 
14959     break;
14960   }
14961   }
14962 
14963   return TargetLowering::getPrefLoopAlignment(ML);
14964 }
14965 
14966 /// getConstraintType - Given a constraint, return the type of
14967 /// constraint it is for this target.
14968 PPCTargetLowering::ConstraintType
14969 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14970   if (Constraint.size() == 1) {
14971     switch (Constraint[0]) {
14972     default: break;
14973     case 'b':
14974     case 'r':
14975     case 'f':
14976     case 'd':
14977     case 'v':
14978     case 'y':
14979       return C_RegisterClass;
14980     case 'Z':
14981       // FIXME: While Z does indicate a memory constraint, it specifically
14982       // indicates an r+r address (used in conjunction with the 'y' modifier
14983       // in the replacement string). Currently, we're forcing the base
14984       // register to be r0 in the asm printer (which is interpreted as zero)
14985       // and forming the complete address in the second register. This is
14986       // suboptimal.
14987       return C_Memory;
14988     }
14989   } else if (Constraint == "wc") { // individual CR bits.
14990     return C_RegisterClass;
14991   } else if (Constraint == "wa" || Constraint == "wd" ||
14992              Constraint == "wf" || Constraint == "ws" ||
14993              Constraint == "wi" || Constraint == "ww") {
14994     return C_RegisterClass; // VSX registers.
14995   }
14996   return TargetLowering::getConstraintType(Constraint);
14997 }
14998 
14999 /// Examine constraint type and operand type and determine a weight value.
15000 /// This object must already have been set up with the operand type
15001 /// and the current alternative constraint selected.
15002 TargetLowering::ConstraintWeight
15003 PPCTargetLowering::getSingleConstraintMatchWeight(
15004     AsmOperandInfo &info, const char *constraint) const {
15005   ConstraintWeight weight = CW_Invalid;
15006   Value *CallOperandVal = info.CallOperandVal;
15007     // If we don't have a value, we can't do a match,
15008     // but allow it at the lowest weight.
15009   if (!CallOperandVal)
15010     return CW_Default;
15011   Type *type = CallOperandVal->getType();
15012 
15013   // Look at the constraint type.
15014   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
15015     return CW_Register; // an individual CR bit.
15016   else if ((StringRef(constraint) == "wa" ||
15017             StringRef(constraint) == "wd" ||
15018             StringRef(constraint) == "wf") &&
15019            type->isVectorTy())
15020     return CW_Register;
15021   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
15022     return CW_Register; // just hold 64-bit integers data.
15023   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
15024     return CW_Register;
15025   else if (StringRef(constraint) == "ww" && type->isFloatTy())
15026     return CW_Register;
15027 
15028   switch (*constraint) {
15029   default:
15030     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
15031     break;
15032   case 'b':
15033     if (type->isIntegerTy())
15034       weight = CW_Register;
15035     break;
15036   case 'f':
15037     if (type->isFloatTy())
15038       weight = CW_Register;
15039     break;
15040   case 'd':
15041     if (type->isDoubleTy())
15042       weight = CW_Register;
15043     break;
15044   case 'v':
15045     if (type->isVectorTy())
15046       weight = CW_Register;
15047     break;
15048   case 'y':
15049     weight = CW_Register;
15050     break;
15051   case 'Z':
15052     weight = CW_Memory;
15053     break;
15054   }
15055   return weight;
15056 }
15057 
15058 std::pair<unsigned, const TargetRegisterClass *>
15059 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
15060                                                 StringRef Constraint,
15061                                                 MVT VT) const {
15062   if (Constraint.size() == 1) {
15063     // GCC RS6000 Constraint Letters
15064     switch (Constraint[0]) {
15065     case 'b':   // R1-R31
15066       if (VT == MVT::i64 && Subtarget.isPPC64())
15067         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
15068       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
15069     case 'r':   // R0-R31
15070       if (VT == MVT::i64 && Subtarget.isPPC64())
15071         return std::make_pair(0U, &PPC::G8RCRegClass);
15072       return std::make_pair(0U, &PPC::GPRCRegClass);
15073     // 'd' and 'f' constraints are both defined to be "the floating point
15074     // registers", where one is for 32-bit and the other for 64-bit. We don't
15075     // really care overly much here so just give them all the same reg classes.
15076     case 'd':
15077     case 'f':
15078       if (Subtarget.hasSPE()) {
15079         if (VT == MVT::f32 || VT == MVT::i32)
15080           return std::make_pair(0U, &PPC::GPRCRegClass);
15081         if (VT == MVT::f64 || VT == MVT::i64)
15082           return std::make_pair(0U, &PPC::SPERCRegClass);
15083       } else {
15084         if (VT == MVT::f32 || VT == MVT::i32)
15085           return std::make_pair(0U, &PPC::F4RCRegClass);
15086         if (VT == MVT::f64 || VT == MVT::i64)
15087           return std::make_pair(0U, &PPC::F8RCRegClass);
15088       }
15089       break;
15090     case 'v':
15091       if (Subtarget.hasAltivec())
15092         return std::make_pair(0U, &PPC::VRRCRegClass);
15093       break;
15094     case 'y':   // crrc
15095       return std::make_pair(0U, &PPC::CRRCRegClass);
15096     }
15097   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
15098     // An individual CR bit.
15099     return std::make_pair(0U, &PPC::CRBITRCRegClass);
15100   } else if ((Constraint == "wa" || Constraint == "wd" ||
15101              Constraint == "wf" || Constraint == "wi") &&
15102              Subtarget.hasVSX()) {
15103     return std::make_pair(0U, &PPC::VSRCRegClass);
15104   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
15105     if (VT == MVT::f32 && Subtarget.hasP8Vector())
15106       return std::make_pair(0U, &PPC::VSSRCRegClass);
15107     else
15108       return std::make_pair(0U, &PPC::VSFRCRegClass);
15109   }
15110 
15111   // If we name a VSX register, we can't defer to the base class because it
15112   // will not recognize the correct register (their names will be VSL{0-31}
15113   // and V{0-31} so they won't match). So we match them here.
15114   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
15115     int VSNum = atoi(Constraint.data() + 3);
15116     assert(VSNum >= 0 && VSNum <= 63 &&
15117            "Attempted to access a vsr out of range");
15118     if (VSNum < 32)
15119       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
15120     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
15121   }
15122   std::pair<unsigned, const TargetRegisterClass *> R =
15123       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
15124 
15125   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
15126   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
15127   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
15128   // register.
15129   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
15130   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
15131   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
15132       PPC::GPRCRegClass.contains(R.first))
15133     return std::make_pair(TRI->getMatchingSuperReg(R.first,
15134                             PPC::sub_32, &PPC::G8RCRegClass),
15135                           &PPC::G8RCRegClass);
15136 
15137   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
15138   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
15139     R.first = PPC::CR0;
15140     R.second = &PPC::CRRCRegClass;
15141   }
15142 
15143   return R;
15144 }
15145 
15146 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
15147 /// vector.  If it is invalid, don't add anything to Ops.
15148 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
15149                                                      std::string &Constraint,
15150                                                      std::vector<SDValue>&Ops,
15151                                                      SelectionDAG &DAG) const {
15152   SDValue Result;
15153 
15154   // Only support length 1 constraints.
15155   if (Constraint.length() > 1) return;
15156 
15157   char Letter = Constraint[0];
15158   switch (Letter) {
15159   default: break;
15160   case 'I':
15161   case 'J':
15162   case 'K':
15163   case 'L':
15164   case 'M':
15165   case 'N':
15166   case 'O':
15167   case 'P': {
15168     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
15169     if (!CST) return; // Must be an immediate to match.
15170     SDLoc dl(Op);
15171     int64_t Value = CST->getSExtValue();
15172     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
15173                          // numbers are printed as such.
15174     switch (Letter) {
15175     default: llvm_unreachable("Unknown constraint letter!");
15176     case 'I':  // "I" is a signed 16-bit constant.
15177       if (isInt<16>(Value))
15178         Result = DAG.getTargetConstant(Value, dl, TCVT);
15179       break;
15180     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
15181       if (isShiftedUInt<16, 16>(Value))
15182         Result = DAG.getTargetConstant(Value, dl, TCVT);
15183       break;
15184     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
15185       if (isShiftedInt<16, 16>(Value))
15186         Result = DAG.getTargetConstant(Value, dl, TCVT);
15187       break;
15188     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
15189       if (isUInt<16>(Value))
15190         Result = DAG.getTargetConstant(Value, dl, TCVT);
15191       break;
15192     case 'M':  // "M" is a constant that is greater than 31.
15193       if (Value > 31)
15194         Result = DAG.getTargetConstant(Value, dl, TCVT);
15195       break;
15196     case 'N':  // "N" is a positive constant that is an exact power of two.
15197       if (Value > 0 && isPowerOf2_64(Value))
15198         Result = DAG.getTargetConstant(Value, dl, TCVT);
15199       break;
15200     case 'O':  // "O" is the constant zero.
15201       if (Value == 0)
15202         Result = DAG.getTargetConstant(Value, dl, TCVT);
15203       break;
15204     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
15205       if (isInt<16>(-Value))
15206         Result = DAG.getTargetConstant(Value, dl, TCVT);
15207       break;
15208     }
15209     break;
15210   }
15211   }
15212 
15213   if (Result.getNode()) {
15214     Ops.push_back(Result);
15215     return;
15216   }
15217 
15218   // Handle standard constraint letters.
15219   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
15220 }
15221 
15222 // isLegalAddressingMode - Return true if the addressing mode represented
15223 // by AM is legal for this target, for a load/store of the specified type.
15224 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
15225                                               const AddrMode &AM, Type *Ty,
15226                                               unsigned AS,
15227                                               Instruction *I) const {
15228   // Vector type r+i form is supported since power9 as DQ form. We don't check
15229   // the offset matching DQ form requirement(off % 16 == 0), because on PowerPC,
15230   // imm form is preferred and the offset can be adjusted to use imm form later
15231   // in pass PPCLoopInstrFormPrep. Also in LSR, for one LSRUse, it uses min and
15232   // max offset to check legal addressing mode, we should be a little aggressive
15233   // to contain other offsets for that LSRUse.
15234   if (Ty->isVectorTy() && AM.BaseOffs != 0 && !Subtarget.hasP9Vector())
15235     return false;
15236 
15237   // PPC allows a sign-extended 16-bit immediate field.
15238   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
15239     return false;
15240 
15241   // No global is ever allowed as a base.
15242   if (AM.BaseGV)
15243     return false;
15244 
15245   // PPC only support r+r,
15246   switch (AM.Scale) {
15247   case 0:  // "r+i" or just "i", depending on HasBaseReg.
15248     break;
15249   case 1:
15250     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
15251       return false;
15252     // Otherwise we have r+r or r+i.
15253     break;
15254   case 2:
15255     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
15256       return false;
15257     // Allow 2*r as r+r.
15258     break;
15259   default:
15260     // No other scales are supported.
15261     return false;
15262   }
15263 
15264   return true;
15265 }
15266 
15267 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
15268                                            SelectionDAG &DAG) const {
15269   MachineFunction &MF = DAG.getMachineFunction();
15270   MachineFrameInfo &MFI = MF.getFrameInfo();
15271   MFI.setReturnAddressIsTaken(true);
15272 
15273   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15274     return SDValue();
15275 
15276   SDLoc dl(Op);
15277   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15278 
15279   // Make sure the function does not optimize away the store of the RA to
15280   // the stack.
15281   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
15282   FuncInfo->setLRStoreRequired();
15283   bool isPPC64 = Subtarget.isPPC64();
15284   auto PtrVT = getPointerTy(MF.getDataLayout());
15285 
15286   if (Depth > 0) {
15287     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15288     SDValue Offset =
15289         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
15290                         isPPC64 ? MVT::i64 : MVT::i32);
15291     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15292                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
15293                        MachinePointerInfo());
15294   }
15295 
15296   // Just load the return address off the stack.
15297   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
15298   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
15299                      MachinePointerInfo());
15300 }
15301 
15302 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
15303                                           SelectionDAG &DAG) const {
15304   SDLoc dl(Op);
15305   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15306 
15307   MachineFunction &MF = DAG.getMachineFunction();
15308   MachineFrameInfo &MFI = MF.getFrameInfo();
15309   MFI.setFrameAddressIsTaken(true);
15310 
15311   EVT PtrVT = getPointerTy(MF.getDataLayout());
15312   bool isPPC64 = PtrVT == MVT::i64;
15313 
15314   // Naked functions never have a frame pointer, and so we use r1. For all
15315   // other functions, this decision must be delayed until during PEI.
15316   unsigned FrameReg;
15317   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
15318     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
15319   else
15320     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
15321 
15322   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
15323                                          PtrVT);
15324   while (Depth--)
15325     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
15326                             FrameAddr, MachinePointerInfo());
15327   return FrameAddr;
15328 }
15329 
15330 // FIXME? Maybe this could be a TableGen attribute on some registers and
15331 // this table could be generated automatically from RegInfo.
15332 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
15333                                               const MachineFunction &MF) const {
15334   bool isPPC64 = Subtarget.isPPC64();
15335 
15336   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
15337   if (!is64Bit && VT != LLT::scalar(32))
15338     report_fatal_error("Invalid register global variable type");
15339 
15340   Register Reg = StringSwitch<Register>(RegName)
15341                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
15342                      .Case("r2", isPPC64 ? Register() : PPC::R2)
15343                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
15344                      .Default(Register());
15345 
15346   if (Reg)
15347     return Reg;
15348   report_fatal_error("Invalid register name global variable");
15349 }
15350 
15351 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
15352   // 32-bit SVR4 ABI access everything as got-indirect.
15353   if (Subtarget.is32BitELFABI())
15354     return true;
15355 
15356   // AIX accesses everything indirectly through the TOC, which is similar to
15357   // the GOT.
15358   if (Subtarget.isAIXABI())
15359     return true;
15360 
15361   CodeModel::Model CModel = getTargetMachine().getCodeModel();
15362   // If it is small or large code model, module locals are accessed
15363   // indirectly by loading their address from .toc/.got.
15364   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
15365     return true;
15366 
15367   // JumpTable and BlockAddress are accessed as got-indirect.
15368   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
15369     return true;
15370 
15371   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
15372     return Subtarget.isGVIndirectSymbol(G->getGlobal());
15373 
15374   return false;
15375 }
15376 
15377 bool
15378 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
15379   // The PowerPC target isn't yet aware of offsets.
15380   return false;
15381 }
15382 
15383 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
15384                                            const CallInst &I,
15385                                            MachineFunction &MF,
15386                                            unsigned Intrinsic) const {
15387   switch (Intrinsic) {
15388   case Intrinsic::ppc_altivec_lvx:
15389   case Intrinsic::ppc_altivec_lvxl:
15390   case Intrinsic::ppc_altivec_lvebx:
15391   case Intrinsic::ppc_altivec_lvehx:
15392   case Intrinsic::ppc_altivec_lvewx:
15393   case Intrinsic::ppc_vsx_lxvd2x:
15394   case Intrinsic::ppc_vsx_lxvw4x: {
15395     EVT VT;
15396     switch (Intrinsic) {
15397     case Intrinsic::ppc_altivec_lvebx:
15398       VT = MVT::i8;
15399       break;
15400     case Intrinsic::ppc_altivec_lvehx:
15401       VT = MVT::i16;
15402       break;
15403     case Intrinsic::ppc_altivec_lvewx:
15404       VT = MVT::i32;
15405       break;
15406     case Intrinsic::ppc_vsx_lxvd2x:
15407       VT = MVT::v2f64;
15408       break;
15409     default:
15410       VT = MVT::v4i32;
15411       break;
15412     }
15413 
15414     Info.opc = ISD::INTRINSIC_W_CHAIN;
15415     Info.memVT = VT;
15416     Info.ptrVal = I.getArgOperand(0);
15417     Info.offset = -VT.getStoreSize()+1;
15418     Info.size = 2*VT.getStoreSize()-1;
15419     Info.align = Align(1);
15420     Info.flags = MachineMemOperand::MOLoad;
15421     return true;
15422   }
15423   case Intrinsic::ppc_altivec_stvx:
15424   case Intrinsic::ppc_altivec_stvxl:
15425   case Intrinsic::ppc_altivec_stvebx:
15426   case Intrinsic::ppc_altivec_stvehx:
15427   case Intrinsic::ppc_altivec_stvewx:
15428   case Intrinsic::ppc_vsx_stxvd2x:
15429   case Intrinsic::ppc_vsx_stxvw4x: {
15430     EVT VT;
15431     switch (Intrinsic) {
15432     case Intrinsic::ppc_altivec_stvebx:
15433       VT = MVT::i8;
15434       break;
15435     case Intrinsic::ppc_altivec_stvehx:
15436       VT = MVT::i16;
15437       break;
15438     case Intrinsic::ppc_altivec_stvewx:
15439       VT = MVT::i32;
15440       break;
15441     case Intrinsic::ppc_vsx_stxvd2x:
15442       VT = MVT::v2f64;
15443       break;
15444     default:
15445       VT = MVT::v4i32;
15446       break;
15447     }
15448 
15449     Info.opc = ISD::INTRINSIC_VOID;
15450     Info.memVT = VT;
15451     Info.ptrVal = I.getArgOperand(1);
15452     Info.offset = -VT.getStoreSize()+1;
15453     Info.size = 2*VT.getStoreSize()-1;
15454     Info.align = Align(1);
15455     Info.flags = MachineMemOperand::MOStore;
15456     return true;
15457   }
15458   default:
15459     break;
15460   }
15461 
15462   return false;
15463 }
15464 
15465 /// It returns EVT::Other if the type should be determined using generic
15466 /// target-independent logic.
15467 EVT PPCTargetLowering::getOptimalMemOpType(
15468     const MemOp &Op, const AttributeList &FuncAttributes) const {
15469   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15470     // We should use Altivec/VSX loads and stores when available. For unaligned
15471     // addresses, unaligned VSX loads are only fast starting with the P8.
15472     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15473         (Op.isAligned(Align(16)) ||
15474          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15475       return MVT::v4i32;
15476   }
15477 
15478   if (Subtarget.isPPC64()) {
15479     return MVT::i64;
15480   }
15481 
15482   return MVT::i32;
15483 }
15484 
15485 /// Returns true if it is beneficial to convert a load of a constant
15486 /// to just the constant itself.
15487 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15488                                                           Type *Ty) const {
15489   assert(Ty->isIntegerTy());
15490 
15491   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15492   return !(BitSize == 0 || BitSize > 64);
15493 }
15494 
15495 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15496   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15497     return false;
15498   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15499   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15500   return NumBits1 == 64 && NumBits2 == 32;
15501 }
15502 
15503 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15504   if (!VT1.isInteger() || !VT2.isInteger())
15505     return false;
15506   unsigned NumBits1 = VT1.getSizeInBits();
15507   unsigned NumBits2 = VT2.getSizeInBits();
15508   return NumBits1 == 64 && NumBits2 == 32;
15509 }
15510 
15511 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15512   // Generally speaking, zexts are not free, but they are free when they can be
15513   // folded with other operations.
15514   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15515     EVT MemVT = LD->getMemoryVT();
15516     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15517          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15518         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15519          LD->getExtensionType() == ISD::ZEXTLOAD))
15520       return true;
15521   }
15522 
15523   // FIXME: Add other cases...
15524   //  - 32-bit shifts with a zext to i64
15525   //  - zext after ctlz, bswap, etc.
15526   //  - zext after and by a constant mask
15527 
15528   return TargetLowering::isZExtFree(Val, VT2);
15529 }
15530 
15531 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15532   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15533          "invalid fpext types");
15534   // Extending to float128 is not free.
15535   if (DestVT == MVT::f128)
15536     return false;
15537   return true;
15538 }
15539 
15540 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15541   return isInt<16>(Imm) || isUInt<16>(Imm);
15542 }
15543 
15544 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15545   return isInt<16>(Imm) || isUInt<16>(Imm);
15546 }
15547 
15548 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15549                                                        unsigned,
15550                                                        unsigned,
15551                                                        MachineMemOperand::Flags,
15552                                                        bool *Fast) const {
15553   if (DisablePPCUnaligned)
15554     return false;
15555 
15556   // PowerPC supports unaligned memory access for simple non-vector types.
15557   // Although accessing unaligned addresses is not as efficient as accessing
15558   // aligned addresses, it is generally more efficient than manual expansion,
15559   // and generally only traps for software emulation when crossing page
15560   // boundaries.
15561 
15562   if (!VT.isSimple())
15563     return false;
15564 
15565   if (VT.isFloatingPoint() && !VT.isVector() &&
15566       !Subtarget.allowsUnalignedFPAccess())
15567     return false;
15568 
15569   if (VT.getSimpleVT().isVector()) {
15570     if (Subtarget.hasVSX()) {
15571       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15572           VT != MVT::v4f32 && VT != MVT::v4i32)
15573         return false;
15574     } else {
15575       return false;
15576     }
15577   }
15578 
15579   if (VT == MVT::ppcf128)
15580     return false;
15581 
15582   if (Fast)
15583     *Fast = true;
15584 
15585   return true;
15586 }
15587 
15588 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15589                                                    EVT VT) const {
15590   return isFMAFasterThanFMulAndFAdd(
15591       MF.getFunction(), VT.getTypeForEVT(MF.getFunction().getContext()));
15592 }
15593 
15594 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
15595                                                    Type *Ty) const {
15596   switch (Ty->getScalarType()->getTypeID()) {
15597   case Type::FloatTyID:
15598   case Type::DoubleTyID:
15599     return true;
15600   case Type::FP128TyID:
15601     return Subtarget.hasP9Vector();
15602   default:
15603     return false;
15604   }
15605 }
15606 
15607 // FIXME: add more patterns which are not profitable to hoist.
15608 bool PPCTargetLowering::isProfitableToHoist(Instruction *I) const {
15609   if (!I->hasOneUse())
15610     return true;
15611 
15612   Instruction *User = I->user_back();
15613   assert(User && "A single use instruction with no uses.");
15614 
15615   switch (I->getOpcode()) {
15616   case Instruction::FMul: {
15617     // Don't break FMA, PowerPC prefers FMA.
15618     if (User->getOpcode() != Instruction::FSub &&
15619         User->getOpcode() != Instruction::FAdd)
15620       return true;
15621 
15622     const TargetOptions &Options = getTargetMachine().Options;
15623     const Function *F = I->getFunction();
15624     const DataLayout &DL = F->getParent()->getDataLayout();
15625     Type *Ty = User->getOperand(0)->getType();
15626 
15627     return !(
15628         isFMAFasterThanFMulAndFAdd(*F, Ty) &&
15629         isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
15630         (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath));
15631   }
15632   case Instruction::Load: {
15633     // Don't break "store (load float*)" pattern, this pattern will be combined
15634     // to "store (load int32)" in later InstCombine pass. See function
15635     // combineLoadToOperationType. On PowerPC, loading a float point takes more
15636     // cycles than loading a 32 bit integer.
15637     LoadInst *LI = cast<LoadInst>(I);
15638     // For the loads that combineLoadToOperationType does nothing, like
15639     // ordered load, it should be profitable to hoist them.
15640     // For swifterror load, it can only be used for pointer to pointer type, so
15641     // later type check should get rid of this case.
15642     if (!LI->isUnordered())
15643       return true;
15644 
15645     if (User->getOpcode() != Instruction::Store)
15646       return true;
15647 
15648     if (I->getType()->getTypeID() != Type::FloatTyID)
15649       return true;
15650 
15651     return false;
15652   }
15653   default:
15654     return true;
15655   }
15656   return true;
15657 }
15658 
15659 const MCPhysReg *
15660 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15661   // LR is a callee-save register, but we must treat it as clobbered by any call
15662   // site. Hence we include LR in the scratch registers, which are in turn added
15663   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15664   // to CTR, which is used by any indirect call.
15665   static const MCPhysReg ScratchRegs[] = {
15666     PPC::X12, PPC::LR8, PPC::CTR8, 0
15667   };
15668 
15669   return ScratchRegs;
15670 }
15671 
15672 Register PPCTargetLowering::getExceptionPointerRegister(
15673     const Constant *PersonalityFn) const {
15674   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15675 }
15676 
15677 Register PPCTargetLowering::getExceptionSelectorRegister(
15678     const Constant *PersonalityFn) const {
15679   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15680 }
15681 
15682 bool
15683 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15684                      EVT VT , unsigned DefinedValues) const {
15685   if (VT == MVT::v2i64)
15686     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15687 
15688   if (Subtarget.hasVSX())
15689     return true;
15690 
15691   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15692 }
15693 
15694 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15695   if (DisableILPPref || Subtarget.enableMachineScheduler())
15696     return TargetLowering::getSchedulingPreference(N);
15697 
15698   return Sched::ILP;
15699 }
15700 
15701 // Create a fast isel object.
15702 FastISel *
15703 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15704                                   const TargetLibraryInfo *LibInfo) const {
15705   return PPC::createFastISel(FuncInfo, LibInfo);
15706 }
15707 
15708 // 'Inverted' means the FMA opcode after negating one multiplicand.
15709 // For example, (fma -a b c) = (fnmsub a b c)
15710 static unsigned invertFMAOpcode(unsigned Opc) {
15711   switch (Opc) {
15712   default:
15713     llvm_unreachable("Invalid FMA opcode for PowerPC!");
15714   case ISD::FMA:
15715     return PPCISD::FNMSUB;
15716   case PPCISD::FNMSUB:
15717     return ISD::FMA;
15718   }
15719 }
15720 
15721 SDValue PPCTargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
15722                                                 bool LegalOps, bool OptForSize,
15723                                                 NegatibleCost &Cost,
15724                                                 unsigned Depth) const {
15725   if (Depth > SelectionDAG::MaxRecursionDepth)
15726     return SDValue();
15727 
15728   unsigned Opc = Op.getOpcode();
15729   EVT VT = Op.getValueType();
15730   SDNodeFlags Flags = Op.getNode()->getFlags();
15731 
15732   switch (Opc) {
15733   case PPCISD::FNMSUB:
15734     if (!Op.hasOneUse() || !isTypeLegal(VT))
15735       break;
15736 
15737     const TargetOptions &Options = getTargetMachine().Options;
15738     SDValue N0 = Op.getOperand(0);
15739     SDValue N1 = Op.getOperand(1);
15740     SDValue N2 = Op.getOperand(2);
15741     SDLoc Loc(Op);
15742 
15743     NegatibleCost N2Cost = NegatibleCost::Expensive;
15744     SDValue NegN2 =
15745         getNegatedExpression(N2, DAG, LegalOps, OptForSize, N2Cost, Depth + 1);
15746 
15747     if (!NegN2)
15748       return SDValue();
15749 
15750     // (fneg (fnmsub a b c)) => (fnmsub (fneg a) b (fneg c))
15751     // (fneg (fnmsub a b c)) => (fnmsub a (fneg b) (fneg c))
15752     // These transformations may change sign of zeroes. For example,
15753     // -(-ab-(-c))=-0 while -(-(ab-c))=+0 when a=b=c=1.
15754     if (Flags.hasNoSignedZeros() || Options.NoSignedZerosFPMath) {
15755       // Try and choose the cheaper one to negate.
15756       NegatibleCost N0Cost = NegatibleCost::Expensive;
15757       SDValue NegN0 = getNegatedExpression(N0, DAG, LegalOps, OptForSize,
15758                                            N0Cost, Depth + 1);
15759 
15760       NegatibleCost N1Cost = NegatibleCost::Expensive;
15761       SDValue NegN1 = getNegatedExpression(N1, DAG, LegalOps, OptForSize,
15762                                            N1Cost, Depth + 1);
15763 
15764       if (NegN0 && N0Cost <= N1Cost) {
15765         Cost = std::min(N0Cost, N2Cost);
15766         return DAG.getNode(Opc, Loc, VT, NegN0, N1, NegN2, Flags);
15767       } else if (NegN1) {
15768         Cost = std::min(N1Cost, N2Cost);
15769         return DAG.getNode(Opc, Loc, VT, N0, NegN1, NegN2, Flags);
15770       }
15771     }
15772 
15773     // (fneg (fnmsub a b c)) => (fma a b (fneg c))
15774     if (isOperationLegal(ISD::FMA, VT)) {
15775       Cost = N2Cost;
15776       return DAG.getNode(ISD::FMA, Loc, VT, N0, N1, NegN2, Flags);
15777     }
15778 
15779     break;
15780   }
15781 
15782   return TargetLowering::getNegatedExpression(Op, DAG, LegalOps, OptForSize,
15783                                               Cost, Depth);
15784 }
15785 
15786 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15787 bool PPCTargetLowering::useLoadStackGuardNode() const {
15788   if (!Subtarget.isTargetLinux())
15789     return TargetLowering::useLoadStackGuardNode();
15790   return true;
15791 }
15792 
15793 // Override to disable global variable loading on Linux.
15794 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15795   if (!Subtarget.isTargetLinux())
15796     return TargetLowering::insertSSPDeclarations(M);
15797 }
15798 
15799 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15800                                      bool ForCodeSize) const {
15801   if (!VT.isSimple() || !Subtarget.hasVSX())
15802     return false;
15803 
15804   switch(VT.getSimpleVT().SimpleTy) {
15805   default:
15806     // For FP types that are currently not supported by PPC backend, return
15807     // false. Examples: f16, f80.
15808     return false;
15809   case MVT::f32:
15810   case MVT::f64:
15811     if (Subtarget.hasPrefixInstrs()) {
15812       // With prefixed instructions, we can materialize anything that can be
15813       // represented with a 32-bit immediate, not just positive zero.
15814       APFloat APFloatOfImm = Imm;
15815       return convertToNonDenormSingle(APFloatOfImm);
15816     }
15817     LLVM_FALLTHROUGH;
15818   case MVT::ppcf128:
15819     return Imm.isPosZero();
15820   }
15821 }
15822 
15823 // For vector shift operation op, fold
15824 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15825 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15826                                   SelectionDAG &DAG) {
15827   SDValue N0 = N->getOperand(0);
15828   SDValue N1 = N->getOperand(1);
15829   EVT VT = N0.getValueType();
15830   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15831   unsigned Opcode = N->getOpcode();
15832   unsigned TargetOpcode;
15833 
15834   switch (Opcode) {
15835   default:
15836     llvm_unreachable("Unexpected shift operation");
15837   case ISD::SHL:
15838     TargetOpcode = PPCISD::SHL;
15839     break;
15840   case ISD::SRL:
15841     TargetOpcode = PPCISD::SRL;
15842     break;
15843   case ISD::SRA:
15844     TargetOpcode = PPCISD::SRA;
15845     break;
15846   }
15847 
15848   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15849       N1->getOpcode() == ISD::AND)
15850     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15851       if (Mask->getZExtValue() == OpSizeInBits - 1)
15852         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15853 
15854   return SDValue();
15855 }
15856 
15857 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15858   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15859     return Value;
15860 
15861   SDValue N0 = N->getOperand(0);
15862   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15863   if (!Subtarget.isISA3_0() ||
15864       N0.getOpcode() != ISD::SIGN_EXTEND ||
15865       N0.getOperand(0).getValueType() != MVT::i32 ||
15866       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15867     return SDValue();
15868 
15869   // We can't save an operation here if the value is already extended, and
15870   // the existing shift is easier to combine.
15871   SDValue ExtsSrc = N0.getOperand(0);
15872   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15873       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15874     return SDValue();
15875 
15876   SDLoc DL(N0);
15877   SDValue ShiftBy = SDValue(CN1, 0);
15878   // We want the shift amount to be i32 on the extswli, but the shift could
15879   // have an i64.
15880   if (ShiftBy.getValueType() == MVT::i64)
15881     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15882 
15883   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15884                          ShiftBy);
15885 }
15886 
15887 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15888   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15889     return Value;
15890 
15891   return SDValue();
15892 }
15893 
15894 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15895   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15896     return Value;
15897 
15898   return SDValue();
15899 }
15900 
15901 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15902 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15903 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15904 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15905 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15906                                  const PPCSubtarget &Subtarget) {
15907   if (!Subtarget.isPPC64())
15908     return SDValue();
15909 
15910   SDValue LHS = N->getOperand(0);
15911   SDValue RHS = N->getOperand(1);
15912 
15913   auto isZextOfCompareWithConstant = [](SDValue Op) {
15914     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15915         Op.getValueType() != MVT::i64)
15916       return false;
15917 
15918     SDValue Cmp = Op.getOperand(0);
15919     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15920         Cmp.getOperand(0).getValueType() != MVT::i64)
15921       return false;
15922 
15923     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15924       int64_t NegConstant = 0 - Constant->getSExtValue();
15925       // Due to the limitations of the addi instruction,
15926       // -C is required to be [-32768, 32767].
15927       return isInt<16>(NegConstant);
15928     }
15929 
15930     return false;
15931   };
15932 
15933   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15934   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15935 
15936   // If there is a pattern, canonicalize a zext operand to the RHS.
15937   if (LHSHasPattern && !RHSHasPattern)
15938     std::swap(LHS, RHS);
15939   else if (!LHSHasPattern && !RHSHasPattern)
15940     return SDValue();
15941 
15942   SDLoc DL(N);
15943   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15944   SDValue Cmp = RHS.getOperand(0);
15945   SDValue Z = Cmp.getOperand(0);
15946   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15947 
15948   assert(Constant && "Constant Should not be a null pointer.");
15949   int64_t NegConstant = 0 - Constant->getSExtValue();
15950 
15951   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15952   default: break;
15953   case ISD::SETNE: {
15954     //                                 when C == 0
15955     //                             --> addze X, (addic Z, -1).carry
15956     //                            /
15957     // add X, (zext(setne Z, C))--
15958     //                            \    when -32768 <= -C <= 32767 && C != 0
15959     //                             --> addze X, (addic (addi Z, -C), -1).carry
15960     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15961                               DAG.getConstant(NegConstant, DL, MVT::i64));
15962     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15963     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15964                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15965     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15966                        SDValue(Addc.getNode(), 1));
15967     }
15968   case ISD::SETEQ: {
15969     //                                 when C == 0
15970     //                             --> addze X, (subfic Z, 0).carry
15971     //                            /
15972     // add X, (zext(sete  Z, C))--
15973     //                            \    when -32768 <= -C <= 32767 && C != 0
15974     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15975     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15976                               DAG.getConstant(NegConstant, DL, MVT::i64));
15977     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15978     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15979                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15980     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15981                        SDValue(Subc.getNode(), 1));
15982     }
15983   }
15984 
15985   return SDValue();
15986 }
15987 
15988 // Transform
15989 // (add C1, (MAT_PCREL_ADDR GlobalAddr+C2)) to
15990 // (MAT_PCREL_ADDR GlobalAddr+(C1+C2))
15991 // In this case both C1 and C2 must be known constants.
15992 // C1+C2 must fit into a 34 bit signed integer.
15993 static SDValue combineADDToMAT_PCREL_ADDR(SDNode *N, SelectionDAG &DAG,
15994                                           const PPCSubtarget &Subtarget) {
15995   if (!Subtarget.isUsingPCRelativeCalls())
15996     return SDValue();
15997 
15998   // Check both Operand 0 and Operand 1 of the ADD node for the PCRel node.
15999   // If we find that node try to cast the Global Address and the Constant.
16000   SDValue LHS = N->getOperand(0);
16001   SDValue RHS = N->getOperand(1);
16002 
16003   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16004     std::swap(LHS, RHS);
16005 
16006   if (LHS.getOpcode() != PPCISD::MAT_PCREL_ADDR)
16007     return SDValue();
16008 
16009   // Operand zero of PPCISD::MAT_PCREL_ADDR is the GA node.
16010   GlobalAddressSDNode *GSDN = dyn_cast<GlobalAddressSDNode>(LHS.getOperand(0));
16011   ConstantSDNode* ConstNode = dyn_cast<ConstantSDNode>(RHS);
16012 
16013   // Check that both casts succeeded.
16014   if (!GSDN || !ConstNode)
16015     return SDValue();
16016 
16017   int64_t NewOffset = GSDN->getOffset() + ConstNode->getSExtValue();
16018   SDLoc DL(GSDN);
16019 
16020   // The signed int offset needs to fit in 34 bits.
16021   if (!isInt<34>(NewOffset))
16022     return SDValue();
16023 
16024   // The new global address is a copy of the old global address except
16025   // that it has the updated Offset.
16026   SDValue GA =
16027       DAG.getTargetGlobalAddress(GSDN->getGlobal(), DL, GSDN->getValueType(0),
16028                                  NewOffset, GSDN->getTargetFlags());
16029   SDValue MatPCRel =
16030       DAG.getNode(PPCISD::MAT_PCREL_ADDR, DL, GSDN->getValueType(0), GA);
16031   return MatPCRel;
16032 }
16033 
16034 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
16035   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
16036     return Value;
16037 
16038   if (auto Value = combineADDToMAT_PCREL_ADDR(N, DCI.DAG, Subtarget))
16039     return Value;
16040 
16041   return SDValue();
16042 }
16043 
16044 // Detect TRUNCATE operations on bitcasts of float128 values.
16045 // What we are looking for here is the situtation where we extract a subset
16046 // of bits from a 128 bit float.
16047 // This can be of two forms:
16048 // 1) BITCAST of f128 feeding TRUNCATE
16049 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
16050 // The reason this is required is because we do not have a legal i128 type
16051 // and so we want to prevent having to store the f128 and then reload part
16052 // of it.
16053 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
16054                                            DAGCombinerInfo &DCI) const {
16055   // If we are using CRBits then try that first.
16056   if (Subtarget.useCRBits()) {
16057     // Check if CRBits did anything and return that if it did.
16058     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
16059       return CRTruncValue;
16060   }
16061 
16062   SDLoc dl(N);
16063   SDValue Op0 = N->getOperand(0);
16064 
16065   // fold (truncate (abs (sub (zext a), (zext b)))) -> (vabsd a, b)
16066   if (Subtarget.hasP9Altivec() && Op0.getOpcode() == ISD::ABS) {
16067     EVT VT = N->getValueType(0);
16068     if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16069       return SDValue();
16070     SDValue Sub = Op0.getOperand(0);
16071     if (Sub.getOpcode() == ISD::SUB) {
16072       SDValue SubOp0 = Sub.getOperand(0);
16073       SDValue SubOp1 = Sub.getOperand(1);
16074       if ((SubOp0.getOpcode() == ISD::ZERO_EXTEND) &&
16075           (SubOp1.getOpcode() == ISD::ZERO_EXTEND)) {
16076         return DCI.DAG.getNode(PPCISD::VABSD, dl, VT, SubOp0.getOperand(0),
16077                                SubOp1.getOperand(0),
16078                                DCI.DAG.getTargetConstant(0, dl, MVT::i32));
16079       }
16080     }
16081   }
16082 
16083   // Looking for a truncate of i128 to i64.
16084   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
16085     return SDValue();
16086 
16087   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
16088 
16089   // SRL feeding TRUNCATE.
16090   if (Op0.getOpcode() == ISD::SRL) {
16091     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
16092     // The right shift has to be by 64 bits.
16093     if (!ConstNode || ConstNode->getZExtValue() != 64)
16094       return SDValue();
16095 
16096     // Switch the element number to extract.
16097     EltToExtract = EltToExtract ? 0 : 1;
16098     // Update Op0 past the SRL.
16099     Op0 = Op0.getOperand(0);
16100   }
16101 
16102   // BITCAST feeding a TRUNCATE possibly via SRL.
16103   if (Op0.getOpcode() == ISD::BITCAST &&
16104       Op0.getValueType() == MVT::i128 &&
16105       Op0.getOperand(0).getValueType() == MVT::f128) {
16106     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
16107     return DCI.DAG.getNode(
16108         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
16109         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
16110   }
16111   return SDValue();
16112 }
16113 
16114 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
16115   SelectionDAG &DAG = DCI.DAG;
16116 
16117   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
16118   if (!ConstOpOrElement)
16119     return SDValue();
16120 
16121   // An imul is usually smaller than the alternative sequence for legal type.
16122   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
16123       isOperationLegal(ISD::MUL, N->getValueType(0)))
16124     return SDValue();
16125 
16126   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
16127     switch (this->Subtarget.getCPUDirective()) {
16128     default:
16129       // TODO: enhance the condition for subtarget before pwr8
16130       return false;
16131     case PPC::DIR_PWR8:
16132       //  type        mul     add    shl
16133       // scalar        4       1      1
16134       // vector        7       2      2
16135       return true;
16136     case PPC::DIR_PWR9:
16137     case PPC::DIR_PWR10:
16138     case PPC::DIR_PWR_FUTURE:
16139       //  type        mul     add    shl
16140       // scalar        5       2      2
16141       // vector        7       2      2
16142 
16143       // The cycle RATIO of related operations are showed as a table above.
16144       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
16145       // scalar and vector type. For 2 instrs patterns, add/sub + shl
16146       // are 4, it is always profitable; but for 3 instrs patterns
16147       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
16148       // So we should only do it for vector type.
16149       return IsAddOne && IsNeg ? VT.isVector() : true;
16150     }
16151   };
16152 
16153   EVT VT = N->getValueType(0);
16154   SDLoc DL(N);
16155 
16156   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
16157   bool IsNeg = MulAmt.isNegative();
16158   APInt MulAmtAbs = MulAmt.abs();
16159 
16160   if ((MulAmtAbs - 1).isPowerOf2()) {
16161     // (mul x, 2^N + 1) => (add (shl x, N), x)
16162     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
16163 
16164     if (!IsProfitable(IsNeg, true, VT))
16165       return SDValue();
16166 
16167     SDValue Op0 = N->getOperand(0);
16168     SDValue Op1 =
16169         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16170                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
16171     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
16172 
16173     if (!IsNeg)
16174       return Res;
16175 
16176     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
16177   } else if ((MulAmtAbs + 1).isPowerOf2()) {
16178     // (mul x, 2^N - 1) => (sub (shl x, N), x)
16179     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
16180 
16181     if (!IsProfitable(IsNeg, false, VT))
16182       return SDValue();
16183 
16184     SDValue Op0 = N->getOperand(0);
16185     SDValue Op1 =
16186         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
16187                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
16188 
16189     if (!IsNeg)
16190       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
16191     else
16192       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
16193 
16194   } else {
16195     return SDValue();
16196   }
16197 }
16198 
16199 // Combine fma-like op (like fnmsub) with fnegs to appropriate op. Do this
16200 // in combiner since we need to check SD flags and other subtarget features.
16201 SDValue PPCTargetLowering::combineFMALike(SDNode *N,
16202                                           DAGCombinerInfo &DCI) const {
16203   SDValue N0 = N->getOperand(0);
16204   SDValue N1 = N->getOperand(1);
16205   SDValue N2 = N->getOperand(2);
16206   SDNodeFlags Flags = N->getFlags();
16207   EVT VT = N->getValueType(0);
16208   SelectionDAG &DAG = DCI.DAG;
16209   const TargetOptions &Options = getTargetMachine().Options;
16210   unsigned Opc = N->getOpcode();
16211   bool CodeSize = DAG.getMachineFunction().getFunction().hasOptSize();
16212   bool LegalOps = !DCI.isBeforeLegalizeOps();
16213   SDLoc Loc(N);
16214 
16215   if (!isOperationLegal(ISD::FMA, VT))
16216     return SDValue();
16217 
16218   // Allowing transformation to FNMSUB may change sign of zeroes when ab-c=0
16219   // since (fnmsub a b c)=-0 while c-ab=+0.
16220   if (!Flags.hasNoSignedZeros() && !Options.NoSignedZerosFPMath)
16221     return SDValue();
16222 
16223   // (fma (fneg a) b c) => (fnmsub a b c)
16224   // (fnmsub (fneg a) b c) => (fma a b c)
16225   if (SDValue NegN0 = getCheaperNegatedExpression(N0, DAG, LegalOps, CodeSize))
16226     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, NegN0, N1, N2, Flags);
16227 
16228   // (fma a (fneg b) c) => (fnmsub a b c)
16229   // (fnmsub a (fneg b) c) => (fma a b c)
16230   if (SDValue NegN1 = getCheaperNegatedExpression(N1, DAG, LegalOps, CodeSize))
16231     return DAG.getNode(invertFMAOpcode(Opc), Loc, VT, N0, NegN1, N2, Flags);
16232 
16233   return SDValue();
16234 }
16235 
16236 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
16237   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
16238   if (!Subtarget.is64BitELFABI())
16239     return false;
16240 
16241   // If not a tail call then no need to proceed.
16242   if (!CI->isTailCall())
16243     return false;
16244 
16245   // If sibling calls have been disabled and tail-calls aren't guaranteed
16246   // there is no reason to duplicate.
16247   auto &TM = getTargetMachine();
16248   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
16249     return false;
16250 
16251   // Can't tail call a function called indirectly, or if it has variadic args.
16252   const Function *Callee = CI->getCalledFunction();
16253   if (!Callee || Callee->isVarArg())
16254     return false;
16255 
16256   // Make sure the callee and caller calling conventions are eligible for tco.
16257   const Function *Caller = CI->getParent()->getParent();
16258   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
16259                                            CI->getCallingConv()))
16260       return false;
16261 
16262   // If the function is local then we have a good chance at tail-calling it
16263   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
16264 }
16265 
16266 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
16267   if (!Subtarget.hasVSX())
16268     return false;
16269   if (Subtarget.hasP9Vector() && VT == MVT::f128)
16270     return true;
16271   return VT == MVT::f32 || VT == MVT::f64 ||
16272     VT == MVT::v4f32 || VT == MVT::v2f64;
16273 }
16274 
16275 bool PPCTargetLowering::
16276 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
16277   const Value *Mask = AndI.getOperand(1);
16278   // If the mask is suitable for andi. or andis. we should sink the and.
16279   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
16280     // Can't handle constants wider than 64-bits.
16281     if (CI->getBitWidth() > 64)
16282       return false;
16283     int64_t ConstVal = CI->getZExtValue();
16284     return isUInt<16>(ConstVal) ||
16285       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
16286   }
16287 
16288   // For non-constant masks, we can always use the record-form and.
16289   return true;
16290 }
16291 
16292 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
16293 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
16294 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
16295 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
16296 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
16297 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
16298   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
16299   assert(Subtarget.hasP9Altivec() &&
16300          "Only combine this when P9 altivec supported!");
16301   EVT VT = N->getValueType(0);
16302   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16303     return SDValue();
16304 
16305   SelectionDAG &DAG = DCI.DAG;
16306   SDLoc dl(N);
16307   if (N->getOperand(0).getOpcode() == ISD::SUB) {
16308     // Even for signed integers, if it's known to be positive (as signed
16309     // integer) due to zero-extended inputs.
16310     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
16311     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
16312     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
16313          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
16314         (SubOpcd1 == ISD::ZERO_EXTEND ||
16315          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
16316       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16317                          N->getOperand(0)->getOperand(0),
16318                          N->getOperand(0)->getOperand(1),
16319                          DAG.getTargetConstant(0, dl, MVT::i32));
16320     }
16321 
16322     // For type v4i32, it can be optimized with xvnegsp + vabsduw
16323     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
16324         N->getOperand(0).hasOneUse()) {
16325       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
16326                          N->getOperand(0)->getOperand(0),
16327                          N->getOperand(0)->getOperand(1),
16328                          DAG.getTargetConstant(1, dl, MVT::i32));
16329     }
16330   }
16331 
16332   return SDValue();
16333 }
16334 
16335 // For type v4i32/v8ii16/v16i8, transform
16336 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
16337 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
16338 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
16339 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
16340 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
16341                                           DAGCombinerInfo &DCI) const {
16342   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
16343   assert(Subtarget.hasP9Altivec() &&
16344          "Only combine this when P9 altivec supported!");
16345 
16346   SelectionDAG &DAG = DCI.DAG;
16347   SDLoc dl(N);
16348   SDValue Cond = N->getOperand(0);
16349   SDValue TrueOpnd = N->getOperand(1);
16350   SDValue FalseOpnd = N->getOperand(2);
16351   EVT VT = N->getOperand(1).getValueType();
16352 
16353   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
16354       FalseOpnd.getOpcode() != ISD::SUB)
16355     return SDValue();
16356 
16357   // ABSD only available for type v4i32/v8i16/v16i8
16358   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
16359     return SDValue();
16360 
16361   // At least to save one more dependent computation
16362   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
16363     return SDValue();
16364 
16365   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
16366 
16367   // Can only handle unsigned comparison here
16368   switch (CC) {
16369   default:
16370     return SDValue();
16371   case ISD::SETUGT:
16372   case ISD::SETUGE:
16373     break;
16374   case ISD::SETULT:
16375   case ISD::SETULE:
16376     std::swap(TrueOpnd, FalseOpnd);
16377     break;
16378   }
16379 
16380   SDValue CmpOpnd1 = Cond.getOperand(0);
16381   SDValue CmpOpnd2 = Cond.getOperand(1);
16382 
16383   // SETCC CmpOpnd1 CmpOpnd2 cond
16384   // TrueOpnd = CmpOpnd1 - CmpOpnd2
16385   // FalseOpnd = CmpOpnd2 - CmpOpnd1
16386   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
16387       TrueOpnd.getOperand(1) == CmpOpnd2 &&
16388       FalseOpnd.getOperand(0) == CmpOpnd2 &&
16389       FalseOpnd.getOperand(1) == CmpOpnd1) {
16390     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
16391                        CmpOpnd1, CmpOpnd2,
16392                        DAG.getTargetConstant(0, dl, MVT::i32));
16393   }
16394 
16395   return SDValue();
16396 }
16397