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/CallSite.h"
59 #include "llvm/IR/CallingConv.h"
60 #include "llvm/IR/Constant.h"
61 #include "llvm/IR/Constants.h"
62 #include "llvm/IR/DataLayout.h"
63 #include "llvm/IR/DebugLoc.h"
64 #include "llvm/IR/DerivedTypes.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/GlobalValue.h"
67 #include "llvm/IR/IRBuilder.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Intrinsics.h"
70 #include "llvm/IR/IntrinsicsPowerPC.h"
71 #include "llvm/IR/Module.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/MC/MCContext.h"
76 #include "llvm/MC/MCExpr.h"
77 #include "llvm/MC/MCRegisterInfo.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> EnableQuadPrecision("enable-ppc-quad-precision",
122 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
123 
124 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
125 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
126 
127 STATISTIC(NumTailCalls, "Number of tail calls");
128 STATISTIC(NumSiblingCalls, "Number of sibling calls");
129 
130 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
131 
132 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
133 
134 // FIXME: Remove this once the bug has been fixed!
135 extern cl::opt<bool> ANDIGlueBug;
136 
137 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
138                                      const PPCSubtarget &STI)
139     : TargetLowering(TM), Subtarget(STI) {
140   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
141   // arguments are at least 4/8 bytes aligned.
142   bool isPPC64 = Subtarget.isPPC64();
143   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
144 
145   // Set up the register classes.
146   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
147   if (!useSoftFloat()) {
148     if (hasSPE()) {
149       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
150       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
151     } else {
152       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
153       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
154     }
155   }
156 
157   // Match BITREVERSE to customized fast code sequence in the td file.
158   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
159   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
160 
161   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
162   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
163 
164   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
165   for (MVT VT : MVT::integer_valuetypes()) {
166     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
167     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
168   }
169 
170   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
171 
172   // PowerPC has pre-inc load and store's.
173   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
174   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
175   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
178   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
179   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
180   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
183   if (!Subtarget.hasSPE()) {
184     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
185     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
186     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
187     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
188   }
189 
190   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
191   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
192   for (MVT VT : ScalarIntVTs) {
193     setOperationAction(ISD::ADDC, VT, Legal);
194     setOperationAction(ISD::ADDE, VT, Legal);
195     setOperationAction(ISD::SUBC, VT, Legal);
196     setOperationAction(ISD::SUBE, VT, Legal);
197   }
198 
199   if (Subtarget.useCRBits()) {
200     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
201 
202     if (isPPC64 || Subtarget.hasFPCVT()) {
203       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
204       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
205                          isPPC64 ? MVT::i64 : MVT::i32);
206       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
207       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
208                         isPPC64 ? MVT::i64 : MVT::i32);
209     } else {
210       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
211       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
212     }
213 
214     // PowerPC does not support direct load/store of condition registers.
215     setOperationAction(ISD::LOAD, MVT::i1, Custom);
216     setOperationAction(ISD::STORE, MVT::i1, Custom);
217 
218     // FIXME: Remove this once the ANDI glue bug is fixed:
219     if (ANDIGlueBug)
220       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
221 
222     for (MVT VT : MVT::integer_valuetypes()) {
223       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
225       setTruncStoreAction(VT, MVT::i1, Expand);
226     }
227 
228     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
229   }
230 
231   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
232   // PPC (the libcall is not available).
233   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
234   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
235 
236   // We do not currently implement these libm ops for PowerPC.
237   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
238   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
239   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
240   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
241   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
242   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
243 
244   // PowerPC has no SREM/UREM instructions unless we are on P9
245   // On P9 we may use a hardware instruction to compute the remainder.
246   // The instructions are not legalized directly because in the cases where the
247   // result of both the remainder and the division is required it is more
248   // efficient to compute the remainder from the result of the division rather
249   // than use the remainder instruction.
250   if (Subtarget.isISA3_0()) {
251     setOperationAction(ISD::SREM, MVT::i32, Custom);
252     setOperationAction(ISD::UREM, MVT::i32, Custom);
253     setOperationAction(ISD::SREM, MVT::i64, Custom);
254     setOperationAction(ISD::UREM, MVT::i64, Custom);
255   } else {
256     setOperationAction(ISD::SREM, MVT::i32, Expand);
257     setOperationAction(ISD::UREM, MVT::i32, Expand);
258     setOperationAction(ISD::SREM, MVT::i64, Expand);
259     setOperationAction(ISD::UREM, MVT::i64, Expand);
260   }
261 
262   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
263   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
264   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
265   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
266   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
267   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
268   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
269   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
270   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
271 
272   // We don't support sin/cos/sqrt/fmod/pow
273   setOperationAction(ISD::FSIN , MVT::f64, Expand);
274   setOperationAction(ISD::FCOS , MVT::f64, Expand);
275   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
276   setOperationAction(ISD::FREM , MVT::f64, Expand);
277   setOperationAction(ISD::FPOW , MVT::f64, Expand);
278   setOperationAction(ISD::FSIN , MVT::f32, Expand);
279   setOperationAction(ISD::FCOS , MVT::f32, Expand);
280   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
281   setOperationAction(ISD::FREM , MVT::f32, Expand);
282   setOperationAction(ISD::FPOW , MVT::f32, Expand);
283   if (Subtarget.hasSPE()) {
284     setOperationAction(ISD::FMA  , MVT::f64, Expand);
285     setOperationAction(ISD::FMA  , MVT::f32, Expand);
286   } else {
287     setOperationAction(ISD::FMA  , MVT::f64, Legal);
288     setOperationAction(ISD::FMA  , MVT::f32, Legal);
289   }
290 
291   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
292 
293   // If we're enabling GP optimizations, use hardware square root
294   if (!Subtarget.hasFSQRT() &&
295       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
296         Subtarget.hasFRE()))
297     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
298 
299   if (!Subtarget.hasFSQRT() &&
300       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
301         Subtarget.hasFRES()))
302     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
303 
304   if (Subtarget.hasFCPSGN()) {
305     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
306     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
307   } else {
308     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
309     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
310   }
311 
312   if (Subtarget.hasFPRND()) {
313     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
314     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
315     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
316     setOperationAction(ISD::FROUND, MVT::f64, Legal);
317 
318     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
319     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
320     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
321     setOperationAction(ISD::FROUND, MVT::f32, Legal);
322   }
323 
324   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
325   // to speed up scalar BSWAP64.
326   // CTPOP or CTTZ were introduced in P8/P9 respectively
327   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
328   if (Subtarget.hasP9Vector())
329     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
330   else
331     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
332   if (Subtarget.isISA3_0()) {
333     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
334     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
335   } else {
336     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
337     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
338   }
339 
340   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
341     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
342     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
343   } else {
344     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
345     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
346   }
347 
348   // PowerPC does not have ROTR
349   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
350   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
351 
352   if (!Subtarget.useCRBits()) {
353     // PowerPC does not have Select
354     setOperationAction(ISD::SELECT, MVT::i32, Expand);
355     setOperationAction(ISD::SELECT, MVT::i64, Expand);
356     setOperationAction(ISD::SELECT, MVT::f32, Expand);
357     setOperationAction(ISD::SELECT, MVT::f64, Expand);
358   }
359 
360   // PowerPC wants to turn select_cc of FP into fsel when possible.
361   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
362   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
363 
364   // PowerPC wants to optimize integer setcc a bit
365   if (!Subtarget.useCRBits())
366     setOperationAction(ISD::SETCC, MVT::i32, Custom);
367 
368   // PowerPC does not have BRCOND which requires SetCC
369   if (!Subtarget.useCRBits())
370     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
371 
372   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
373 
374   if (Subtarget.hasSPE()) {
375     // SPE has built-in conversions
376     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
377     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
378     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
379   } else {
380     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
381     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
382 
383     // PowerPC does not have [U|S]INT_TO_FP
384     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
385     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
386   }
387 
388   if (Subtarget.hasDirectMove() && isPPC64) {
389     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
390     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
391     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
392     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
393     if (TM.Options.UnsafeFPMath) {
394       setOperationAction(ISD::LRINT, MVT::f64, Legal);
395       setOperationAction(ISD::LRINT, MVT::f32, Legal);
396       setOperationAction(ISD::LLRINT, MVT::f64, Legal);
397       setOperationAction(ISD::LLRINT, MVT::f32, Legal);
398       setOperationAction(ISD::LROUND, MVT::f64, Legal);
399       setOperationAction(ISD::LROUND, MVT::f32, Legal);
400       setOperationAction(ISD::LLROUND, MVT::f64, Legal);
401       setOperationAction(ISD::LLROUND, MVT::f32, Legal);
402     }
403   } else {
404     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
405     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
406     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
407     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
408   }
409 
410   // We cannot sextinreg(i1).  Expand to shifts.
411   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
412 
413   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
414   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
415   // support continuation, user-level threading, and etc.. As a result, no
416   // other SjLj exception interfaces are implemented and please don't build
417   // your own exception handling based on them.
418   // LLVM/Clang supports zero-cost DWARF exception handling.
419   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
420   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
421 
422   // We want to legalize GlobalAddress and ConstantPool nodes into the
423   // appropriate instructions to materialize the address.
424   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
425   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
426   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
427   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
428   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
429   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
430   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
431   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
432   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
433   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
434 
435   // TRAP is legal.
436   setOperationAction(ISD::TRAP, MVT::Other, Legal);
437 
438   // TRAMPOLINE is custom lowered.
439   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
440   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
441 
442   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
443   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
444 
445   if (Subtarget.is64BitELFABI()) {
446     // VAARG always uses double-word chunks, so promote anything smaller.
447     setOperationAction(ISD::VAARG, MVT::i1, Promote);
448     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
449     setOperationAction(ISD::VAARG, MVT::i8, Promote);
450     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
451     setOperationAction(ISD::VAARG, MVT::i16, Promote);
452     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
453     setOperationAction(ISD::VAARG, MVT::i32, Promote);
454     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
455     setOperationAction(ISD::VAARG, MVT::Other, Expand);
456   } else if (Subtarget.is32BitELFABI()) {
457     // VAARG is custom lowered with the 32-bit SVR4 ABI.
458     setOperationAction(ISD::VAARG, MVT::Other, Custom);
459     setOperationAction(ISD::VAARG, MVT::i64, Custom);
460   } else
461     setOperationAction(ISD::VAARG, MVT::Other, Expand);
462 
463   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
464   if (Subtarget.is32BitELFABI())
465     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
466   else
467     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
468 
469   // Use the default implementation.
470   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
471   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
472   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
473   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
474   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
475   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
476   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
477   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
478   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
479 
480   // We want to custom lower some of our intrinsics.
481   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
482 
483   // To handle counter-based loop conditions.
484   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
485 
486   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
487   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
488   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
489   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
490 
491   // Comparisons that require checking two conditions.
492   if (Subtarget.hasSPE()) {
493     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
494     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
495     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
496     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
497   }
498   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
499   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
500   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
501   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
502   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
503   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
504   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
505   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
506   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
507   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
508   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
509   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
510 
511   if (Subtarget.has64BitSupport()) {
512     // They also have instructions for converting between i64 and fp.
513     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
514     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
515     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
516     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
517     // This is just the low 32 bits of a (signed) fp->i64 conversion.
518     // We cannot do this with Promote because i64 is not a legal type.
519     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
520 
521     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
522       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
523   } else {
524     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
525     if (Subtarget.hasSPE())
526       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
527     else
528       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
529   }
530 
531   // With the instructions enabled under FPCVT, we can do everything.
532   if (Subtarget.hasFPCVT()) {
533     if (Subtarget.has64BitSupport()) {
534       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
535       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
536       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
537       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
538     }
539 
540     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
541     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
542     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
543     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
544   }
545 
546   if (Subtarget.use64BitRegs()) {
547     // 64-bit PowerPC implementations can support i64 types directly
548     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
549     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
550     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
551     // 64-bit PowerPC wants to expand i128 shifts itself.
552     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
553     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
554     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
555   } else {
556     // 32-bit PowerPC wants to expand i64 shifts itself.
557     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
558     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
559     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
560   }
561 
562   if (Subtarget.hasVSX()) {
563     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
564     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
565     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
566     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
567   }
568 
569   if (Subtarget.hasAltivec()) {
570     for (MVT VT : { MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
571       setOperationAction(ISD::SADDSAT, VT, Legal);
572       setOperationAction(ISD::SSUBSAT, VT, Legal);
573       setOperationAction(ISD::UADDSAT, VT, Legal);
574       setOperationAction(ISD::USUBSAT, VT, Legal);
575     }
576     // First set operation action for all vector types to expand. Then we
577     // will selectively turn on ones that can be effectively codegen'd.
578     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
579       // add/sub are legal for all supported vector VT's.
580       setOperationAction(ISD::ADD, VT, Legal);
581       setOperationAction(ISD::SUB, VT, Legal);
582 
583       // For v2i64, these are only valid with P8Vector. This is corrected after
584       // the loop.
585       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
586         setOperationAction(ISD::SMAX, VT, Legal);
587         setOperationAction(ISD::SMIN, VT, Legal);
588         setOperationAction(ISD::UMAX, VT, Legal);
589         setOperationAction(ISD::UMIN, VT, Legal);
590       }
591       else {
592         setOperationAction(ISD::SMAX, VT, Expand);
593         setOperationAction(ISD::SMIN, VT, Expand);
594         setOperationAction(ISD::UMAX, VT, Expand);
595         setOperationAction(ISD::UMIN, VT, Expand);
596       }
597 
598       if (Subtarget.hasVSX()) {
599         setOperationAction(ISD::FMAXNUM, VT, Legal);
600         setOperationAction(ISD::FMINNUM, VT, Legal);
601       }
602 
603       // Vector instructions introduced in P8
604       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
605         setOperationAction(ISD::CTPOP, VT, Legal);
606         setOperationAction(ISD::CTLZ, VT, Legal);
607       }
608       else {
609         setOperationAction(ISD::CTPOP, VT, Expand);
610         setOperationAction(ISD::CTLZ, VT, Expand);
611       }
612 
613       // Vector instructions introduced in P9
614       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
615         setOperationAction(ISD::CTTZ, VT, Legal);
616       else
617         setOperationAction(ISD::CTTZ, VT, Expand);
618 
619       // We promote all shuffles to v16i8.
620       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
621       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
622 
623       // We promote all non-typed operations to v4i32.
624       setOperationAction(ISD::AND   , VT, Promote);
625       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
626       setOperationAction(ISD::OR    , VT, Promote);
627       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
628       setOperationAction(ISD::XOR   , VT, Promote);
629       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
630       setOperationAction(ISD::LOAD  , VT, Promote);
631       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
632       setOperationAction(ISD::SELECT, VT, Promote);
633       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
634       setOperationAction(ISD::VSELECT, VT, Legal);
635       setOperationAction(ISD::SELECT_CC, VT, Promote);
636       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
637       setOperationAction(ISD::STORE, VT, Promote);
638       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
639 
640       // No other operations are legal.
641       setOperationAction(ISD::MUL , VT, Expand);
642       setOperationAction(ISD::SDIV, VT, Expand);
643       setOperationAction(ISD::SREM, VT, Expand);
644       setOperationAction(ISD::UDIV, VT, Expand);
645       setOperationAction(ISD::UREM, VT, Expand);
646       setOperationAction(ISD::FDIV, VT, Expand);
647       setOperationAction(ISD::FREM, VT, Expand);
648       setOperationAction(ISD::FNEG, VT, Expand);
649       setOperationAction(ISD::FSQRT, VT, Expand);
650       setOperationAction(ISD::FLOG, VT, Expand);
651       setOperationAction(ISD::FLOG10, VT, Expand);
652       setOperationAction(ISD::FLOG2, VT, Expand);
653       setOperationAction(ISD::FEXP, VT, Expand);
654       setOperationAction(ISD::FEXP2, VT, Expand);
655       setOperationAction(ISD::FSIN, VT, Expand);
656       setOperationAction(ISD::FCOS, VT, Expand);
657       setOperationAction(ISD::FABS, VT, Expand);
658       setOperationAction(ISD::FFLOOR, VT, Expand);
659       setOperationAction(ISD::FCEIL,  VT, Expand);
660       setOperationAction(ISD::FTRUNC, VT, Expand);
661       setOperationAction(ISD::FRINT,  VT, Expand);
662       setOperationAction(ISD::FNEARBYINT, VT, Expand);
663       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
664       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
665       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
666       setOperationAction(ISD::MULHU, VT, Expand);
667       setOperationAction(ISD::MULHS, VT, Expand);
668       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
669       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
670       setOperationAction(ISD::UDIVREM, VT, Expand);
671       setOperationAction(ISD::SDIVREM, VT, Expand);
672       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
673       setOperationAction(ISD::FPOW, VT, Expand);
674       setOperationAction(ISD::BSWAP, VT, Expand);
675       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
676       setOperationAction(ISD::ROTL, VT, Expand);
677       setOperationAction(ISD::ROTR, VT, Expand);
678 
679       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
680         setTruncStoreAction(VT, InnerVT, Expand);
681         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
682         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
683         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
684       }
685     }
686     if (!Subtarget.hasP8Vector()) {
687       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
688       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
689       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
690       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
691     }
692 
693     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
694       setOperationAction(ISD::ABS, VT, Custom);
695 
696     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
697     // with merges, splats, etc.
698     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
699 
700     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
701     // are cheap, so handle them before they get expanded to scalar.
702     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
703     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
704     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
705     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
706     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
707 
708     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
709     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
710     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
711     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
712     setOperationAction(ISD::SELECT, MVT::v4i32,
713                        Subtarget.useCRBits() ? Legal : Expand);
714     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
715     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
716     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
717     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
718     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
719     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
720     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
721     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
722     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
723 
724     // Without hasP8Altivec set, v2i64 SMAX isn't available.
725     // But ABS custom lowering requires SMAX support.
726     if (!Subtarget.hasP8Altivec())
727       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
728 
729     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
730     if (Subtarget.hasAltivec())
731       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
732         setOperationAction(ISD::ROTL, VT, Legal);
733     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
734     if (Subtarget.hasP8Altivec())
735       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
736 
737     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
738     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
739     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
740     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
741 
742     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
743     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
744 
745     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
746       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
747       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
748     }
749 
750     if (Subtarget.hasP8Altivec())
751       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
752     else
753       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
754 
755     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
756     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
757 
758     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
759     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
760 
761     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
762     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
763     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
764     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
765 
766     // Altivec does not contain unordered floating-point compare instructions
767     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
768     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
769     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
770     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
771 
772     if (Subtarget.hasVSX()) {
773       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
774       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
775       if (Subtarget.hasP8Vector()) {
776         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
777         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
778       }
779       if (Subtarget.hasDirectMove() && isPPC64) {
780         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
781         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
782         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
783         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
784         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
785         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
786         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
787         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
788       }
789       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
790 
791       // The nearbyint variants are not allowed to raise the inexact exception
792       // so we can only code-gen them with unsafe math.
793       if (TM.Options.UnsafeFPMath) {
794         setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
795         setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
796       }
797 
798       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
799       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
800       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
801       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
802       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
803       setOperationAction(ISD::FROUND, MVT::f64, Legal);
804 
805       setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
806       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
807       setOperationAction(ISD::FROUND, MVT::f32, Legal);
808 
809       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
810       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
811 
812       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
813       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
814 
815       // Share the Altivec comparison restrictions.
816       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
817       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
818       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
819       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
820 
821       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
822       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
823 
824       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
825 
826       if (Subtarget.hasP8Vector())
827         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
828 
829       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
830 
831       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
832       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
833       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
834 
835       if (Subtarget.hasP8Altivec()) {
836         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
837         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
838         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
839 
840         // 128 bit shifts can be accomplished via 3 instructions for SHL and
841         // SRL, but not for SRA because of the instructions available:
842         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
843         // doing
844         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
845         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
846         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
847 
848         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
849       }
850       else {
851         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
852         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
853         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
854 
855         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
856 
857         // VSX v2i64 only supports non-arithmetic operations.
858         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
859         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
860       }
861 
862       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
863       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
864       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
865       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
866 
867       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
868 
869       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
870       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
871       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
872       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
873 
874       // Custom handling for partial vectors of integers converted to
875       // floating point. We already have optimal handling for v2i32 through
876       // the DAG combine, so those aren't necessary.
877       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
878       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
879       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
880       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
881       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
882       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
883       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
884       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
885 
886       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
887       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
888       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
889       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
890       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
891       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
892 
893       if (Subtarget.hasDirectMove())
894         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
895       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
896 
897       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
898     }
899 
900     if (Subtarget.hasP8Altivec()) {
901       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
902       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
903     }
904 
905     if (Subtarget.hasP9Vector()) {
906       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
907       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
908 
909       // 128 bit shifts can be accomplished via 3 instructions for SHL and
910       // SRL, but not for SRA because of the instructions available:
911       // VS{RL} and VS{RL}O.
912       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
913       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
914       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
915 
916       if (EnableQuadPrecision) {
917         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
918         setOperationAction(ISD::FADD, MVT::f128, Legal);
919         setOperationAction(ISD::FSUB, MVT::f128, Legal);
920         setOperationAction(ISD::FDIV, MVT::f128, Legal);
921         setOperationAction(ISD::FMUL, MVT::f128, Legal);
922         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
923         // No extending loads to f128 on PPC.
924         for (MVT FPT : MVT::fp_valuetypes())
925           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
926         setOperationAction(ISD::FMA, MVT::f128, Legal);
927         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
928         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
929         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
930         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
931         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
932         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
933 
934         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
935         setOperationAction(ISD::FRINT, MVT::f128, Legal);
936         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
937         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
938         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
939         setOperationAction(ISD::FROUND, MVT::f128, Legal);
940 
941         setOperationAction(ISD::SELECT, MVT::f128, Expand);
942         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
943         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
944         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
945         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
946         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
947         // No implementation for these ops for PowerPC.
948         setOperationAction(ISD::FSIN , MVT::f128, Expand);
949         setOperationAction(ISD::FCOS , MVT::f128, Expand);
950         setOperationAction(ISD::FPOW, MVT::f128, Expand);
951         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
952         setOperationAction(ISD::FREM, MVT::f128, Expand);
953       }
954       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
955       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
956       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
957       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
958       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
959     }
960 
961     if (Subtarget.hasP9Altivec()) {
962       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
963       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
964 
965       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
966       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
967       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
968       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
969       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
970       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
971       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
972     }
973   }
974 
975   if (Subtarget.hasQPX()) {
976     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
977     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
978     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
979     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
980 
981     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
982     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
983 
984     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
985     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
986 
987     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
988     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
989 
990     if (!Subtarget.useCRBits())
991       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
992     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
993 
994     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
995     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
996     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
997     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
998     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
999     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
1000     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
1001 
1002     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
1003     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
1004 
1005     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
1006     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
1007 
1008     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
1009     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
1010     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
1011     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
1012     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
1013     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
1014     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
1015     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
1016     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
1017     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
1018 
1019     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
1020     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
1021 
1022     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1023     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1024 
1025     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1026 
1027     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1028     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1029     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1030     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1031 
1032     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1033     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1034 
1035     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1036     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1037 
1038     if (!Subtarget.useCRBits())
1039       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1040     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1041 
1042     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1043     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1044     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1045     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1046     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1047     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1048     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1049 
1050     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1051     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1052 
1053     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1054     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1055     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1056     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1057     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1058     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1059     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1060     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1061     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1062     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1063 
1064     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1065     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1066 
1067     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1068     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1069 
1070     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1071 
1072     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1073     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1074     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1075 
1076     if (!Subtarget.useCRBits())
1077       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1078     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1079 
1080     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1081     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1082 
1083     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1085     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1086     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1087     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1088     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1089     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1090 
1091     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1092     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1093 
1094     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1095 
1096     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1097     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1098     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1099     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1100 
1101     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1104     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1105 
1106     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1107     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1108 
1109     // These need to set FE_INEXACT, and so cannot be vectorized here.
1110     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1111     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1112 
1113     if (TM.Options.UnsafeFPMath) {
1114       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1115       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1116 
1117       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1118       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1119     } else {
1120       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1121       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1122 
1123       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1124       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1125     }
1126   }
1127 
1128   if (Subtarget.has64BitSupport())
1129     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1130 
1131   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1132 
1133   if (!isPPC64) {
1134     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1135     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1136   }
1137 
1138   setBooleanContents(ZeroOrOneBooleanContent);
1139 
1140   if (Subtarget.hasAltivec()) {
1141     // Altivec instructions set fields to all zeros or all ones.
1142     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1143   }
1144 
1145   if (!isPPC64) {
1146     // These libcalls are not available in 32-bit.
1147     setLibcallName(RTLIB::SHL_I128, nullptr);
1148     setLibcallName(RTLIB::SRL_I128, nullptr);
1149     setLibcallName(RTLIB::SRA_I128, nullptr);
1150   }
1151 
1152   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1153 
1154   // We have target-specific dag combine patterns for the following nodes:
1155   setTargetDAGCombine(ISD::ADD);
1156   setTargetDAGCombine(ISD::SHL);
1157   setTargetDAGCombine(ISD::SRA);
1158   setTargetDAGCombine(ISD::SRL);
1159   setTargetDAGCombine(ISD::MUL);
1160   setTargetDAGCombine(ISD::SINT_TO_FP);
1161   setTargetDAGCombine(ISD::BUILD_VECTOR);
1162   if (Subtarget.hasFPCVT())
1163     setTargetDAGCombine(ISD::UINT_TO_FP);
1164   setTargetDAGCombine(ISD::LOAD);
1165   setTargetDAGCombine(ISD::STORE);
1166   setTargetDAGCombine(ISD::BR_CC);
1167   if (Subtarget.useCRBits())
1168     setTargetDAGCombine(ISD::BRCOND);
1169   setTargetDAGCombine(ISD::BSWAP);
1170   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1171   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1172   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1173 
1174   setTargetDAGCombine(ISD::SIGN_EXTEND);
1175   setTargetDAGCombine(ISD::ZERO_EXTEND);
1176   setTargetDAGCombine(ISD::ANY_EXTEND);
1177 
1178   setTargetDAGCombine(ISD::TRUNCATE);
1179   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1180 
1181 
1182   if (Subtarget.useCRBits()) {
1183     setTargetDAGCombine(ISD::TRUNCATE);
1184     setTargetDAGCombine(ISD::SETCC);
1185     setTargetDAGCombine(ISD::SELECT_CC);
1186   }
1187 
1188   // Use reciprocal estimates.
1189   if (TM.Options.UnsafeFPMath) {
1190     setTargetDAGCombine(ISD::FDIV);
1191     setTargetDAGCombine(ISD::FSQRT);
1192   }
1193 
1194   if (Subtarget.hasP9Altivec()) {
1195     setTargetDAGCombine(ISD::ABS);
1196     setTargetDAGCombine(ISD::VSELECT);
1197   }
1198 
1199   if (EnableQuadPrecision) {
1200     setLibcallName(RTLIB::LOG_F128, "logf128");
1201     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1202     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1203     setLibcallName(RTLIB::EXP_F128, "expf128");
1204     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1205     setLibcallName(RTLIB::SIN_F128, "sinf128");
1206     setLibcallName(RTLIB::COS_F128, "cosf128");
1207     setLibcallName(RTLIB::POW_F128, "powf128");
1208     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1209     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1210     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1211     setLibcallName(RTLIB::REM_F128, "fmodf128");
1212   }
1213 
1214   // With 32 condition bits, we don't need to sink (and duplicate) compares
1215   // aggressively in CodeGenPrep.
1216   if (Subtarget.useCRBits()) {
1217     setHasMultipleConditionRegisters();
1218     setJumpIsExpensive();
1219   }
1220 
1221   setMinFunctionAlignment(Align(4));
1222 
1223   switch (Subtarget.getCPUDirective()) {
1224   default: break;
1225   case PPC::DIR_970:
1226   case PPC::DIR_A2:
1227   case PPC::DIR_E500:
1228   case PPC::DIR_E500mc:
1229   case PPC::DIR_E5500:
1230   case PPC::DIR_PWR4:
1231   case PPC::DIR_PWR5:
1232   case PPC::DIR_PWR5X:
1233   case PPC::DIR_PWR6:
1234   case PPC::DIR_PWR6X:
1235   case PPC::DIR_PWR7:
1236   case PPC::DIR_PWR8:
1237   case PPC::DIR_PWR9:
1238   case PPC::DIR_PWR_FUTURE:
1239     setPrefLoopAlignment(Align(16));
1240     setPrefFunctionAlignment(Align(16));
1241     break;
1242   }
1243 
1244   if (Subtarget.enableMachineScheduler())
1245     setSchedulingPreference(Sched::Source);
1246   else
1247     setSchedulingPreference(Sched::Hybrid);
1248 
1249   computeRegisterProperties(STI.getRegisterInfo());
1250 
1251   // The Freescale cores do better with aggressive inlining of memcpy and
1252   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1253   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1254       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1255     MaxStoresPerMemset = 32;
1256     MaxStoresPerMemsetOptSize = 16;
1257     MaxStoresPerMemcpy = 32;
1258     MaxStoresPerMemcpyOptSize = 8;
1259     MaxStoresPerMemmove = 32;
1260     MaxStoresPerMemmoveOptSize = 8;
1261   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1262     // The A2 also benefits from (very) aggressive inlining of memcpy and
1263     // friends. The overhead of a the function call, even when warm, can be
1264     // over one hundred cycles.
1265     MaxStoresPerMemset = 128;
1266     MaxStoresPerMemcpy = 128;
1267     MaxStoresPerMemmove = 128;
1268     MaxLoadsPerMemcmp = 128;
1269   } else {
1270     MaxLoadsPerMemcmp = 8;
1271     MaxLoadsPerMemcmpOptSize = 4;
1272   }
1273 }
1274 
1275 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1276 /// the desired ByVal argument alignment.
1277 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1278                              unsigned MaxMaxAlign) {
1279   if (MaxAlign == MaxMaxAlign)
1280     return;
1281   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1282     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1283       MaxAlign = 32;
1284     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1285       MaxAlign = 16;
1286   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1287     unsigned EltAlign = 0;
1288     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1289     if (EltAlign > MaxAlign)
1290       MaxAlign = EltAlign;
1291   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1292     for (auto *EltTy : STy->elements()) {
1293       unsigned EltAlign = 0;
1294       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1295       if (EltAlign > MaxAlign)
1296         MaxAlign = EltAlign;
1297       if (MaxAlign == MaxMaxAlign)
1298         break;
1299     }
1300   }
1301 }
1302 
1303 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1304 /// function arguments in the caller parameter area.
1305 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1306                                                   const DataLayout &DL) const {
1307   // 16byte and wider vectors are passed on 16byte boundary.
1308   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1309   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1310   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1311     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1312   return Align;
1313 }
1314 
1315 bool PPCTargetLowering::useSoftFloat() const {
1316   return Subtarget.useSoftFloat();
1317 }
1318 
1319 bool PPCTargetLowering::hasSPE() const {
1320   return Subtarget.hasSPE();
1321 }
1322 
1323 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1324   return VT.isScalarInteger();
1325 }
1326 
1327 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1328   switch ((PPCISD::NodeType)Opcode) {
1329   case PPCISD::FIRST_NUMBER:    break;
1330   case PPCISD::FSEL:            return "PPCISD::FSEL";
1331   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1332   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1333   case PPCISD::FCFID:           return "PPCISD::FCFID";
1334   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1335   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1336   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1337   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1338   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1339   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1340   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1341   case PPCISD::FP_TO_UINT_IN_VSR:
1342                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1343   case PPCISD::FP_TO_SINT_IN_VSR:
1344                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1345   case PPCISD::FRE:             return "PPCISD::FRE";
1346   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1347   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1348   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1349   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1350   case PPCISD::VPERM:           return "PPCISD::VPERM";
1351   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1352   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1353   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1354   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1355   case PPCISD::CMPB:            return "PPCISD::CMPB";
1356   case PPCISD::Hi:              return "PPCISD::Hi";
1357   case PPCISD::Lo:              return "PPCISD::Lo";
1358   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1359   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1360   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1361   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1362   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1363   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1364   case PPCISD::SRL:             return "PPCISD::SRL";
1365   case PPCISD::SRA:             return "PPCISD::SRA";
1366   case PPCISD::SHL:             return "PPCISD::SHL";
1367   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1368   case PPCISD::CALL:            return "PPCISD::CALL";
1369   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1370   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1371   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1372   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1373   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1374   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1375   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1376   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1377   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1378   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1379   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1380   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1381   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1382   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1383   case PPCISD::ANDI_rec_1_EQ_BIT:
1384     return "PPCISD::ANDI_rec_1_EQ_BIT";
1385   case PPCISD::ANDI_rec_1_GT_BIT:
1386     return "PPCISD::ANDI_rec_1_GT_BIT";
1387   case PPCISD::VCMP:            return "PPCISD::VCMP";
1388   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1389   case PPCISD::LBRX:            return "PPCISD::LBRX";
1390   case PPCISD::STBRX:           return "PPCISD::STBRX";
1391   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1392   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1393   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1394   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1395   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1396   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1397   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1398   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1399   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1400   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1401   case PPCISD::ST_VSR_SCAL_INT:
1402                                 return "PPCISD::ST_VSR_SCAL_INT";
1403   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1404   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1405   case PPCISD::BDZ:             return "PPCISD::BDZ";
1406   case PPCISD::MFFS:            return "PPCISD::MFFS";
1407   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1408   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1409   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1410   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1411   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1412   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1413   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1414   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1415   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1416   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1417   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1418   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1419   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1420   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1421   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1422   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1423   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1424   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1425   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1426   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1427   case PPCISD::SC:              return "PPCISD::SC";
1428   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1429   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1430   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1431   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1432   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1433   case PPCISD::VABSD:           return "PPCISD::VABSD";
1434   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1435   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1436   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1437   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1438   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1439   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1440   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1441   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1442   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1443   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1444   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1445   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1446   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1447   }
1448   return nullptr;
1449 }
1450 
1451 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1452                                           EVT VT) const {
1453   if (!VT.isVector())
1454     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1455 
1456   if (Subtarget.hasQPX())
1457     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1458 
1459   return VT.changeVectorElementTypeToInteger();
1460 }
1461 
1462 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1463   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1464   return true;
1465 }
1466 
1467 //===----------------------------------------------------------------------===//
1468 // Node matching predicates, for use by the tblgen matching code.
1469 //===----------------------------------------------------------------------===//
1470 
1471 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1472 static bool isFloatingPointZero(SDValue Op) {
1473   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1474     return CFP->getValueAPF().isZero();
1475   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1476     // Maybe this has already been legalized into the constant pool?
1477     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1478       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1479         return CFP->getValueAPF().isZero();
1480   }
1481   return false;
1482 }
1483 
1484 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1485 /// true if Op is undef or if it matches the specified value.
1486 static bool isConstantOrUndef(int Op, int Val) {
1487   return Op < 0 || Op == Val;
1488 }
1489 
1490 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1491 /// VPKUHUM instruction.
1492 /// The ShuffleKind distinguishes between big-endian operations with
1493 /// two different inputs (0), either-endian operations with two identical
1494 /// inputs (1), and little-endian operations with two different inputs (2).
1495 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1496 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1497                                SelectionDAG &DAG) {
1498   bool IsLE = DAG.getDataLayout().isLittleEndian();
1499   if (ShuffleKind == 0) {
1500     if (IsLE)
1501       return false;
1502     for (unsigned i = 0; i != 16; ++i)
1503       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1504         return false;
1505   } else if (ShuffleKind == 2) {
1506     if (!IsLE)
1507       return false;
1508     for (unsigned i = 0; i != 16; ++i)
1509       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1510         return false;
1511   } else if (ShuffleKind == 1) {
1512     unsigned j = IsLE ? 0 : 1;
1513     for (unsigned i = 0; i != 8; ++i)
1514       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1515           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1516         return false;
1517   }
1518   return true;
1519 }
1520 
1521 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1522 /// VPKUWUM instruction.
1523 /// The ShuffleKind distinguishes between big-endian operations with
1524 /// two different inputs (0), either-endian operations with two identical
1525 /// inputs (1), and little-endian operations with two different inputs (2).
1526 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1527 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1528                                SelectionDAG &DAG) {
1529   bool IsLE = DAG.getDataLayout().isLittleEndian();
1530   if (ShuffleKind == 0) {
1531     if (IsLE)
1532       return false;
1533     for (unsigned i = 0; i != 16; i += 2)
1534       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1535           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1536         return false;
1537   } else if (ShuffleKind == 2) {
1538     if (!IsLE)
1539       return false;
1540     for (unsigned i = 0; i != 16; i += 2)
1541       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1542           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1543         return false;
1544   } else if (ShuffleKind == 1) {
1545     unsigned j = IsLE ? 0 : 2;
1546     for (unsigned i = 0; i != 8; i += 2)
1547       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1548           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1549           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1550           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1551         return false;
1552   }
1553   return true;
1554 }
1555 
1556 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1557 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1558 /// current subtarget.
1559 ///
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::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1565                                SelectionDAG &DAG) {
1566   const PPCSubtarget& Subtarget =
1567       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1568   if (!Subtarget.hasP8Vector())
1569     return false;
1570 
1571   bool IsLE = DAG.getDataLayout().isLittleEndian();
1572   if (ShuffleKind == 0) {
1573     if (IsLE)
1574       return false;
1575     for (unsigned i = 0; i != 16; i += 4)
1576       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1577           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1578           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1579           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1580         return false;
1581   } else if (ShuffleKind == 2) {
1582     if (!IsLE)
1583       return false;
1584     for (unsigned i = 0; i != 16; i += 4)
1585       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1586           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1587           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1588           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1589         return false;
1590   } else if (ShuffleKind == 1) {
1591     unsigned j = IsLE ? 0 : 4;
1592     for (unsigned i = 0; i != 8; i += 4)
1593       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1594           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1595           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1596           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1597           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1598           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1599           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1600           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1601         return false;
1602   }
1603   return true;
1604 }
1605 
1606 /// isVMerge - Common function, used to match vmrg* shuffles.
1607 ///
1608 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1609                      unsigned LHSStart, unsigned RHSStart) {
1610   if (N->getValueType(0) != MVT::v16i8)
1611     return false;
1612   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1613          "Unsupported merge size!");
1614 
1615   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1616     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1617       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1618                              LHSStart+j+i*UnitSize) ||
1619           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1620                              RHSStart+j+i*UnitSize))
1621         return false;
1622     }
1623   return true;
1624 }
1625 
1626 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1627 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1628 /// The ShuffleKind distinguishes between big-endian merges with two
1629 /// different inputs (0), either-endian merges with two identical inputs (1),
1630 /// and little-endian merges with two different inputs (2).  For the latter,
1631 /// the input operands are swapped (see PPCInstrAltivec.td).
1632 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1633                              unsigned ShuffleKind, SelectionDAG &DAG) {
1634   if (DAG.getDataLayout().isLittleEndian()) {
1635     if (ShuffleKind == 1) // unary
1636       return isVMerge(N, UnitSize, 0, 0);
1637     else if (ShuffleKind == 2) // swapped
1638       return isVMerge(N, UnitSize, 0, 16);
1639     else
1640       return false;
1641   } else {
1642     if (ShuffleKind == 1) // unary
1643       return isVMerge(N, UnitSize, 8, 8);
1644     else if (ShuffleKind == 0) // normal
1645       return isVMerge(N, UnitSize, 8, 24);
1646     else
1647       return false;
1648   }
1649 }
1650 
1651 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1652 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1653 /// The ShuffleKind distinguishes between big-endian merges with two
1654 /// different inputs (0), either-endian merges with two identical inputs (1),
1655 /// and little-endian merges with two different inputs (2).  For the latter,
1656 /// the input operands are swapped (see PPCInstrAltivec.td).
1657 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1658                              unsigned ShuffleKind, SelectionDAG &DAG) {
1659   if (DAG.getDataLayout().isLittleEndian()) {
1660     if (ShuffleKind == 1) // unary
1661       return isVMerge(N, UnitSize, 8, 8);
1662     else if (ShuffleKind == 2) // swapped
1663       return isVMerge(N, UnitSize, 8, 24);
1664     else
1665       return false;
1666   } else {
1667     if (ShuffleKind == 1) // unary
1668       return isVMerge(N, UnitSize, 0, 0);
1669     else if (ShuffleKind == 0) // normal
1670       return isVMerge(N, UnitSize, 0, 16);
1671     else
1672       return false;
1673   }
1674 }
1675 
1676 /**
1677  * Common function used to match vmrgew and vmrgow shuffles
1678  *
1679  * The indexOffset determines whether to look for even or odd words in
1680  * the shuffle mask. This is based on the of the endianness of the target
1681  * machine.
1682  *   - Little Endian:
1683  *     - Use offset of 0 to check for odd elements
1684  *     - Use offset of 4 to check for even elements
1685  *   - Big Endian:
1686  *     - Use offset of 0 to check for even elements
1687  *     - Use offset of 4 to check for odd elements
1688  * A detailed description of the vector element ordering for little endian and
1689  * big endian can be found at
1690  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1691  * Targeting your applications - what little endian and big endian IBM XL C/C++
1692  * compiler differences mean to you
1693  *
1694  * The mask to the shuffle vector instruction specifies the indices of the
1695  * elements from the two input vectors to place in the result. The elements are
1696  * numbered in array-access order, starting with the first vector. These vectors
1697  * are always of type v16i8, thus each vector will contain 16 elements of size
1698  * 8. More info on the shuffle vector can be found in the
1699  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1700  * Language Reference.
1701  *
1702  * The RHSStartValue indicates whether the same input vectors are used (unary)
1703  * or two different input vectors are used, based on the following:
1704  *   - If the instruction uses the same vector for both inputs, the range of the
1705  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1706  *     be 0.
1707  *   - If the instruction has two different vectors then the range of the
1708  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1709  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1710  *     to 31 specify elements in the second vector).
1711  *
1712  * \param[in] N The shuffle vector SD Node to analyze
1713  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1714  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1715  * vector to the shuffle_vector instruction
1716  * \return true iff this shuffle vector represents an even or odd word merge
1717  */
1718 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1719                      unsigned RHSStartValue) {
1720   if (N->getValueType(0) != MVT::v16i8)
1721     return false;
1722 
1723   for (unsigned i = 0; i < 2; ++i)
1724     for (unsigned j = 0; j < 4; ++j)
1725       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1726                              i*RHSStartValue+j+IndexOffset) ||
1727           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1728                              i*RHSStartValue+j+IndexOffset+8))
1729         return false;
1730   return true;
1731 }
1732 
1733 /**
1734  * Determine if the specified shuffle mask is suitable for the vmrgew or
1735  * vmrgow instructions.
1736  *
1737  * \param[in] N The shuffle vector SD Node to analyze
1738  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1739  * \param[in] ShuffleKind Identify the type of merge:
1740  *   - 0 = big-endian merge with two different inputs;
1741  *   - 1 = either-endian merge with two identical inputs;
1742  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1743  *     little-endian merges).
1744  * \param[in] DAG The current SelectionDAG
1745  * \return true iff this shuffle mask
1746  */
1747 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1748                               unsigned ShuffleKind, SelectionDAG &DAG) {
1749   if (DAG.getDataLayout().isLittleEndian()) {
1750     unsigned indexOffset = CheckEven ? 4 : 0;
1751     if (ShuffleKind == 1) // Unary
1752       return isVMerge(N, indexOffset, 0);
1753     else if (ShuffleKind == 2) // swapped
1754       return isVMerge(N, indexOffset, 16);
1755     else
1756       return false;
1757   }
1758   else {
1759     unsigned indexOffset = CheckEven ? 0 : 4;
1760     if (ShuffleKind == 1) // Unary
1761       return isVMerge(N, indexOffset, 0);
1762     else if (ShuffleKind == 0) // Normal
1763       return isVMerge(N, indexOffset, 16);
1764     else
1765       return false;
1766   }
1767   return false;
1768 }
1769 
1770 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1771 /// amount, otherwise return -1.
1772 /// The ShuffleKind distinguishes between big-endian operations with two
1773 /// different inputs (0), either-endian operations with two identical inputs
1774 /// (1), and little-endian operations with two different inputs (2).  For the
1775 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1776 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1777                              SelectionDAG &DAG) {
1778   if (N->getValueType(0) != MVT::v16i8)
1779     return -1;
1780 
1781   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1782 
1783   // Find the first non-undef value in the shuffle mask.
1784   unsigned i;
1785   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1786     /*search*/;
1787 
1788   if (i == 16) return -1;  // all undef.
1789 
1790   // Otherwise, check to see if the rest of the elements are consecutively
1791   // numbered from this value.
1792   unsigned ShiftAmt = SVOp->getMaskElt(i);
1793   if (ShiftAmt < i) return -1;
1794 
1795   ShiftAmt -= i;
1796   bool isLE = DAG.getDataLayout().isLittleEndian();
1797 
1798   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1799     // Check the rest of the elements to see if they are consecutive.
1800     for (++i; i != 16; ++i)
1801       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1802         return -1;
1803   } else if (ShuffleKind == 1) {
1804     // Check the rest of the elements to see if they are consecutive.
1805     for (++i; i != 16; ++i)
1806       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1807         return -1;
1808   } else
1809     return -1;
1810 
1811   if (isLE)
1812     ShiftAmt = 16 - ShiftAmt;
1813 
1814   return ShiftAmt;
1815 }
1816 
1817 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1818 /// specifies a splat of a single element that is suitable for input to
1819 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1820 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1821   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1822          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1823 
1824   // The consecutive indices need to specify an element, not part of two
1825   // different elements.  So abandon ship early if this isn't the case.
1826   if (N->getMaskElt(0) % EltSize != 0)
1827     return false;
1828 
1829   // This is a splat operation if each element of the permute is the same, and
1830   // if the value doesn't reference the second vector.
1831   unsigned ElementBase = N->getMaskElt(0);
1832 
1833   // FIXME: Handle UNDEF elements too!
1834   if (ElementBase >= 16)
1835     return false;
1836 
1837   // Check that the indices are consecutive, in the case of a multi-byte element
1838   // splatted with a v16i8 mask.
1839   for (unsigned i = 1; i != EltSize; ++i)
1840     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1841       return false;
1842 
1843   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1844     if (N->getMaskElt(i) < 0) continue;
1845     for (unsigned j = 0; j != EltSize; ++j)
1846       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1847         return false;
1848   }
1849   return true;
1850 }
1851 
1852 /// Check that the mask is shuffling N byte elements. Within each N byte
1853 /// element of the mask, the indices could be either in increasing or
1854 /// decreasing order as long as they are consecutive.
1855 /// \param[in] N the shuffle vector SD Node to analyze
1856 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1857 /// Word/DoubleWord/QuadWord).
1858 /// \param[in] StepLen the delta indices number among the N byte element, if
1859 /// the mask is in increasing/decreasing order then it is 1/-1.
1860 /// \return true iff the mask is shuffling N byte elements.
1861 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1862                                    int StepLen) {
1863   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1864          "Unexpected element width.");
1865   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1866 
1867   unsigned NumOfElem = 16 / Width;
1868   unsigned MaskVal[16]; //  Width is never greater than 16
1869   for (unsigned i = 0; i < NumOfElem; ++i) {
1870     MaskVal[0] = N->getMaskElt(i * Width);
1871     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1872       return false;
1873     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1874       return false;
1875     }
1876 
1877     for (unsigned int j = 1; j < Width; ++j) {
1878       MaskVal[j] = N->getMaskElt(i * Width + j);
1879       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1880         return false;
1881       }
1882     }
1883   }
1884 
1885   return true;
1886 }
1887 
1888 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1889                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1890   if (!isNByteElemShuffleMask(N, 4, 1))
1891     return false;
1892 
1893   // Now we look at mask elements 0,4,8,12
1894   unsigned M0 = N->getMaskElt(0) / 4;
1895   unsigned M1 = N->getMaskElt(4) / 4;
1896   unsigned M2 = N->getMaskElt(8) / 4;
1897   unsigned M3 = N->getMaskElt(12) / 4;
1898   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1899   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1900 
1901   // Below, let H and L be arbitrary elements of the shuffle mask
1902   // where H is in the range [4,7] and L is in the range [0,3].
1903   // H, 1, 2, 3 or L, 5, 6, 7
1904   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1905       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1906     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1907     InsertAtByte = IsLE ? 12 : 0;
1908     Swap = M0 < 4;
1909     return true;
1910   }
1911   // 0, H, 2, 3 or 4, L, 6, 7
1912   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1913       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1914     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1915     InsertAtByte = IsLE ? 8 : 4;
1916     Swap = M1 < 4;
1917     return true;
1918   }
1919   // 0, 1, H, 3 or 4, 5, L, 7
1920   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1921       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1922     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1923     InsertAtByte = IsLE ? 4 : 8;
1924     Swap = M2 < 4;
1925     return true;
1926   }
1927   // 0, 1, 2, H or 4, 5, 6, L
1928   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1929       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1930     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1931     InsertAtByte = IsLE ? 0 : 12;
1932     Swap = M3 < 4;
1933     return true;
1934   }
1935 
1936   // If both vector operands for the shuffle are the same vector, the mask will
1937   // contain only elements from the first one and the second one will be undef.
1938   if (N->getOperand(1).isUndef()) {
1939     ShiftElts = 0;
1940     Swap = true;
1941     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1942     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1943       InsertAtByte = IsLE ? 12 : 0;
1944       return true;
1945     }
1946     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1947       InsertAtByte = IsLE ? 8 : 4;
1948       return true;
1949     }
1950     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1951       InsertAtByte = IsLE ? 4 : 8;
1952       return true;
1953     }
1954     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1955       InsertAtByte = IsLE ? 0 : 12;
1956       return true;
1957     }
1958   }
1959 
1960   return false;
1961 }
1962 
1963 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1964                                bool &Swap, bool IsLE) {
1965   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1966   // Ensure each byte index of the word is consecutive.
1967   if (!isNByteElemShuffleMask(N, 4, 1))
1968     return false;
1969 
1970   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1971   unsigned M0 = N->getMaskElt(0) / 4;
1972   unsigned M1 = N->getMaskElt(4) / 4;
1973   unsigned M2 = N->getMaskElt(8) / 4;
1974   unsigned M3 = N->getMaskElt(12) / 4;
1975 
1976   // If both vector operands for the shuffle are the same vector, the mask will
1977   // contain only elements from the first one and the second one will be undef.
1978   if (N->getOperand(1).isUndef()) {
1979     assert(M0 < 4 && "Indexing into an undef vector?");
1980     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1981       return false;
1982 
1983     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1984     Swap = false;
1985     return true;
1986   }
1987 
1988   // Ensure each word index of the ShuffleVector Mask is consecutive.
1989   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1990     return false;
1991 
1992   if (IsLE) {
1993     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1994       // Input vectors don't need to be swapped if the leading element
1995       // of the result is one of the 3 left elements of the second vector
1996       // (or if there is no shift to be done at all).
1997       Swap = false;
1998       ShiftElts = (8 - M0) % 8;
1999     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
2000       // Input vectors need to be swapped if the leading element
2001       // of the result is one of the 3 left elements of the first vector
2002       // (or if we're shifting by 4 - thereby simply swapping the vectors).
2003       Swap = true;
2004       ShiftElts = (4 - M0) % 4;
2005     }
2006 
2007     return true;
2008   } else {                                          // BE
2009     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2010       // Input vectors don't need to be swapped if the leading element
2011       // of the result is one of the 4 elements of the first vector.
2012       Swap = false;
2013       ShiftElts = M0;
2014     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2015       // Input vectors need to be swapped if the leading element
2016       // of the result is one of the 4 elements of the right vector.
2017       Swap = true;
2018       ShiftElts = M0 - 4;
2019     }
2020 
2021     return true;
2022   }
2023 }
2024 
2025 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2026   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2027 
2028   if (!isNByteElemShuffleMask(N, Width, -1))
2029     return false;
2030 
2031   for (int i = 0; i < 16; i += Width)
2032     if (N->getMaskElt(i) != i + Width - 1)
2033       return false;
2034 
2035   return true;
2036 }
2037 
2038 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2039   return isXXBRShuffleMaskHelper(N, 2);
2040 }
2041 
2042 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2043   return isXXBRShuffleMaskHelper(N, 4);
2044 }
2045 
2046 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2047   return isXXBRShuffleMaskHelper(N, 8);
2048 }
2049 
2050 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2051   return isXXBRShuffleMaskHelper(N, 16);
2052 }
2053 
2054 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2055 /// if the inputs to the instruction should be swapped and set \p DM to the
2056 /// value for the immediate.
2057 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2058 /// AND element 0 of the result comes from the first input (LE) or second input
2059 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2060 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2061 /// mask.
2062 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2063                                bool &Swap, bool IsLE) {
2064   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2065 
2066   // Ensure each byte index of the double word is consecutive.
2067   if (!isNByteElemShuffleMask(N, 8, 1))
2068     return false;
2069 
2070   unsigned M0 = N->getMaskElt(0) / 8;
2071   unsigned M1 = N->getMaskElt(8) / 8;
2072   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2073 
2074   // If both vector operands for the shuffle are the same vector, the mask will
2075   // contain only elements from the first one and the second one will be undef.
2076   if (N->getOperand(1).isUndef()) {
2077     if ((M0 | M1) < 2) {
2078       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2079       Swap = false;
2080       return true;
2081     } else
2082       return false;
2083   }
2084 
2085   if (IsLE) {
2086     if (M0 > 1 && M1 < 2) {
2087       Swap = false;
2088     } else if (M0 < 2 && M1 > 1) {
2089       M0 = (M0 + 2) % 4;
2090       M1 = (M1 + 2) % 4;
2091       Swap = true;
2092     } else
2093       return false;
2094 
2095     // Note: if control flow comes here that means Swap is already set above
2096     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2097     return true;
2098   } else { // BE
2099     if (M0 < 2 && M1 > 1) {
2100       Swap = false;
2101     } else if (M0 > 1 && M1 < 2) {
2102       M0 = (M0 + 2) % 4;
2103       M1 = (M1 + 2) % 4;
2104       Swap = true;
2105     } else
2106       return false;
2107 
2108     // Note: if control flow comes here that means Swap is already set above
2109     DM = (M0 << 1) + (M1 & 1);
2110     return true;
2111   }
2112 }
2113 
2114 
2115 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2116 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2117 /// elements are counted from the left of the vector register).
2118 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2119                                          SelectionDAG &DAG) {
2120   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2121   assert(isSplatShuffleMask(SVOp, EltSize));
2122   if (DAG.getDataLayout().isLittleEndian())
2123     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2124   else
2125     return SVOp->getMaskElt(0) / EltSize;
2126 }
2127 
2128 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2129 /// by using a vspltis[bhw] instruction of the specified element size, return
2130 /// the constant being splatted.  The ByteSize field indicates the number of
2131 /// bytes of each element [124] -> [bhw].
2132 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2133   SDValue OpVal(nullptr, 0);
2134 
2135   // If ByteSize of the splat is bigger than the element size of the
2136   // build_vector, then we have a case where we are checking for a splat where
2137   // multiple elements of the buildvector are folded together into a single
2138   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2139   unsigned EltSize = 16/N->getNumOperands();
2140   if (EltSize < ByteSize) {
2141     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2142     SDValue UniquedVals[4];
2143     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2144 
2145     // See if all of the elements in the buildvector agree across.
2146     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2147       if (N->getOperand(i).isUndef()) continue;
2148       // If the element isn't a constant, bail fully out.
2149       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2150 
2151       if (!UniquedVals[i&(Multiple-1)].getNode())
2152         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2153       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2154         return SDValue();  // no match.
2155     }
2156 
2157     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2158     // either constant or undef values that are identical for each chunk.  See
2159     // if these chunks can form into a larger vspltis*.
2160 
2161     // Check to see if all of the leading entries are either 0 or -1.  If
2162     // neither, then this won't fit into the immediate field.
2163     bool LeadingZero = true;
2164     bool LeadingOnes = true;
2165     for (unsigned i = 0; i != Multiple-1; ++i) {
2166       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2167 
2168       LeadingZero &= isNullConstant(UniquedVals[i]);
2169       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2170     }
2171     // Finally, check the least significant entry.
2172     if (LeadingZero) {
2173       if (!UniquedVals[Multiple-1].getNode())
2174         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2175       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2176       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2177         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2178     }
2179     if (LeadingOnes) {
2180       if (!UniquedVals[Multiple-1].getNode())
2181         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2182       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2183       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2184         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2185     }
2186 
2187     return SDValue();
2188   }
2189 
2190   // Check to see if this buildvec has a single non-undef value in its elements.
2191   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2192     if (N->getOperand(i).isUndef()) continue;
2193     if (!OpVal.getNode())
2194       OpVal = N->getOperand(i);
2195     else if (OpVal != N->getOperand(i))
2196       return SDValue();
2197   }
2198 
2199   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2200 
2201   unsigned ValSizeInBytes = EltSize;
2202   uint64_t Value = 0;
2203   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2204     Value = CN->getZExtValue();
2205   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2206     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2207     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2208   }
2209 
2210   // If the splat value is larger than the element value, then we can never do
2211   // this splat.  The only case that we could fit the replicated bits into our
2212   // immediate field for would be zero, and we prefer to use vxor for it.
2213   if (ValSizeInBytes < ByteSize) return SDValue();
2214 
2215   // If the element value is larger than the splat value, check if it consists
2216   // of a repeated bit pattern of size ByteSize.
2217   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2218     return SDValue();
2219 
2220   // Properly sign extend the value.
2221   int MaskVal = SignExtend32(Value, ByteSize * 8);
2222 
2223   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2224   if (MaskVal == 0) return SDValue();
2225 
2226   // Finally, if this value fits in a 5 bit sext field, return it
2227   if (SignExtend32<5>(MaskVal) == MaskVal)
2228     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2229   return SDValue();
2230 }
2231 
2232 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2233 /// amount, otherwise return -1.
2234 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2235   EVT VT = N->getValueType(0);
2236   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2237     return -1;
2238 
2239   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2240 
2241   // Find the first non-undef value in the shuffle mask.
2242   unsigned i;
2243   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2244     /*search*/;
2245 
2246   if (i == 4) return -1;  // all undef.
2247 
2248   // Otherwise, check to see if the rest of the elements are consecutively
2249   // numbered from this value.
2250   unsigned ShiftAmt = SVOp->getMaskElt(i);
2251   if (ShiftAmt < i) return -1;
2252   ShiftAmt -= i;
2253 
2254   // Check the rest of the elements to see if they are consecutive.
2255   for (++i; i != 4; ++i)
2256     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2257       return -1;
2258 
2259   return ShiftAmt;
2260 }
2261 
2262 //===----------------------------------------------------------------------===//
2263 //  Addressing Mode Selection
2264 //===----------------------------------------------------------------------===//
2265 
2266 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2267 /// or 64-bit immediate, and if the value can be accurately represented as a
2268 /// sign extension from a 16-bit value.  If so, this returns true and the
2269 /// immediate.
2270 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2271   if (!isa<ConstantSDNode>(N))
2272     return false;
2273 
2274   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2275   if (N->getValueType(0) == MVT::i32)
2276     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2277   else
2278     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2279 }
2280 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2281   return isIntS16Immediate(Op.getNode(), Imm);
2282 }
2283 
2284 
2285 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2286 /// be represented as an indexed [r+r] operation.
2287 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2288                                                SDValue &Index,
2289                                                SelectionDAG &DAG) const {
2290   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2291       UI != E; ++UI) {
2292     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2293       if (Memop->getMemoryVT() == MVT::f64) {
2294           Base = N.getOperand(0);
2295           Index = N.getOperand(1);
2296           return true;
2297       }
2298     }
2299   }
2300   return false;
2301 }
2302 
2303 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2304 /// can be represented as an indexed [r+r] operation.  Returns false if it
2305 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2306 /// non-zero and N can be represented by a base register plus a signed 16-bit
2307 /// displacement, make a more precise judgement by checking (displacement % \p
2308 /// EncodingAlignment).
2309 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2310                                             SDValue &Index, SelectionDAG &DAG,
2311                                             unsigned EncodingAlignment) const {
2312   int16_t imm = 0;
2313   if (N.getOpcode() == ISD::ADD) {
2314     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2315     // SPE load/store can only handle 8-bit offsets.
2316     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2317         return true;
2318     if (isIntS16Immediate(N.getOperand(1), imm) &&
2319         (!EncodingAlignment || !(imm % EncodingAlignment)))
2320       return false; // r+i
2321     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2322       return false;    // r+i
2323 
2324     Base = N.getOperand(0);
2325     Index = N.getOperand(1);
2326     return true;
2327   } else if (N.getOpcode() == ISD::OR) {
2328     if (isIntS16Immediate(N.getOperand(1), imm) &&
2329         (!EncodingAlignment || !(imm % EncodingAlignment)))
2330       return false; // r+i can fold it if we can.
2331 
2332     // If this is an or of disjoint bitfields, we can codegen this as an add
2333     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2334     // disjoint.
2335     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2336 
2337     if (LHSKnown.Zero.getBoolValue()) {
2338       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2339       // If all of the bits are known zero on the LHS or RHS, the add won't
2340       // carry.
2341       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2342         Base = N.getOperand(0);
2343         Index = N.getOperand(1);
2344         return true;
2345       }
2346     }
2347   }
2348 
2349   return false;
2350 }
2351 
2352 // If we happen to be doing an i64 load or store into a stack slot that has
2353 // less than a 4-byte alignment, then the frame-index elimination may need to
2354 // use an indexed load or store instruction (because the offset may not be a
2355 // multiple of 4). The extra register needed to hold the offset comes from the
2356 // register scavenger, and it is possible that the scavenger will need to use
2357 // an emergency spill slot. As a result, we need to make sure that a spill slot
2358 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2359 // stack slot.
2360 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2361   // FIXME: This does not handle the LWA case.
2362   if (VT != MVT::i64)
2363     return;
2364 
2365   // NOTE: We'll exclude negative FIs here, which come from argument
2366   // lowering, because there are no known test cases triggering this problem
2367   // using packed structures (or similar). We can remove this exclusion if
2368   // we find such a test case. The reason why this is so test-case driven is
2369   // because this entire 'fixup' is only to prevent crashes (from the
2370   // register scavenger) on not-really-valid inputs. For example, if we have:
2371   //   %a = alloca i1
2372   //   %b = bitcast i1* %a to i64*
2373   //   store i64* a, i64 b
2374   // then the store should really be marked as 'align 1', but is not. If it
2375   // were marked as 'align 1' then the indexed form would have been
2376   // instruction-selected initially, and the problem this 'fixup' is preventing
2377   // won't happen regardless.
2378   if (FrameIdx < 0)
2379     return;
2380 
2381   MachineFunction &MF = DAG.getMachineFunction();
2382   MachineFrameInfo &MFI = MF.getFrameInfo();
2383 
2384   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2385   if (Align >= 4)
2386     return;
2387 
2388   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2389   FuncInfo->setHasNonRISpills();
2390 }
2391 
2392 /// Returns true if the address N can be represented by a base register plus
2393 /// a signed 16-bit displacement [r+imm], and if it is not better
2394 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2395 /// displacements that are multiples of that value.
2396 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2397                                             SDValue &Base,
2398                                             SelectionDAG &DAG,
2399                                             unsigned EncodingAlignment) const {
2400   // FIXME dl should come from parent load or store, not from address
2401   SDLoc dl(N);
2402   // If this can be more profitably realized as r+r, fail.
2403   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2404     return false;
2405 
2406   if (N.getOpcode() == ISD::ADD) {
2407     int16_t imm = 0;
2408     if (isIntS16Immediate(N.getOperand(1), imm) &&
2409         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2410       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2411       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2412         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2413         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2414       } else {
2415         Base = N.getOperand(0);
2416       }
2417       return true; // [r+i]
2418     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2419       // Match LOAD (ADD (X, Lo(G))).
2420       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2421              && "Cannot handle constant offsets yet!");
2422       Disp = N.getOperand(1).getOperand(0);  // The global address.
2423       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2424              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2425              Disp.getOpcode() == ISD::TargetConstantPool ||
2426              Disp.getOpcode() == ISD::TargetJumpTable);
2427       Base = N.getOperand(0);
2428       return true;  // [&g+r]
2429     }
2430   } else if (N.getOpcode() == ISD::OR) {
2431     int16_t imm = 0;
2432     if (isIntS16Immediate(N.getOperand(1), imm) &&
2433         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2434       // If this is an or of disjoint bitfields, we can codegen this as an add
2435       // (for better address arithmetic) if the LHS and RHS of the OR are
2436       // provably disjoint.
2437       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2438 
2439       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2440         // If all of the bits are known zero on the LHS or RHS, the add won't
2441         // carry.
2442         if (FrameIndexSDNode *FI =
2443               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2444           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2445           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2446         } else {
2447           Base = N.getOperand(0);
2448         }
2449         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2450         return true;
2451       }
2452     }
2453   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2454     // Loading from a constant address.
2455 
2456     // If this address fits entirely in a 16-bit sext immediate field, codegen
2457     // this as "d, 0"
2458     int16_t Imm;
2459     if (isIntS16Immediate(CN, Imm) &&
2460         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2461       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2462       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2463                              CN->getValueType(0));
2464       return true;
2465     }
2466 
2467     // Handle 32-bit sext immediates with LIS + addr mode.
2468     if ((CN->getValueType(0) == MVT::i32 ||
2469          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2470         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2471       int Addr = (int)CN->getZExtValue();
2472 
2473       // Otherwise, break this down into an LIS + disp.
2474       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2475 
2476       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2477                                    MVT::i32);
2478       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2479       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2480       return true;
2481     }
2482   }
2483 
2484   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2485   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2486     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2487     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2488   } else
2489     Base = N;
2490   return true;      // [r+0]
2491 }
2492 
2493 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2494 /// represented as an indexed [r+r] operation.
2495 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2496                                                 SDValue &Index,
2497                                                 SelectionDAG &DAG) const {
2498   // Check to see if we can easily represent this as an [r+r] address.  This
2499   // will fail if it thinks that the address is more profitably represented as
2500   // reg+imm, e.g. where imm = 0.
2501   if (SelectAddressRegReg(N, Base, Index, DAG))
2502     return true;
2503 
2504   // If the address is the result of an add, we will utilize the fact that the
2505   // address calculation includes an implicit add.  However, we can reduce
2506   // register pressure if we do not materialize a constant just for use as the
2507   // index register.  We only get rid of the add if it is not an add of a
2508   // value and a 16-bit signed constant and both have a single use.
2509   int16_t imm = 0;
2510   if (N.getOpcode() == ISD::ADD &&
2511       (!isIntS16Immediate(N.getOperand(1), imm) ||
2512        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2513     Base = N.getOperand(0);
2514     Index = N.getOperand(1);
2515     return true;
2516   }
2517 
2518   // Otherwise, do it the hard way, using R0 as the base register.
2519   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2520                          N.getValueType());
2521   Index = N;
2522   return true;
2523 }
2524 
2525 /// Returns true if we should use a direct load into vector instruction
2526 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2527 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2528 
2529   // If there are any other uses other than scalar to vector, then we should
2530   // keep it as a scalar load -> direct move pattern to prevent multiple
2531   // loads.
2532   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2533   if (!LD)
2534     return false;
2535 
2536   EVT MemVT = LD->getMemoryVT();
2537   if (!MemVT.isSimple())
2538     return false;
2539   switch(MemVT.getSimpleVT().SimpleTy) {
2540   case MVT::i64:
2541     break;
2542   case MVT::i32:
2543     if (!ST.hasP8Vector())
2544       return false;
2545     break;
2546   case MVT::i16:
2547   case MVT::i8:
2548     if (!ST.hasP9Vector())
2549       return false;
2550     break;
2551   default:
2552     return false;
2553   }
2554 
2555   SDValue LoadedVal(N, 0);
2556   if (!LoadedVal.hasOneUse())
2557     return false;
2558 
2559   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2560        UI != UE; ++UI)
2561     if (UI.getUse().get().getResNo() == 0 &&
2562         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2563       return false;
2564 
2565   return true;
2566 }
2567 
2568 /// getPreIndexedAddressParts - returns true by value, base pointer and
2569 /// offset pointer and addressing mode by reference if the node's address
2570 /// can be legally represented as pre-indexed load / store address.
2571 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2572                                                   SDValue &Offset,
2573                                                   ISD::MemIndexedMode &AM,
2574                                                   SelectionDAG &DAG) const {
2575   if (DisablePPCPreinc) return false;
2576 
2577   bool isLoad = true;
2578   SDValue Ptr;
2579   EVT VT;
2580   unsigned Alignment;
2581   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2582     Ptr = LD->getBasePtr();
2583     VT = LD->getMemoryVT();
2584     Alignment = LD->getAlignment();
2585   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2586     Ptr = ST->getBasePtr();
2587     VT  = ST->getMemoryVT();
2588     Alignment = ST->getAlignment();
2589     isLoad = false;
2590   } else
2591     return false;
2592 
2593   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2594   // instructions because we can fold these into a more efficient instruction
2595   // instead, (such as LXSD).
2596   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2597     return false;
2598   }
2599 
2600   // PowerPC doesn't have preinc load/store instructions for vectors (except
2601   // for QPX, which does have preinc r+r forms).
2602   if (VT.isVector()) {
2603     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2604       return false;
2605     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2606       AM = ISD::PRE_INC;
2607       return true;
2608     }
2609   }
2610 
2611   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2612     // Common code will reject creating a pre-inc form if the base pointer
2613     // is a frame index, or if N is a store and the base pointer is either
2614     // the same as or a predecessor of the value being stored.  Check for
2615     // those situations here, and try with swapped Base/Offset instead.
2616     bool Swap = false;
2617 
2618     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2619       Swap = true;
2620     else if (!isLoad) {
2621       SDValue Val = cast<StoreSDNode>(N)->getValue();
2622       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2623         Swap = true;
2624     }
2625 
2626     if (Swap)
2627       std::swap(Base, Offset);
2628 
2629     AM = ISD::PRE_INC;
2630     return true;
2631   }
2632 
2633   // LDU/STU can only handle immediates that are a multiple of 4.
2634   if (VT != MVT::i64) {
2635     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2636       return false;
2637   } else {
2638     // LDU/STU need an address with at least 4-byte alignment.
2639     if (Alignment < 4)
2640       return false;
2641 
2642     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2643       return false;
2644   }
2645 
2646   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2647     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2648     // sext i32 to i64 when addr mode is r+i.
2649     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2650         LD->getExtensionType() == ISD::SEXTLOAD &&
2651         isa<ConstantSDNode>(Offset))
2652       return false;
2653   }
2654 
2655   AM = ISD::PRE_INC;
2656   return true;
2657 }
2658 
2659 //===----------------------------------------------------------------------===//
2660 //  LowerOperation implementation
2661 //===----------------------------------------------------------------------===//
2662 
2663 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2664 /// and LoOpFlags to the target MO flags.
2665 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2666                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2667                                const GlobalValue *GV = nullptr) {
2668   HiOpFlags = PPCII::MO_HA;
2669   LoOpFlags = PPCII::MO_LO;
2670 
2671   // Don't use the pic base if not in PIC relocation model.
2672   if (IsPIC) {
2673     HiOpFlags |= PPCII::MO_PIC_FLAG;
2674     LoOpFlags |= PPCII::MO_PIC_FLAG;
2675   }
2676 }
2677 
2678 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2679                              SelectionDAG &DAG) {
2680   SDLoc DL(HiPart);
2681   EVT PtrVT = HiPart.getValueType();
2682   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2683 
2684   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2685   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2686 
2687   // With PIC, the first instruction is actually "GR+hi(&G)".
2688   if (isPIC)
2689     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2690                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2691 
2692   // Generate non-pic code that has direct accesses to the constant pool.
2693   // The address of the global is just (hi(&g)+lo(&g)).
2694   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2695 }
2696 
2697 static void setUsesTOCBasePtr(MachineFunction &MF) {
2698   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2699   FuncInfo->setUsesTOCBasePtr();
2700 }
2701 
2702 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2703   setUsesTOCBasePtr(DAG.getMachineFunction());
2704 }
2705 
2706 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2707                                        SDValue GA) const {
2708   const bool Is64Bit = Subtarget.isPPC64();
2709   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2710   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2711                         : Subtarget.isAIXABI()
2712                               ? DAG.getRegister(PPC::R2, VT)
2713                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2714   SDValue Ops[] = { GA, Reg };
2715   return DAG.getMemIntrinsicNode(
2716       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2717       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2718       MachineMemOperand::MOLoad);
2719 }
2720 
2721 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2722                                              SelectionDAG &DAG) const {
2723   EVT PtrVT = Op.getValueType();
2724   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2725   const Constant *C = CP->getConstVal();
2726 
2727   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2728   // The actual address of the GlobalValue is stored in the TOC.
2729   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2730     setUsesTOCBasePtr(DAG);
2731     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2732     return getTOCEntry(DAG, SDLoc(CP), GA);
2733   }
2734 
2735   unsigned MOHiFlag, MOLoFlag;
2736   bool IsPIC = isPositionIndependent();
2737   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2738 
2739   if (IsPIC && Subtarget.isSVR4ABI()) {
2740     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2741                                            PPCII::MO_PIC_FLAG);
2742     return getTOCEntry(DAG, SDLoc(CP), GA);
2743   }
2744 
2745   SDValue CPIHi =
2746     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2747   SDValue CPILo =
2748     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2749   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2750 }
2751 
2752 // For 64-bit PowerPC, prefer the more compact relative encodings.
2753 // This trades 32 bits per jump table entry for one or two instructions
2754 // on the jump site.
2755 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2756   if (isJumpTableRelative())
2757     return MachineJumpTableInfo::EK_LabelDifference32;
2758 
2759   return TargetLowering::getJumpTableEncoding();
2760 }
2761 
2762 bool PPCTargetLowering::isJumpTableRelative() const {
2763   if (UseAbsoluteJumpTables)
2764     return false;
2765   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2766     return true;
2767   return TargetLowering::isJumpTableRelative();
2768 }
2769 
2770 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2771                                                     SelectionDAG &DAG) const {
2772   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2773     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2774 
2775   switch (getTargetMachine().getCodeModel()) {
2776   case CodeModel::Small:
2777   case CodeModel::Medium:
2778     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2779   default:
2780     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2781                        getPointerTy(DAG.getDataLayout()));
2782   }
2783 }
2784 
2785 const MCExpr *
2786 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2787                                                 unsigned JTI,
2788                                                 MCContext &Ctx) const {
2789   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2790     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2791 
2792   switch (getTargetMachine().getCodeModel()) {
2793   case CodeModel::Small:
2794   case CodeModel::Medium:
2795     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2796   default:
2797     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2798   }
2799 }
2800 
2801 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2802   EVT PtrVT = Op.getValueType();
2803   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2804 
2805   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2806   // The actual address of the GlobalValue is stored in the TOC.
2807   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2808     setUsesTOCBasePtr(DAG);
2809     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2810     return getTOCEntry(DAG, SDLoc(JT), GA);
2811   }
2812 
2813   unsigned MOHiFlag, MOLoFlag;
2814   bool IsPIC = isPositionIndependent();
2815   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2816 
2817   if (IsPIC && Subtarget.isSVR4ABI()) {
2818     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2819                                         PPCII::MO_PIC_FLAG);
2820     return getTOCEntry(DAG, SDLoc(GA), GA);
2821   }
2822 
2823   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2824   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2825   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2826 }
2827 
2828 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2829                                              SelectionDAG &DAG) const {
2830   EVT PtrVT = Op.getValueType();
2831   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2832   const BlockAddress *BA = BASDN->getBlockAddress();
2833 
2834   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2835   // The actual BlockAddress is stored in the TOC.
2836   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2837     setUsesTOCBasePtr(DAG);
2838     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2839     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2840   }
2841 
2842   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2843   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2844     return getTOCEntry(
2845         DAG, SDLoc(BASDN),
2846         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2847 
2848   unsigned MOHiFlag, MOLoFlag;
2849   bool IsPIC = isPositionIndependent();
2850   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2851   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2852   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2853   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2854 }
2855 
2856 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2857                                               SelectionDAG &DAG) const {
2858   // FIXME: TLS addresses currently use medium model code sequences,
2859   // which is the most useful form.  Eventually support for small and
2860   // large models could be added if users need it, at the cost of
2861   // additional complexity.
2862   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2863   if (DAG.getTarget().useEmulatedTLS())
2864     return LowerToTLSEmulatedModel(GA, DAG);
2865 
2866   SDLoc dl(GA);
2867   const GlobalValue *GV = GA->getGlobal();
2868   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2869   bool is64bit = Subtarget.isPPC64();
2870   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2871   PICLevel::Level picLevel = M->getPICLevel();
2872 
2873   const TargetMachine &TM = getTargetMachine();
2874   TLSModel::Model Model = TM.getTLSModel(GV);
2875 
2876   if (Model == TLSModel::LocalExec) {
2877     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2878                                                PPCII::MO_TPREL_HA);
2879     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2880                                                PPCII::MO_TPREL_LO);
2881     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2882                              : DAG.getRegister(PPC::R2, MVT::i32);
2883 
2884     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2885     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2886   }
2887 
2888   if (Model == TLSModel::InitialExec) {
2889     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2890     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2891                                                 PPCII::MO_TLS);
2892     SDValue GOTPtr;
2893     if (is64bit) {
2894       setUsesTOCBasePtr(DAG);
2895       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2896       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2897                            PtrVT, GOTReg, TGA);
2898     } else {
2899       if (!TM.isPositionIndependent())
2900         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2901       else if (picLevel == PICLevel::SmallPIC)
2902         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2903       else
2904         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2905     }
2906     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2907                                    PtrVT, TGA, GOTPtr);
2908     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2909   }
2910 
2911   if (Model == TLSModel::GeneralDynamic) {
2912     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2913     SDValue GOTPtr;
2914     if (is64bit) {
2915       setUsesTOCBasePtr(DAG);
2916       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2917       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2918                                    GOTReg, TGA);
2919     } else {
2920       if (picLevel == PICLevel::SmallPIC)
2921         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2922       else
2923         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2924     }
2925     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2926                        GOTPtr, TGA, TGA);
2927   }
2928 
2929   if (Model == TLSModel::LocalDynamic) {
2930     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2931     SDValue GOTPtr;
2932     if (is64bit) {
2933       setUsesTOCBasePtr(DAG);
2934       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2935       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2936                            GOTReg, TGA);
2937     } else {
2938       if (picLevel == PICLevel::SmallPIC)
2939         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2940       else
2941         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2942     }
2943     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2944                                   PtrVT, GOTPtr, TGA, TGA);
2945     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2946                                       PtrVT, TLSAddr, TGA);
2947     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2948   }
2949 
2950   llvm_unreachable("Unknown TLS model!");
2951 }
2952 
2953 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2954                                               SelectionDAG &DAG) const {
2955   EVT PtrVT = Op.getValueType();
2956   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2957   SDLoc DL(GSDN);
2958   const GlobalValue *GV = GSDN->getGlobal();
2959 
2960   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2961   // The actual address of the GlobalValue is stored in the TOC.
2962   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2963     setUsesTOCBasePtr(DAG);
2964     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2965     return getTOCEntry(DAG, DL, GA);
2966   }
2967 
2968   unsigned MOHiFlag, MOLoFlag;
2969   bool IsPIC = isPositionIndependent();
2970   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2971 
2972   if (IsPIC && Subtarget.isSVR4ABI()) {
2973     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2974                                             GSDN->getOffset(),
2975                                             PPCII::MO_PIC_FLAG);
2976     return getTOCEntry(DAG, DL, GA);
2977   }
2978 
2979   SDValue GAHi =
2980     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2981   SDValue GALo =
2982     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2983 
2984   return LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2985 }
2986 
2987 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2988   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2989   SDLoc dl(Op);
2990 
2991   if (Op.getValueType() == MVT::v2i64) {
2992     // When the operands themselves are v2i64 values, we need to do something
2993     // special because VSX has no underlying comparison operations for these.
2994     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2995       // Equality can be handled by casting to the legal type for Altivec
2996       // comparisons, everything else needs to be expanded.
2997       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2998         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2999                  DAG.getSetCC(dl, MVT::v4i32,
3000                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3001                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3002                    CC));
3003       }
3004 
3005       return SDValue();
3006     }
3007 
3008     // We handle most of these in the usual way.
3009     return Op;
3010   }
3011 
3012   // If we're comparing for equality to zero, expose the fact that this is
3013   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3014   // fold the new nodes.
3015   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3016     return V;
3017 
3018   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3019     // Leave comparisons against 0 and -1 alone for now, since they're usually
3020     // optimized.  FIXME: revisit this when we can custom lower all setcc
3021     // optimizations.
3022     if (C->isAllOnesValue() || C->isNullValue())
3023       return SDValue();
3024   }
3025 
3026   // If we have an integer seteq/setne, turn it into a compare against zero
3027   // by xor'ing the rhs with the lhs, which is faster than setting a
3028   // condition register, reading it back out, and masking the correct bit.  The
3029   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3030   // the result to other bit-twiddling opportunities.
3031   EVT LHSVT = Op.getOperand(0).getValueType();
3032   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3033     EVT VT = Op.getValueType();
3034     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3035                                 Op.getOperand(1));
3036     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3037   }
3038   return SDValue();
3039 }
3040 
3041 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3042   SDNode *Node = Op.getNode();
3043   EVT VT = Node->getValueType(0);
3044   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3045   SDValue InChain = Node->getOperand(0);
3046   SDValue VAListPtr = Node->getOperand(1);
3047   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3048   SDLoc dl(Node);
3049 
3050   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3051 
3052   // gpr_index
3053   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3054                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3055   InChain = GprIndex.getValue(1);
3056 
3057   if (VT == MVT::i64) {
3058     // Check if GprIndex is even
3059     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3060                                  DAG.getConstant(1, dl, MVT::i32));
3061     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3062                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3063     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3064                                           DAG.getConstant(1, dl, MVT::i32));
3065     // Align GprIndex to be even if it isn't
3066     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3067                            GprIndex);
3068   }
3069 
3070   // fpr index is 1 byte after gpr
3071   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3072                                DAG.getConstant(1, dl, MVT::i32));
3073 
3074   // fpr
3075   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3076                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3077   InChain = FprIndex.getValue(1);
3078 
3079   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3080                                        DAG.getConstant(8, dl, MVT::i32));
3081 
3082   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3083                                         DAG.getConstant(4, dl, MVT::i32));
3084 
3085   // areas
3086   SDValue OverflowArea =
3087       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3088   InChain = OverflowArea.getValue(1);
3089 
3090   SDValue RegSaveArea =
3091       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3092   InChain = RegSaveArea.getValue(1);
3093 
3094   // select overflow_area if index > 8
3095   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3096                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3097 
3098   // adjustment constant gpr_index * 4/8
3099   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3100                                     VT.isInteger() ? GprIndex : FprIndex,
3101                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3102                                                     MVT::i32));
3103 
3104   // OurReg = RegSaveArea + RegConstant
3105   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3106                                RegConstant);
3107 
3108   // Floating types are 32 bytes into RegSaveArea
3109   if (VT.isFloatingPoint())
3110     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3111                          DAG.getConstant(32, dl, MVT::i32));
3112 
3113   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3114   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3115                                    VT.isInteger() ? GprIndex : FprIndex,
3116                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3117                                                    MVT::i32));
3118 
3119   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3120                               VT.isInteger() ? VAListPtr : FprPtr,
3121                               MachinePointerInfo(SV), MVT::i8);
3122 
3123   // determine if we should load from reg_save_area or overflow_area
3124   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3125 
3126   // increase overflow_area by 4/8 if gpr/fpr > 8
3127   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3128                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3129                                           dl, MVT::i32));
3130 
3131   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3132                              OverflowAreaPlusN);
3133 
3134   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3135                               MachinePointerInfo(), MVT::i32);
3136 
3137   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3138 }
3139 
3140 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3141   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3142 
3143   // We have to copy the entire va_list struct:
3144   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3145   return DAG.getMemcpy(Op.getOperand(0), Op, Op.getOperand(1), Op.getOperand(2),
3146                        DAG.getConstant(12, SDLoc(Op), MVT::i32), Align(8),
3147                        false, true, false, MachinePointerInfo(),
3148                        MachinePointerInfo());
3149 }
3150 
3151 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3152                                                   SelectionDAG &DAG) const {
3153   if (Subtarget.isAIXABI())
3154     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3155 
3156   return Op.getOperand(0);
3157 }
3158 
3159 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3160                                                 SelectionDAG &DAG) const {
3161   if (Subtarget.isAIXABI())
3162     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3163 
3164   SDValue Chain = Op.getOperand(0);
3165   SDValue Trmp = Op.getOperand(1); // trampoline
3166   SDValue FPtr = Op.getOperand(2); // nested function
3167   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3168   SDLoc dl(Op);
3169 
3170   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3171   bool isPPC64 = (PtrVT == MVT::i64);
3172   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3173 
3174   TargetLowering::ArgListTy Args;
3175   TargetLowering::ArgListEntry Entry;
3176 
3177   Entry.Ty = IntPtrTy;
3178   Entry.Node = Trmp; Args.push_back(Entry);
3179 
3180   // TrampSize == (isPPC64 ? 48 : 40);
3181   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3182                                isPPC64 ? MVT::i64 : MVT::i32);
3183   Args.push_back(Entry);
3184 
3185   Entry.Node = FPtr; Args.push_back(Entry);
3186   Entry.Node = Nest; Args.push_back(Entry);
3187 
3188   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3189   TargetLowering::CallLoweringInfo CLI(DAG);
3190   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3191       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3192       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3193 
3194   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3195   return CallResult.second;
3196 }
3197 
3198 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3199   MachineFunction &MF = DAG.getMachineFunction();
3200   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3201   EVT PtrVT = getPointerTy(MF.getDataLayout());
3202 
3203   SDLoc dl(Op);
3204 
3205   if (Subtarget.isPPC64()) {
3206     // vastart just stores the address of the VarArgsFrameIndex slot into the
3207     // memory location argument.
3208     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3209     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3210     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3211                         MachinePointerInfo(SV));
3212   }
3213 
3214   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3215   // We suppose the given va_list is already allocated.
3216   //
3217   // typedef struct {
3218   //  char gpr;     /* index into the array of 8 GPRs
3219   //                 * stored in the register save area
3220   //                 * gpr=0 corresponds to r3,
3221   //                 * gpr=1 to r4, etc.
3222   //                 */
3223   //  char fpr;     /* index into the array of 8 FPRs
3224   //                 * stored in the register save area
3225   //                 * fpr=0 corresponds to f1,
3226   //                 * fpr=1 to f2, etc.
3227   //                 */
3228   //  char *overflow_arg_area;
3229   //                /* location on stack that holds
3230   //                 * the next overflow argument
3231   //                 */
3232   //  char *reg_save_area;
3233   //               /* where r3:r10 and f1:f8 (if saved)
3234   //                * are stored
3235   //                */
3236   // } va_list[1];
3237 
3238   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3239   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3240   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3241                                             PtrVT);
3242   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3243                                  PtrVT);
3244 
3245   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3246   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3247 
3248   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3249   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3250 
3251   uint64_t FPROffset = 1;
3252   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3253 
3254   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3255 
3256   // Store first byte : number of int regs
3257   SDValue firstStore =
3258       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3259                         MachinePointerInfo(SV), MVT::i8);
3260   uint64_t nextOffset = FPROffset;
3261   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3262                                   ConstFPROffset);
3263 
3264   // Store second byte : number of float regs
3265   SDValue secondStore =
3266       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3267                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3268   nextOffset += StackOffset;
3269   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3270 
3271   // Store second word : arguments given on stack
3272   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3273                                     MachinePointerInfo(SV, nextOffset));
3274   nextOffset += FrameOffset;
3275   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3276 
3277   // Store third word : arguments given in registers
3278   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3279                       MachinePointerInfo(SV, nextOffset));
3280 }
3281 
3282 /// FPR - The set of FP registers that should be allocated for arguments
3283 /// on Darwin and AIX.
3284 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3285                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3286                                 PPC::F11, PPC::F12, PPC::F13};
3287 
3288 /// QFPR - The set of QPX registers that should be allocated for arguments.
3289 static const MCPhysReg QFPR[] = {
3290     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3291     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3292 
3293 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3294 /// the stack.
3295 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3296                                        unsigned PtrByteSize) {
3297   unsigned ArgSize = ArgVT.getStoreSize();
3298   if (Flags.isByVal())
3299     ArgSize = Flags.getByValSize();
3300 
3301   // Round up to multiples of the pointer size, except for array members,
3302   // which are always packed.
3303   if (!Flags.isInConsecutiveRegs())
3304     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3305 
3306   return ArgSize;
3307 }
3308 
3309 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3310 /// on the stack.
3311 static Align CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3312                                          ISD::ArgFlagsTy Flags,
3313                                          unsigned PtrByteSize) {
3314   Align Alignment(PtrByteSize);
3315 
3316   // Altivec parameters are padded to a 16 byte boundary.
3317   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3318       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3319       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3320       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3321     Alignment = Align(16);
3322   // QPX vector types stored in double-precision are padded to a 32 byte
3323   // boundary.
3324   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3325     Alignment = Align(32);
3326 
3327   // ByVal parameters are aligned as requested.
3328   if (Flags.isByVal()) {
3329     auto BVAlign = Flags.getNonZeroByValAlign();
3330     if (BVAlign > PtrByteSize) {
3331       if (BVAlign.value() % PtrByteSize != 0)
3332         llvm_unreachable(
3333             "ByVal alignment is not a multiple of the pointer size");
3334 
3335       Alignment = BVAlign;
3336     }
3337   }
3338 
3339   // Array members are always packed to their original alignment.
3340   if (Flags.isInConsecutiveRegs()) {
3341     // If the array member was split into multiple registers, the first
3342     // needs to be aligned to the size of the full type.  (Except for
3343     // ppcf128, which is only aligned as its f64 components.)
3344     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3345       Alignment = Align(OrigVT.getStoreSize());
3346     else
3347       Alignment = Align(ArgVT.getStoreSize());
3348   }
3349 
3350   return Alignment;
3351 }
3352 
3353 /// CalculateStackSlotUsed - Return whether this argument will use its
3354 /// stack slot (instead of being passed in registers).  ArgOffset,
3355 /// AvailableFPRs, and AvailableVRs must hold the current argument
3356 /// position, and will be updated to account for this argument.
3357 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3358                                    ISD::ArgFlagsTy Flags,
3359                                    unsigned PtrByteSize,
3360                                    unsigned LinkageSize,
3361                                    unsigned ParamAreaSize,
3362                                    unsigned &ArgOffset,
3363                                    unsigned &AvailableFPRs,
3364                                    unsigned &AvailableVRs, bool HasQPX) {
3365   bool UseMemory = false;
3366 
3367   // Respect alignment of argument on the stack.
3368   Align Alignment =
3369       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3370   ArgOffset = alignTo(ArgOffset, Alignment);
3371   // If there's no space left in the argument save area, we must
3372   // use memory (this check also catches zero-sized arguments).
3373   if (ArgOffset >= LinkageSize + ParamAreaSize)
3374     UseMemory = true;
3375 
3376   // Allocate argument on the stack.
3377   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3378   if (Flags.isInConsecutiveRegsLast())
3379     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3380   // If we overran the argument save area, we must use memory
3381   // (this check catches arguments passed partially in memory)
3382   if (ArgOffset > LinkageSize + ParamAreaSize)
3383     UseMemory = true;
3384 
3385   // However, if the argument is actually passed in an FPR or a VR,
3386   // we don't use memory after all.
3387   if (!Flags.isByVal()) {
3388     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3389         // QPX registers overlap with the scalar FP registers.
3390         (HasQPX && (ArgVT == MVT::v4f32 ||
3391                     ArgVT == MVT::v4f64 ||
3392                     ArgVT == MVT::v4i1)))
3393       if (AvailableFPRs > 0) {
3394         --AvailableFPRs;
3395         return false;
3396       }
3397     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3398         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3399         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3400         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3401       if (AvailableVRs > 0) {
3402         --AvailableVRs;
3403         return false;
3404       }
3405   }
3406 
3407   return UseMemory;
3408 }
3409 
3410 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3411 /// ensure minimum alignment required for target.
3412 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3413                                      unsigned NumBytes) {
3414   unsigned TargetAlign = Lowering->getStackAlignment();
3415   unsigned AlignMask = TargetAlign - 1;
3416   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3417   return NumBytes;
3418 }
3419 
3420 SDValue PPCTargetLowering::LowerFormalArguments(
3421     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3422     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3423     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3424   if (Subtarget.isAIXABI())
3425     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3426                                     InVals);
3427   if (Subtarget.is64BitELFABI())
3428     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3429                                        InVals);
3430   if (Subtarget.is32BitELFABI())
3431     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3432                                        InVals);
3433 
3434   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3435                                      InVals);
3436 }
3437 
3438 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3439     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3440     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3441     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3442 
3443   // 32-bit SVR4 ABI Stack Frame Layout:
3444   //              +-----------------------------------+
3445   //        +-->  |            Back chain             |
3446   //        |     +-----------------------------------+
3447   //        |     | Floating-point register save area |
3448   //        |     +-----------------------------------+
3449   //        |     |    General register save area     |
3450   //        |     +-----------------------------------+
3451   //        |     |          CR save word             |
3452   //        |     +-----------------------------------+
3453   //        |     |         VRSAVE save word          |
3454   //        |     +-----------------------------------+
3455   //        |     |         Alignment padding         |
3456   //        |     +-----------------------------------+
3457   //        |     |     Vector register save area     |
3458   //        |     +-----------------------------------+
3459   //        |     |       Local variable space        |
3460   //        |     +-----------------------------------+
3461   //        |     |        Parameter list area        |
3462   //        |     +-----------------------------------+
3463   //        |     |           LR save word            |
3464   //        |     +-----------------------------------+
3465   // SP-->  +---  |            Back chain             |
3466   //              +-----------------------------------+
3467   //
3468   // Specifications:
3469   //   System V Application Binary Interface PowerPC Processor Supplement
3470   //   AltiVec Technology Programming Interface Manual
3471 
3472   MachineFunction &MF = DAG.getMachineFunction();
3473   MachineFrameInfo &MFI = MF.getFrameInfo();
3474   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3475 
3476   EVT PtrVT = getPointerTy(MF.getDataLayout());
3477   // Potential tail calls could cause overwriting of argument stack slots.
3478   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3479                        (CallConv == CallingConv::Fast));
3480   unsigned PtrByteSize = 4;
3481 
3482   // Assign locations to all of the incoming arguments.
3483   SmallVector<CCValAssign, 16> ArgLocs;
3484   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3485                  *DAG.getContext());
3486 
3487   // Reserve space for the linkage area on the stack.
3488   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3489   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3490   if (useSoftFloat())
3491     CCInfo.PreAnalyzeFormalArguments(Ins);
3492 
3493   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3494   CCInfo.clearWasPPCF128();
3495 
3496   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3497     CCValAssign &VA = ArgLocs[i];
3498 
3499     // Arguments stored in registers.
3500     if (VA.isRegLoc()) {
3501       const TargetRegisterClass *RC;
3502       EVT ValVT = VA.getValVT();
3503 
3504       switch (ValVT.getSimpleVT().SimpleTy) {
3505         default:
3506           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3507         case MVT::i1:
3508         case MVT::i32:
3509           RC = &PPC::GPRCRegClass;
3510           break;
3511         case MVT::f32:
3512           if (Subtarget.hasP8Vector())
3513             RC = &PPC::VSSRCRegClass;
3514           else if (Subtarget.hasSPE())
3515             RC = &PPC::GPRCRegClass;
3516           else
3517             RC = &PPC::F4RCRegClass;
3518           break;
3519         case MVT::f64:
3520           if (Subtarget.hasVSX())
3521             RC = &PPC::VSFRCRegClass;
3522           else if (Subtarget.hasSPE())
3523             // SPE passes doubles in GPR pairs.
3524             RC = &PPC::GPRCRegClass;
3525           else
3526             RC = &PPC::F8RCRegClass;
3527           break;
3528         case MVT::v16i8:
3529         case MVT::v8i16:
3530         case MVT::v4i32:
3531           RC = &PPC::VRRCRegClass;
3532           break;
3533         case MVT::v4f32:
3534           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3535           break;
3536         case MVT::v2f64:
3537         case MVT::v2i64:
3538           RC = &PPC::VRRCRegClass;
3539           break;
3540         case MVT::v4f64:
3541           RC = &PPC::QFRCRegClass;
3542           break;
3543         case MVT::v4i1:
3544           RC = &PPC::QBRCRegClass;
3545           break;
3546       }
3547 
3548       SDValue ArgValue;
3549       // Transform the arguments stored in physical registers into
3550       // virtual ones.
3551       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3552         assert(i + 1 < e && "No second half of double precision argument");
3553         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3554         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3555         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3556         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3557         if (!Subtarget.isLittleEndian())
3558           std::swap (ArgValueLo, ArgValueHi);
3559         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3560                                ArgValueHi);
3561       } else {
3562         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3563         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3564                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3565         if (ValVT == MVT::i1)
3566           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3567       }
3568 
3569       InVals.push_back(ArgValue);
3570     } else {
3571       // Argument stored in memory.
3572       assert(VA.isMemLoc());
3573 
3574       // Get the extended size of the argument type in stack
3575       unsigned ArgSize = VA.getLocVT().getStoreSize();
3576       // Get the actual size of the argument type
3577       unsigned ObjSize = VA.getValVT().getStoreSize();
3578       unsigned ArgOffset = VA.getLocMemOffset();
3579       // Stack objects in PPC32 are right justified.
3580       ArgOffset += ArgSize - ObjSize;
3581       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3582 
3583       // Create load nodes to retrieve arguments from the stack.
3584       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3585       InVals.push_back(
3586           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3587     }
3588   }
3589 
3590   // Assign locations to all of the incoming aggregate by value arguments.
3591   // Aggregates passed by value are stored in the local variable space of the
3592   // caller's stack frame, right above the parameter list area.
3593   SmallVector<CCValAssign, 16> ByValArgLocs;
3594   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3595                       ByValArgLocs, *DAG.getContext());
3596 
3597   // Reserve stack space for the allocations in CCInfo.
3598   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3599 
3600   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3601 
3602   // Area that is at least reserved in the caller of this function.
3603   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3604   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3605 
3606   // Set the size that is at least reserved in caller of this function.  Tail
3607   // call optimized function's reserved stack space needs to be aligned so that
3608   // taking the difference between two stack areas will result in an aligned
3609   // stack.
3610   MinReservedArea =
3611       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3612   FuncInfo->setMinReservedArea(MinReservedArea);
3613 
3614   SmallVector<SDValue, 8> MemOps;
3615 
3616   // If the function takes variable number of arguments, make a frame index for
3617   // the start of the first vararg value... for expansion of llvm.va_start.
3618   if (isVarArg) {
3619     static const MCPhysReg GPArgRegs[] = {
3620       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3621       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3622     };
3623     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3624 
3625     static const MCPhysReg FPArgRegs[] = {
3626       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3627       PPC::F8
3628     };
3629     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3630 
3631     if (useSoftFloat() || hasSPE())
3632        NumFPArgRegs = 0;
3633 
3634     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3635     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3636 
3637     // Make room for NumGPArgRegs and NumFPArgRegs.
3638     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3639                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3640 
3641     FuncInfo->setVarArgsStackOffset(
3642       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3643                             CCInfo.getNextStackOffset(), true));
3644 
3645     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3646     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3647 
3648     // The fixed integer arguments of a variadic function are stored to the
3649     // VarArgsFrameIndex on the stack so that they may be loaded by
3650     // dereferencing the result of va_next.
3651     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3652       // Get an existing live-in vreg, or add a new one.
3653       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3654       if (!VReg)
3655         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3656 
3657       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3658       SDValue Store =
3659           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3660       MemOps.push_back(Store);
3661       // Increment the address by four for the next argument to store
3662       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3663       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3664     }
3665 
3666     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3667     // is set.
3668     // The double arguments are stored to the VarArgsFrameIndex
3669     // on the stack.
3670     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3671       // Get an existing live-in vreg, or add a new one.
3672       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3673       if (!VReg)
3674         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3675 
3676       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3677       SDValue Store =
3678           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3679       MemOps.push_back(Store);
3680       // Increment the address by eight for the next argument to store
3681       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3682                                          PtrVT);
3683       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3684     }
3685   }
3686 
3687   if (!MemOps.empty())
3688     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3689 
3690   return Chain;
3691 }
3692 
3693 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3694 // value to MVT::i64 and then truncate to the correct register size.
3695 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3696                                              EVT ObjectVT, SelectionDAG &DAG,
3697                                              SDValue ArgVal,
3698                                              const SDLoc &dl) const {
3699   if (Flags.isSExt())
3700     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3701                          DAG.getValueType(ObjectVT));
3702   else if (Flags.isZExt())
3703     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3704                          DAG.getValueType(ObjectVT));
3705 
3706   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3707 }
3708 
3709 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3710     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3711     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3712     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3713   // TODO: add description of PPC stack frame format, or at least some docs.
3714   //
3715   bool isELFv2ABI = Subtarget.isELFv2ABI();
3716   bool isLittleEndian = Subtarget.isLittleEndian();
3717   MachineFunction &MF = DAG.getMachineFunction();
3718   MachineFrameInfo &MFI = MF.getFrameInfo();
3719   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3720 
3721   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3722          "fastcc not supported on varargs functions");
3723 
3724   EVT PtrVT = getPointerTy(MF.getDataLayout());
3725   // Potential tail calls could cause overwriting of argument stack slots.
3726   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3727                        (CallConv == CallingConv::Fast));
3728   unsigned PtrByteSize = 8;
3729   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3730 
3731   static const MCPhysReg GPR[] = {
3732     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3733     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3734   };
3735   static const MCPhysReg VR[] = {
3736     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3737     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3738   };
3739 
3740   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3741   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3742   const unsigned Num_VR_Regs  = array_lengthof(VR);
3743   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3744 
3745   // Do a first pass over the arguments to determine whether the ABI
3746   // guarantees that our caller has allocated the parameter save area
3747   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3748   // in the ELFv2 ABI, it is true if this is a vararg function or if
3749   // any parameter is located in a stack slot.
3750 
3751   bool HasParameterArea = !isELFv2ABI || isVarArg;
3752   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3753   unsigned NumBytes = LinkageSize;
3754   unsigned AvailableFPRs = Num_FPR_Regs;
3755   unsigned AvailableVRs = Num_VR_Regs;
3756   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3757     if (Ins[i].Flags.isNest())
3758       continue;
3759 
3760     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3761                                PtrByteSize, LinkageSize, ParamAreaSize,
3762                                NumBytes, AvailableFPRs, AvailableVRs,
3763                                Subtarget.hasQPX()))
3764       HasParameterArea = true;
3765   }
3766 
3767   // Add DAG nodes to load the arguments or copy them out of registers.  On
3768   // entry to a function on PPC, the arguments start after the linkage area,
3769   // although the first ones are often in registers.
3770 
3771   unsigned ArgOffset = LinkageSize;
3772   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3773   unsigned &QFPR_idx = FPR_idx;
3774   SmallVector<SDValue, 8> MemOps;
3775   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3776   unsigned CurArgIdx = 0;
3777   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3778     SDValue ArgVal;
3779     bool needsLoad = false;
3780     EVT ObjectVT = Ins[ArgNo].VT;
3781     EVT OrigVT = Ins[ArgNo].ArgVT;
3782     unsigned ObjSize = ObjectVT.getStoreSize();
3783     unsigned ArgSize = ObjSize;
3784     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3785     if (Ins[ArgNo].isOrigArg()) {
3786       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3787       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3788     }
3789     // We re-align the argument offset for each argument, except when using the
3790     // fast calling convention, when we need to make sure we do that only when
3791     // we'll actually use a stack slot.
3792     unsigned CurArgOffset;
3793     Align Alignment;
3794     auto ComputeArgOffset = [&]() {
3795       /* Respect alignment of argument on the stack.  */
3796       Alignment =
3797           CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3798       ArgOffset = alignTo(ArgOffset, Alignment);
3799       CurArgOffset = ArgOffset;
3800     };
3801 
3802     if (CallConv != CallingConv::Fast) {
3803       ComputeArgOffset();
3804 
3805       /* Compute GPR index associated with argument offset.  */
3806       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3807       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3808     }
3809 
3810     // FIXME the codegen can be much improved in some cases.
3811     // We do not have to keep everything in memory.
3812     if (Flags.isByVal()) {
3813       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3814 
3815       if (CallConv == CallingConv::Fast)
3816         ComputeArgOffset();
3817 
3818       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3819       ObjSize = Flags.getByValSize();
3820       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3821       // Empty aggregate parameters do not take up registers.  Examples:
3822       //   struct { } a;
3823       //   union  { } b;
3824       //   int c[0];
3825       // etc.  However, we have to provide a place-holder in InVals, so
3826       // pretend we have an 8-byte item at the current address for that
3827       // purpose.
3828       if (!ObjSize) {
3829         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3830         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3831         InVals.push_back(FIN);
3832         continue;
3833       }
3834 
3835       // Create a stack object covering all stack doublewords occupied
3836       // by the argument.  If the argument is (fully or partially) on
3837       // the stack, or if the argument is fully in registers but the
3838       // caller has allocated the parameter save anyway, we can refer
3839       // directly to the caller's stack frame.  Otherwise, create a
3840       // local copy in our own frame.
3841       int FI;
3842       if (HasParameterArea ||
3843           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3844         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3845       else
3846         FI = MFI.CreateStackObject(ArgSize, Alignment, false);
3847       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3848 
3849       // Handle aggregates smaller than 8 bytes.
3850       if (ObjSize < PtrByteSize) {
3851         // The value of the object is its address, which differs from the
3852         // address of the enclosing doubleword on big-endian systems.
3853         SDValue Arg = FIN;
3854         if (!isLittleEndian) {
3855           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3856           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3857         }
3858         InVals.push_back(Arg);
3859 
3860         if (GPR_idx != Num_GPR_Regs) {
3861           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3862           FuncInfo->addLiveInAttr(VReg, Flags);
3863           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3864           SDValue Store;
3865 
3866           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3867             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3868                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3869             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3870                                       MachinePointerInfo(&*FuncArg), ObjType);
3871           } else {
3872             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3873             // store the whole register as-is to the parameter save area
3874             // slot.
3875             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3876                                  MachinePointerInfo(&*FuncArg));
3877           }
3878 
3879           MemOps.push_back(Store);
3880         }
3881         // Whether we copied from a register or not, advance the offset
3882         // into the parameter save area by a full doubleword.
3883         ArgOffset += PtrByteSize;
3884         continue;
3885       }
3886 
3887       // The value of the object is its address, which is the address of
3888       // its first stack doubleword.
3889       InVals.push_back(FIN);
3890 
3891       // Store whatever pieces of the object are in registers to memory.
3892       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3893         if (GPR_idx == Num_GPR_Regs)
3894           break;
3895 
3896         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3897         FuncInfo->addLiveInAttr(VReg, Flags);
3898         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3899         SDValue Addr = FIN;
3900         if (j) {
3901           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3902           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3903         }
3904         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3905                                      MachinePointerInfo(&*FuncArg, j));
3906         MemOps.push_back(Store);
3907         ++GPR_idx;
3908       }
3909       ArgOffset += ArgSize;
3910       continue;
3911     }
3912 
3913     switch (ObjectVT.getSimpleVT().SimpleTy) {
3914     default: llvm_unreachable("Unhandled argument type!");
3915     case MVT::i1:
3916     case MVT::i32:
3917     case MVT::i64:
3918       if (Flags.isNest()) {
3919         // The 'nest' parameter, if any, is passed in R11.
3920         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3921         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3922 
3923         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3924           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3925 
3926         break;
3927       }
3928 
3929       // These can be scalar arguments or elements of an integer array type
3930       // passed directly.  Clang may use those instead of "byval" aggregate
3931       // types to avoid forcing arguments to memory unnecessarily.
3932       if (GPR_idx != Num_GPR_Regs) {
3933         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3934         FuncInfo->addLiveInAttr(VReg, Flags);
3935         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3936 
3937         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3938           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3939           // value to MVT::i64 and then truncate to the correct register size.
3940           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3941       } else {
3942         if (CallConv == CallingConv::Fast)
3943           ComputeArgOffset();
3944 
3945         needsLoad = true;
3946         ArgSize = PtrByteSize;
3947       }
3948       if (CallConv != CallingConv::Fast || needsLoad)
3949         ArgOffset += 8;
3950       break;
3951 
3952     case MVT::f32:
3953     case MVT::f64:
3954       // These can be scalar arguments or elements of a float array type
3955       // passed directly.  The latter are used to implement ELFv2 homogenous
3956       // float aggregates.
3957       if (FPR_idx != Num_FPR_Regs) {
3958         unsigned VReg;
3959 
3960         if (ObjectVT == MVT::f32)
3961           VReg = MF.addLiveIn(FPR[FPR_idx],
3962                               Subtarget.hasP8Vector()
3963                                   ? &PPC::VSSRCRegClass
3964                                   : &PPC::F4RCRegClass);
3965         else
3966           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3967                                                 ? &PPC::VSFRCRegClass
3968                                                 : &PPC::F8RCRegClass);
3969 
3970         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3971         ++FPR_idx;
3972       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3973         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3974         // once we support fp <-> gpr moves.
3975 
3976         // This can only ever happen in the presence of f32 array types,
3977         // since otherwise we never run out of FPRs before running out
3978         // of GPRs.
3979         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3980         FuncInfo->addLiveInAttr(VReg, Flags);
3981         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3982 
3983         if (ObjectVT == MVT::f32) {
3984           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3985             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3986                                  DAG.getConstant(32, dl, MVT::i32));
3987           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3988         }
3989 
3990         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3991       } else {
3992         if (CallConv == CallingConv::Fast)
3993           ComputeArgOffset();
3994 
3995         needsLoad = true;
3996       }
3997 
3998       // When passing an array of floats, the array occupies consecutive
3999       // space in the argument area; only round up to the next doubleword
4000       // at the end of the array.  Otherwise, each float takes 8 bytes.
4001       if (CallConv != CallingConv::Fast || needsLoad) {
4002         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4003         ArgOffset += ArgSize;
4004         if (Flags.isInConsecutiveRegsLast())
4005           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4006       }
4007       break;
4008     case MVT::v4f32:
4009     case MVT::v4i32:
4010     case MVT::v8i16:
4011     case MVT::v16i8:
4012     case MVT::v2f64:
4013     case MVT::v2i64:
4014     case MVT::v1i128:
4015     case MVT::f128:
4016       if (!Subtarget.hasQPX()) {
4017         // These can be scalar arguments or elements of a vector array type
4018         // passed directly.  The latter are used to implement ELFv2 homogenous
4019         // vector aggregates.
4020         if (VR_idx != Num_VR_Regs) {
4021           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4022           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4023           ++VR_idx;
4024         } else {
4025           if (CallConv == CallingConv::Fast)
4026             ComputeArgOffset();
4027           needsLoad = true;
4028         }
4029         if (CallConv != CallingConv::Fast || needsLoad)
4030           ArgOffset += 16;
4031         break;
4032       } // not QPX
4033 
4034       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4035              "Invalid QPX parameter type");
4036       LLVM_FALLTHROUGH;
4037 
4038     case MVT::v4f64:
4039     case MVT::v4i1:
4040       // QPX vectors are treated like their scalar floating-point subregisters
4041       // (except that they're larger).
4042       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4043       if (QFPR_idx != Num_QFPR_Regs) {
4044         const TargetRegisterClass *RC;
4045         switch (ObjectVT.getSimpleVT().SimpleTy) {
4046         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4047         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4048         default:         RC = &PPC::QBRCRegClass; break;
4049         }
4050 
4051         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4052         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4053         ++QFPR_idx;
4054       } else {
4055         if (CallConv == CallingConv::Fast)
4056           ComputeArgOffset();
4057         needsLoad = true;
4058       }
4059       if (CallConv != CallingConv::Fast || needsLoad)
4060         ArgOffset += Sz;
4061       break;
4062     }
4063 
4064     // We need to load the argument to a virtual register if we determined
4065     // above that we ran out of physical registers of the appropriate type.
4066     if (needsLoad) {
4067       if (ObjSize < ArgSize && !isLittleEndian)
4068         CurArgOffset += ArgSize - ObjSize;
4069       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4070       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4071       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4072     }
4073 
4074     InVals.push_back(ArgVal);
4075   }
4076 
4077   // Area that is at least reserved in the caller of this function.
4078   unsigned MinReservedArea;
4079   if (HasParameterArea)
4080     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4081   else
4082     MinReservedArea = LinkageSize;
4083 
4084   // Set the size that is at least reserved in caller of this function.  Tail
4085   // call optimized functions' reserved stack space needs to be aligned so that
4086   // taking the difference between two stack areas will result in an aligned
4087   // stack.
4088   MinReservedArea =
4089       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4090   FuncInfo->setMinReservedArea(MinReservedArea);
4091 
4092   // If the function takes variable number of arguments, make a frame index for
4093   // the start of the first vararg value... for expansion of llvm.va_start.
4094   if (isVarArg) {
4095     int Depth = ArgOffset;
4096 
4097     FuncInfo->setVarArgsFrameIndex(
4098       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4099     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4100 
4101     // If this function is vararg, store any remaining integer argument regs
4102     // to their spots on the stack so that they may be loaded by dereferencing
4103     // the result of va_next.
4104     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4105          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4106       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4107       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4108       SDValue Store =
4109           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4110       MemOps.push_back(Store);
4111       // Increment the address by four for the next argument to store
4112       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4113       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4114     }
4115   }
4116 
4117   if (!MemOps.empty())
4118     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4119 
4120   return Chain;
4121 }
4122 
4123 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4124     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4125     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4126     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4127   // TODO: add description of PPC stack frame format, or at least some docs.
4128   //
4129   MachineFunction &MF = DAG.getMachineFunction();
4130   MachineFrameInfo &MFI = MF.getFrameInfo();
4131   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4132 
4133   EVT PtrVT = getPointerTy(MF.getDataLayout());
4134   bool isPPC64 = PtrVT == MVT::i64;
4135   // Potential tail calls could cause overwriting of argument stack slots.
4136   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4137                        (CallConv == CallingConv::Fast));
4138   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4139   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4140   unsigned ArgOffset = LinkageSize;
4141   // Area that is at least reserved in caller of this function.
4142   unsigned MinReservedArea = ArgOffset;
4143 
4144   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4145     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4146     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4147   };
4148   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4149     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4150     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4151   };
4152   static const MCPhysReg VR[] = {
4153     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4154     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4155   };
4156 
4157   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4158   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4159   const unsigned Num_VR_Regs  = array_lengthof( VR);
4160 
4161   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4162 
4163   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4164 
4165   // In 32-bit non-varargs functions, the stack space for vectors is after the
4166   // stack space for non-vectors.  We do not use this space unless we have
4167   // too many vectors to fit in registers, something that only occurs in
4168   // constructed examples:), but we have to walk the arglist to figure
4169   // that out...for the pathological case, compute VecArgOffset as the
4170   // start of the vector parameter area.  Computing VecArgOffset is the
4171   // entire point of the following loop.
4172   unsigned VecArgOffset = ArgOffset;
4173   if (!isVarArg && !isPPC64) {
4174     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4175          ++ArgNo) {
4176       EVT ObjectVT = Ins[ArgNo].VT;
4177       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4178 
4179       if (Flags.isByVal()) {
4180         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4181         unsigned ObjSize = Flags.getByValSize();
4182         unsigned ArgSize =
4183                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4184         VecArgOffset += ArgSize;
4185         continue;
4186       }
4187 
4188       switch(ObjectVT.getSimpleVT().SimpleTy) {
4189       default: llvm_unreachable("Unhandled argument type!");
4190       case MVT::i1:
4191       case MVT::i32:
4192       case MVT::f32:
4193         VecArgOffset += 4;
4194         break;
4195       case MVT::i64:  // PPC64
4196       case MVT::f64:
4197         // FIXME: We are guaranteed to be !isPPC64 at this point.
4198         // Does MVT::i64 apply?
4199         VecArgOffset += 8;
4200         break;
4201       case MVT::v4f32:
4202       case MVT::v4i32:
4203       case MVT::v8i16:
4204       case MVT::v16i8:
4205         // Nothing to do, we're only looking at Nonvector args here.
4206         break;
4207       }
4208     }
4209   }
4210   // We've found where the vector parameter area in memory is.  Skip the
4211   // first 12 parameters; these don't use that memory.
4212   VecArgOffset = ((VecArgOffset+15)/16)*16;
4213   VecArgOffset += 12*16;
4214 
4215   // Add DAG nodes to load the arguments or copy them out of registers.  On
4216   // entry to a function on PPC, the arguments start after the linkage area,
4217   // although the first ones are often in registers.
4218 
4219   SmallVector<SDValue, 8> MemOps;
4220   unsigned nAltivecParamsAtEnd = 0;
4221   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4222   unsigned CurArgIdx = 0;
4223   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4224     SDValue ArgVal;
4225     bool needsLoad = false;
4226     EVT ObjectVT = Ins[ArgNo].VT;
4227     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4228     unsigned ArgSize = ObjSize;
4229     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4230     if (Ins[ArgNo].isOrigArg()) {
4231       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4232       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4233     }
4234     unsigned CurArgOffset = ArgOffset;
4235 
4236     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4237     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4238         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4239       if (isVarArg || isPPC64) {
4240         MinReservedArea = ((MinReservedArea+15)/16)*16;
4241         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4242                                                   Flags,
4243                                                   PtrByteSize);
4244       } else  nAltivecParamsAtEnd++;
4245     } else
4246       // Calculate min reserved area.
4247       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4248                                                 Flags,
4249                                                 PtrByteSize);
4250 
4251     // FIXME the codegen can be much improved in some cases.
4252     // We do not have to keep everything in memory.
4253     if (Flags.isByVal()) {
4254       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4255 
4256       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4257       ObjSize = Flags.getByValSize();
4258       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4259       // Objects of size 1 and 2 are right justified, everything else is
4260       // left justified.  This means the memory address is adjusted forwards.
4261       if (ObjSize==1 || ObjSize==2) {
4262         CurArgOffset = CurArgOffset + (4 - ObjSize);
4263       }
4264       // The value of the object is its address.
4265       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4266       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4267       InVals.push_back(FIN);
4268       if (ObjSize==1 || ObjSize==2) {
4269         if (GPR_idx != Num_GPR_Regs) {
4270           unsigned VReg;
4271           if (isPPC64)
4272             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4273           else
4274             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4275           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4276           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4277           SDValue Store =
4278               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4279                                 MachinePointerInfo(&*FuncArg), ObjType);
4280           MemOps.push_back(Store);
4281           ++GPR_idx;
4282         }
4283 
4284         ArgOffset += PtrByteSize;
4285 
4286         continue;
4287       }
4288       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4289         // Store whatever pieces of the object are in registers
4290         // to memory.  ArgOffset will be the address of the beginning
4291         // of the object.
4292         if (GPR_idx != Num_GPR_Regs) {
4293           unsigned VReg;
4294           if (isPPC64)
4295             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4296           else
4297             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4298           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4299           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4300           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4301           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4302                                        MachinePointerInfo(&*FuncArg, j));
4303           MemOps.push_back(Store);
4304           ++GPR_idx;
4305           ArgOffset += PtrByteSize;
4306         } else {
4307           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4308           break;
4309         }
4310       }
4311       continue;
4312     }
4313 
4314     switch (ObjectVT.getSimpleVT().SimpleTy) {
4315     default: llvm_unreachable("Unhandled argument type!");
4316     case MVT::i1:
4317     case MVT::i32:
4318       if (!isPPC64) {
4319         if (GPR_idx != Num_GPR_Regs) {
4320           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4321           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4322 
4323           if (ObjectVT == MVT::i1)
4324             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4325 
4326           ++GPR_idx;
4327         } else {
4328           needsLoad = true;
4329           ArgSize = PtrByteSize;
4330         }
4331         // All int arguments reserve stack space in the Darwin ABI.
4332         ArgOffset += PtrByteSize;
4333         break;
4334       }
4335       LLVM_FALLTHROUGH;
4336     case MVT::i64:  // PPC64
4337       if (GPR_idx != Num_GPR_Regs) {
4338         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4339         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4340 
4341         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4342           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4343           // value to MVT::i64 and then truncate to the correct register size.
4344           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4345 
4346         ++GPR_idx;
4347       } else {
4348         needsLoad = true;
4349         ArgSize = PtrByteSize;
4350       }
4351       // All int arguments reserve stack space in the Darwin ABI.
4352       ArgOffset += 8;
4353       break;
4354 
4355     case MVT::f32:
4356     case MVT::f64:
4357       // Every 4 bytes of argument space consumes one of the GPRs available for
4358       // argument passing.
4359       if (GPR_idx != Num_GPR_Regs) {
4360         ++GPR_idx;
4361         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4362           ++GPR_idx;
4363       }
4364       if (FPR_idx != Num_FPR_Regs) {
4365         unsigned VReg;
4366 
4367         if (ObjectVT == MVT::f32)
4368           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4369         else
4370           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4371 
4372         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4373         ++FPR_idx;
4374       } else {
4375         needsLoad = true;
4376       }
4377 
4378       // All FP arguments reserve stack space in the Darwin ABI.
4379       ArgOffset += isPPC64 ? 8 : ObjSize;
4380       break;
4381     case MVT::v4f32:
4382     case MVT::v4i32:
4383     case MVT::v8i16:
4384     case MVT::v16i8:
4385       // Note that vector arguments in registers don't reserve stack space,
4386       // except in varargs functions.
4387       if (VR_idx != Num_VR_Regs) {
4388         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4389         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4390         if (isVarArg) {
4391           while ((ArgOffset % 16) != 0) {
4392             ArgOffset += PtrByteSize;
4393             if (GPR_idx != Num_GPR_Regs)
4394               GPR_idx++;
4395           }
4396           ArgOffset += 16;
4397           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4398         }
4399         ++VR_idx;
4400       } else {
4401         if (!isVarArg && !isPPC64) {
4402           // Vectors go after all the nonvectors.
4403           CurArgOffset = VecArgOffset;
4404           VecArgOffset += 16;
4405         } else {
4406           // Vectors are aligned.
4407           ArgOffset = ((ArgOffset+15)/16)*16;
4408           CurArgOffset = ArgOffset;
4409           ArgOffset += 16;
4410         }
4411         needsLoad = true;
4412       }
4413       break;
4414     }
4415 
4416     // We need to load the argument to a virtual register if we determined above
4417     // that we ran out of physical registers of the appropriate type.
4418     if (needsLoad) {
4419       int FI = MFI.CreateFixedObject(ObjSize,
4420                                      CurArgOffset + (ArgSize - ObjSize),
4421                                      isImmutable);
4422       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4423       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4424     }
4425 
4426     InVals.push_back(ArgVal);
4427   }
4428 
4429   // Allow for Altivec parameters at the end, if needed.
4430   if (nAltivecParamsAtEnd) {
4431     MinReservedArea = ((MinReservedArea+15)/16)*16;
4432     MinReservedArea += 16*nAltivecParamsAtEnd;
4433   }
4434 
4435   // Area that is at least reserved in the caller of this function.
4436   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4437 
4438   // Set the size that is at least reserved in caller of this function.  Tail
4439   // call optimized functions' reserved stack space needs to be aligned so that
4440   // taking the difference between two stack areas will result in an aligned
4441   // stack.
4442   MinReservedArea =
4443       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4444   FuncInfo->setMinReservedArea(MinReservedArea);
4445 
4446   // If the function takes variable number of arguments, make a frame index for
4447   // the start of the first vararg value... for expansion of llvm.va_start.
4448   if (isVarArg) {
4449     int Depth = ArgOffset;
4450 
4451     FuncInfo->setVarArgsFrameIndex(
4452       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4453                             Depth, true));
4454     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4455 
4456     // If this function is vararg, store any remaining integer argument regs
4457     // to their spots on the stack so that they may be loaded by dereferencing
4458     // the result of va_next.
4459     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4460       unsigned VReg;
4461 
4462       if (isPPC64)
4463         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4464       else
4465         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4466 
4467       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4468       SDValue Store =
4469           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4470       MemOps.push_back(Store);
4471       // Increment the address by four for the next argument to store
4472       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4473       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4474     }
4475   }
4476 
4477   if (!MemOps.empty())
4478     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4479 
4480   return Chain;
4481 }
4482 
4483 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4484 /// adjusted to accommodate the arguments for the tailcall.
4485 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4486                                    unsigned ParamSize) {
4487 
4488   if (!isTailCall) return 0;
4489 
4490   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4491   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4492   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4493   // Remember only if the new adjustment is bigger.
4494   if (SPDiff < FI->getTailCallSPDelta())
4495     FI->setTailCallSPDelta(SPDiff);
4496 
4497   return SPDiff;
4498 }
4499 
4500 static bool isFunctionGlobalAddress(SDValue Callee);
4501 
4502 static bool
4503 callsShareTOCBase(const Function *Caller, SDValue Callee,
4504                     const TargetMachine &TM) {
4505    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4506    // don't have enough information to determine if the caller and calle share
4507    // the same  TOC base, so we have to pessimistically assume they don't for
4508    // correctness.
4509    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4510    if (!G)
4511      return false;
4512 
4513    const GlobalValue *GV = G->getGlobal();
4514   // The medium and large code models are expected to provide a sufficiently
4515   // large TOC to provide all data addressing needs of a module with a
4516   // single TOC. Since each module will be addressed with a single TOC then we
4517   // only need to check that caller and callee don't cross dso boundaries.
4518   if (CodeModel::Medium == TM.getCodeModel() ||
4519       CodeModel::Large == TM.getCodeModel())
4520     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4521 
4522   // Otherwise we need to ensure callee and caller are in the same section,
4523   // since the linker may allocate multiple TOCs, and we don't know which
4524   // sections will belong to the same TOC base.
4525 
4526   if (!GV->isStrongDefinitionForLinker())
4527     return false;
4528 
4529   // Any explicitly-specified sections and section prefixes must also match.
4530   // Also, if we're using -ffunction-sections, then each function is always in
4531   // a different section (the same is true for COMDAT functions).
4532   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4533       GV->getSection() != Caller->getSection())
4534     return false;
4535   if (const auto *F = dyn_cast<Function>(GV)) {
4536     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4537       return false;
4538   }
4539 
4540   // If the callee might be interposed, then we can't assume the ultimate call
4541   // target will be in the same section. Even in cases where we can assume that
4542   // interposition won't happen, in any case where the linker might insert a
4543   // stub to allow for interposition, we must generate code as though
4544   // interposition might occur. To understand why this matters, consider a
4545   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4546   // in the same section, but a is in a different module (i.e. has a different
4547   // TOC base pointer). If the linker allows for interposition between b and c,
4548   // then it will generate a stub for the call edge between b and c which will
4549   // save the TOC pointer into the designated stack slot allocated by b. If we
4550   // return true here, and therefore allow a tail call between b and c, that
4551   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4552   // pointer into the stack slot allocated by a (where the a -> b stub saved
4553   // a's TOC base pointer). If we're not considering a tail call, but rather,
4554   // whether a nop is needed after the call instruction in b, because the linker
4555   // will insert a stub, it might complain about a missing nop if we omit it
4556   // (although many don't complain in this case).
4557   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4558     return false;
4559 
4560   return true;
4561 }
4562 
4563 static bool
4564 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4565                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4566   assert(Subtarget.is64BitELFABI());
4567 
4568   const unsigned PtrByteSize = 8;
4569   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4570 
4571   static const MCPhysReg GPR[] = {
4572     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4573     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4574   };
4575   static const MCPhysReg VR[] = {
4576     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4577     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4578   };
4579 
4580   const unsigned NumGPRs = array_lengthof(GPR);
4581   const unsigned NumFPRs = 13;
4582   const unsigned NumVRs = array_lengthof(VR);
4583   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4584 
4585   unsigned NumBytes = LinkageSize;
4586   unsigned AvailableFPRs = NumFPRs;
4587   unsigned AvailableVRs = NumVRs;
4588 
4589   for (const ISD::OutputArg& Param : Outs) {
4590     if (Param.Flags.isNest()) continue;
4591 
4592     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4593                                PtrByteSize, LinkageSize, ParamAreaSize,
4594                                NumBytes, AvailableFPRs, AvailableVRs,
4595                                Subtarget.hasQPX()))
4596       return true;
4597   }
4598   return false;
4599 }
4600 
4601 static bool
4602 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4603   if (CS.arg_size() != CallerFn->arg_size())
4604     return false;
4605 
4606   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4607   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4608   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4609 
4610   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4611     const Value* CalleeArg = *CalleeArgIter;
4612     const Value* CallerArg = &(*CallerArgIter);
4613     if (CalleeArg == CallerArg)
4614       continue;
4615 
4616     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4617     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4618     //      }
4619     // 1st argument of callee is undef and has the same type as caller.
4620     if (CalleeArg->getType() == CallerArg->getType() &&
4621         isa<UndefValue>(CalleeArg))
4622       continue;
4623 
4624     return false;
4625   }
4626 
4627   return true;
4628 }
4629 
4630 // Returns true if TCO is possible between the callers and callees
4631 // calling conventions.
4632 static bool
4633 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4634                                     CallingConv::ID CalleeCC) {
4635   // Tail calls are possible with fastcc and ccc.
4636   auto isTailCallableCC  = [] (CallingConv::ID CC){
4637       return  CC == CallingConv::C || CC == CallingConv::Fast;
4638   };
4639   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4640     return false;
4641 
4642   // We can safely tail call both fastcc and ccc callees from a c calling
4643   // convention caller. If the caller is fastcc, we may have less stack space
4644   // than a non-fastcc caller with the same signature so disable tail-calls in
4645   // that case.
4646   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4647 }
4648 
4649 bool
4650 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4651                                     SDValue Callee,
4652                                     CallingConv::ID CalleeCC,
4653                                     ImmutableCallSite CS,
4654                                     bool isVarArg,
4655                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4656                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4657                                     SelectionDAG& DAG) const {
4658   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4659 
4660   if (DisableSCO && !TailCallOpt) return false;
4661 
4662   // Variadic argument functions are not supported.
4663   if (isVarArg) return false;
4664 
4665   auto &Caller = DAG.getMachineFunction().getFunction();
4666   // Check that the calling conventions are compatible for tco.
4667   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4668     return false;
4669 
4670   // Caller contains any byval parameter is not supported.
4671   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4672     return false;
4673 
4674   // Callee contains any byval parameter is not supported, too.
4675   // Note: This is a quick work around, because in some cases, e.g.
4676   // caller's stack size > callee's stack size, we are still able to apply
4677   // sibling call optimization. For example, gcc is able to do SCO for caller1
4678   // in the following example, but not for caller2.
4679   //   struct test {
4680   //     long int a;
4681   //     char ary[56];
4682   //   } gTest;
4683   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4684   //     b->a = v.a;
4685   //     return 0;
4686   //   }
4687   //   void caller1(struct test a, struct test c, struct test *b) {
4688   //     callee(gTest, b); }
4689   //   void caller2(struct test *b) { callee(gTest, b); }
4690   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4691     return false;
4692 
4693   // If callee and caller use different calling conventions, we cannot pass
4694   // parameters on stack since offsets for the parameter area may be different.
4695   if (Caller.getCallingConv() != CalleeCC &&
4696       needStackSlotPassParameters(Subtarget, Outs))
4697     return false;
4698 
4699   // No TCO/SCO on indirect call because Caller have to restore its TOC
4700   if (!isFunctionGlobalAddress(Callee) &&
4701       !isa<ExternalSymbolSDNode>(Callee))
4702     return false;
4703 
4704   // If the caller and callee potentially have different TOC bases then we
4705   // cannot tail call since we need to restore the TOC pointer after the call.
4706   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4707   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4708     return false;
4709 
4710   // TCO allows altering callee ABI, so we don't have to check further.
4711   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4712     return true;
4713 
4714   if (DisableSCO) return false;
4715 
4716   // If callee use the same argument list that caller is using, then we can
4717   // apply SCO on this case. If it is not, then we need to check if callee needs
4718   // stack for passing arguments.
4719   if (!hasSameArgumentList(&Caller, CS) &&
4720       needStackSlotPassParameters(Subtarget, Outs)) {
4721     return false;
4722   }
4723 
4724   return true;
4725 }
4726 
4727 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4728 /// for tail call optimization. Targets which want to do tail call
4729 /// optimization should implement this function.
4730 bool
4731 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4732                                                      CallingConv::ID CalleeCC,
4733                                                      bool isVarArg,
4734                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4735                                                      SelectionDAG& DAG) const {
4736   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4737     return false;
4738 
4739   // Variable argument functions are not supported.
4740   if (isVarArg)
4741     return false;
4742 
4743   MachineFunction &MF = DAG.getMachineFunction();
4744   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4745   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4746     // Functions containing by val parameters are not supported.
4747     for (unsigned i = 0; i != Ins.size(); i++) {
4748        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4749        if (Flags.isByVal()) return false;
4750     }
4751 
4752     // Non-PIC/GOT tail calls are supported.
4753     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4754       return true;
4755 
4756     // At the moment we can only do local tail calls (in same module, hidden
4757     // or protected) if we are generating PIC.
4758     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4759       return G->getGlobal()->hasHiddenVisibility()
4760           || G->getGlobal()->hasProtectedVisibility();
4761   }
4762 
4763   return false;
4764 }
4765 
4766 /// isCallCompatibleAddress - Return the immediate to use if the specified
4767 /// 32-bit value is representable in the immediate field of a BxA instruction.
4768 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4769   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4770   if (!C) return nullptr;
4771 
4772   int Addr = C->getZExtValue();
4773   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4774       SignExtend32<26>(Addr) != Addr)
4775     return nullptr;  // Top 6 bits have to be sext of immediate.
4776 
4777   return DAG
4778       .getConstant(
4779           (int)C->getZExtValue() >> 2, SDLoc(Op),
4780           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4781       .getNode();
4782 }
4783 
4784 namespace {
4785 
4786 struct TailCallArgumentInfo {
4787   SDValue Arg;
4788   SDValue FrameIdxOp;
4789   int FrameIdx = 0;
4790 
4791   TailCallArgumentInfo() = default;
4792 };
4793 
4794 } // end anonymous namespace
4795 
4796 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4797 static void StoreTailCallArgumentsToStackSlot(
4798     SelectionDAG &DAG, SDValue Chain,
4799     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4800     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4801   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4802     SDValue Arg = TailCallArgs[i].Arg;
4803     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4804     int FI = TailCallArgs[i].FrameIdx;
4805     // Store relative to framepointer.
4806     MemOpChains.push_back(DAG.getStore(
4807         Chain, dl, Arg, FIN,
4808         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4809   }
4810 }
4811 
4812 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4813 /// the appropriate stack slot for the tail call optimized function call.
4814 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4815                                              SDValue OldRetAddr, SDValue OldFP,
4816                                              int SPDiff, const SDLoc &dl) {
4817   if (SPDiff) {
4818     // Calculate the new stack slot for the return address.
4819     MachineFunction &MF = DAG.getMachineFunction();
4820     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4821     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4822     bool isPPC64 = Subtarget.isPPC64();
4823     int SlotSize = isPPC64 ? 8 : 4;
4824     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4825     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4826                                                          NewRetAddrLoc, true);
4827     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4828     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4829     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4830                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4831   }
4832   return Chain;
4833 }
4834 
4835 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4836 /// the position of the argument.
4837 static void
4838 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4839                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4840                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4841   int Offset = ArgOffset + SPDiff;
4842   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4843   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4844   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4845   SDValue FIN = DAG.getFrameIndex(FI, VT);
4846   TailCallArgumentInfo Info;
4847   Info.Arg = Arg;
4848   Info.FrameIdxOp = FIN;
4849   Info.FrameIdx = FI;
4850   TailCallArguments.push_back(Info);
4851 }
4852 
4853 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4854 /// stack slot. Returns the chain as result and the loaded frame pointers in
4855 /// LROpOut/FPOpout. Used when tail calling.
4856 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4857     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4858     SDValue &FPOpOut, const SDLoc &dl) const {
4859   if (SPDiff) {
4860     // Load the LR and FP stack slot for later adjusting.
4861     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4862     LROpOut = getReturnAddrFrameIndex(DAG);
4863     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4864     Chain = SDValue(LROpOut.getNode(), 1);
4865   }
4866   return Chain;
4867 }
4868 
4869 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4870 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4871 /// specified by the specific parameter attribute. The copy will be passed as
4872 /// a byval function parameter.
4873 /// Sometimes what we are copying is the end of a larger object, the part that
4874 /// does not fit in registers.
4875 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4876                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4877                                          SelectionDAG &DAG, const SDLoc &dl) {
4878   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4879   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode,
4880                        Flags.getNonZeroByValAlign(), false, false, false,
4881                        MachinePointerInfo(), MachinePointerInfo());
4882 }
4883 
4884 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4885 /// tail calls.
4886 static void LowerMemOpCallTo(
4887     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4888     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4889     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4890     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4891   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4892   if (!isTailCall) {
4893     if (isVector) {
4894       SDValue StackPtr;
4895       if (isPPC64)
4896         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4897       else
4898         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4899       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4900                            DAG.getConstant(ArgOffset, dl, PtrVT));
4901     }
4902     MemOpChains.push_back(
4903         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4904     // Calculate and remember argument location.
4905   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4906                                   TailCallArguments);
4907 }
4908 
4909 static void
4910 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4911                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4912                 SDValue FPOp,
4913                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4914   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4915   // might overwrite each other in case of tail call optimization.
4916   SmallVector<SDValue, 8> MemOpChains2;
4917   // Do not flag preceding copytoreg stuff together with the following stuff.
4918   InFlag = SDValue();
4919   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4920                                     MemOpChains2, dl);
4921   if (!MemOpChains2.empty())
4922     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4923 
4924   // Store the return address to the appropriate stack slot.
4925   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4926 
4927   // Emit callseq_end just before tailcall node.
4928   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4929                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4930   InFlag = Chain.getValue(1);
4931 }
4932 
4933 // Is this global address that of a function that can be called by name? (as
4934 // opposed to something that must hold a descriptor for an indirect call).
4935 static bool isFunctionGlobalAddress(SDValue Callee) {
4936   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4937     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4938         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4939       return false;
4940 
4941     return G->getGlobal()->getValueType()->isFunctionTy();
4942   }
4943 
4944   return false;
4945 }
4946 
4947 SDValue PPCTargetLowering::LowerCallResult(
4948     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4949     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4950     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4951   SmallVector<CCValAssign, 16> RVLocs;
4952   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4953                     *DAG.getContext());
4954 
4955   CCRetInfo.AnalyzeCallResult(
4956       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4957                ? RetCC_PPC_Cold
4958                : RetCC_PPC);
4959 
4960   // Copy all of the result registers out of their specified physreg.
4961   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4962     CCValAssign &VA = RVLocs[i];
4963     assert(VA.isRegLoc() && "Can only return in registers!");
4964 
4965     SDValue Val;
4966 
4967     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4968       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4969                                       InFlag);
4970       Chain = Lo.getValue(1);
4971       InFlag = Lo.getValue(2);
4972       VA = RVLocs[++i]; // skip ahead to next loc
4973       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4974                                       InFlag);
4975       Chain = Hi.getValue(1);
4976       InFlag = Hi.getValue(2);
4977       if (!Subtarget.isLittleEndian())
4978         std::swap (Lo, Hi);
4979       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4980     } else {
4981       Val = DAG.getCopyFromReg(Chain, dl,
4982                                VA.getLocReg(), VA.getLocVT(), InFlag);
4983       Chain = Val.getValue(1);
4984       InFlag = Val.getValue(2);
4985     }
4986 
4987     switch (VA.getLocInfo()) {
4988     default: llvm_unreachable("Unknown loc info!");
4989     case CCValAssign::Full: break;
4990     case CCValAssign::AExt:
4991       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4992       break;
4993     case CCValAssign::ZExt:
4994       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4995                         DAG.getValueType(VA.getValVT()));
4996       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4997       break;
4998     case CCValAssign::SExt:
4999       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5000                         DAG.getValueType(VA.getValVT()));
5001       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5002       break;
5003     }
5004 
5005     InVals.push_back(Val);
5006   }
5007 
5008   return Chain;
5009 }
5010 
5011 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5012                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5013   // PatchPoint calls are not indirect.
5014   if (isPatchPoint)
5015     return false;
5016 
5017   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5018     return false;
5019 
5020   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5021   // becuase the immediate function pointer points to a descriptor instead of
5022   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5023   // pointer immediate points to the global entry point, while the BLA would
5024   // need to jump to the local entry point (see rL211174).
5025   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5026       isBLACompatibleAddress(Callee, DAG))
5027     return false;
5028 
5029   return true;
5030 }
5031 
5032 static unsigned getCallOpcode(PPCTargetLowering::CallFlags CFlags,
5033                               const Function &Caller,
5034                               const SDValue &Callee,
5035                               const PPCSubtarget &Subtarget,
5036                               const TargetMachine &TM) {
5037   if (CFlags.IsTailCall)
5038     return PPCISD::TC_RETURN;
5039 
5040   // This is a call through a function pointer.
5041   if (CFlags.IsIndirect) {
5042     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5043     // indirect calls. The save of the caller's TOC pointer to the stack will be
5044     // inserted into the DAG as part of call lowering. The restore of the TOC
5045     // pointer is modeled by using a pseudo instruction for the call opcode that
5046     // represents the 2 instruction sequence of an indirect branch and link,
5047     // immediately followed by a load of the TOC pointer from the the stack save
5048     // slot into gpr2.
5049     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5050       return PPCISD::BCTRL_LOAD_TOC;
5051 
5052     // An indirect call that does not need a TOC restore.
5053     return PPCISD::BCTRL;
5054   }
5055 
5056   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5057   // immediately following the call instruction if the caller and callee may
5058   // have different TOC bases. At link time if the linker determines the calls
5059   // may not share a TOC base, the call is redirected to a trampoline inserted
5060   // by the linker. The trampoline will (among other things) save the callers
5061   // TOC pointer at an ABI designated offset in the linkage area and the linker
5062   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5063   // into gpr2.
5064   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5065     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5066                                                   : PPCISD::CALL_NOP;
5067 
5068   return PPCISD::CALL;
5069 }
5070 
5071 static bool isValidAIXExternalSymSDNode(StringRef SymName) {
5072   return StringSwitch<bool>(SymName)
5073       .Cases("__divdi3", "__fixunsdfdi", "__floatundidf", "__floatundisf",
5074              "__moddi3", "__udivdi3", "__umoddi3", true)
5075       .Cases("ceil", "floor", "memcpy", "memmove", "memset", "round", true)
5076       .Default(false);
5077 }
5078 
5079 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5080                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5081   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5082     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5083       return SDValue(Dest, 0);
5084 
5085   // Returns true if the callee is local, and false otherwise.
5086   auto isLocalCallee = [&]() {
5087     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5088     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5089     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5090 
5091     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5092            !dyn_cast_or_null<GlobalIFunc>(GV);
5093   };
5094 
5095   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5096   // a static relocation model causes some versions of GNU LD (2.17.50, at
5097   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5098   // built with secure-PLT.
5099   bool UsePlt =
5100       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5101       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5102 
5103   // On AIX, direct function calls reference the symbol for the function's
5104   // entry point, which is named by prepending a "." before the function's
5105   // C-linkage name.
5106   const auto getAIXFuncEntryPointSymbolSDNode =
5107       [&](StringRef FuncName, bool IsDeclaration,
5108           const XCOFF::StorageClass &SC) {
5109         auto &Context = DAG.getMachineFunction().getMMI().getContext();
5110 
5111         MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5112             Context.getOrCreateSymbol(Twine(".") + Twine(FuncName)));
5113 
5114         if (IsDeclaration && !S->hasContainingCsect()) {
5115           // On AIX, an undefined symbol needs to be associated with a
5116           // MCSectionXCOFF to get the correct storage mapping class.
5117           // In this case, XCOFF::XMC_PR.
5118           MCSectionXCOFF *Sec = Context.getXCOFFSection(
5119               S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER, SC,
5120               SectionKind::getMetadata());
5121           S->setContainingCsect(Sec);
5122         }
5123 
5124         MVT PtrVT =
5125             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5126         return DAG.getMCSymbol(S, PtrVT);
5127       };
5128 
5129   if (isFunctionGlobalAddress(Callee)) {
5130     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5131     const GlobalValue *GV = G->getGlobal();
5132 
5133     if (!Subtarget.isAIXABI())
5134       return DAG.getTargetGlobalAddress(GV, dl, Callee.getValueType(), 0,
5135                                         UsePlt ? PPCII::MO_PLT : 0);
5136 
5137     assert(!isa<GlobalIFunc>(GV) && "IFunc is not supported on AIX.");
5138     const GlobalObject *GO = cast<GlobalObject>(GV);
5139     const XCOFF::StorageClass SC =
5140         TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5141     return getAIXFuncEntryPointSymbolSDNode(GO->getName(), GO->isDeclaration(),
5142                                             SC);
5143   }
5144 
5145   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
5146     const char *SymName = S->getSymbol();
5147     if (!Subtarget.isAIXABI())
5148       return DAG.getTargetExternalSymbol(SymName, Callee.getValueType(),
5149                                          UsePlt ? PPCII::MO_PLT : 0);
5150 
5151     // If there exists a user-declared function whose name is the same as the
5152     // ExternalSymbol's, then we pick up the user-declared version.
5153     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5154     if (const Function *F =
5155             dyn_cast_or_null<Function>(Mod->getNamedValue(SymName))) {
5156       const XCOFF::StorageClass SC =
5157           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(F);
5158       return getAIXFuncEntryPointSymbolSDNode(F->getName(), F->isDeclaration(),
5159                                               SC);
5160     }
5161 
5162     // TODO: Remove this when the support for ExternalSymbolSDNode is complete.
5163     if (isValidAIXExternalSymSDNode(SymName)) {
5164       return getAIXFuncEntryPointSymbolSDNode(SymName, true, XCOFF::C_EXT);
5165     }
5166 
5167     report_fatal_error("Unexpected ExternalSymbolSDNode: " + Twine(SymName));
5168   }
5169 
5170   // No transformation needed.
5171   assert(Callee.getNode() && "What no callee?");
5172   return Callee;
5173 }
5174 
5175 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5176   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5177          "Expected a CALLSEQ_STARTSDNode.");
5178 
5179   // The last operand is the chain, except when the node has glue. If the node
5180   // has glue, then the last operand is the glue, and the chain is the second
5181   // last operand.
5182   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5183   if (LastValue.getValueType() != MVT::Glue)
5184     return LastValue;
5185 
5186   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5187 }
5188 
5189 // Creates the node that moves a functions address into the count register
5190 // to prepare for an indirect call instruction.
5191 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5192                                 SDValue &Glue, SDValue &Chain,
5193                                 const SDLoc &dl) {
5194   SDValue MTCTROps[] = {Chain, Callee, Glue};
5195   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5196   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5197                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5198   // The glue is the second value produced.
5199   Glue = Chain.getValue(1);
5200 }
5201 
5202 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5203                                           SDValue &Glue, SDValue &Chain,
5204                                           SDValue CallSeqStart,
5205                                           ImmutableCallSite CS, const SDLoc &dl,
5206                                           bool hasNest,
5207                                           const PPCSubtarget &Subtarget) {
5208   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5209   // entry point, but to the function descriptor (the function entry point
5210   // address is part of the function descriptor though).
5211   // The function descriptor is a three doubleword structure with the
5212   // following fields: function entry point, TOC base address and
5213   // environment pointer.
5214   // Thus for a call through a function pointer, the following actions need
5215   // to be performed:
5216   //   1. Save the TOC of the caller in the TOC save area of its stack
5217   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5218   //   2. Load the address of the function entry point from the function
5219   //      descriptor.
5220   //   3. Load the TOC of the callee from the function descriptor into r2.
5221   //   4. Load the environment pointer from the function descriptor into
5222   //      r11.
5223   //   5. Branch to the function entry point address.
5224   //   6. On return of the callee, the TOC of the caller needs to be
5225   //      restored (this is done in FinishCall()).
5226   //
5227   // The loads are scheduled at the beginning of the call sequence, and the
5228   // register copies are flagged together to ensure that no other
5229   // operations can be scheduled in between. E.g. without flagging the
5230   // copies together, a TOC access in the caller could be scheduled between
5231   // the assignment of the callee TOC and the branch to the callee, which leads
5232   // to incorrect code.
5233 
5234   // Start by loading the function address from the descriptor.
5235   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5236   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5237                       ? (MachineMemOperand::MODereferenceable |
5238                          MachineMemOperand::MOInvariant)
5239                       : MachineMemOperand::MONone;
5240 
5241   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5242 
5243   // Registers used in building the DAG.
5244   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5245   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5246 
5247   // Offsets of descriptor members.
5248   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5249   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5250 
5251   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5252   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5253 
5254   // One load for the functions entry point address.
5255   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5256                                     Alignment, MMOFlags);
5257 
5258   // One for loading the TOC anchor for the module that contains the called
5259   // function.
5260   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5261   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5262   SDValue TOCPtr =
5263       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5264                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5265 
5266   // One for loading the environment pointer.
5267   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5268   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5269   SDValue LoadEnvPtr =
5270       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5271                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5272 
5273 
5274   // Then copy the newly loaded TOC anchor to the TOC pointer.
5275   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5276   Chain = TOCVal.getValue(0);
5277   Glue = TOCVal.getValue(1);
5278 
5279   // If the function call has an explicit 'nest' parameter, it takes the
5280   // place of the environment pointer.
5281   assert((!hasNest || !Subtarget.isAIXABI()) &&
5282          "Nest parameter is not supported on AIX.");
5283   if (!hasNest) {
5284     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5285     Chain = EnvVal.getValue(0);
5286     Glue = EnvVal.getValue(1);
5287   }
5288 
5289   // The rest of the indirect call sequence is the same as the non-descriptor
5290   // DAG.
5291   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5292 }
5293 
5294 static void
5295 buildCallOperands(SmallVectorImpl<SDValue> &Ops,
5296                   PPCTargetLowering::CallFlags CFlags, const SDLoc &dl,
5297                   SelectionDAG &DAG,
5298                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5299                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5300                   const PPCSubtarget &Subtarget) {
5301   const bool IsPPC64 = Subtarget.isPPC64();
5302   // MVT for a general purpose register.
5303   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5304 
5305   // First operand is always the chain.
5306   Ops.push_back(Chain);
5307 
5308   // If it's a direct call pass the callee as the second operand.
5309   if (!CFlags.IsIndirect)
5310     Ops.push_back(Callee);
5311   else {
5312     assert(!CFlags.IsPatchPoint && "Patch point calls are not indirect.");
5313 
5314     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5315     // on the stack (this would have been done in `LowerCall_64SVR4` or
5316     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5317     // represents both the indirect branch and a load that restores the TOC
5318     // pointer from the linkage area. The operand for the TOC restore is an add
5319     // of the TOC save offset to the stack pointer. This must be the second
5320     // operand: after the chain input but before any other variadic arguments.
5321     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5322       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5323 
5324       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5325       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5326       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5327       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5328       Ops.push_back(AddTOC);
5329     }
5330 
5331     // Add the register used for the environment pointer.
5332     if (Subtarget.usesFunctionDescriptors() && !CFlags.HasNest)
5333       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5334                                     RegVT));
5335 
5336 
5337     // Add CTR register as callee so a bctr can be emitted later.
5338     if (CFlags.IsTailCall)
5339       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5340   }
5341 
5342   // If this is a tail call add stack pointer delta.
5343   if (CFlags.IsTailCall)
5344     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5345 
5346   // Add argument registers to the end of the list so that they are known live
5347   // into the call.
5348   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5349     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5350                                   RegsToPass[i].second.getValueType()));
5351 
5352   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5353   // no way to mark dependencies as implicit here.
5354   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5355   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) &&
5356       !CFlags.IsPatchPoint)
5357     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5358 
5359   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5360   if (CFlags.IsVarArg && Subtarget.is32BitELFABI())
5361     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5362 
5363   // Add a register mask operand representing the call-preserved registers.
5364   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5365   const uint32_t *Mask =
5366       TRI->getCallPreservedMask(DAG.getMachineFunction(), CFlags.CallConv);
5367   assert(Mask && "Missing call preserved mask for calling convention");
5368   Ops.push_back(DAG.getRegisterMask(Mask));
5369 
5370   // If the glue is valid, it is the last operand.
5371   if (Glue.getNode())
5372     Ops.push_back(Glue);
5373 }
5374 
5375 SDValue PPCTargetLowering::FinishCall(
5376     CallFlags CFlags, const SDLoc &dl, SelectionDAG &DAG,
5377     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5378     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5379     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5380     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5381 
5382   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5383     setUsesTOCBasePtr(DAG);
5384 
5385   unsigned CallOpc =
5386       getCallOpcode(CFlags, DAG.getMachineFunction().getFunction(), Callee,
5387                     Subtarget, DAG.getTarget());
5388 
5389   if (!CFlags.IsIndirect)
5390     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5391   else if (Subtarget.usesFunctionDescriptors())
5392     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5393                                   dl, CFlags.HasNest, Subtarget);
5394   else
5395     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5396 
5397   // Build the operand list for the call instruction.
5398   SmallVector<SDValue, 8> Ops;
5399   buildCallOperands(Ops, CFlags, dl, DAG, RegsToPass, Glue, Chain, Callee,
5400                     SPDiff, Subtarget);
5401 
5402   // Emit tail call.
5403   if (CFlags.IsTailCall) {
5404     assert(((Callee.getOpcode() == ISD::Register &&
5405              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5406             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5407             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5408             isa<ConstantSDNode>(Callee)) &&
5409            "Expecting a global address, external symbol, absolute value or "
5410            "register");
5411     assert(CallOpc == PPCISD::TC_RETURN &&
5412            "Unexpected call opcode for a tail call.");
5413     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5414     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5415   }
5416 
5417   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5418   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5419   Glue = Chain.getValue(1);
5420 
5421   // When performing tail call optimization the callee pops its arguments off
5422   // the stack. Account for this here so these bytes can be pushed back on in
5423   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5424   int BytesCalleePops = (CFlags.CallConv == CallingConv::Fast &&
5425                          getTargetMachine().Options.GuaranteedTailCallOpt)
5426                             ? NumBytes
5427                             : 0;
5428 
5429   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5430                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5431                              Glue, dl);
5432   Glue = Chain.getValue(1);
5433 
5434   return LowerCallResult(Chain, Glue, CFlags.CallConv, CFlags.IsVarArg, Ins, dl,
5435                          DAG, InVals);
5436 }
5437 
5438 SDValue
5439 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5440                              SmallVectorImpl<SDValue> &InVals) const {
5441   SelectionDAG &DAG                     = CLI.DAG;
5442   SDLoc &dl                             = CLI.DL;
5443   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5444   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5445   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5446   SDValue Chain                         = CLI.Chain;
5447   SDValue Callee                        = CLI.Callee;
5448   bool &isTailCall                      = CLI.IsTailCall;
5449   CallingConv::ID CallConv              = CLI.CallConv;
5450   bool isVarArg                         = CLI.IsVarArg;
5451   bool isPatchPoint                     = CLI.IsPatchPoint;
5452   ImmutableCallSite CS                  = CLI.CS;
5453 
5454   if (isTailCall) {
5455     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5456       isTailCall = false;
5457     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5458       isTailCall =
5459         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5460                                                  isVarArg, Outs, Ins, DAG);
5461     else
5462       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5463                                                      Ins, DAG);
5464     if (isTailCall) {
5465       ++NumTailCalls;
5466       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5467         ++NumSiblingCalls;
5468 
5469       assert(isa<GlobalAddressSDNode>(Callee) &&
5470              "Callee should be an llvm::Function object.");
5471       LLVM_DEBUG(
5472           const GlobalValue *GV =
5473               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5474           const unsigned Width =
5475               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5476           dbgs() << "TCO caller: "
5477                  << left_justify(DAG.getMachineFunction().getName(), Width)
5478                  << ", callee linkage: " << GV->getVisibility() << ", "
5479                  << GV->getLinkage() << "\n");
5480     }
5481   }
5482 
5483   if (!isTailCall && CS && CS.isMustTailCall())
5484     report_fatal_error("failed to perform tail call elimination on a call "
5485                        "site marked musttail");
5486 
5487   // When long calls (i.e. indirect calls) are always used, calls are always
5488   // made via function pointer. If we have a function name, first translate it
5489   // into a pointer.
5490   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5491       !isTailCall)
5492     Callee = LowerGlobalAddress(Callee, DAG);
5493 
5494   CallFlags CFlags(
5495       CallConv, isTailCall, isVarArg, isPatchPoint,
5496       isIndirectCall(Callee, DAG, Subtarget, isPatchPoint),
5497       // hasNest
5498       Subtarget.is64BitELFABI() &&
5499           any_of(Outs, [](ISD::OutputArg Arg) { return Arg.Flags.isNest(); }));
5500 
5501   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5502     return LowerCall_64SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5503                             InVals, CS);
5504 
5505   if (Subtarget.isSVR4ABI())
5506     return LowerCall_32SVR4(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5507                             InVals, CS);
5508 
5509   if (Subtarget.isAIXABI())
5510     return LowerCall_AIX(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5511                          InVals, CS);
5512 
5513   return LowerCall_Darwin(Chain, Callee, CFlags, Outs, OutVals, Ins, dl, DAG,
5514                           InVals, CS);
5515 }
5516 
5517 SDValue PPCTargetLowering::LowerCall_32SVR4(
5518     SDValue Chain, SDValue Callee, CallFlags CFlags,
5519     const SmallVectorImpl<ISD::OutputArg> &Outs,
5520     const SmallVectorImpl<SDValue> &OutVals,
5521     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5522     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5523     ImmutableCallSite CS) const {
5524   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5525   // of the 32-bit SVR4 ABI stack frame layout.
5526 
5527   const CallingConv::ID CallConv = CFlags.CallConv;
5528   const bool IsVarArg = CFlags.IsVarArg;
5529   const bool IsTailCall = CFlags.IsTailCall;
5530 
5531   assert((CallConv == CallingConv::C ||
5532           CallConv == CallingConv::Cold ||
5533           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5534 
5535   unsigned PtrByteSize = 4;
5536 
5537   MachineFunction &MF = DAG.getMachineFunction();
5538 
5539   // Mark this function as potentially containing a function that contains a
5540   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5541   // and restoring the callers stack pointer in this functions epilog. This is
5542   // done because by tail calling the called function might overwrite the value
5543   // in this function's (MF) stack pointer stack slot 0(SP).
5544   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5545       CallConv == CallingConv::Fast)
5546     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5547 
5548   // Count how many bytes are to be pushed on the stack, including the linkage
5549   // area, parameter list area and the part of the local variable space which
5550   // contains copies of aggregates which are passed by value.
5551 
5552   // Assign locations to all of the outgoing arguments.
5553   SmallVector<CCValAssign, 16> ArgLocs;
5554   PPCCCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
5555 
5556   // Reserve space for the linkage area on the stack.
5557   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5558                        PtrByteSize);
5559   if (useSoftFloat())
5560     CCInfo.PreAnalyzeCallOperands(Outs);
5561 
5562   if (IsVarArg) {
5563     // Handle fixed and variable vector arguments differently.
5564     // Fixed vector arguments go into registers as long as registers are
5565     // available. Variable vector arguments always go into memory.
5566     unsigned NumArgs = Outs.size();
5567 
5568     for (unsigned i = 0; i != NumArgs; ++i) {
5569       MVT ArgVT = Outs[i].VT;
5570       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5571       bool Result;
5572 
5573       if (Outs[i].IsFixed) {
5574         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5575                                CCInfo);
5576       } else {
5577         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5578                                       ArgFlags, CCInfo);
5579       }
5580 
5581       if (Result) {
5582 #ifndef NDEBUG
5583         errs() << "Call operand #" << i << " has unhandled type "
5584              << EVT(ArgVT).getEVTString() << "\n";
5585 #endif
5586         llvm_unreachable(nullptr);
5587       }
5588     }
5589   } else {
5590     // All arguments are treated the same.
5591     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5592   }
5593   CCInfo.clearWasPPCF128();
5594 
5595   // Assign locations to all of the outgoing aggregate by value arguments.
5596   SmallVector<CCValAssign, 16> ByValArgLocs;
5597   CCState CCByValInfo(CallConv, IsVarArg, MF, ByValArgLocs, *DAG.getContext());
5598 
5599   // Reserve stack space for the allocations in CCInfo.
5600   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5601 
5602   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5603 
5604   // Size of the linkage area, parameter list area and the part of the local
5605   // space variable where copies of aggregates which are passed by value are
5606   // stored.
5607   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5608 
5609   // Calculate by how many bytes the stack has to be adjusted in case of tail
5610   // call optimization.
5611   int SPDiff = CalculateTailCallSPDiff(DAG, IsTailCall, NumBytes);
5612 
5613   // Adjust the stack pointer for the new arguments...
5614   // These operations are automatically eliminated by the prolog/epilog pass
5615   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5616   SDValue CallSeqStart = Chain;
5617 
5618   // Load the return address and frame pointer so it can be moved somewhere else
5619   // later.
5620   SDValue LROp, FPOp;
5621   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5622 
5623   // Set up a copy of the stack pointer for use loading and storing any
5624   // arguments that may not fit in the registers available for argument
5625   // passing.
5626   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5627 
5628   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5629   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5630   SmallVector<SDValue, 8> MemOpChains;
5631 
5632   bool seenFloatArg = false;
5633   // Walk the register/memloc assignments, inserting copies/loads.
5634   // i - Tracks the index into the list of registers allocated for the call
5635   // RealArgIdx - Tracks the index into the list of actual function arguments
5636   // j - Tracks the index into the list of byval arguments
5637   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5638        i != e;
5639        ++i, ++RealArgIdx) {
5640     CCValAssign &VA = ArgLocs[i];
5641     SDValue Arg = OutVals[RealArgIdx];
5642     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5643 
5644     if (Flags.isByVal()) {
5645       // Argument is an aggregate which is passed by value, thus we need to
5646       // create a copy of it in the local variable space of the current stack
5647       // frame (which is the stack frame of the caller) and pass the address of
5648       // this copy to the callee.
5649       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5650       CCValAssign &ByValVA = ByValArgLocs[j++];
5651       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5652 
5653       // Memory reserved in the local variable space of the callers stack frame.
5654       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5655 
5656       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5657       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5658                            StackPtr, PtrOff);
5659 
5660       // Create a copy of the argument in the local area of the current
5661       // stack frame.
5662       SDValue MemcpyCall =
5663         CreateCopyOfByValArgument(Arg, PtrOff,
5664                                   CallSeqStart.getNode()->getOperand(0),
5665                                   Flags, DAG, dl);
5666 
5667       // This must go outside the CALLSEQ_START..END.
5668       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5669                                                      SDLoc(MemcpyCall));
5670       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5671                              NewCallSeqStart.getNode());
5672       Chain = CallSeqStart = NewCallSeqStart;
5673 
5674       // Pass the address of the aggregate copy on the stack either in a
5675       // physical register or in the parameter list area of the current stack
5676       // frame to the callee.
5677       Arg = PtrOff;
5678     }
5679 
5680     // When useCRBits() is true, there can be i1 arguments.
5681     // It is because getRegisterType(MVT::i1) => MVT::i1,
5682     // and for other integer types getRegisterType() => MVT::i32.
5683     // Extend i1 and ensure callee will get i32.
5684     if (Arg.getValueType() == MVT::i1)
5685       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5686                         dl, MVT::i32, Arg);
5687 
5688     if (VA.isRegLoc()) {
5689       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5690       // Put argument in a physical register.
5691       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5692         bool IsLE = Subtarget.isLittleEndian();
5693         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5694                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5695         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5696         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5697                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5698         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5699                              SVal.getValue(0)));
5700       } else
5701         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5702     } else {
5703       // Put argument in the parameter list area of the current stack frame.
5704       assert(VA.isMemLoc());
5705       unsigned LocMemOffset = VA.getLocMemOffset();
5706 
5707       if (!IsTailCall) {
5708         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5709         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5710                              StackPtr, PtrOff);
5711 
5712         MemOpChains.push_back(
5713             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5714       } else {
5715         // Calculate and remember argument location.
5716         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5717                                  TailCallArguments);
5718       }
5719     }
5720   }
5721 
5722   if (!MemOpChains.empty())
5723     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5724 
5725   // Build a sequence of copy-to-reg nodes chained together with token chain
5726   // and flag operands which copy the outgoing args into the appropriate regs.
5727   SDValue InFlag;
5728   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5729     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5730                              RegsToPass[i].second, InFlag);
5731     InFlag = Chain.getValue(1);
5732   }
5733 
5734   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5735   // registers.
5736   if (IsVarArg) {
5737     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5738     SDValue Ops[] = { Chain, InFlag };
5739 
5740     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5741                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5742 
5743     InFlag = Chain.getValue(1);
5744   }
5745 
5746   if (IsTailCall)
5747     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5748                     TailCallArguments);
5749 
5750   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
5751                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
5752 }
5753 
5754 // Copy an argument into memory, being careful to do this outside the
5755 // call sequence for the call to which the argument belongs.
5756 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5757     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5758     SelectionDAG &DAG, const SDLoc &dl) const {
5759   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5760                         CallSeqStart.getNode()->getOperand(0),
5761                         Flags, DAG, dl);
5762   // The MEMCPY must go outside the CALLSEQ_START..END.
5763   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5764   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5765                                                  SDLoc(MemcpyCall));
5766   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5767                          NewCallSeqStart.getNode());
5768   return NewCallSeqStart;
5769 }
5770 
5771 SDValue PPCTargetLowering::LowerCall_64SVR4(
5772     SDValue Chain, SDValue Callee, CallFlags CFlags,
5773     const SmallVectorImpl<ISD::OutputArg> &Outs,
5774     const SmallVectorImpl<SDValue> &OutVals,
5775     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5776     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5777     ImmutableCallSite CS) const {
5778   bool isELFv2ABI = Subtarget.isELFv2ABI();
5779   bool isLittleEndian = Subtarget.isLittleEndian();
5780   unsigned NumOps = Outs.size();
5781   bool IsSibCall = false;
5782   bool IsFastCall = CFlags.CallConv == CallingConv::Fast;
5783 
5784   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5785   unsigned PtrByteSize = 8;
5786 
5787   MachineFunction &MF = DAG.getMachineFunction();
5788 
5789   if (CFlags.IsTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5790     IsSibCall = true;
5791 
5792   // Mark this function as potentially containing a function that contains a
5793   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5794   // and restoring the callers stack pointer in this functions epilog. This is
5795   // done because by tail calling the called function might overwrite the value
5796   // in this function's (MF) stack pointer stack slot 0(SP).
5797   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5798     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5799 
5800   assert(!(IsFastCall && CFlags.IsVarArg) &&
5801          "fastcc not supported on varargs functions");
5802 
5803   // Count how many bytes are to be pushed on the stack, including the linkage
5804   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5805   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5806   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5807   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5808   unsigned NumBytes = LinkageSize;
5809   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5810   unsigned &QFPR_idx = FPR_idx;
5811 
5812   static const MCPhysReg GPR[] = {
5813     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5814     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5815   };
5816   static const MCPhysReg VR[] = {
5817     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5818     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5819   };
5820 
5821   const unsigned NumGPRs = array_lengthof(GPR);
5822   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5823   const unsigned NumVRs  = array_lengthof(VR);
5824   const unsigned NumQFPRs = NumFPRs;
5825 
5826   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5827   // can be passed to the callee in registers.
5828   // For the fast calling convention, there is another check below.
5829   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5830   bool HasParameterArea = !isELFv2ABI || CFlags.IsVarArg || IsFastCall;
5831   if (!HasParameterArea) {
5832     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5833     unsigned AvailableFPRs = NumFPRs;
5834     unsigned AvailableVRs = NumVRs;
5835     unsigned NumBytesTmp = NumBytes;
5836     for (unsigned i = 0; i != NumOps; ++i) {
5837       if (Outs[i].Flags.isNest()) continue;
5838       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5839                                 PtrByteSize, LinkageSize, ParamAreaSize,
5840                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5841                                 Subtarget.hasQPX()))
5842         HasParameterArea = true;
5843     }
5844   }
5845 
5846   // When using the fast calling convention, we don't provide backing for
5847   // arguments that will be in registers.
5848   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5849 
5850   // Avoid allocating parameter area for fastcc functions if all the arguments
5851   // can be passed in the registers.
5852   if (IsFastCall)
5853     HasParameterArea = false;
5854 
5855   // Add up all the space actually used.
5856   for (unsigned i = 0; i != NumOps; ++i) {
5857     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5858     EVT ArgVT = Outs[i].VT;
5859     EVT OrigVT = Outs[i].ArgVT;
5860 
5861     if (Flags.isNest())
5862       continue;
5863 
5864     if (IsFastCall) {
5865       if (Flags.isByVal()) {
5866         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5867         if (NumGPRsUsed > NumGPRs)
5868           HasParameterArea = true;
5869       } else {
5870         switch (ArgVT.getSimpleVT().SimpleTy) {
5871         default: llvm_unreachable("Unexpected ValueType for argument!");
5872         case MVT::i1:
5873         case MVT::i32:
5874         case MVT::i64:
5875           if (++NumGPRsUsed <= NumGPRs)
5876             continue;
5877           break;
5878         case MVT::v4i32:
5879         case MVT::v8i16:
5880         case MVT::v16i8:
5881         case MVT::v2f64:
5882         case MVT::v2i64:
5883         case MVT::v1i128:
5884         case MVT::f128:
5885           if (++NumVRsUsed <= NumVRs)
5886             continue;
5887           break;
5888         case MVT::v4f32:
5889           // When using QPX, this is handled like a FP register, otherwise, it
5890           // is an Altivec register.
5891           if (Subtarget.hasQPX()) {
5892             if (++NumFPRsUsed <= NumFPRs)
5893               continue;
5894           } else {
5895             if (++NumVRsUsed <= NumVRs)
5896               continue;
5897           }
5898           break;
5899         case MVT::f32:
5900         case MVT::f64:
5901         case MVT::v4f64: // QPX
5902         case MVT::v4i1:  // QPX
5903           if (++NumFPRsUsed <= NumFPRs)
5904             continue;
5905           break;
5906         }
5907         HasParameterArea = true;
5908       }
5909     }
5910 
5911     /* Respect alignment of argument on the stack.  */
5912     auto Alignement =
5913         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5914     NumBytes = alignTo(NumBytes, Alignement);
5915 
5916     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5917     if (Flags.isInConsecutiveRegsLast())
5918       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5919   }
5920 
5921   unsigned NumBytesActuallyUsed = NumBytes;
5922 
5923   // In the old ELFv1 ABI,
5924   // the prolog code of the callee may store up to 8 GPR argument registers to
5925   // the stack, allowing va_start to index over them in memory if its varargs.
5926   // Because we cannot tell if this is needed on the caller side, we have to
5927   // conservatively assume that it is needed.  As such, make sure we have at
5928   // least enough stack space for the caller to store the 8 GPRs.
5929   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5930   // really requires memory operands, e.g. a vararg function.
5931   if (HasParameterArea)
5932     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5933   else
5934     NumBytes = LinkageSize;
5935 
5936   // Tail call needs the stack to be aligned.
5937   if (getTargetMachine().Options.GuaranteedTailCallOpt && IsFastCall)
5938     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5939 
5940   int SPDiff = 0;
5941 
5942   // Calculate by how many bytes the stack has to be adjusted in case of tail
5943   // call optimization.
5944   if (!IsSibCall)
5945     SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
5946 
5947   // To protect arguments on the stack from being clobbered in a tail call,
5948   // force all the loads to happen before doing any other lowering.
5949   if (CFlags.IsTailCall)
5950     Chain = DAG.getStackArgumentTokenFactor(Chain);
5951 
5952   // Adjust the stack pointer for the new arguments...
5953   // These operations are automatically eliminated by the prolog/epilog pass
5954   if (!IsSibCall)
5955     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5956   SDValue CallSeqStart = Chain;
5957 
5958   // Load the return address and frame pointer so it can be move somewhere else
5959   // later.
5960   SDValue LROp, FPOp;
5961   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5962 
5963   // Set up a copy of the stack pointer for use loading and storing any
5964   // arguments that may not fit in the registers available for argument
5965   // passing.
5966   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5967 
5968   // Figure out which arguments are going to go in registers, and which in
5969   // memory.  Also, if this is a vararg function, floating point operations
5970   // must be stored to our stack, and loaded into integer regs as well, if
5971   // any integer regs are available for argument passing.
5972   unsigned ArgOffset = LinkageSize;
5973 
5974   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5975   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5976 
5977   SmallVector<SDValue, 8> MemOpChains;
5978   for (unsigned i = 0; i != NumOps; ++i) {
5979     SDValue Arg = OutVals[i];
5980     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5981     EVT ArgVT = Outs[i].VT;
5982     EVT OrigVT = Outs[i].ArgVT;
5983 
5984     // PtrOff will be used to store the current argument to the stack if a
5985     // register cannot be found for it.
5986     SDValue PtrOff;
5987 
5988     // We re-align the argument offset for each argument, except when using the
5989     // fast calling convention, when we need to make sure we do that only when
5990     // we'll actually use a stack slot.
5991     auto ComputePtrOff = [&]() {
5992       /* Respect alignment of argument on the stack.  */
5993       auto Alignment =
5994           CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5995       ArgOffset = alignTo(ArgOffset, Alignment);
5996 
5997       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5998 
5999       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6000     };
6001 
6002     if (!IsFastCall) {
6003       ComputePtrOff();
6004 
6005       /* Compute GPR index associated with argument offset.  */
6006       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
6007       GPR_idx = std::min(GPR_idx, NumGPRs);
6008     }
6009 
6010     // Promote integers to 64-bit values.
6011     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6012       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6013       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6014       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6015     }
6016 
6017     // FIXME memcpy is used way more than necessary.  Correctness first.
6018     // Note: "by value" is code for passing a structure by value, not
6019     // basic types.
6020     if (Flags.isByVal()) {
6021       // Note: Size includes alignment padding, so
6022       //   struct x { short a; char b; }
6023       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6024       // These are the proper values we need for right-justifying the
6025       // aggregate in a parameter register.
6026       unsigned Size = Flags.getByValSize();
6027 
6028       // An empty aggregate parameter takes up no storage and no
6029       // registers.
6030       if (Size == 0)
6031         continue;
6032 
6033       if (IsFastCall)
6034         ComputePtrOff();
6035 
6036       // All aggregates smaller than 8 bytes must be passed right-justified.
6037       if (Size==1 || Size==2 || Size==4) {
6038         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6039         if (GPR_idx != NumGPRs) {
6040           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6041                                         MachinePointerInfo(), VT);
6042           MemOpChains.push_back(Load.getValue(1));
6043           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6044 
6045           ArgOffset += PtrByteSize;
6046           continue;
6047         }
6048       }
6049 
6050       if (GPR_idx == NumGPRs && Size < 8) {
6051         SDValue AddPtr = PtrOff;
6052         if (!isLittleEndian) {
6053           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6054                                           PtrOff.getValueType());
6055           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6056         }
6057         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6058                                                           CallSeqStart,
6059                                                           Flags, DAG, dl);
6060         ArgOffset += PtrByteSize;
6061         continue;
6062       }
6063       // Copy entire object into memory.  There are cases where gcc-generated
6064       // code assumes it is there, even if it could be put entirely into
6065       // registers.  (This is not what the doc says.)
6066 
6067       // FIXME: The above statement is likely due to a misunderstanding of the
6068       // documents.  All arguments must be copied into the parameter area BY
6069       // THE CALLEE in the event that the callee takes the address of any
6070       // formal argument.  That has not yet been implemented.  However, it is
6071       // reasonable to use the stack area as a staging area for the register
6072       // load.
6073 
6074       // Skip this for small aggregates, as we will use the same slot for a
6075       // right-justified copy, below.
6076       if (Size >= 8)
6077         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6078                                                           CallSeqStart,
6079                                                           Flags, DAG, dl);
6080 
6081       // When a register is available, pass a small aggregate right-justified.
6082       if (Size < 8 && GPR_idx != NumGPRs) {
6083         // The easiest way to get this right-justified in a register
6084         // is to copy the structure into the rightmost portion of a
6085         // local variable slot, then load the whole slot into the
6086         // register.
6087         // FIXME: The memcpy seems to produce pretty awful code for
6088         // small aggregates, particularly for packed ones.
6089         // FIXME: It would be preferable to use the slot in the
6090         // parameter save area instead of a new local variable.
6091         SDValue AddPtr = PtrOff;
6092         if (!isLittleEndian) {
6093           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6094           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6095         }
6096         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6097                                                           CallSeqStart,
6098                                                           Flags, DAG, dl);
6099 
6100         // Load the slot into the register.
6101         SDValue Load =
6102             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6103         MemOpChains.push_back(Load.getValue(1));
6104         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6105 
6106         // Done with this argument.
6107         ArgOffset += PtrByteSize;
6108         continue;
6109       }
6110 
6111       // For aggregates larger than PtrByteSize, copy the pieces of the
6112       // object that fit into registers from the parameter save area.
6113       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6114         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6115         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6116         if (GPR_idx != NumGPRs) {
6117           SDValue Load =
6118               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6119           MemOpChains.push_back(Load.getValue(1));
6120           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6121           ArgOffset += PtrByteSize;
6122         } else {
6123           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6124           break;
6125         }
6126       }
6127       continue;
6128     }
6129 
6130     switch (Arg.getSimpleValueType().SimpleTy) {
6131     default: llvm_unreachable("Unexpected ValueType for argument!");
6132     case MVT::i1:
6133     case MVT::i32:
6134     case MVT::i64:
6135       if (Flags.isNest()) {
6136         // The 'nest' parameter, if any, is passed in R11.
6137         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6138         break;
6139       }
6140 
6141       // These can be scalar arguments or elements of an integer array type
6142       // passed directly.  Clang may use those instead of "byval" aggregate
6143       // types to avoid forcing arguments to memory unnecessarily.
6144       if (GPR_idx != NumGPRs) {
6145         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6146       } else {
6147         if (IsFastCall)
6148           ComputePtrOff();
6149 
6150         assert(HasParameterArea &&
6151                "Parameter area must exist to pass an argument in memory.");
6152         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6153                          true, CFlags.IsTailCall, false, MemOpChains,
6154                          TailCallArguments, dl);
6155         if (IsFastCall)
6156           ArgOffset += PtrByteSize;
6157       }
6158       if (!IsFastCall)
6159         ArgOffset += PtrByteSize;
6160       break;
6161     case MVT::f32:
6162     case MVT::f64: {
6163       // These can be scalar arguments or elements of a float array type
6164       // passed directly.  The latter are used to implement ELFv2 homogenous
6165       // float aggregates.
6166 
6167       // Named arguments go into FPRs first, and once they overflow, the
6168       // remaining arguments go into GPRs and then the parameter save area.
6169       // Unnamed arguments for vararg functions always go to GPRs and
6170       // then the parameter save area.  For now, put all arguments to vararg
6171       // routines always in both locations (FPR *and* GPR or stack slot).
6172       bool NeedGPROrStack = CFlags.IsVarArg || FPR_idx == NumFPRs;
6173       bool NeededLoad = false;
6174 
6175       // First load the argument into the next available FPR.
6176       if (FPR_idx != NumFPRs)
6177         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6178 
6179       // Next, load the argument into GPR or stack slot if needed.
6180       if (!NeedGPROrStack)
6181         ;
6182       else if (GPR_idx != NumGPRs && !IsFastCall) {
6183         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6184         // once we support fp <-> gpr moves.
6185 
6186         // In the non-vararg case, this can only ever happen in the
6187         // presence of f32 array types, since otherwise we never run
6188         // out of FPRs before running out of GPRs.
6189         SDValue ArgVal;
6190 
6191         // Double values are always passed in a single GPR.
6192         if (Arg.getValueType() != MVT::f32) {
6193           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6194 
6195         // Non-array float values are extended and passed in a GPR.
6196         } else if (!Flags.isInConsecutiveRegs()) {
6197           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6198           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6199 
6200         // If we have an array of floats, we collect every odd element
6201         // together with its predecessor into one GPR.
6202         } else if (ArgOffset % PtrByteSize != 0) {
6203           SDValue Lo, Hi;
6204           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6205           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6206           if (!isLittleEndian)
6207             std::swap(Lo, Hi);
6208           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6209 
6210         // The final element, if even, goes into the first half of a GPR.
6211         } else if (Flags.isInConsecutiveRegsLast()) {
6212           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6213           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6214           if (!isLittleEndian)
6215             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6216                                  DAG.getConstant(32, dl, MVT::i32));
6217 
6218         // Non-final even elements are skipped; they will be handled
6219         // together the with subsequent argument on the next go-around.
6220         } else
6221           ArgVal = SDValue();
6222 
6223         if (ArgVal.getNode())
6224           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6225       } else {
6226         if (IsFastCall)
6227           ComputePtrOff();
6228 
6229         // Single-precision floating-point values are mapped to the
6230         // second (rightmost) word of the stack doubleword.
6231         if (Arg.getValueType() == MVT::f32 &&
6232             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6233           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6234           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6235         }
6236 
6237         assert(HasParameterArea &&
6238                "Parameter area must exist to pass an argument in memory.");
6239         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6240                          true, CFlags.IsTailCall, false, MemOpChains,
6241                          TailCallArguments, dl);
6242 
6243         NeededLoad = true;
6244       }
6245       // When passing an array of floats, the array occupies consecutive
6246       // space in the argument area; only round up to the next doubleword
6247       // at the end of the array.  Otherwise, each float takes 8 bytes.
6248       if (!IsFastCall || NeededLoad) {
6249         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6250                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6251         if (Flags.isInConsecutiveRegsLast())
6252           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6253       }
6254       break;
6255     }
6256     case MVT::v4f32:
6257     case MVT::v4i32:
6258     case MVT::v8i16:
6259     case MVT::v16i8:
6260     case MVT::v2f64:
6261     case MVT::v2i64:
6262     case MVT::v1i128:
6263     case MVT::f128:
6264       if (!Subtarget.hasQPX()) {
6265       // These can be scalar arguments or elements of a vector array type
6266       // passed directly.  The latter are used to implement ELFv2 homogenous
6267       // vector aggregates.
6268 
6269       // For a varargs call, named arguments go into VRs or on the stack as
6270       // usual; unnamed arguments always go to the stack or the corresponding
6271       // GPRs when within range.  For now, we always put the value in both
6272       // locations (or even all three).
6273       if (CFlags.IsVarArg) {
6274         assert(HasParameterArea &&
6275                "Parameter area must exist if we have a varargs call.");
6276         // We could elide this store in the case where the object fits
6277         // entirely in R registers.  Maybe later.
6278         SDValue Store =
6279             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6280         MemOpChains.push_back(Store);
6281         if (VR_idx != NumVRs) {
6282           SDValue Load =
6283               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6284           MemOpChains.push_back(Load.getValue(1));
6285           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6286         }
6287         ArgOffset += 16;
6288         for (unsigned i=0; i<16; i+=PtrByteSize) {
6289           if (GPR_idx == NumGPRs)
6290             break;
6291           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6292                                    DAG.getConstant(i, dl, PtrVT));
6293           SDValue Load =
6294               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6295           MemOpChains.push_back(Load.getValue(1));
6296           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6297         }
6298         break;
6299       }
6300 
6301       // Non-varargs Altivec params go into VRs or on the stack.
6302       if (VR_idx != NumVRs) {
6303         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6304       } else {
6305         if (IsFastCall)
6306           ComputePtrOff();
6307 
6308         assert(HasParameterArea &&
6309                "Parameter area must exist to pass an argument in memory.");
6310         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6311                          true, CFlags.IsTailCall, true, MemOpChains,
6312                          TailCallArguments, dl);
6313         if (IsFastCall)
6314           ArgOffset += 16;
6315       }
6316 
6317       if (!IsFastCall)
6318         ArgOffset += 16;
6319       break;
6320       } // not QPX
6321 
6322       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6323              "Invalid QPX parameter type");
6324 
6325       LLVM_FALLTHROUGH;
6326     case MVT::v4f64:
6327     case MVT::v4i1: {
6328       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6329       if (CFlags.IsVarArg) {
6330         assert(HasParameterArea &&
6331                "Parameter area must exist if we have a varargs call.");
6332         // We could elide this store in the case where the object fits
6333         // entirely in R registers.  Maybe later.
6334         SDValue Store =
6335             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6336         MemOpChains.push_back(Store);
6337         if (QFPR_idx != NumQFPRs) {
6338           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6339                                      PtrOff, MachinePointerInfo());
6340           MemOpChains.push_back(Load.getValue(1));
6341           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6342         }
6343         ArgOffset += (IsF32 ? 16 : 32);
6344         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6345           if (GPR_idx == NumGPRs)
6346             break;
6347           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6348                                    DAG.getConstant(i, dl, PtrVT));
6349           SDValue Load =
6350               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6351           MemOpChains.push_back(Load.getValue(1));
6352           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6353         }
6354         break;
6355       }
6356 
6357       // Non-varargs QPX params go into registers or on the stack.
6358       if (QFPR_idx != NumQFPRs) {
6359         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6360       } else {
6361         if (IsFastCall)
6362           ComputePtrOff();
6363 
6364         assert(HasParameterArea &&
6365                "Parameter area must exist to pass an argument in memory.");
6366         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6367                          true, CFlags.IsTailCall, true, MemOpChains,
6368                          TailCallArguments, dl);
6369         if (IsFastCall)
6370           ArgOffset += (IsF32 ? 16 : 32);
6371       }
6372 
6373       if (!IsFastCall)
6374         ArgOffset += (IsF32 ? 16 : 32);
6375       break;
6376       }
6377     }
6378   }
6379 
6380   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6381          "mismatch in size of parameter area");
6382   (void)NumBytesActuallyUsed;
6383 
6384   if (!MemOpChains.empty())
6385     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6386 
6387   // Check if this is an indirect call (MTCTR/BCTRL).
6388   // See prepareDescriptorIndirectCall and buildCallOperands for more
6389   // information about calls through function pointers in the 64-bit SVR4 ABI.
6390   if (CFlags.IsIndirect) {
6391     assert(!CFlags.IsTailCall &&  "Indirect tails calls not supported");
6392     // Load r2 into a virtual register and store it to the TOC save area.
6393     setUsesTOCBasePtr(DAG);
6394     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6395     // TOC save area offset.
6396     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6397     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6398     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6399     Chain = DAG.getStore(
6400         Val.getValue(1), dl, Val, AddPtr,
6401         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6402     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6403     // This does not mean the MTCTR instruction must use R12; it's easier
6404     // to model this as an extra parameter, so do that.
6405     if (isELFv2ABI && !CFlags.IsPatchPoint)
6406       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6407   }
6408 
6409   // Build a sequence of copy-to-reg nodes chained together with token chain
6410   // and flag operands which copy the outgoing args into the appropriate regs.
6411   SDValue InFlag;
6412   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6413     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6414                              RegsToPass[i].second, InFlag);
6415     InFlag = Chain.getValue(1);
6416   }
6417 
6418   if (CFlags.IsTailCall && !IsSibCall)
6419     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6420                     TailCallArguments);
6421 
6422   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6423                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6424 }
6425 
6426 SDValue PPCTargetLowering::LowerCall_Darwin(
6427     SDValue Chain, SDValue Callee, CallFlags CFlags,
6428     const SmallVectorImpl<ISD::OutputArg> &Outs,
6429     const SmallVectorImpl<SDValue> &OutVals,
6430     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6431     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6432     ImmutableCallSite CS) const {
6433   unsigned NumOps = Outs.size();
6434 
6435   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6436   bool isPPC64 = PtrVT == MVT::i64;
6437   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6438 
6439   MachineFunction &MF = DAG.getMachineFunction();
6440 
6441   // Mark this function as potentially containing a function that contains a
6442   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6443   // and restoring the callers stack pointer in this functions epilog. This is
6444   // done because by tail calling the called function might overwrite the value
6445   // in this function's (MF) stack pointer stack slot 0(SP).
6446   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6447       CFlags.CallConv == CallingConv::Fast)
6448     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6449 
6450   // Count how many bytes are to be pushed on the stack, including the linkage
6451   // area, and parameter passing area.  We start with 24/48 bytes, which is
6452   // prereserved space for [SP][CR][LR][3 x unused].
6453   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6454   unsigned NumBytes = LinkageSize;
6455 
6456   // Add up all the space actually used.
6457   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6458   // they all go in registers, but we must reserve stack space for them for
6459   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6460   // assigned stack space in order, with padding so Altivec parameters are
6461   // 16-byte aligned.
6462   unsigned nAltivecParamsAtEnd = 0;
6463   for (unsigned i = 0; i != NumOps; ++i) {
6464     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6465     EVT ArgVT = Outs[i].VT;
6466     // Varargs Altivec parameters are padded to a 16 byte boundary.
6467     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6468         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6469         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6470       if (!CFlags.IsVarArg && !isPPC64) {
6471         // Non-varargs Altivec parameters go after all the non-Altivec
6472         // parameters; handle those later so we know how much padding we need.
6473         nAltivecParamsAtEnd++;
6474         continue;
6475       }
6476       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6477       NumBytes = ((NumBytes+15)/16)*16;
6478     }
6479     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6480   }
6481 
6482   // Allow for Altivec parameters at the end, if needed.
6483   if (nAltivecParamsAtEnd) {
6484     NumBytes = ((NumBytes+15)/16)*16;
6485     NumBytes += 16*nAltivecParamsAtEnd;
6486   }
6487 
6488   // The prolog code of the callee may store up to 8 GPR argument registers to
6489   // the stack, allowing va_start to index over them in memory if its varargs.
6490   // Because we cannot tell if this is needed on the caller side, we have to
6491   // conservatively assume that it is needed.  As such, make sure we have at
6492   // least enough stack space for the caller to store the 8 GPRs.
6493   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6494 
6495   // Tail call needs the stack to be aligned.
6496   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6497       CFlags.CallConv == CallingConv::Fast)
6498     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6499 
6500   // Calculate by how many bytes the stack has to be adjusted in case of tail
6501   // call optimization.
6502   int SPDiff = CalculateTailCallSPDiff(DAG, CFlags.IsTailCall, NumBytes);
6503 
6504   // To protect arguments on the stack from being clobbered in a tail call,
6505   // force all the loads to happen before doing any other lowering.
6506   if (CFlags.IsTailCall)
6507     Chain = DAG.getStackArgumentTokenFactor(Chain);
6508 
6509   // Adjust the stack pointer for the new arguments...
6510   // These operations are automatically eliminated by the prolog/epilog pass
6511   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6512   SDValue CallSeqStart = Chain;
6513 
6514   // Load the return address and frame pointer so it can be move somewhere else
6515   // later.
6516   SDValue LROp, FPOp;
6517   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6518 
6519   // Set up a copy of the stack pointer for use loading and storing any
6520   // arguments that may not fit in the registers available for argument
6521   // passing.
6522   SDValue StackPtr;
6523   if (isPPC64)
6524     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6525   else
6526     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6527 
6528   // Figure out which arguments are going to go in registers, and which in
6529   // memory.  Also, if this is a vararg function, floating point operations
6530   // must be stored to our stack, and loaded into integer regs as well, if
6531   // any integer regs are available for argument passing.
6532   unsigned ArgOffset = LinkageSize;
6533   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6534 
6535   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6536     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6537     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6538   };
6539   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6540     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6541     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6542   };
6543   static const MCPhysReg VR[] = {
6544     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6545     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6546   };
6547   const unsigned NumGPRs = array_lengthof(GPR_32);
6548   const unsigned NumFPRs = 13;
6549   const unsigned NumVRs  = array_lengthof(VR);
6550 
6551   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6552 
6553   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6554   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6555 
6556   SmallVector<SDValue, 8> MemOpChains;
6557   for (unsigned i = 0; i != NumOps; ++i) {
6558     SDValue Arg = OutVals[i];
6559     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6560 
6561     // PtrOff will be used to store the current argument to the stack if a
6562     // register cannot be found for it.
6563     SDValue PtrOff;
6564 
6565     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6566 
6567     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6568 
6569     // On PPC64, promote integers to 64-bit values.
6570     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6571       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6572       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6573       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6574     }
6575 
6576     // FIXME memcpy is used way more than necessary.  Correctness first.
6577     // Note: "by value" is code for passing a structure by value, not
6578     // basic types.
6579     if (Flags.isByVal()) {
6580       unsigned Size = Flags.getByValSize();
6581       // Very small objects are passed right-justified.  Everything else is
6582       // passed left-justified.
6583       if (Size==1 || Size==2) {
6584         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6585         if (GPR_idx != NumGPRs) {
6586           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6587                                         MachinePointerInfo(), VT);
6588           MemOpChains.push_back(Load.getValue(1));
6589           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6590 
6591           ArgOffset += PtrByteSize;
6592         } else {
6593           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6594                                           PtrOff.getValueType());
6595           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6596           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6597                                                             CallSeqStart,
6598                                                             Flags, DAG, dl);
6599           ArgOffset += PtrByteSize;
6600         }
6601         continue;
6602       }
6603       // Copy entire object into memory.  There are cases where gcc-generated
6604       // code assumes it is there, even if it could be put entirely into
6605       // registers.  (This is not what the doc says.)
6606       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6607                                                         CallSeqStart,
6608                                                         Flags, DAG, dl);
6609 
6610       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6611       // copy the pieces of the object that fit into registers from the
6612       // parameter save area.
6613       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6614         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6615         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6616         if (GPR_idx != NumGPRs) {
6617           SDValue Load =
6618               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6619           MemOpChains.push_back(Load.getValue(1));
6620           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6621           ArgOffset += PtrByteSize;
6622         } else {
6623           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6624           break;
6625         }
6626       }
6627       continue;
6628     }
6629 
6630     switch (Arg.getSimpleValueType().SimpleTy) {
6631     default: llvm_unreachable("Unexpected ValueType for argument!");
6632     case MVT::i1:
6633     case MVT::i32:
6634     case MVT::i64:
6635       if (GPR_idx != NumGPRs) {
6636         if (Arg.getValueType() == MVT::i1)
6637           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6638 
6639         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6640       } else {
6641         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6642                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6643                          TailCallArguments, dl);
6644       }
6645       ArgOffset += PtrByteSize;
6646       break;
6647     case MVT::f32:
6648     case MVT::f64:
6649       if (FPR_idx != NumFPRs) {
6650         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6651 
6652         if (CFlags.IsVarArg) {
6653           SDValue Store =
6654               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6655           MemOpChains.push_back(Store);
6656 
6657           // Float varargs are always shadowed in available integer registers
6658           if (GPR_idx != NumGPRs) {
6659             SDValue Load =
6660                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6661             MemOpChains.push_back(Load.getValue(1));
6662             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6663           }
6664           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6665             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6666             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6667             SDValue Load =
6668                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6669             MemOpChains.push_back(Load.getValue(1));
6670             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6671           }
6672         } else {
6673           // If we have any FPRs remaining, we may also have GPRs remaining.
6674           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6675           // GPRs.
6676           if (GPR_idx != NumGPRs)
6677             ++GPR_idx;
6678           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6679               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6680             ++GPR_idx;
6681         }
6682       } else
6683         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6684                          isPPC64, CFlags.IsTailCall, false, MemOpChains,
6685                          TailCallArguments, dl);
6686       if (isPPC64)
6687         ArgOffset += 8;
6688       else
6689         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6690       break;
6691     case MVT::v4f32:
6692     case MVT::v4i32:
6693     case MVT::v8i16:
6694     case MVT::v16i8:
6695       if (CFlags.IsVarArg) {
6696         // These go aligned on the stack, or in the corresponding R registers
6697         // when within range.  The Darwin PPC ABI doc claims they also go in
6698         // V registers; in fact gcc does this only for arguments that are
6699         // prototyped, not for those that match the ...  We do it for all
6700         // arguments, seems to work.
6701         while (ArgOffset % 16 !=0) {
6702           ArgOffset += PtrByteSize;
6703           if (GPR_idx != NumGPRs)
6704             GPR_idx++;
6705         }
6706         // We could elide this store in the case where the object fits
6707         // entirely in R registers.  Maybe later.
6708         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6709                              DAG.getConstant(ArgOffset, dl, PtrVT));
6710         SDValue Store =
6711             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6712         MemOpChains.push_back(Store);
6713         if (VR_idx != NumVRs) {
6714           SDValue Load =
6715               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6716           MemOpChains.push_back(Load.getValue(1));
6717           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6718         }
6719         ArgOffset += 16;
6720         for (unsigned i=0; i<16; i+=PtrByteSize) {
6721           if (GPR_idx == NumGPRs)
6722             break;
6723           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6724                                    DAG.getConstant(i, dl, PtrVT));
6725           SDValue Load =
6726               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6727           MemOpChains.push_back(Load.getValue(1));
6728           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6729         }
6730         break;
6731       }
6732 
6733       // Non-varargs Altivec params generally go in registers, but have
6734       // stack space allocated at the end.
6735       if (VR_idx != NumVRs) {
6736         // Doesn't have GPR space allocated.
6737         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6738       } else if (nAltivecParamsAtEnd==0) {
6739         // We are emitting Altivec params in order.
6740         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6741                          isPPC64, CFlags.IsTailCall, true, MemOpChains,
6742                          TailCallArguments, dl);
6743         ArgOffset += 16;
6744       }
6745       break;
6746     }
6747   }
6748   // If all Altivec parameters fit in registers, as they usually do,
6749   // they get stack space following the non-Altivec parameters.  We
6750   // don't track this here because nobody below needs it.
6751   // If there are more Altivec parameters than fit in registers emit
6752   // the stores here.
6753   if (!CFlags.IsVarArg && nAltivecParamsAtEnd > NumVRs) {
6754     unsigned j = 0;
6755     // Offset is aligned; skip 1st 12 params which go in V registers.
6756     ArgOffset = ((ArgOffset+15)/16)*16;
6757     ArgOffset += 12*16;
6758     for (unsigned i = 0; i != NumOps; ++i) {
6759       SDValue Arg = OutVals[i];
6760       EVT ArgType = Outs[i].VT;
6761       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6762           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6763         if (++j > NumVRs) {
6764           SDValue PtrOff;
6765           // We are emitting Altivec params in order.
6766           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6767                            isPPC64, CFlags.IsTailCall, true, MemOpChains,
6768                            TailCallArguments, dl);
6769           ArgOffset += 16;
6770         }
6771       }
6772     }
6773   }
6774 
6775   if (!MemOpChains.empty())
6776     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6777 
6778   // On Darwin, R12 must contain the address of an indirect callee.  This does
6779   // not mean the MTCTR instruction must use R12; it's easier to model this as
6780   // an extra parameter, so do that.
6781   if (CFlags.IsIndirect) {
6782     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
6783     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6784                                                    PPC::R12), Callee));
6785   }
6786 
6787   // Build a sequence of copy-to-reg nodes chained together with token chain
6788   // and flag operands which copy the outgoing args into the appropriate regs.
6789   SDValue InFlag;
6790   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6791     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6792                              RegsToPass[i].second, InFlag);
6793     InFlag = Chain.getValue(1);
6794   }
6795 
6796   if (CFlags.IsTailCall)
6797     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6798                     TailCallArguments);
6799 
6800   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
6801                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
6802 }
6803 
6804 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6805                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6806                    CCState &State) {
6807 
6808   if (ValVT == MVT::f128)
6809     report_fatal_error("f128 is unimplemented on AIX.");
6810 
6811   if (ArgFlags.isByVal())
6812     report_fatal_error("Passing structure by value is unimplemented.");
6813 
6814   if (ArgFlags.isNest())
6815     report_fatal_error("Nest arguments are unimplemented.");
6816 
6817   if (ValVT.isVector() || LocVT.isVector())
6818     report_fatal_error("Vector arguments are unimplemented on AIX.");
6819 
6820   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6821       State.getMachineFunction().getSubtarget());
6822   const bool IsPPC64 = Subtarget.isPPC64();
6823   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6824 
6825   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6826                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6827                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6828   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6829                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6830                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6831 
6832   // Arguments always reserve parameter save area.
6833   switch (ValVT.SimpleTy) {
6834   default:
6835     report_fatal_error("Unhandled value type for argument.");
6836   case MVT::i64:
6837     // i64 arguments should have been split to i32 for PPC32.
6838     assert(IsPPC64 && "PPC32 should have split i64 values.");
6839     LLVM_FALLTHROUGH;
6840   case MVT::i1:
6841   case MVT::i32:
6842     State.AllocateStack(PtrByteSize, PtrByteSize);
6843     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6844       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6845       // Promote integers if needed.
6846       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6847         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6848                                     : CCValAssign::LocInfo::ZExt;
6849       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6850     }
6851     else
6852       report_fatal_error("Handling of placing parameters on the stack is "
6853                          "unimplemented!");
6854     return false;
6855 
6856   case MVT::f32:
6857   case MVT::f64: {
6858     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6859     const unsigned StoreSize = LocVT.getStoreSize();
6860     // Floats are always 4-byte aligned in the PSA on AIX.
6861     // This includes f64 in 64-bit mode for ABI compatibility.
6862     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6863     if (unsigned Reg = State.AllocateReg(FPR))
6864       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
6865     else
6866       report_fatal_error("Handling of placing parameters on the stack is "
6867                          "unimplemented!");
6868 
6869     // AIX requires that GPRs are reserved for float arguments.
6870     // Successfully reserved GPRs are only initialized for vararg calls.
6871     MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6872     for (unsigned I = 0; I < StoreSize; I += PtrByteSize) {
6873       if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6874         if (State.isVarArg()) {
6875           // Custom handling is required for:
6876           //   f64 in PPC32 needs to be split into 2 GPRs.
6877           //   f32 in PPC64 needs to occupy only lower 32 bits of 64-bit GPR.
6878           State.addLoc(
6879               CCValAssign::getCustomReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6880         }
6881       } else if (State.isVarArg()) {
6882         report_fatal_error("Handling of placing parameters on the stack is "
6883                            "unimplemented!");
6884       }
6885     }
6886 
6887     return false;
6888   }
6889   }
6890   return true;
6891 }
6892 
6893 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6894                                                     bool IsPPC64) {
6895   assert((IsPPC64 || SVT != MVT::i64) &&
6896          "i64 should have been split for 32-bit codegen.");
6897 
6898   switch (SVT) {
6899   default:
6900     report_fatal_error("Unexpected value type for formal argument");
6901   case MVT::i1:
6902   case MVT::i32:
6903   case MVT::i64:
6904     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6905   case MVT::f32:
6906     return &PPC::F4RCRegClass;
6907   case MVT::f64:
6908     return &PPC::F8RCRegClass;
6909   }
6910 }
6911 
6912 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6913                                         SelectionDAG &DAG, SDValue ArgValue,
6914                                         MVT LocVT, const SDLoc &dl) {
6915   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6916   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6917 
6918   if (Flags.isSExt())
6919     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6920                            DAG.getValueType(ValVT));
6921   else if (Flags.isZExt())
6922     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6923                            DAG.getValueType(ValVT));
6924 
6925   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6926 }
6927 
6928 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6929     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6930     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6931     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6932 
6933   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6934           CallConv == CallingConv::Fast) &&
6935          "Unexpected calling convention!");
6936 
6937   if (isVarArg)
6938     report_fatal_error("This call type is unimplemented on AIX.");
6939 
6940   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6941     report_fatal_error("Tail call support is unimplemented on AIX.");
6942 
6943   if (useSoftFloat())
6944     report_fatal_error("Soft float support is unimplemented on AIX.");
6945 
6946   const PPCSubtarget &Subtarget =
6947       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6948   if (Subtarget.hasQPX())
6949     report_fatal_error("QPX support is not supported on AIX.");
6950 
6951   const bool IsPPC64 = Subtarget.isPPC64();
6952   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6953 
6954   // Assign locations to all of the incoming arguments.
6955   SmallVector<CCValAssign, 16> ArgLocs;
6956   MachineFunction &MF = DAG.getMachineFunction();
6957   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6958 
6959   // Reserve space for the linkage area on the stack.
6960   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6961   // On AIX a minimum of 8 words is saved to the parameter save area.
6962   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6963   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6964   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6965 
6966   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6967     CCValAssign &VA = ArgLocs[i];
6968     SDValue ArgValue;
6969     ISD::ArgFlagsTy Flags = Ins[i].Flags;
6970     if (VA.isRegLoc()) {
6971       EVT ValVT = VA.getValVT();
6972       MVT LocVT = VA.getLocVT();
6973       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6974       unsigned VReg =
6975           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6976       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6977       if (ValVT.isScalarInteger() &&
6978           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
6979         ArgValue =
6980             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6981       }
6982       InVals.push_back(ArgValue);
6983     } else {
6984       report_fatal_error("Handling of formal arguments on the stack is "
6985                          "unimplemented!");
6986     }
6987   }
6988 
6989   // Area that is at least reserved in the caller of this function.
6990   unsigned MinReservedArea = CCInfo.getNextStackOffset();
6991 
6992   // Set the size that is at least reserved in caller of this function. Tail
6993   // call optimized function's reserved stack space needs to be aligned so
6994   // that taking the difference between two stack areas will result in an
6995   // aligned stack.
6996   MinReservedArea =
6997       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
6998   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6999   FuncInfo->setMinReservedArea(MinReservedArea);
7000 
7001   return Chain;
7002 }
7003 
7004 SDValue PPCTargetLowering::LowerCall_AIX(
7005     SDValue Chain, SDValue Callee, CallFlags CFlags,
7006     const SmallVectorImpl<ISD::OutputArg> &Outs,
7007     const SmallVectorImpl<SDValue> &OutVals,
7008     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
7009     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
7010     ImmutableCallSite CS) const {
7011 
7012   assert((CFlags.CallConv == CallingConv::C ||
7013           CFlags.CallConv == CallingConv::Cold ||
7014           CFlags.CallConv == CallingConv::Fast) &&
7015          "Unexpected calling convention!");
7016 
7017   if (CFlags.IsPatchPoint)
7018     report_fatal_error("This call type is unimplemented on AIX.");
7019 
7020   const PPCSubtarget& Subtarget =
7021       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7022   if (Subtarget.hasQPX())
7023     report_fatal_error("QPX is not supported on AIX.");
7024   if (Subtarget.hasAltivec())
7025     report_fatal_error("Altivec support is unimplemented on AIX.");
7026 
7027   MachineFunction &MF = DAG.getMachineFunction();
7028   SmallVector<CCValAssign, 16> ArgLocs;
7029   CCState CCInfo(CFlags.CallConv, CFlags.IsVarArg, MF, ArgLocs,
7030                  *DAG.getContext());
7031 
7032   // Reserve space for the linkage save area (LSA) on the stack.
7033   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7034   //   [SP][CR][LR][2 x reserved][TOC].
7035   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7036   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7037   const bool IsPPC64 = Subtarget.isPPC64();
7038   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
7039   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7040   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7041 
7042   // The prolog code of the callee may store up to 8 GPR argument registers to
7043   // the stack, allowing va_start to index over them in memory if the callee
7044   // is variadic.
7045   // Because we cannot tell if this is needed on the caller side, we have to
7046   // conservatively assume that it is needed.  As such, make sure we have at
7047   // least enough stack space for the caller to store the 8 GPRs.
7048   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7049   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
7050 
7051   // Adjust the stack pointer for the new arguments...
7052   // These operations are automatically eliminated by the prolog/epilog pass.
7053   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7054   SDValue CallSeqStart = Chain;
7055 
7056   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7057 
7058   for (unsigned I = 0, E = ArgLocs.size(); I != E;) {
7059     CCValAssign &VA = ArgLocs[I++];
7060 
7061     if (VA.isMemLoc())
7062       report_fatal_error("Handling of placing parameters on the stack is "
7063                          "unimplemented!");
7064     if (!VA.isRegLoc())
7065       report_fatal_error(
7066           "Unexpected non-register location for function call argument.");
7067 
7068     SDValue Arg = OutVals[VA.getValNo()];
7069 
7070     if (!VA.needsCustom()) {
7071       switch (VA.getLocInfo()) {
7072       default:
7073         report_fatal_error("Unexpected argument extension type.");
7074       case CCValAssign::Full:
7075         break;
7076       case CCValAssign::ZExt:
7077         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7078         break;
7079       case CCValAssign::SExt:
7080         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7081         break;
7082       }
7083       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7084 
7085       continue;
7086     }
7087 
7088     // Custom handling is used for GPR initializations for vararg float
7089     // arguments.
7090     assert(CFlags.IsVarArg && VA.getValVT().isFloatingPoint() &&
7091            VA.getLocVT().isInteger() &&
7092            "Unexpected custom register handling for calling convention.");
7093 
7094     SDValue ArgAsInt =
7095         DAG.getBitcast(MVT::getIntegerVT(VA.getValVT().getSizeInBits()), Arg);
7096 
7097     if (Arg.getValueType().getStoreSize() == VA.getLocVT().getStoreSize())
7098       // f32 in 32-bit GPR
7099       // f64 in 64-bit GPR
7100       RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgAsInt));
7101     else if (Arg.getValueType().getSizeInBits() < VA.getLocVT().getSizeInBits())
7102       // f32 in 64-bit GPR.
7103       RegsToPass.push_back(std::make_pair(
7104           VA.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, VA.getLocVT())));
7105     else {
7106       // f64 in two 32-bit GPRs
7107       // The 2 GPRs are marked custom and expected to be adjacent in ArgLocs.
7108       assert(Arg.getValueType() == MVT::f64 && CFlags.IsVarArg && !IsPPC64 &&
7109              "Unexpected custom register for argument!");
7110       CCValAssign &GPR1 = VA;
7111       SDValue MSWAsI64 = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgAsInt,
7112                                      DAG.getConstant(32, dl, MVT::i8));
7113       RegsToPass.push_back(std::make_pair(
7114           GPR1.getLocReg(), DAG.getZExtOrTrunc(MSWAsI64, dl, MVT::i32)));
7115       assert(I != E && "A second custom GPR is expected!");
7116       CCValAssign &GPR2 = ArgLocs[I++];
7117       assert(GPR2.isRegLoc() && GPR2.getValNo() == GPR1.getValNo() &&
7118              GPR2.needsCustom() && "A second custom GPR is expected!");
7119       RegsToPass.push_back(std::make_pair(
7120           GPR2.getLocReg(), DAG.getZExtOrTrunc(ArgAsInt, dl, MVT::i32)));
7121     }
7122   }
7123 
7124   // For indirect calls, we need to save the TOC base to the stack for
7125   // restoration after the call.
7126   if (CFlags.IsIndirect) {
7127     assert(!CFlags.IsTailCall && "Indirect tail-calls not supported.");
7128     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7129     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7130     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7131     const unsigned TOCSaveOffset =
7132         Subtarget.getFrameLowering()->getTOCSaveOffset();
7133 
7134     setUsesTOCBasePtr(DAG);
7135     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7136     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7137     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7138     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7139     Chain = DAG.getStore(
7140         Val.getValue(1), dl, Val, AddPtr,
7141         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7142   }
7143 
7144   // Build a sequence of copy-to-reg nodes chained together with token chain
7145   // and flag operands which copy the outgoing args into the appropriate regs.
7146   SDValue InFlag;
7147   for (auto Reg : RegsToPass) {
7148     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7149     InFlag = Chain.getValue(1);
7150   }
7151 
7152   const int SPDiff = 0;
7153   return FinishCall(CFlags, dl, DAG, RegsToPass, InFlag, Chain, CallSeqStart,
7154                     Callee, SPDiff, NumBytes, Ins, InVals, CS);
7155 }
7156 
7157 bool
7158 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7159                                   MachineFunction &MF, bool isVarArg,
7160                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7161                                   LLVMContext &Context) const {
7162   SmallVector<CCValAssign, 16> RVLocs;
7163   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7164   return CCInfo.CheckReturn(
7165       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7166                 ? RetCC_PPC_Cold
7167                 : RetCC_PPC);
7168 }
7169 
7170 SDValue
7171 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7172                                bool isVarArg,
7173                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7174                                const SmallVectorImpl<SDValue> &OutVals,
7175                                const SDLoc &dl, SelectionDAG &DAG) const {
7176   SmallVector<CCValAssign, 16> RVLocs;
7177   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7178                  *DAG.getContext());
7179   CCInfo.AnalyzeReturn(Outs,
7180                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7181                            ? RetCC_PPC_Cold
7182                            : RetCC_PPC);
7183 
7184   SDValue Flag;
7185   SmallVector<SDValue, 4> RetOps(1, Chain);
7186 
7187   // Copy the result values into the output registers.
7188   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7189     CCValAssign &VA = RVLocs[i];
7190     assert(VA.isRegLoc() && "Can only return in registers!");
7191 
7192     SDValue Arg = OutVals[RealResIdx];
7193 
7194     switch (VA.getLocInfo()) {
7195     default: llvm_unreachable("Unknown loc info!");
7196     case CCValAssign::Full: break;
7197     case CCValAssign::AExt:
7198       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7199       break;
7200     case CCValAssign::ZExt:
7201       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7202       break;
7203     case CCValAssign::SExt:
7204       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7205       break;
7206     }
7207     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7208       bool isLittleEndian = Subtarget.isLittleEndian();
7209       // Legalize ret f64 -> ret 2 x i32.
7210       SDValue SVal =
7211           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7212                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7213       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7214       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7215       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7216                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7217       Flag = Chain.getValue(1);
7218       VA = RVLocs[++i]; // skip ahead to next loc
7219       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7220     } else
7221       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7222     Flag = Chain.getValue(1);
7223     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7224   }
7225 
7226   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7227   const MCPhysReg *I =
7228     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7229   if (I) {
7230     for (; *I; ++I) {
7231 
7232       if (PPC::G8RCRegClass.contains(*I))
7233         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7234       else if (PPC::F8RCRegClass.contains(*I))
7235         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7236       else if (PPC::CRRCRegClass.contains(*I))
7237         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7238       else if (PPC::VRRCRegClass.contains(*I))
7239         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7240       else
7241         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7242     }
7243   }
7244 
7245   RetOps[0] = Chain;  // Update chain.
7246 
7247   // Add the flag if we have it.
7248   if (Flag.getNode())
7249     RetOps.push_back(Flag);
7250 
7251   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7252 }
7253 
7254 SDValue
7255 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7256                                                 SelectionDAG &DAG) const {
7257   SDLoc dl(Op);
7258 
7259   // Get the correct type for integers.
7260   EVT IntVT = Op.getValueType();
7261 
7262   // Get the inputs.
7263   SDValue Chain = Op.getOperand(0);
7264   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7265   // Build a DYNAREAOFFSET node.
7266   SDValue Ops[2] = {Chain, FPSIdx};
7267   SDVTList VTs = DAG.getVTList(IntVT);
7268   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7269 }
7270 
7271 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7272                                              SelectionDAG &DAG) const {
7273   // When we pop the dynamic allocation we need to restore the SP link.
7274   SDLoc dl(Op);
7275 
7276   // Get the correct type for pointers.
7277   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7278 
7279   // Construct the stack pointer operand.
7280   bool isPPC64 = Subtarget.isPPC64();
7281   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7282   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7283 
7284   // Get the operands for the STACKRESTORE.
7285   SDValue Chain = Op.getOperand(0);
7286   SDValue SaveSP = Op.getOperand(1);
7287 
7288   // Load the old link SP.
7289   SDValue LoadLinkSP =
7290       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7291 
7292   // Restore the stack pointer.
7293   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7294 
7295   // Store the old link SP.
7296   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7297 }
7298 
7299 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7300   MachineFunction &MF = DAG.getMachineFunction();
7301   bool isPPC64 = Subtarget.isPPC64();
7302   EVT PtrVT = getPointerTy(MF.getDataLayout());
7303 
7304   // Get current frame pointer save index.  The users of this index will be
7305   // primarily DYNALLOC instructions.
7306   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7307   int RASI = FI->getReturnAddrSaveIndex();
7308 
7309   // If the frame pointer save index hasn't been defined yet.
7310   if (!RASI) {
7311     // Find out what the fix offset of the frame pointer save area.
7312     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7313     // Allocate the frame index for frame pointer save area.
7314     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7315     // Save the result.
7316     FI->setReturnAddrSaveIndex(RASI);
7317   }
7318   return DAG.getFrameIndex(RASI, PtrVT);
7319 }
7320 
7321 SDValue
7322 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7323   MachineFunction &MF = DAG.getMachineFunction();
7324   bool isPPC64 = Subtarget.isPPC64();
7325   EVT PtrVT = getPointerTy(MF.getDataLayout());
7326 
7327   // Get current frame pointer save index.  The users of this index will be
7328   // primarily DYNALLOC instructions.
7329   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7330   int FPSI = FI->getFramePointerSaveIndex();
7331 
7332   // If the frame pointer save index hasn't been defined yet.
7333   if (!FPSI) {
7334     // Find out what the fix offset of the frame pointer save area.
7335     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7336     // Allocate the frame index for frame pointer save area.
7337     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7338     // Save the result.
7339     FI->setFramePointerSaveIndex(FPSI);
7340   }
7341   return DAG.getFrameIndex(FPSI, PtrVT);
7342 }
7343 
7344 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7345                                                    SelectionDAG &DAG) const {
7346   // Get the inputs.
7347   SDValue Chain = Op.getOperand(0);
7348   SDValue Size  = Op.getOperand(1);
7349   SDLoc dl(Op);
7350 
7351   // Get the correct type for pointers.
7352   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7353   // Negate the size.
7354   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7355                                 DAG.getConstant(0, dl, PtrVT), Size);
7356   // Construct a node for the frame pointer save index.
7357   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7358   // Build a DYNALLOC node.
7359   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7360   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7361   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7362 }
7363 
7364 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7365                                                      SelectionDAG &DAG) const {
7366   MachineFunction &MF = DAG.getMachineFunction();
7367 
7368   bool isPPC64 = Subtarget.isPPC64();
7369   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7370 
7371   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7372   return DAG.getFrameIndex(FI, PtrVT);
7373 }
7374 
7375 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7376                                                SelectionDAG &DAG) const {
7377   SDLoc DL(Op);
7378   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7379                      DAG.getVTList(MVT::i32, MVT::Other),
7380                      Op.getOperand(0), Op.getOperand(1));
7381 }
7382 
7383 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7384                                                 SelectionDAG &DAG) const {
7385   SDLoc DL(Op);
7386   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7387                      Op.getOperand(0), Op.getOperand(1));
7388 }
7389 
7390 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7391   if (Op.getValueType().isVector())
7392     return LowerVectorLoad(Op, DAG);
7393 
7394   assert(Op.getValueType() == MVT::i1 &&
7395          "Custom lowering only for i1 loads");
7396 
7397   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7398 
7399   SDLoc dl(Op);
7400   LoadSDNode *LD = cast<LoadSDNode>(Op);
7401 
7402   SDValue Chain = LD->getChain();
7403   SDValue BasePtr = LD->getBasePtr();
7404   MachineMemOperand *MMO = LD->getMemOperand();
7405 
7406   SDValue NewLD =
7407       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7408                      BasePtr, MVT::i8, MMO);
7409   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7410 
7411   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7412   return DAG.getMergeValues(Ops, dl);
7413 }
7414 
7415 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7416   if (Op.getOperand(1).getValueType().isVector())
7417     return LowerVectorStore(Op, DAG);
7418 
7419   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7420          "Custom lowering only for i1 stores");
7421 
7422   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7423 
7424   SDLoc dl(Op);
7425   StoreSDNode *ST = cast<StoreSDNode>(Op);
7426 
7427   SDValue Chain = ST->getChain();
7428   SDValue BasePtr = ST->getBasePtr();
7429   SDValue Value = ST->getValue();
7430   MachineMemOperand *MMO = ST->getMemOperand();
7431 
7432   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7433                       Value);
7434   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7435 }
7436 
7437 // FIXME: Remove this once the ANDI glue bug is fixed:
7438 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7439   assert(Op.getValueType() == MVT::i1 &&
7440          "Custom lowering only for i1 results");
7441 
7442   SDLoc DL(Op);
7443   return DAG.getNode(PPCISD::ANDI_rec_1_GT_BIT, DL, MVT::i1, Op.getOperand(0));
7444 }
7445 
7446 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7447                                                SelectionDAG &DAG) const {
7448 
7449   // Implements a vector truncate that fits in a vector register as a shuffle.
7450   // We want to legalize vector truncates down to where the source fits in
7451   // a vector register (and target is therefore smaller than vector register
7452   // size).  At that point legalization will try to custom lower the sub-legal
7453   // result and get here - where we can contain the truncate as a single target
7454   // operation.
7455 
7456   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7457   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7458   //
7459   // We will implement it for big-endian ordering as this (where x denotes
7460   // undefined):
7461   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7462   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7463   //
7464   // The same operation in little-endian ordering will be:
7465   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7466   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7467 
7468   assert(Op.getValueType().isVector() && "Vector type expected.");
7469 
7470   SDLoc DL(Op);
7471   SDValue N1 = Op.getOperand(0);
7472   unsigned SrcSize = N1.getValueType().getSizeInBits();
7473   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7474   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7475 
7476   EVT TrgVT = Op.getValueType();
7477   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7478   EVT EltVT = TrgVT.getVectorElementType();
7479   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7480   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7481 
7482   // First list the elements we want to keep.
7483   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7484   SmallVector<int, 16> ShuffV;
7485   if (Subtarget.isLittleEndian())
7486     for (unsigned i = 0; i < TrgNumElts; ++i)
7487       ShuffV.push_back(i * SizeMult);
7488   else
7489     for (unsigned i = 1; i <= TrgNumElts; ++i)
7490       ShuffV.push_back(i * SizeMult - 1);
7491 
7492   // Populate the remaining elements with undefs.
7493   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7494     // ShuffV.push_back(i + WideNumElts);
7495     ShuffV.push_back(WideNumElts + 1);
7496 
7497   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7498   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7499 }
7500 
7501 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7502 /// possible.
7503 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7504   // Not FP? Not a fsel.
7505   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7506       !Op.getOperand(2).getValueType().isFloatingPoint())
7507     return Op;
7508 
7509   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7510   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7511   // We might be able to do better than this under some circumstances, but in
7512   // general, fsel-based lowering of select is a finite-math-only optimization.
7513   // For more information, see section F.3 of the 2.06 ISA specification.
7514   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7515   // presence of infinities.
7516   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7517     return Op;
7518   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7519 
7520   EVT ResVT = Op.getValueType();
7521   EVT CmpVT = Op.getOperand(0).getValueType();
7522   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7523   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7524   SDLoc dl(Op);
7525 
7526   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7527     switch (CC) {
7528     default:
7529       // Not a min/max but with finite math, we may still be able to use fsel.
7530       if (HasNoInfs && HasNoNaNs)
7531         break;
7532       return Op;
7533     case ISD::SETOGT:
7534     case ISD::SETGT:
7535       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7536     case ISD::SETOLT:
7537     case ISD::SETLT:
7538       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7539     }
7540   }
7541 
7542   // TODO: Propagate flags from the select rather than global settings.
7543   SDNodeFlags Flags;
7544   Flags.setNoInfs(true);
7545   Flags.setNoNaNs(true);
7546 
7547   // If the RHS of the comparison is a 0.0, we don't need to do the
7548   // subtraction at all.
7549   SDValue Sel1;
7550   if (isFloatingPointZero(RHS))
7551     switch (CC) {
7552     default: break;       // SETUO etc aren't handled by fsel.
7553     case ISD::SETNE:
7554       std::swap(TV, FV);
7555       LLVM_FALLTHROUGH;
7556     case ISD::SETEQ:
7557       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7558         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7559       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7560       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7561         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7562       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7563                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7564     case ISD::SETULT:
7565     case ISD::SETLT:
7566       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7567       LLVM_FALLTHROUGH;
7568     case ISD::SETOGE:
7569     case ISD::SETGE:
7570       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7571         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7572       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7573     case ISD::SETUGT:
7574     case ISD::SETGT:
7575       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7576       LLVM_FALLTHROUGH;
7577     case ISD::SETOLE:
7578     case ISD::SETLE:
7579       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7580         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7581       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7582                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7583     }
7584 
7585   SDValue Cmp;
7586   switch (CC) {
7587   default: break;       // SETUO etc aren't handled by fsel.
7588   case ISD::SETNE:
7589     std::swap(TV, FV);
7590     LLVM_FALLTHROUGH;
7591   case ISD::SETEQ:
7592     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7593     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7594       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7595     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7596     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7597       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7598     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7599                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7600   case ISD::SETULT:
7601   case ISD::SETLT:
7602     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7603     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7604       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7605     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7606   case ISD::SETOGE:
7607   case ISD::SETGE:
7608     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7609     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7610       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7611     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7612   case ISD::SETUGT:
7613   case ISD::SETGT:
7614     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7615     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7616       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7617     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7618   case ISD::SETOLE:
7619   case ISD::SETLE:
7620     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7621     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7622       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7623     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7624   }
7625   return Op;
7626 }
7627 
7628 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7629                                                SelectionDAG &DAG,
7630                                                const SDLoc &dl) const {
7631   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7632   SDValue Src = Op.getOperand(0);
7633   if (Src.getValueType() == MVT::f32)
7634     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7635 
7636   SDValue Tmp;
7637   switch (Op.getSimpleValueType().SimpleTy) {
7638   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7639   case MVT::i32:
7640     Tmp = DAG.getNode(
7641         Op.getOpcode() == ISD::FP_TO_SINT
7642             ? PPCISD::FCTIWZ
7643             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7644         dl, MVT::f64, Src);
7645     break;
7646   case MVT::i64:
7647     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7648            "i64 FP_TO_UINT is supported only with FPCVT");
7649     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7650                                                         PPCISD::FCTIDUZ,
7651                       dl, MVT::f64, Src);
7652     break;
7653   }
7654 
7655   // Convert the FP value to an int value through memory.
7656   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7657     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7658   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7659   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7660   MachinePointerInfo MPI =
7661       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7662 
7663   // Emit a store to the stack slot.
7664   SDValue Chain;
7665   if (i32Stack) {
7666     MachineFunction &MF = DAG.getMachineFunction();
7667     MachineMemOperand *MMO =
7668       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7669     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7670     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7671               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7672   } else
7673     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7674 
7675   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7676   // add in a bias on big endian.
7677   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7678     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7679                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7680     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7681   }
7682 
7683   RLI.Chain = Chain;
7684   RLI.Ptr = FIPtr;
7685   RLI.MPI = MPI;
7686 }
7687 
7688 /// Custom lowers floating point to integer conversions to use
7689 /// the direct move instructions available in ISA 2.07 to avoid the
7690 /// need for load/store combinations.
7691 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7692                                                     SelectionDAG &DAG,
7693                                                     const SDLoc &dl) const {
7694   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7695   SDValue Src = Op.getOperand(0);
7696 
7697   if (Src.getValueType() == MVT::f32)
7698     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7699 
7700   SDValue Tmp;
7701   switch (Op.getSimpleValueType().SimpleTy) {
7702   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7703   case MVT::i32:
7704     Tmp = DAG.getNode(
7705         Op.getOpcode() == ISD::FP_TO_SINT
7706             ? PPCISD::FCTIWZ
7707             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7708         dl, MVT::f64, Src);
7709     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7710     break;
7711   case MVT::i64:
7712     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7713            "i64 FP_TO_UINT is supported only with FPCVT");
7714     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7715                                                         PPCISD::FCTIDUZ,
7716                       dl, MVT::f64, Src);
7717     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7718     break;
7719   }
7720   return Tmp;
7721 }
7722 
7723 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7724                                           const SDLoc &dl) const {
7725 
7726   // FP to INT conversions are legal for f128.
7727   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7728     return Op;
7729 
7730   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7731   // PPC (the libcall is not available).
7732   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7733     if (Op.getValueType() == MVT::i32) {
7734       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7735         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7736                                  MVT::f64, Op.getOperand(0),
7737                                  DAG.getIntPtrConstant(0, dl));
7738         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7739                                  MVT::f64, Op.getOperand(0),
7740                                  DAG.getIntPtrConstant(1, dl));
7741 
7742         // Add the two halves of the long double in round-to-zero mode.
7743         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7744 
7745         // Now use a smaller FP_TO_SINT.
7746         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7747       }
7748       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7749         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7750         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7751         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7752         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7753         // FIXME: generated code sucks.
7754         // TODO: Are there fast-math-flags to propagate to this FSUB?
7755         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7756                                    Op.getOperand(0), Tmp);
7757         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7758         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7759                            DAG.getConstant(0x80000000, dl, MVT::i32));
7760         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7761                                     Op.getOperand(0));
7762         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7763                                ISD::SETGE);
7764       }
7765     }
7766 
7767     return SDValue();
7768   }
7769 
7770   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7771     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7772 
7773   ReuseLoadInfo RLI;
7774   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7775 
7776   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7777                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7778 }
7779 
7780 // We're trying to insert a regular store, S, and then a load, L. If the
7781 // incoming value, O, is a load, we might just be able to have our load use the
7782 // address used by O. However, we don't know if anything else will store to
7783 // that address before we can load from it. To prevent this situation, we need
7784 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7785 // the same chain operand as O, we create a token factor from the chain results
7786 // of O and L, and we replace all uses of O's chain result with that token
7787 // factor (see spliceIntoChain below for this last part).
7788 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7789                                             ReuseLoadInfo &RLI,
7790                                             SelectionDAG &DAG,
7791                                             ISD::LoadExtType ET) const {
7792   SDLoc dl(Op);
7793   if (ET == ISD::NON_EXTLOAD &&
7794       (Op.getOpcode() == ISD::FP_TO_UINT ||
7795        Op.getOpcode() == ISD::FP_TO_SINT) &&
7796       isOperationLegalOrCustom(Op.getOpcode(),
7797                                Op.getOperand(0).getValueType())) {
7798 
7799     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7800     return true;
7801   }
7802 
7803   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7804   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7805       LD->isNonTemporal())
7806     return false;
7807   if (LD->getMemoryVT() != MemVT)
7808     return false;
7809 
7810   RLI.Ptr = LD->getBasePtr();
7811   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7812     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7813            "Non-pre-inc AM on PPC?");
7814     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7815                           LD->getOffset());
7816   }
7817 
7818   RLI.Chain = LD->getChain();
7819   RLI.MPI = LD->getPointerInfo();
7820   RLI.IsDereferenceable = LD->isDereferenceable();
7821   RLI.IsInvariant = LD->isInvariant();
7822   RLI.Alignment = LD->getAlignment();
7823   RLI.AAInfo = LD->getAAInfo();
7824   RLI.Ranges = LD->getRanges();
7825 
7826   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7827   return true;
7828 }
7829 
7830 // Given the head of the old chain, ResChain, insert a token factor containing
7831 // it and NewResChain, and make users of ResChain now be users of that token
7832 // factor.
7833 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7834 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7835                                         SDValue NewResChain,
7836                                         SelectionDAG &DAG) const {
7837   if (!ResChain)
7838     return;
7839 
7840   SDLoc dl(NewResChain);
7841 
7842   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7843                            NewResChain, DAG.getUNDEF(MVT::Other));
7844   assert(TF.getNode() != NewResChain.getNode() &&
7845          "A new TF really is required here");
7846 
7847   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7848   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7849 }
7850 
7851 /// Analyze profitability of direct move
7852 /// prefer float load to int load plus direct move
7853 /// when there is no integer use of int load
7854 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7855   SDNode *Origin = Op.getOperand(0).getNode();
7856   if (Origin->getOpcode() != ISD::LOAD)
7857     return true;
7858 
7859   // If there is no LXSIBZX/LXSIHZX, like Power8,
7860   // prefer direct move if the memory size is 1 or 2 bytes.
7861   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7862   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7863     return true;
7864 
7865   for (SDNode::use_iterator UI = Origin->use_begin(),
7866                             UE = Origin->use_end();
7867        UI != UE; ++UI) {
7868 
7869     // Only look at the users of the loaded value.
7870     if (UI.getUse().get().getResNo() != 0)
7871       continue;
7872 
7873     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7874         UI->getOpcode() != ISD::UINT_TO_FP)
7875       return true;
7876   }
7877 
7878   return false;
7879 }
7880 
7881 /// Custom lowers integer to floating point conversions to use
7882 /// the direct move instructions available in ISA 2.07 to avoid the
7883 /// need for load/store combinations.
7884 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7885                                                     SelectionDAG &DAG,
7886                                                     const SDLoc &dl) const {
7887   assert((Op.getValueType() == MVT::f32 ||
7888           Op.getValueType() == MVT::f64) &&
7889          "Invalid floating point type as target of conversion");
7890   assert(Subtarget.hasFPCVT() &&
7891          "Int to FP conversions with direct moves require FPCVT");
7892   SDValue FP;
7893   SDValue Src = Op.getOperand(0);
7894   bool SinglePrec = Op.getValueType() == MVT::f32;
7895   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7896   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7897   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7898                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7899 
7900   if (WordInt) {
7901     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7902                      dl, MVT::f64, Src);
7903     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7904   }
7905   else {
7906     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7907     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7908   }
7909 
7910   return FP;
7911 }
7912 
7913 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7914 
7915   EVT VecVT = Vec.getValueType();
7916   assert(VecVT.isVector() && "Expected a vector type.");
7917   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7918 
7919   EVT EltVT = VecVT.getVectorElementType();
7920   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7921   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7922 
7923   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7924   SmallVector<SDValue, 16> Ops(NumConcat);
7925   Ops[0] = Vec;
7926   SDValue UndefVec = DAG.getUNDEF(VecVT);
7927   for (unsigned i = 1; i < NumConcat; ++i)
7928     Ops[i] = UndefVec;
7929 
7930   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7931 }
7932 
7933 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7934                                                 const SDLoc &dl) const {
7935 
7936   unsigned Opc = Op.getOpcode();
7937   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7938          "Unexpected conversion type");
7939   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7940          "Supports conversions to v2f64/v4f32 only.");
7941 
7942   bool SignedConv = Opc == ISD::SINT_TO_FP;
7943   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7944 
7945   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7946   EVT WideVT = Wide.getValueType();
7947   unsigned WideNumElts = WideVT.getVectorNumElements();
7948   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7949 
7950   SmallVector<int, 16> ShuffV;
7951   for (unsigned i = 0; i < WideNumElts; ++i)
7952     ShuffV.push_back(i + WideNumElts);
7953 
7954   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7955   int SaveElts = FourEltRes ? 4 : 2;
7956   if (Subtarget.isLittleEndian())
7957     for (int i = 0; i < SaveElts; i++)
7958       ShuffV[i * Stride] = i;
7959   else
7960     for (int i = 1; i <= SaveElts; i++)
7961       ShuffV[i * Stride - 1] = i - 1;
7962 
7963   SDValue ShuffleSrc2 =
7964       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7965   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7966   unsigned ExtendOp =
7967       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7968 
7969   SDValue Extend;
7970   if (!Subtarget.hasP9Altivec() && SignedConv) {
7971     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7972     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7973                          DAG.getValueType(Op.getOperand(0).getValueType()));
7974   } else
7975     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7976 
7977   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7978 }
7979 
7980 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7981                                           SelectionDAG &DAG) const {
7982   SDLoc dl(Op);
7983 
7984   EVT InVT = Op.getOperand(0).getValueType();
7985   EVT OutVT = Op.getValueType();
7986   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7987       isOperationCustom(Op.getOpcode(), InVT))
7988     return LowerINT_TO_FPVector(Op, DAG, dl);
7989 
7990   // Conversions to f128 are legal.
7991   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7992     return Op;
7993 
7994   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7995     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7996       return SDValue();
7997 
7998     SDValue Value = Op.getOperand(0);
7999     // The values are now known to be -1 (false) or 1 (true). To convert this
8000     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8001     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8002     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8003 
8004     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8005 
8006     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8007 
8008     if (Op.getValueType() != MVT::v4f64)
8009       Value = DAG.getNode(ISD::FP_ROUND, dl,
8010                           Op.getValueType(), Value,
8011                           DAG.getIntPtrConstant(1, dl));
8012     return Value;
8013   }
8014 
8015   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
8016   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8017     return SDValue();
8018 
8019   if (Op.getOperand(0).getValueType() == MVT::i1)
8020     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
8021                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
8022                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
8023 
8024   // If we have direct moves, we can do all the conversion, skip the store/load
8025   // however, without FPCVT we can't do most conversions.
8026   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
8027       Subtarget.isPPC64() && Subtarget.hasFPCVT())
8028     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
8029 
8030   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8031          "UINT_TO_FP is supported only with FPCVT");
8032 
8033   // If we have FCFIDS, then use it when converting to single-precision.
8034   // Otherwise, convert to double-precision and then round.
8035   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8036                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
8037                                                             : PPCISD::FCFIDS)
8038                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
8039                                                             : PPCISD::FCFID);
8040   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
8041                   ? MVT::f32
8042                   : MVT::f64;
8043 
8044   if (Op.getOperand(0).getValueType() == MVT::i64) {
8045     SDValue SINT = Op.getOperand(0);
8046     // When converting to single-precision, we actually need to convert
8047     // to double-precision first and then round to single-precision.
8048     // To avoid double-rounding effects during that operation, we have
8049     // to prepare the input operand.  Bits that might be truncated when
8050     // converting to double-precision are replaced by a bit that won't
8051     // be lost at this stage, but is below the single-precision rounding
8052     // position.
8053     //
8054     // However, if -enable-unsafe-fp-math is in effect, accept double
8055     // rounding to avoid the extra overhead.
8056     if (Op.getValueType() == MVT::f32 &&
8057         !Subtarget.hasFPCVT() &&
8058         !DAG.getTarget().Options.UnsafeFPMath) {
8059 
8060       // Twiddle input to make sure the low 11 bits are zero.  (If this
8061       // is the case, we are guaranteed the value will fit into the 53 bit
8062       // mantissa of an IEEE double-precision value without rounding.)
8063       // If any of those low 11 bits were not zero originally, make sure
8064       // bit 12 (value 2048) is set instead, so that the final rounding
8065       // to single-precision gets the correct result.
8066       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8067                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8068       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8069                           Round, DAG.getConstant(2047, dl, MVT::i64));
8070       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8071       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8072                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8073 
8074       // However, we cannot use that value unconditionally: if the magnitude
8075       // of the input value is small, the bit-twiddling we did above might
8076       // end up visibly changing the output.  Fortunately, in that case, we
8077       // don't need to twiddle bits since the original input will convert
8078       // exactly to double-precision floating-point already.  Therefore,
8079       // construct a conditional to use the original value if the top 11
8080       // bits are all sign-bit copies, and use the rounded value computed
8081       // above otherwise.
8082       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8083                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8084       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8085                          Cond, DAG.getConstant(1, dl, MVT::i64));
8086       Cond = DAG.getSetCC(dl, MVT::i32,
8087                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8088 
8089       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8090     }
8091 
8092     ReuseLoadInfo RLI;
8093     SDValue Bits;
8094 
8095     MachineFunction &MF = DAG.getMachineFunction();
8096     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8097       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8098                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8099       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8100     } else if (Subtarget.hasLFIWAX() &&
8101                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8102       MachineMemOperand *MMO =
8103         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8104                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8105       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8106       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8107                                      DAG.getVTList(MVT::f64, MVT::Other),
8108                                      Ops, MVT::i32, MMO);
8109       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8110     } else if (Subtarget.hasFPCVT() &&
8111                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8112       MachineMemOperand *MMO =
8113         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8114                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8115       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8116       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8117                                      DAG.getVTList(MVT::f64, MVT::Other),
8118                                      Ops, MVT::i32, MMO);
8119       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8120     } else if (((Subtarget.hasLFIWAX() &&
8121                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8122                 (Subtarget.hasFPCVT() &&
8123                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8124                SINT.getOperand(0).getValueType() == MVT::i32) {
8125       MachineFrameInfo &MFI = MF.getFrameInfo();
8126       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8127 
8128       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8129       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8130 
8131       SDValue Store =
8132           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8133                        MachinePointerInfo::getFixedStack(
8134                            DAG.getMachineFunction(), FrameIdx));
8135 
8136       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8137              "Expected an i32 store");
8138 
8139       RLI.Ptr = FIdx;
8140       RLI.Chain = Store;
8141       RLI.MPI =
8142           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8143       RLI.Alignment = 4;
8144 
8145       MachineMemOperand *MMO =
8146         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8147                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8148       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8149       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8150                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8151                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8152                                      Ops, MVT::i32, MMO);
8153     } else
8154       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8155 
8156     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8157 
8158     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8159       FP = DAG.getNode(ISD::FP_ROUND, dl,
8160                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8161     return FP;
8162   }
8163 
8164   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8165          "Unhandled INT_TO_FP type in custom expander!");
8166   // Since we only generate this in 64-bit mode, we can take advantage of
8167   // 64-bit registers.  In particular, sign extend the input value into the
8168   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8169   // then lfd it and fcfid it.
8170   MachineFunction &MF = DAG.getMachineFunction();
8171   MachineFrameInfo &MFI = MF.getFrameInfo();
8172   EVT PtrVT = getPointerTy(MF.getDataLayout());
8173 
8174   SDValue Ld;
8175   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8176     ReuseLoadInfo RLI;
8177     bool ReusingLoad;
8178     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8179                                             DAG))) {
8180       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8181       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8182 
8183       SDValue Store =
8184           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8185                        MachinePointerInfo::getFixedStack(
8186                            DAG.getMachineFunction(), FrameIdx));
8187 
8188       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8189              "Expected an i32 store");
8190 
8191       RLI.Ptr = FIdx;
8192       RLI.Chain = Store;
8193       RLI.MPI =
8194           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8195       RLI.Alignment = 4;
8196     }
8197 
8198     MachineMemOperand *MMO =
8199       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8200                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8201     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8202     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8203                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8204                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8205                                  Ops, MVT::i32, MMO);
8206     if (ReusingLoad)
8207       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8208   } else {
8209     assert(Subtarget.isPPC64() &&
8210            "i32->FP without LFIWAX supported only on PPC64");
8211 
8212     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8213     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8214 
8215     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8216                                 Op.getOperand(0));
8217 
8218     // STD the extended value into the stack slot.
8219     SDValue Store = DAG.getStore(
8220         DAG.getEntryNode(), dl, Ext64, FIdx,
8221         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8222 
8223     // Load the value as a double.
8224     Ld = DAG.getLoad(
8225         MVT::f64, dl, Store, FIdx,
8226         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8227   }
8228 
8229   // FCFID it and return it.
8230   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8231   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8232     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8233                      DAG.getIntPtrConstant(0, dl));
8234   return FP;
8235 }
8236 
8237 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8238                                             SelectionDAG &DAG) const {
8239   SDLoc dl(Op);
8240   /*
8241    The rounding mode is in bits 30:31 of FPSR, and has the following
8242    settings:
8243      00 Round to nearest
8244      01 Round to 0
8245      10 Round to +inf
8246      11 Round to -inf
8247 
8248   FLT_ROUNDS, on the other hand, expects the following:
8249     -1 Undefined
8250      0 Round to 0
8251      1 Round to nearest
8252      2 Round to +inf
8253      3 Round to -inf
8254 
8255   To perform the conversion, we do:
8256     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8257   */
8258 
8259   MachineFunction &MF = DAG.getMachineFunction();
8260   EVT VT = Op.getValueType();
8261   EVT PtrVT = getPointerTy(MF.getDataLayout());
8262 
8263   // Save FP Control Word to register
8264   EVT NodeTys[] = {
8265     MVT::f64,    // return register
8266     MVT::Glue    // unused in this context
8267   };
8268   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8269 
8270   // Save FP register to stack slot
8271   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8272   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8273   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8274                                MachinePointerInfo());
8275 
8276   // Load FP Control Word from low 32 bits of stack slot.
8277   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8278   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8279   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8280 
8281   // Transform as necessary
8282   SDValue CWD1 =
8283     DAG.getNode(ISD::AND, dl, MVT::i32,
8284                 CWD, DAG.getConstant(3, dl, MVT::i32));
8285   SDValue CWD2 =
8286     DAG.getNode(ISD::SRL, dl, MVT::i32,
8287                 DAG.getNode(ISD::AND, dl, MVT::i32,
8288                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8289                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8290                             DAG.getConstant(3, dl, MVT::i32)),
8291                 DAG.getConstant(1, dl, MVT::i32));
8292 
8293   SDValue RetVal =
8294     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8295 
8296   return DAG.getNode((VT.getSizeInBits() < 16 ?
8297                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8298 }
8299 
8300 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8301   EVT VT = Op.getValueType();
8302   unsigned BitWidth = VT.getSizeInBits();
8303   SDLoc dl(Op);
8304   assert(Op.getNumOperands() == 3 &&
8305          VT == Op.getOperand(1).getValueType() &&
8306          "Unexpected SHL!");
8307 
8308   // Expand into a bunch of logical ops.  Note that these ops
8309   // depend on the PPC behavior for oversized shift amounts.
8310   SDValue Lo = Op.getOperand(0);
8311   SDValue Hi = Op.getOperand(1);
8312   SDValue Amt = Op.getOperand(2);
8313   EVT AmtVT = Amt.getValueType();
8314 
8315   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8316                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8317   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8318   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8319   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8320   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8321                              DAG.getConstant(-BitWidth, dl, AmtVT));
8322   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8323   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8324   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8325   SDValue OutOps[] = { OutLo, OutHi };
8326   return DAG.getMergeValues(OutOps, dl);
8327 }
8328 
8329 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8330   EVT VT = Op.getValueType();
8331   SDLoc dl(Op);
8332   unsigned BitWidth = VT.getSizeInBits();
8333   assert(Op.getNumOperands() == 3 &&
8334          VT == Op.getOperand(1).getValueType() &&
8335          "Unexpected SRL!");
8336 
8337   // Expand into a bunch of logical ops.  Note that these ops
8338   // depend on the PPC behavior for oversized shift amounts.
8339   SDValue Lo = Op.getOperand(0);
8340   SDValue Hi = Op.getOperand(1);
8341   SDValue Amt = Op.getOperand(2);
8342   EVT AmtVT = Amt.getValueType();
8343 
8344   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8345                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8346   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8347   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8348   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8349   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8350                              DAG.getConstant(-BitWidth, dl, AmtVT));
8351   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8352   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8353   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8354   SDValue OutOps[] = { OutLo, OutHi };
8355   return DAG.getMergeValues(OutOps, dl);
8356 }
8357 
8358 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8359   SDLoc dl(Op);
8360   EVT VT = Op.getValueType();
8361   unsigned BitWidth = VT.getSizeInBits();
8362   assert(Op.getNumOperands() == 3 &&
8363          VT == Op.getOperand(1).getValueType() &&
8364          "Unexpected SRA!");
8365 
8366   // Expand into a bunch of logical ops, followed by a select_cc.
8367   SDValue Lo = Op.getOperand(0);
8368   SDValue Hi = Op.getOperand(1);
8369   SDValue Amt = Op.getOperand(2);
8370   EVT AmtVT = Amt.getValueType();
8371 
8372   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8373                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8374   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8375   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8376   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8377   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8378                              DAG.getConstant(-BitWidth, dl, AmtVT));
8379   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8380   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8381   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8382                                   Tmp4, Tmp6, ISD::SETLE);
8383   SDValue OutOps[] = { OutLo, OutHi };
8384   return DAG.getMergeValues(OutOps, dl);
8385 }
8386 
8387 //===----------------------------------------------------------------------===//
8388 // Vector related lowering.
8389 //
8390 
8391 /// BuildSplatI - Build a canonical splati of Val with an element size of
8392 /// SplatSize.  Cast the result to VT.
8393 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8394                            SelectionDAG &DAG, const SDLoc &dl) {
8395   static const MVT VTys[] = { // canonical VT to use for each size.
8396     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8397   };
8398 
8399   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8400 
8401   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8402   if (Val == -1)
8403     SplatSize = 1;
8404 
8405   EVT CanonicalVT = VTys[SplatSize-1];
8406 
8407   // Build a canonical splat for this value.
8408   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8409 }
8410 
8411 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8412 /// specified intrinsic ID.
8413 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8414                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8415   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8416   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8417                      DAG.getConstant(IID, dl, MVT::i32), Op);
8418 }
8419 
8420 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8421 /// specified intrinsic ID.
8422 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8423                                 SelectionDAG &DAG, const SDLoc &dl,
8424                                 EVT DestVT = MVT::Other) {
8425   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8426   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8427                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8428 }
8429 
8430 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8431 /// specified intrinsic ID.
8432 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8433                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8434                                 EVT DestVT = MVT::Other) {
8435   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8436   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8437                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8438 }
8439 
8440 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8441 /// amount.  The result has the specified value type.
8442 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8443                            SelectionDAG &DAG, const SDLoc &dl) {
8444   // Force LHS/RHS to be the right type.
8445   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8446   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8447 
8448   int Ops[16];
8449   for (unsigned i = 0; i != 16; ++i)
8450     Ops[i] = i + Amt;
8451   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8452   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8453 }
8454 
8455 /// Do we have an efficient pattern in a .td file for this node?
8456 ///
8457 /// \param V - pointer to the BuildVectorSDNode being matched
8458 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8459 ///
8460 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8461 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8462 /// the opposite is true (expansion is beneficial) are:
8463 /// - The node builds a vector out of integers that are not 32 or 64-bits
8464 /// - The node builds a vector out of constants
8465 /// - The node is a "load-and-splat"
8466 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8467 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8468                                             bool HasDirectMove,
8469                                             bool HasP8Vector) {
8470   EVT VecVT = V->getValueType(0);
8471   bool RightType = VecVT == MVT::v2f64 ||
8472     (HasP8Vector && VecVT == MVT::v4f32) ||
8473     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8474   if (!RightType)
8475     return false;
8476 
8477   bool IsSplat = true;
8478   bool IsLoad = false;
8479   SDValue Op0 = V->getOperand(0);
8480 
8481   // This function is called in a block that confirms the node is not a constant
8482   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8483   // different constants.
8484   if (V->isConstant())
8485     return false;
8486   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8487     if (V->getOperand(i).isUndef())
8488       return false;
8489     // We want to expand nodes that represent load-and-splat even if the
8490     // loaded value is a floating point truncation or conversion to int.
8491     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8492         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8493          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8494         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8495          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8496         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8497          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8498       IsLoad = true;
8499     // If the operands are different or the input is not a load and has more
8500     // uses than just this BV node, then it isn't a splat.
8501     if (V->getOperand(i) != Op0 ||
8502         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8503       IsSplat = false;
8504   }
8505   return !(IsSplat && IsLoad);
8506 }
8507 
8508 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8509 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8510 
8511   SDLoc dl(Op);
8512   SDValue Op0 = Op->getOperand(0);
8513 
8514   if (!EnableQuadPrecision ||
8515       (Op.getValueType() != MVT::f128 ) ||
8516       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8517       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8518       (Op0.getOperand(1).getValueType() != MVT::i64))
8519     return SDValue();
8520 
8521   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8522                      Op0.getOperand(1));
8523 }
8524 
8525 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8526   const SDValue *InputLoad = &Op;
8527   if (InputLoad->getOpcode() == ISD::BITCAST)
8528     InputLoad = &InputLoad->getOperand(0);
8529   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8530     InputLoad = &InputLoad->getOperand(0);
8531   if (InputLoad->getOpcode() != ISD::LOAD)
8532     return nullptr;
8533   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8534   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8535 }
8536 
8537 // If this is a case we can't handle, return null and let the default
8538 // expansion code take care of it.  If we CAN select this case, and if it
8539 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8540 // this case more efficiently than a constant pool load, lower it to the
8541 // sequence of ops that should be used.
8542 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8543                                              SelectionDAG &DAG) const {
8544   SDLoc dl(Op);
8545   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8546   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8547 
8548   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8549     // We first build an i32 vector, load it into a QPX register,
8550     // then convert it to a floating-point vector and compare it
8551     // to a zero vector to get the boolean result.
8552     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8553     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8554     MachinePointerInfo PtrInfo =
8555         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8556     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8557     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8558 
8559     assert(BVN->getNumOperands() == 4 &&
8560       "BUILD_VECTOR for v4i1 does not have 4 operands");
8561 
8562     bool IsConst = true;
8563     for (unsigned i = 0; i < 4; ++i) {
8564       if (BVN->getOperand(i).isUndef()) continue;
8565       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8566         IsConst = false;
8567         break;
8568       }
8569     }
8570 
8571     if (IsConst) {
8572       Constant *One =
8573         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8574       Constant *NegOne =
8575         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8576 
8577       Constant *CV[4];
8578       for (unsigned i = 0; i < 4; ++i) {
8579         if (BVN->getOperand(i).isUndef())
8580           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8581         else if (isNullConstant(BVN->getOperand(i)))
8582           CV[i] = NegOne;
8583         else
8584           CV[i] = One;
8585       }
8586 
8587       Constant *CP = ConstantVector::get(CV);
8588       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8589                                           16 /* alignment */);
8590 
8591       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8592       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8593       return DAG.getMemIntrinsicNode(
8594           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8595           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8596     }
8597 
8598     SmallVector<SDValue, 4> Stores;
8599     for (unsigned i = 0; i < 4; ++i) {
8600       if (BVN->getOperand(i).isUndef()) continue;
8601 
8602       unsigned Offset = 4*i;
8603       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8604       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8605 
8606       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8607       if (StoreSize > 4) {
8608         Stores.push_back(
8609             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8610                               PtrInfo.getWithOffset(Offset), MVT::i32));
8611       } else {
8612         SDValue StoreValue = BVN->getOperand(i);
8613         if (StoreSize < 4)
8614           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8615 
8616         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8617                                       PtrInfo.getWithOffset(Offset)));
8618       }
8619     }
8620 
8621     SDValue StoreChain;
8622     if (!Stores.empty())
8623       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8624     else
8625       StoreChain = DAG.getEntryNode();
8626 
8627     // Now load from v4i32 into the QPX register; this will extend it to
8628     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8629     // is typed as v4f64 because the QPX register integer states are not
8630     // explicitly represented.
8631 
8632     SDValue Ops[] = {StoreChain,
8633                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8634                      FIdx};
8635     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8636 
8637     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8638       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8639     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8640       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8641       LoadedVect);
8642 
8643     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8644 
8645     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8646   }
8647 
8648   // All other QPX vectors are handled by generic code.
8649   if (Subtarget.hasQPX())
8650     return SDValue();
8651 
8652   // Check if this is a splat of a constant value.
8653   APInt APSplatBits, APSplatUndef;
8654   unsigned SplatBitSize;
8655   bool HasAnyUndefs;
8656   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8657                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8658       SplatBitSize > 32) {
8659 
8660     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8661     // Handle load-and-splat patterns as we have instructions that will do this
8662     // in one go.
8663     if (InputLoad && DAG.isSplatValue(Op, true)) {
8664       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8665 
8666       // We have handling for 4 and 8 byte elements.
8667       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8668 
8669       // Checking for a single use of this load, we have to check for vector
8670       // width (128 bits) / ElementSize uses (since each operand of the
8671       // BUILD_VECTOR is a separate use of the value.
8672       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8673           ((Subtarget.hasVSX() && ElementSize == 64) ||
8674            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8675         SDValue Ops[] = {
8676           LD->getChain(),    // Chain
8677           LD->getBasePtr(),  // Ptr
8678           DAG.getValueType(Op.getValueType()) // VT
8679         };
8680         return
8681           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8682                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8683                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8684       }
8685     }
8686 
8687     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8688     // lowered to VSX instructions under certain conditions.
8689     // Without VSX, there is no pattern more efficient than expanding the node.
8690     if (Subtarget.hasVSX() &&
8691         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8692                                         Subtarget.hasP8Vector()))
8693       return Op;
8694     return SDValue();
8695   }
8696 
8697   unsigned SplatBits = APSplatBits.getZExtValue();
8698   unsigned SplatUndef = APSplatUndef.getZExtValue();
8699   unsigned SplatSize = SplatBitSize / 8;
8700 
8701   // First, handle single instruction cases.
8702 
8703   // All zeros?
8704   if (SplatBits == 0) {
8705     // Canonicalize all zero vectors to be v4i32.
8706     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8707       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8708       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8709     }
8710     return Op;
8711   }
8712 
8713   // We have XXSPLTIB for constant splats one byte wide
8714   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8715   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8716   if (Subtarget.hasP9Vector() && SplatSize == 1)
8717     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8718 
8719   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8720   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8721                     (32-SplatBitSize));
8722   if (SextVal >= -16 && SextVal <= 15)
8723     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8724 
8725   // Two instruction sequences.
8726 
8727   // If this value is in the range [-32,30] and is even, use:
8728   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8729   // If this value is in the range [17,31] and is odd, use:
8730   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8731   // If this value is in the range [-31,-17] and is odd, use:
8732   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8733   // Note the last two are three-instruction sequences.
8734   if (SextVal >= -32 && SextVal <= 31) {
8735     // To avoid having these optimizations undone by constant folding,
8736     // we convert to a pseudo that will be expanded later into one of
8737     // the above forms.
8738     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8739     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8740               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8741     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8742     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8743     if (VT == Op.getValueType())
8744       return RetVal;
8745     else
8746       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8747   }
8748 
8749   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8750   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8751   // for fneg/fabs.
8752   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8753     // Make -1 and vspltisw -1:
8754     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8755 
8756     // Make the VSLW intrinsic, computing 0x8000_0000.
8757     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8758                                    OnesV, DAG, dl);
8759 
8760     // xor by OnesV to invert it.
8761     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8762     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8763   }
8764 
8765   // Check to see if this is a wide variety of vsplti*, binop self cases.
8766   static const signed char SplatCsts[] = {
8767     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8768     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8769   };
8770 
8771   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8772     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8773     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8774     int i = SplatCsts[idx];
8775 
8776     // Figure out what shift amount will be used by altivec if shifted by i in
8777     // this splat size.
8778     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8779 
8780     // vsplti + shl self.
8781     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8782       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8783       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8784         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8785         Intrinsic::ppc_altivec_vslw
8786       };
8787       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8788       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8789     }
8790 
8791     // vsplti + srl self.
8792     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8793       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8794       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8795         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8796         Intrinsic::ppc_altivec_vsrw
8797       };
8798       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8799       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8800     }
8801 
8802     // vsplti + sra self.
8803     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8804       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8805       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8806         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8807         Intrinsic::ppc_altivec_vsraw
8808       };
8809       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8810       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8811     }
8812 
8813     // vsplti + rol self.
8814     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8815                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8816       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8817       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8818         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8819         Intrinsic::ppc_altivec_vrlw
8820       };
8821       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8822       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8823     }
8824 
8825     // t = vsplti c, result = vsldoi t, t, 1
8826     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8827       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8828       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8829       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8830     }
8831     // t = vsplti c, result = vsldoi t, t, 2
8832     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8833       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8834       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8835       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8836     }
8837     // t = vsplti c, result = vsldoi t, t, 3
8838     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8839       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8840       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8841       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8842     }
8843   }
8844 
8845   return SDValue();
8846 }
8847 
8848 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8849 /// the specified operations to build the shuffle.
8850 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8851                                       SDValue RHS, SelectionDAG &DAG,
8852                                       const SDLoc &dl) {
8853   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8854   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8855   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8856 
8857   enum {
8858     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8859     OP_VMRGHW,
8860     OP_VMRGLW,
8861     OP_VSPLTISW0,
8862     OP_VSPLTISW1,
8863     OP_VSPLTISW2,
8864     OP_VSPLTISW3,
8865     OP_VSLDOI4,
8866     OP_VSLDOI8,
8867     OP_VSLDOI12
8868   };
8869 
8870   if (OpNum == OP_COPY) {
8871     if (LHSID == (1*9+2)*9+3) return LHS;
8872     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8873     return RHS;
8874   }
8875 
8876   SDValue OpLHS, OpRHS;
8877   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8878   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8879 
8880   int ShufIdxs[16];
8881   switch (OpNum) {
8882   default: llvm_unreachable("Unknown i32 permute!");
8883   case OP_VMRGHW:
8884     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8885     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8886     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8887     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8888     break;
8889   case OP_VMRGLW:
8890     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8891     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8892     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8893     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8894     break;
8895   case OP_VSPLTISW0:
8896     for (unsigned i = 0; i != 16; ++i)
8897       ShufIdxs[i] = (i&3)+0;
8898     break;
8899   case OP_VSPLTISW1:
8900     for (unsigned i = 0; i != 16; ++i)
8901       ShufIdxs[i] = (i&3)+4;
8902     break;
8903   case OP_VSPLTISW2:
8904     for (unsigned i = 0; i != 16; ++i)
8905       ShufIdxs[i] = (i&3)+8;
8906     break;
8907   case OP_VSPLTISW3:
8908     for (unsigned i = 0; i != 16; ++i)
8909       ShufIdxs[i] = (i&3)+12;
8910     break;
8911   case OP_VSLDOI4:
8912     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8913   case OP_VSLDOI8:
8914     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8915   case OP_VSLDOI12:
8916     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8917   }
8918   EVT VT = OpLHS.getValueType();
8919   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8920   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8921   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8922   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8923 }
8924 
8925 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8926 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8927 /// SDValue.
8928 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8929                                            SelectionDAG &DAG) const {
8930   const unsigned BytesInVector = 16;
8931   bool IsLE = Subtarget.isLittleEndian();
8932   SDLoc dl(N);
8933   SDValue V1 = N->getOperand(0);
8934   SDValue V2 = N->getOperand(1);
8935   unsigned ShiftElts = 0, InsertAtByte = 0;
8936   bool Swap = false;
8937 
8938   // Shifts required to get the byte we want at element 7.
8939   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8940                                    0, 15, 14, 13, 12, 11, 10, 9};
8941   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8942                                 1, 2,  3,  4,  5,  6,  7,  8};
8943 
8944   ArrayRef<int> Mask = N->getMask();
8945   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8946 
8947   // For each mask element, find out if we're just inserting something
8948   // from V2 into V1 or vice versa.
8949   // Possible permutations inserting an element from V2 into V1:
8950   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8951   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8952   //   ...
8953   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8954   // Inserting from V1 into V2 will be similar, except mask range will be
8955   // [16,31].
8956 
8957   bool FoundCandidate = false;
8958   // If both vector operands for the shuffle are the same vector, the mask
8959   // will contain only elements from the first one and the second one will be
8960   // undef.
8961   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8962   // Go through the mask of half-words to find an element that's being moved
8963   // from one vector to the other.
8964   for (unsigned i = 0; i < BytesInVector; ++i) {
8965     unsigned CurrentElement = Mask[i];
8966     // If 2nd operand is undefined, we should only look for element 7 in the
8967     // Mask.
8968     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8969       continue;
8970 
8971     bool OtherElementsInOrder = true;
8972     // Examine the other elements in the Mask to see if they're in original
8973     // order.
8974     for (unsigned j = 0; j < BytesInVector; ++j) {
8975       if (j == i)
8976         continue;
8977       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8978       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8979       // in which we always assume we're always picking from the 1st operand.
8980       int MaskOffset =
8981           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8982       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8983         OtherElementsInOrder = false;
8984         break;
8985       }
8986     }
8987     // If other elements are in original order, we record the number of shifts
8988     // we need to get the element we want into element 7. Also record which byte
8989     // in the vector we should insert into.
8990     if (OtherElementsInOrder) {
8991       // If 2nd operand is undefined, we assume no shifts and no swapping.
8992       if (V2.isUndef()) {
8993         ShiftElts = 0;
8994         Swap = false;
8995       } else {
8996         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8997         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8998                          : BigEndianShifts[CurrentElement & 0xF];
8999         Swap = CurrentElement < BytesInVector;
9000       }
9001       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
9002       FoundCandidate = true;
9003       break;
9004     }
9005   }
9006 
9007   if (!FoundCandidate)
9008     return SDValue();
9009 
9010   // Candidate found, construct the proper SDAG sequence with VINSERTB,
9011   // optionally with VECSHL if shift is required.
9012   if (Swap)
9013     std::swap(V1, V2);
9014   if (V2.isUndef())
9015     V2 = V1;
9016   if (ShiftElts) {
9017     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9018                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9019     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
9020                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9021   }
9022   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
9023                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
9024 }
9025 
9026 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
9027 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
9028 /// SDValue.
9029 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
9030                                            SelectionDAG &DAG) const {
9031   const unsigned NumHalfWords = 8;
9032   const unsigned BytesInVector = NumHalfWords * 2;
9033   // Check that the shuffle is on half-words.
9034   if (!isNByteElemShuffleMask(N, 2, 1))
9035     return SDValue();
9036 
9037   bool IsLE = Subtarget.isLittleEndian();
9038   SDLoc dl(N);
9039   SDValue V1 = N->getOperand(0);
9040   SDValue V2 = N->getOperand(1);
9041   unsigned ShiftElts = 0, InsertAtByte = 0;
9042   bool Swap = false;
9043 
9044   // Shifts required to get the half-word we want at element 3.
9045   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
9046   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
9047 
9048   uint32_t Mask = 0;
9049   uint32_t OriginalOrderLow = 0x1234567;
9050   uint32_t OriginalOrderHigh = 0x89ABCDEF;
9051   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
9052   // 32-bit space, only need 4-bit nibbles per element.
9053   for (unsigned i = 0; i < NumHalfWords; ++i) {
9054     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9055     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
9056   }
9057 
9058   // For each mask element, find out if we're just inserting something
9059   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9060   // from V2 into V1:
9061   //   X, 1, 2, 3, 4, 5, 6, 7
9062   //   0, X, 2, 3, 4, 5, 6, 7
9063   //   0, 1, X, 3, 4, 5, 6, 7
9064   //   0, 1, 2, X, 4, 5, 6, 7
9065   //   0, 1, 2, 3, X, 5, 6, 7
9066   //   0, 1, 2, 3, 4, X, 6, 7
9067   //   0, 1, 2, 3, 4, 5, X, 7
9068   //   0, 1, 2, 3, 4, 5, 6, X
9069   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9070 
9071   bool FoundCandidate = false;
9072   // Go through the mask of half-words to find an element that's being moved
9073   // from one vector to the other.
9074   for (unsigned i = 0; i < NumHalfWords; ++i) {
9075     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9076     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9077     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9078     uint32_t TargetOrder = 0x0;
9079 
9080     // If both vector operands for the shuffle are the same vector, the mask
9081     // will contain only elements from the first one and the second one will be
9082     // undef.
9083     if (V2.isUndef()) {
9084       ShiftElts = 0;
9085       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9086       TargetOrder = OriginalOrderLow;
9087       Swap = false;
9088       // Skip if not the correct element or mask of other elements don't equal
9089       // to our expected order.
9090       if (MaskOneElt == VINSERTHSrcElem &&
9091           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9092         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9093         FoundCandidate = true;
9094         break;
9095       }
9096     } else { // If both operands are defined.
9097       // Target order is [8,15] if the current mask is between [0,7].
9098       TargetOrder =
9099           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9100       // Skip if mask of other elements don't equal our expected order.
9101       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9102         // We only need the last 3 bits for the number of shifts.
9103         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9104                          : BigEndianShifts[MaskOneElt & 0x7];
9105         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9106         Swap = MaskOneElt < NumHalfWords;
9107         FoundCandidate = true;
9108         break;
9109       }
9110     }
9111   }
9112 
9113   if (!FoundCandidate)
9114     return SDValue();
9115 
9116   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9117   // optionally with VECSHL if shift is required.
9118   if (Swap)
9119     std::swap(V1, V2);
9120   if (V2.isUndef())
9121     V2 = V1;
9122   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9123   if (ShiftElts) {
9124     // Double ShiftElts because we're left shifting on v16i8 type.
9125     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9126                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9127     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9128     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9129                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9130     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9131   }
9132   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9133   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9134                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9135   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9136 }
9137 
9138 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9139 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9140 /// return the code it can be lowered into.  Worst case, it can always be
9141 /// lowered into a vperm.
9142 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9143                                                SelectionDAG &DAG) const {
9144   SDLoc dl(Op);
9145   SDValue V1 = Op.getOperand(0);
9146   SDValue V2 = Op.getOperand(1);
9147   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9148   EVT VT = Op.getValueType();
9149   bool isLittleEndian = Subtarget.isLittleEndian();
9150 
9151   unsigned ShiftElts, InsertAtByte;
9152   bool Swap = false;
9153 
9154   // If this is a load-and-splat, we can do that with a single instruction
9155   // in some cases. However if the load has multiple uses, we don't want to
9156   // combine it because that will just produce multiple loads.
9157   const SDValue *InputLoad = getNormalLoadInput(V1);
9158   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9159       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9160       InputLoad->hasOneUse()) {
9161     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9162     int SplatIdx =
9163       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9164 
9165     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9166     // For 4-byte load-and-splat, we need Power9.
9167     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9168       uint64_t Offset = 0;
9169       if (IsFourByte)
9170         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9171       else
9172         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9173       SDValue BasePtr = LD->getBasePtr();
9174       if (Offset != 0)
9175         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9176                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9177       SDValue Ops[] = {
9178         LD->getChain(),    // Chain
9179         BasePtr,           // BasePtr
9180         DAG.getValueType(Op.getValueType()) // VT
9181       };
9182       SDVTList VTL =
9183         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9184       SDValue LdSplt =
9185         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9186                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9187       if (LdSplt.getValueType() != SVOp->getValueType(0))
9188         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9189       return LdSplt;
9190     }
9191   }
9192   if (Subtarget.hasP9Vector() &&
9193       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9194                            isLittleEndian)) {
9195     if (Swap)
9196       std::swap(V1, V2);
9197     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9198     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9199     if (ShiftElts) {
9200       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9201                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9202       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9203                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9204       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9205     }
9206     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9207                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9208     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9209   }
9210 
9211   if (Subtarget.hasP9Altivec()) {
9212     SDValue NewISDNode;
9213     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9214       return NewISDNode;
9215 
9216     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9217       return NewISDNode;
9218   }
9219 
9220   if (Subtarget.hasVSX() &&
9221       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9222     if (Swap)
9223       std::swap(V1, V2);
9224     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9225     SDValue Conv2 =
9226         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9227 
9228     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9229                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9230     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9231   }
9232 
9233   if (Subtarget.hasVSX() &&
9234     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9235     if (Swap)
9236       std::swap(V1, V2);
9237     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9238     SDValue Conv2 =
9239         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9240 
9241     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9242                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9243     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9244   }
9245 
9246   if (Subtarget.hasP9Vector()) {
9247      if (PPC::isXXBRHShuffleMask(SVOp)) {
9248       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9249       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9250       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9251     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9252       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9253       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9254       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9255     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9256       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9257       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9258       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9259     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9260       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9261       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9262       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9263     }
9264   }
9265 
9266   if (Subtarget.hasVSX()) {
9267     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9268       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9269 
9270       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9271       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9272                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9273       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9274     }
9275 
9276     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9277     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9278       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9279       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9280       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9281     }
9282   }
9283 
9284   if (Subtarget.hasQPX()) {
9285     if (VT.getVectorNumElements() != 4)
9286       return SDValue();
9287 
9288     if (V2.isUndef()) V2 = V1;
9289 
9290     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9291     if (AlignIdx != -1) {
9292       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9293                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9294     } else if (SVOp->isSplat()) {
9295       int SplatIdx = SVOp->getSplatIndex();
9296       if (SplatIdx >= 4) {
9297         std::swap(V1, V2);
9298         SplatIdx -= 4;
9299       }
9300 
9301       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9302                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9303     }
9304 
9305     // Lower this into a qvgpci/qvfperm pair.
9306 
9307     // Compute the qvgpci literal
9308     unsigned idx = 0;
9309     for (unsigned i = 0; i < 4; ++i) {
9310       int m = SVOp->getMaskElt(i);
9311       unsigned mm = m >= 0 ? (unsigned) m : i;
9312       idx |= mm << (3-i)*3;
9313     }
9314 
9315     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9316                              DAG.getConstant(idx, dl, MVT::i32));
9317     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9318   }
9319 
9320   // Cases that are handled by instructions that take permute immediates
9321   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9322   // selected by the instruction selector.
9323   if (V2.isUndef()) {
9324     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9325         PPC::isSplatShuffleMask(SVOp, 2) ||
9326         PPC::isSplatShuffleMask(SVOp, 4) ||
9327         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9328         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9329         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9330         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9331         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9332         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9333         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9334         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9335         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9336         (Subtarget.hasP8Altivec() && (
9337          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9338          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9339          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9340       return Op;
9341     }
9342   }
9343 
9344   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9345   // and produce a fixed permutation.  If any of these match, do not lower to
9346   // VPERM.
9347   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9348   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9349       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9350       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9351       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9352       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9353       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9354       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9355       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9356       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9357       (Subtarget.hasP8Altivec() && (
9358        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9359        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9360        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9361     return Op;
9362 
9363   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9364   // perfect shuffle table to emit an optimal matching sequence.
9365   ArrayRef<int> PermMask = SVOp->getMask();
9366 
9367   unsigned PFIndexes[4];
9368   bool isFourElementShuffle = true;
9369   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9370     unsigned EltNo = 8;   // Start out undef.
9371     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9372       if (PermMask[i*4+j] < 0)
9373         continue;   // Undef, ignore it.
9374 
9375       unsigned ByteSource = PermMask[i*4+j];
9376       if ((ByteSource & 3) != j) {
9377         isFourElementShuffle = false;
9378         break;
9379       }
9380 
9381       if (EltNo == 8) {
9382         EltNo = ByteSource/4;
9383       } else if (EltNo != ByteSource/4) {
9384         isFourElementShuffle = false;
9385         break;
9386       }
9387     }
9388     PFIndexes[i] = EltNo;
9389   }
9390 
9391   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9392   // perfect shuffle vector to determine if it is cost effective to do this as
9393   // discrete instructions, or whether we should use a vperm.
9394   // For now, we skip this for little endian until such time as we have a
9395   // little-endian perfect shuffle table.
9396   if (isFourElementShuffle && !isLittleEndian) {
9397     // Compute the index in the perfect shuffle table.
9398     unsigned PFTableIndex =
9399       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9400 
9401     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9402     unsigned Cost  = (PFEntry >> 30);
9403 
9404     // Determining when to avoid vperm is tricky.  Many things affect the cost
9405     // of vperm, particularly how many times the perm mask needs to be computed.
9406     // For example, if the perm mask can be hoisted out of a loop or is already
9407     // used (perhaps because there are multiple permutes with the same shuffle
9408     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9409     // the loop requires an extra register.
9410     //
9411     // As a compromise, we only emit discrete instructions if the shuffle can be
9412     // generated in 3 or fewer operations.  When we have loop information
9413     // available, if this block is within a loop, we should avoid using vperm
9414     // for 3-operation perms and use a constant pool load instead.
9415     if (Cost < 3)
9416       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9417   }
9418 
9419   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9420   // vector that will get spilled to the constant pool.
9421   if (V2.isUndef()) V2 = V1;
9422 
9423   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9424   // that it is in input element units, not in bytes.  Convert now.
9425 
9426   // For little endian, the order of the input vectors is reversed, and
9427   // the permutation mask is complemented with respect to 31.  This is
9428   // necessary to produce proper semantics with the big-endian-biased vperm
9429   // instruction.
9430   EVT EltVT = V1.getValueType().getVectorElementType();
9431   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9432 
9433   SmallVector<SDValue, 16> ResultMask;
9434   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9435     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9436 
9437     for (unsigned j = 0; j != BytesPerElement; ++j)
9438       if (isLittleEndian)
9439         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9440                                              dl, MVT::i32));
9441       else
9442         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9443                                              MVT::i32));
9444   }
9445 
9446   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9447   if (isLittleEndian)
9448     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9449                        V2, V1, VPermMask);
9450   else
9451     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9452                        V1, V2, VPermMask);
9453 }
9454 
9455 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9456 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9457 /// information about the intrinsic.
9458 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9459                                  bool &isDot, const PPCSubtarget &Subtarget) {
9460   unsigned IntrinsicID =
9461       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9462   CompareOpc = -1;
9463   isDot = false;
9464   switch (IntrinsicID) {
9465   default:
9466     return false;
9467   // Comparison predicates.
9468   case Intrinsic::ppc_altivec_vcmpbfp_p:
9469     CompareOpc = 966;
9470     isDot = true;
9471     break;
9472   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9473     CompareOpc = 198;
9474     isDot = true;
9475     break;
9476   case Intrinsic::ppc_altivec_vcmpequb_p:
9477     CompareOpc = 6;
9478     isDot = true;
9479     break;
9480   case Intrinsic::ppc_altivec_vcmpequh_p:
9481     CompareOpc = 70;
9482     isDot = true;
9483     break;
9484   case Intrinsic::ppc_altivec_vcmpequw_p:
9485     CompareOpc = 134;
9486     isDot = true;
9487     break;
9488   case Intrinsic::ppc_altivec_vcmpequd_p:
9489     if (Subtarget.hasP8Altivec()) {
9490       CompareOpc = 199;
9491       isDot = true;
9492     } else
9493       return false;
9494     break;
9495   case Intrinsic::ppc_altivec_vcmpneb_p:
9496   case Intrinsic::ppc_altivec_vcmpneh_p:
9497   case Intrinsic::ppc_altivec_vcmpnew_p:
9498   case Intrinsic::ppc_altivec_vcmpnezb_p:
9499   case Intrinsic::ppc_altivec_vcmpnezh_p:
9500   case Intrinsic::ppc_altivec_vcmpnezw_p:
9501     if (Subtarget.hasP9Altivec()) {
9502       switch (IntrinsicID) {
9503       default:
9504         llvm_unreachable("Unknown comparison intrinsic.");
9505       case Intrinsic::ppc_altivec_vcmpneb_p:
9506         CompareOpc = 7;
9507         break;
9508       case Intrinsic::ppc_altivec_vcmpneh_p:
9509         CompareOpc = 71;
9510         break;
9511       case Intrinsic::ppc_altivec_vcmpnew_p:
9512         CompareOpc = 135;
9513         break;
9514       case Intrinsic::ppc_altivec_vcmpnezb_p:
9515         CompareOpc = 263;
9516         break;
9517       case Intrinsic::ppc_altivec_vcmpnezh_p:
9518         CompareOpc = 327;
9519         break;
9520       case Intrinsic::ppc_altivec_vcmpnezw_p:
9521         CompareOpc = 391;
9522         break;
9523       }
9524       isDot = true;
9525     } else
9526       return false;
9527     break;
9528   case Intrinsic::ppc_altivec_vcmpgefp_p:
9529     CompareOpc = 454;
9530     isDot = true;
9531     break;
9532   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9533     CompareOpc = 710;
9534     isDot = true;
9535     break;
9536   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9537     CompareOpc = 774;
9538     isDot = true;
9539     break;
9540   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9541     CompareOpc = 838;
9542     isDot = true;
9543     break;
9544   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9545     CompareOpc = 902;
9546     isDot = true;
9547     break;
9548   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9549     if (Subtarget.hasP8Altivec()) {
9550       CompareOpc = 967;
9551       isDot = true;
9552     } else
9553       return false;
9554     break;
9555   case Intrinsic::ppc_altivec_vcmpgtub_p:
9556     CompareOpc = 518;
9557     isDot = true;
9558     break;
9559   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9560     CompareOpc = 582;
9561     isDot = true;
9562     break;
9563   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9564     CompareOpc = 646;
9565     isDot = true;
9566     break;
9567   case Intrinsic::ppc_altivec_vcmpgtud_p:
9568     if (Subtarget.hasP8Altivec()) {
9569       CompareOpc = 711;
9570       isDot = true;
9571     } else
9572       return false;
9573     break;
9574 
9575   // VSX predicate comparisons use the same infrastructure
9576   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9577   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9578   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9579   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9580   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9581   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9582     if (Subtarget.hasVSX()) {
9583       switch (IntrinsicID) {
9584       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9585         CompareOpc = 99;
9586         break;
9587       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9588         CompareOpc = 115;
9589         break;
9590       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9591         CompareOpc = 107;
9592         break;
9593       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9594         CompareOpc = 67;
9595         break;
9596       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9597         CompareOpc = 83;
9598         break;
9599       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9600         CompareOpc = 75;
9601         break;
9602       }
9603       isDot = true;
9604     } else
9605       return false;
9606     break;
9607 
9608   // Normal Comparisons.
9609   case Intrinsic::ppc_altivec_vcmpbfp:
9610     CompareOpc = 966;
9611     break;
9612   case Intrinsic::ppc_altivec_vcmpeqfp:
9613     CompareOpc = 198;
9614     break;
9615   case Intrinsic::ppc_altivec_vcmpequb:
9616     CompareOpc = 6;
9617     break;
9618   case Intrinsic::ppc_altivec_vcmpequh:
9619     CompareOpc = 70;
9620     break;
9621   case Intrinsic::ppc_altivec_vcmpequw:
9622     CompareOpc = 134;
9623     break;
9624   case Intrinsic::ppc_altivec_vcmpequd:
9625     if (Subtarget.hasP8Altivec())
9626       CompareOpc = 199;
9627     else
9628       return false;
9629     break;
9630   case Intrinsic::ppc_altivec_vcmpneb:
9631   case Intrinsic::ppc_altivec_vcmpneh:
9632   case Intrinsic::ppc_altivec_vcmpnew:
9633   case Intrinsic::ppc_altivec_vcmpnezb:
9634   case Intrinsic::ppc_altivec_vcmpnezh:
9635   case Intrinsic::ppc_altivec_vcmpnezw:
9636     if (Subtarget.hasP9Altivec())
9637       switch (IntrinsicID) {
9638       default:
9639         llvm_unreachable("Unknown comparison intrinsic.");
9640       case Intrinsic::ppc_altivec_vcmpneb:
9641         CompareOpc = 7;
9642         break;
9643       case Intrinsic::ppc_altivec_vcmpneh:
9644         CompareOpc = 71;
9645         break;
9646       case Intrinsic::ppc_altivec_vcmpnew:
9647         CompareOpc = 135;
9648         break;
9649       case Intrinsic::ppc_altivec_vcmpnezb:
9650         CompareOpc = 263;
9651         break;
9652       case Intrinsic::ppc_altivec_vcmpnezh:
9653         CompareOpc = 327;
9654         break;
9655       case Intrinsic::ppc_altivec_vcmpnezw:
9656         CompareOpc = 391;
9657         break;
9658       }
9659     else
9660       return false;
9661     break;
9662   case Intrinsic::ppc_altivec_vcmpgefp:
9663     CompareOpc = 454;
9664     break;
9665   case Intrinsic::ppc_altivec_vcmpgtfp:
9666     CompareOpc = 710;
9667     break;
9668   case Intrinsic::ppc_altivec_vcmpgtsb:
9669     CompareOpc = 774;
9670     break;
9671   case Intrinsic::ppc_altivec_vcmpgtsh:
9672     CompareOpc = 838;
9673     break;
9674   case Intrinsic::ppc_altivec_vcmpgtsw:
9675     CompareOpc = 902;
9676     break;
9677   case Intrinsic::ppc_altivec_vcmpgtsd:
9678     if (Subtarget.hasP8Altivec())
9679       CompareOpc = 967;
9680     else
9681       return false;
9682     break;
9683   case Intrinsic::ppc_altivec_vcmpgtub:
9684     CompareOpc = 518;
9685     break;
9686   case Intrinsic::ppc_altivec_vcmpgtuh:
9687     CompareOpc = 582;
9688     break;
9689   case Intrinsic::ppc_altivec_vcmpgtuw:
9690     CompareOpc = 646;
9691     break;
9692   case Intrinsic::ppc_altivec_vcmpgtud:
9693     if (Subtarget.hasP8Altivec())
9694       CompareOpc = 711;
9695     else
9696       return false;
9697     break;
9698   }
9699   return true;
9700 }
9701 
9702 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9703 /// lower, do it, otherwise return null.
9704 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9705                                                    SelectionDAG &DAG) const {
9706   unsigned IntrinsicID =
9707     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9708 
9709   SDLoc dl(Op);
9710 
9711   if (IntrinsicID == Intrinsic::thread_pointer) {
9712     // Reads the thread pointer register, used for __builtin_thread_pointer.
9713     if (Subtarget.isPPC64())
9714       return DAG.getRegister(PPC::X13, MVT::i64);
9715     return DAG.getRegister(PPC::R2, MVT::i32);
9716   }
9717 
9718   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9719   // opcode number of the comparison.
9720   int CompareOpc;
9721   bool isDot;
9722   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9723     return SDValue();    // Don't custom lower most intrinsics.
9724 
9725   // If this is a non-dot comparison, make the VCMP node and we are done.
9726   if (!isDot) {
9727     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9728                               Op.getOperand(1), Op.getOperand(2),
9729                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9730     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9731   }
9732 
9733   // Create the PPCISD altivec 'dot' comparison node.
9734   SDValue Ops[] = {
9735     Op.getOperand(2),  // LHS
9736     Op.getOperand(3),  // RHS
9737     DAG.getConstant(CompareOpc, dl, MVT::i32)
9738   };
9739   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9740   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9741 
9742   // Now that we have the comparison, emit a copy from the CR to a GPR.
9743   // This is flagged to the above dot comparison.
9744   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9745                                 DAG.getRegister(PPC::CR6, MVT::i32),
9746                                 CompNode.getValue(1));
9747 
9748   // Unpack the result based on how the target uses it.
9749   unsigned BitNo;   // Bit # of CR6.
9750   bool InvertBit;   // Invert result?
9751   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9752   default:  // Can't happen, don't crash on invalid number though.
9753   case 0:   // Return the value of the EQ bit of CR6.
9754     BitNo = 0; InvertBit = false;
9755     break;
9756   case 1:   // Return the inverted value of the EQ bit of CR6.
9757     BitNo = 0; InvertBit = true;
9758     break;
9759   case 2:   // Return the value of the LT bit of CR6.
9760     BitNo = 2; InvertBit = false;
9761     break;
9762   case 3:   // Return the inverted value of the LT bit of CR6.
9763     BitNo = 2; InvertBit = true;
9764     break;
9765   }
9766 
9767   // Shift the bit into the low position.
9768   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9769                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9770   // Isolate the bit.
9771   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9772                       DAG.getConstant(1, dl, MVT::i32));
9773 
9774   // If we are supposed to, toggle the bit.
9775   if (InvertBit)
9776     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9777                         DAG.getConstant(1, dl, MVT::i32));
9778   return Flags;
9779 }
9780 
9781 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9782                                                SelectionDAG &DAG) const {
9783   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9784   // the beginning of the argument list.
9785   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9786   SDLoc DL(Op);
9787   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9788   case Intrinsic::ppc_cfence: {
9789     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9790     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9791     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9792                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9793                                                   Op.getOperand(ArgStart + 1)),
9794                                       Op.getOperand(0)),
9795                    0);
9796   }
9797   default:
9798     break;
9799   }
9800   return SDValue();
9801 }
9802 
9803 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9804   // Check for a DIV with the same operands as this REM.
9805   for (auto UI : Op.getOperand(1)->uses()) {
9806     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9807         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9808       if (UI->getOperand(0) == Op.getOperand(0) &&
9809           UI->getOperand(1) == Op.getOperand(1))
9810         return SDValue();
9811   }
9812   return Op;
9813 }
9814 
9815 // Lower scalar BSWAP64 to xxbrd.
9816 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9817   SDLoc dl(Op);
9818   // MTVSRDD
9819   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9820                    Op.getOperand(0));
9821   // XXBRD
9822   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9823   // MFVSRD
9824   int VectorIndex = 0;
9825   if (Subtarget.isLittleEndian())
9826     VectorIndex = 1;
9827   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9828                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9829   return Op;
9830 }
9831 
9832 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9833 // compared to a value that is atomically loaded (atomic loads zero-extend).
9834 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9835                                                 SelectionDAG &DAG) const {
9836   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9837          "Expecting an atomic compare-and-swap here.");
9838   SDLoc dl(Op);
9839   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9840   EVT MemVT = AtomicNode->getMemoryVT();
9841   if (MemVT.getSizeInBits() >= 32)
9842     return Op;
9843 
9844   SDValue CmpOp = Op.getOperand(2);
9845   // If this is already correctly zero-extended, leave it alone.
9846   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9847   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9848     return Op;
9849 
9850   // Clear the high bits of the compare operand.
9851   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9852   SDValue NewCmpOp =
9853     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9854                 DAG.getConstant(MaskVal, dl, MVT::i32));
9855 
9856   // Replace the existing compare operand with the properly zero-extended one.
9857   SmallVector<SDValue, 4> Ops;
9858   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9859     Ops.push_back(AtomicNode->getOperand(i));
9860   Ops[2] = NewCmpOp;
9861   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9862   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9863   auto NodeTy =
9864     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9865   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9866 }
9867 
9868 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9869                                                  SelectionDAG &DAG) const {
9870   SDLoc dl(Op);
9871   // Create a stack slot that is 16-byte aligned.
9872   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9873   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9874   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9875   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9876 
9877   // Store the input value into Value#0 of the stack slot.
9878   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9879                                MachinePointerInfo());
9880   // Load it out.
9881   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9882 }
9883 
9884 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9885                                                   SelectionDAG &DAG) const {
9886   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9887          "Should only be called for ISD::INSERT_VECTOR_ELT");
9888 
9889   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9890   // We have legal lowering for constant indices but not for variable ones.
9891   if (!C)
9892     return SDValue();
9893 
9894   EVT VT = Op.getValueType();
9895   SDLoc dl(Op);
9896   SDValue V1 = Op.getOperand(0);
9897   SDValue V2 = Op.getOperand(1);
9898   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9899   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9900     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9901     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9902     unsigned InsertAtElement = C->getZExtValue();
9903     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9904     if (Subtarget.isLittleEndian()) {
9905       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9906     }
9907     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9908                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9909   }
9910   return Op;
9911 }
9912 
9913 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9914                                                    SelectionDAG &DAG) const {
9915   SDLoc dl(Op);
9916   SDNode *N = Op.getNode();
9917 
9918   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9919          "Unknown extract_vector_elt type");
9920 
9921   SDValue Value = N->getOperand(0);
9922 
9923   // The first part of this is like the store lowering except that we don't
9924   // need to track the chain.
9925 
9926   // The values are now known to be -1 (false) or 1 (true). To convert this
9927   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9928   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9929   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9930 
9931   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9932   // understand how to form the extending load.
9933   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9934 
9935   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9936 
9937   // Now convert to an integer and store.
9938   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9939     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9940     Value);
9941 
9942   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9943   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9944   MachinePointerInfo PtrInfo =
9945       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9946   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9947   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9948 
9949   SDValue StoreChain = DAG.getEntryNode();
9950   SDValue Ops[] = {StoreChain,
9951                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9952                    Value, FIdx};
9953   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9954 
9955   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9956     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9957 
9958   // Extract the value requested.
9959   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9960   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9961   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9962 
9963   SDValue IntVal =
9964       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9965 
9966   if (!Subtarget.useCRBits())
9967     return IntVal;
9968 
9969   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9970 }
9971 
9972 /// Lowering for QPX v4i1 loads
9973 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9974                                            SelectionDAG &DAG) const {
9975   SDLoc dl(Op);
9976   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9977   SDValue LoadChain = LN->getChain();
9978   SDValue BasePtr = LN->getBasePtr();
9979 
9980   if (Op.getValueType() == MVT::v4f64 ||
9981       Op.getValueType() == MVT::v4f32) {
9982     EVT MemVT = LN->getMemoryVT();
9983     unsigned Alignment = LN->getAlignment();
9984 
9985     // If this load is properly aligned, then it is legal.
9986     if (Alignment >= MemVT.getStoreSize())
9987       return Op;
9988 
9989     EVT ScalarVT = Op.getValueType().getScalarType(),
9990         ScalarMemVT = MemVT.getScalarType();
9991     unsigned Stride = ScalarMemVT.getStoreSize();
9992 
9993     SDValue Vals[4], LoadChains[4];
9994     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9995       SDValue Load;
9996       if (ScalarVT != ScalarMemVT)
9997         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9998                               BasePtr,
9999                               LN->getPointerInfo().getWithOffset(Idx * Stride),
10000                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10001                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
10002       else
10003         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
10004                            LN->getPointerInfo().getWithOffset(Idx * Stride),
10005                            MinAlign(Alignment, Idx * Stride),
10006                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
10007 
10008       if (Idx == 0 && LN->isIndexed()) {
10009         assert(LN->getAddressingMode() == ISD::PRE_INC &&
10010                "Unknown addressing mode on vector load");
10011         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
10012                                   LN->getAddressingMode());
10013       }
10014 
10015       Vals[Idx] = Load;
10016       LoadChains[Idx] = Load.getValue(1);
10017 
10018       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10019                             DAG.getConstant(Stride, dl,
10020                                             BasePtr.getValueType()));
10021     }
10022 
10023     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10024     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
10025 
10026     if (LN->isIndexed()) {
10027       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
10028       return DAG.getMergeValues(RetOps, dl);
10029     }
10030 
10031     SDValue RetOps[] = { Value, TF };
10032     return DAG.getMergeValues(RetOps, dl);
10033   }
10034 
10035   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
10036   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
10037 
10038   // To lower v4i1 from a byte array, we load the byte elements of the
10039   // vector and then reuse the BUILD_VECTOR logic.
10040 
10041   SDValue VectElmts[4], VectElmtChains[4];
10042   for (unsigned i = 0; i < 4; ++i) {
10043     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10044     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10045 
10046     VectElmts[i] = DAG.getExtLoad(
10047         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
10048         LN->getPointerInfo().getWithOffset(i), MVT::i8,
10049         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
10050     VectElmtChains[i] = VectElmts[i].getValue(1);
10051   }
10052 
10053   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
10054   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
10055 
10056   SDValue RVals[] = { Value, LoadChain };
10057   return DAG.getMergeValues(RVals, dl);
10058 }
10059 
10060 /// Lowering for QPX v4i1 stores
10061 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10062                                             SelectionDAG &DAG) const {
10063   SDLoc dl(Op);
10064   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10065   SDValue StoreChain = SN->getChain();
10066   SDValue BasePtr = SN->getBasePtr();
10067   SDValue Value = SN->getValue();
10068 
10069   if (Value.getValueType() == MVT::v4f64 ||
10070       Value.getValueType() == MVT::v4f32) {
10071     EVT MemVT = SN->getMemoryVT();
10072     unsigned Alignment = SN->getAlignment();
10073 
10074     // If this store is properly aligned, then it is legal.
10075     if (Alignment >= MemVT.getStoreSize())
10076       return Op;
10077 
10078     EVT ScalarVT = Value.getValueType().getScalarType(),
10079         ScalarMemVT = MemVT.getScalarType();
10080     unsigned Stride = ScalarMemVT.getStoreSize();
10081 
10082     SDValue Stores[4];
10083     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10084       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10085                                DAG.getVectorIdxConstant(Idx, dl));
10086       SDValue Store;
10087       if (ScalarVT != ScalarMemVT)
10088         Store =
10089             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10090                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10091                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10092                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10093       else
10094         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10095                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10096                              MinAlign(Alignment, Idx * Stride),
10097                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10098 
10099       if (Idx == 0 && SN->isIndexed()) {
10100         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10101                "Unknown addressing mode on vector store");
10102         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10103                                     SN->getAddressingMode());
10104       }
10105 
10106       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10107                             DAG.getConstant(Stride, dl,
10108                                             BasePtr.getValueType()));
10109       Stores[Idx] = Store;
10110     }
10111 
10112     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10113 
10114     if (SN->isIndexed()) {
10115       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10116       return DAG.getMergeValues(RetOps, dl);
10117     }
10118 
10119     return TF;
10120   }
10121 
10122   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10123   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10124 
10125   // The values are now known to be -1 (false) or 1 (true). To convert this
10126   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10127   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10128   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10129 
10130   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10131   // understand how to form the extending load.
10132   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10133 
10134   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10135 
10136   // Now convert to an integer and store.
10137   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10138     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10139     Value);
10140 
10141   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10142   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10143   MachinePointerInfo PtrInfo =
10144       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10145   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10146   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10147 
10148   SDValue Ops[] = {StoreChain,
10149                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10150                    Value, FIdx};
10151   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10152 
10153   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10154     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10155 
10156   // Move data into the byte array.
10157   SDValue Loads[4], LoadChains[4];
10158   for (unsigned i = 0; i < 4; ++i) {
10159     unsigned Offset = 4*i;
10160     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10161     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10162 
10163     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10164                            PtrInfo.getWithOffset(Offset));
10165     LoadChains[i] = Loads[i].getValue(1);
10166   }
10167 
10168   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10169 
10170   SDValue Stores[4];
10171   for (unsigned i = 0; i < 4; ++i) {
10172     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10173     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10174 
10175     Stores[i] = DAG.getTruncStore(
10176         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10177         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10178         SN->getAAInfo());
10179   }
10180 
10181   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10182 
10183   return StoreChain;
10184 }
10185 
10186 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10187   SDLoc dl(Op);
10188   if (Op.getValueType() == MVT::v4i32) {
10189     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10190 
10191     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10192     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10193 
10194     SDValue RHSSwap =   // = vrlw RHS, 16
10195       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10196 
10197     // Shrinkify inputs to v8i16.
10198     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10199     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10200     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10201 
10202     // Low parts multiplied together, generating 32-bit results (we ignore the
10203     // top parts).
10204     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10205                                         LHS, RHS, DAG, dl, MVT::v4i32);
10206 
10207     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10208                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10209     // Shift the high parts up 16 bits.
10210     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10211                               Neg16, DAG, dl);
10212     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10213   } else if (Op.getValueType() == MVT::v8i16) {
10214     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10215 
10216     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10217 
10218     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10219                             LHS, RHS, Zero, DAG, dl);
10220   } else if (Op.getValueType() == MVT::v16i8) {
10221     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10222     bool isLittleEndian = Subtarget.isLittleEndian();
10223 
10224     // Multiply the even 8-bit parts, producing 16-bit sums.
10225     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10226                                            LHS, RHS, DAG, dl, MVT::v8i16);
10227     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10228 
10229     // Multiply the odd 8-bit parts, producing 16-bit sums.
10230     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10231                                           LHS, RHS, DAG, dl, MVT::v8i16);
10232     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10233 
10234     // Merge the results together.  Because vmuleub and vmuloub are
10235     // instructions with a big-endian bias, we must reverse the
10236     // element numbering and reverse the meaning of "odd" and "even"
10237     // when generating little endian code.
10238     int Ops[16];
10239     for (unsigned i = 0; i != 8; ++i) {
10240       if (isLittleEndian) {
10241         Ops[i*2  ] = 2*i;
10242         Ops[i*2+1] = 2*i+16;
10243       } else {
10244         Ops[i*2  ] = 2*i+1;
10245         Ops[i*2+1] = 2*i+1+16;
10246       }
10247     }
10248     if (isLittleEndian)
10249       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10250     else
10251       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10252   } else {
10253     llvm_unreachable("Unknown mul to lower!");
10254   }
10255 }
10256 
10257 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10258 
10259   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10260 
10261   EVT VT = Op.getValueType();
10262   assert(VT.isVector() &&
10263          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10264   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10265           VT == MVT::v16i8) &&
10266          "Unexpected vector element type!");
10267   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10268          "Current subtarget doesn't support smax v2i64!");
10269 
10270   // For vector abs, it can be lowered to:
10271   // abs x
10272   // ==>
10273   // y = -x
10274   // smax(x, y)
10275 
10276   SDLoc dl(Op);
10277   SDValue X = Op.getOperand(0);
10278   SDValue Zero = DAG.getConstant(0, dl, VT);
10279   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10280 
10281   // SMAX patch https://reviews.llvm.org/D47332
10282   // hasn't landed yet, so use intrinsic first here.
10283   // TODO: Should use SMAX directly once SMAX patch landed
10284   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10285   if (VT == MVT::v2i64)
10286     BifID = Intrinsic::ppc_altivec_vmaxsd;
10287   else if (VT == MVT::v8i16)
10288     BifID = Intrinsic::ppc_altivec_vmaxsh;
10289   else if (VT == MVT::v16i8)
10290     BifID = Intrinsic::ppc_altivec_vmaxsb;
10291 
10292   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10293 }
10294 
10295 // Custom lowering for fpext vf32 to v2f64
10296 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10297 
10298   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10299          "Should only be called for ISD::FP_EXTEND");
10300 
10301   // We only want to custom lower an extend from v2f32 to v2f64.
10302   if (Op.getValueType() != MVT::v2f64 ||
10303       Op.getOperand(0).getValueType() != MVT::v2f32)
10304     return SDValue();
10305 
10306   SDLoc dl(Op);
10307   SDValue Op0 = Op.getOperand(0);
10308 
10309   switch (Op0.getOpcode()) {
10310   default:
10311     return SDValue();
10312   case ISD::EXTRACT_SUBVECTOR: {
10313     assert(Op0.getNumOperands() == 2 &&
10314            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10315            "Node should have 2 operands with second one being a constant!");
10316 
10317     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10318       return SDValue();
10319 
10320     // Custom lower is only done for high or low doubleword.
10321     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10322     if (Idx % 2 != 0)
10323       return SDValue();
10324 
10325     // Since input is v4f32, at this point Idx is either 0 or 2.
10326     // Shift to get the doubleword position we want.
10327     int DWord = Idx >> 1;
10328 
10329     // High and low word positions are different on little endian.
10330     if (Subtarget.isLittleEndian())
10331       DWord ^= 0x1;
10332 
10333     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10334                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10335   }
10336   case ISD::FADD:
10337   case ISD::FMUL:
10338   case ISD::FSUB: {
10339     SDValue NewLoad[2];
10340     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10341       // Ensure both input are loads.
10342       SDValue LdOp = Op0.getOperand(i);
10343       if (LdOp.getOpcode() != ISD::LOAD)
10344         return SDValue();
10345       // Generate new load node.
10346       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10347       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10348       NewLoad[i] = DAG.getMemIntrinsicNode(
10349           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10350           LD->getMemoryVT(), LD->getMemOperand());
10351     }
10352     SDValue NewOp =
10353         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10354                     NewLoad[1], Op0.getNode()->getFlags());
10355     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10356                        DAG.getConstant(0, dl, MVT::i32));
10357   }
10358   case ISD::LOAD: {
10359     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10360     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10361     SDValue NewLd = DAG.getMemIntrinsicNode(
10362         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10363         LD->getMemoryVT(), LD->getMemOperand());
10364     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10365                        DAG.getConstant(0, dl, MVT::i32));
10366   }
10367   }
10368   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10369 }
10370 
10371 /// LowerOperation - Provide custom lowering hooks for some operations.
10372 ///
10373 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10374   switch (Op.getOpcode()) {
10375   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10376   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10377   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10378   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10379   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10380   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10381   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10382   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10383   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10384 
10385   // Variable argument lowering.
10386   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10387   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10388   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10389 
10390   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10391   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10392   case ISD::GET_DYNAMIC_AREA_OFFSET:
10393     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10394 
10395   // Exception handling lowering.
10396   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10397   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10398   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10399 
10400   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10401   case ISD::STORE:              return LowerSTORE(Op, DAG);
10402   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10403   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10404   case ISD::FP_TO_UINT:
10405   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10406   case ISD::UINT_TO_FP:
10407   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10408   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10409 
10410   // Lower 64-bit shifts.
10411   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10412   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10413   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10414 
10415   // Vector-related lowering.
10416   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10417   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10418   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10419   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10420   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10421   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10422   case ISD::MUL:                return LowerMUL(Op, DAG);
10423   case ISD::ABS:                return LowerABS(Op, DAG);
10424   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10425 
10426   // For counter-based loop handling.
10427   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10428 
10429   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10430 
10431   // Frame & Return address.
10432   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10433   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10434 
10435   case ISD::INTRINSIC_VOID:
10436     return LowerINTRINSIC_VOID(Op, DAG);
10437   case ISD::SREM:
10438   case ISD::UREM:
10439     return LowerREM(Op, DAG);
10440   case ISD::BSWAP:
10441     return LowerBSWAP(Op, DAG);
10442   case ISD::ATOMIC_CMP_SWAP:
10443     return LowerATOMIC_CMP_SWAP(Op, DAG);
10444   }
10445 }
10446 
10447 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10448                                            SmallVectorImpl<SDValue>&Results,
10449                                            SelectionDAG &DAG) const {
10450   SDLoc dl(N);
10451   switch (N->getOpcode()) {
10452   default:
10453     llvm_unreachable("Do not know how to custom type legalize this operation!");
10454   case ISD::READCYCLECOUNTER: {
10455     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10456     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10457 
10458     Results.push_back(RTB);
10459     Results.push_back(RTB.getValue(1));
10460     Results.push_back(RTB.getValue(2));
10461     break;
10462   }
10463   case ISD::INTRINSIC_W_CHAIN: {
10464     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10465         Intrinsic::loop_decrement)
10466       break;
10467 
10468     assert(N->getValueType(0) == MVT::i1 &&
10469            "Unexpected result type for CTR decrement intrinsic");
10470     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10471                                  N->getValueType(0));
10472     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10473     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10474                                  N->getOperand(1));
10475 
10476     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10477     Results.push_back(NewInt.getValue(1));
10478     break;
10479   }
10480   case ISD::VAARG: {
10481     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10482       return;
10483 
10484     EVT VT = N->getValueType(0);
10485 
10486     if (VT == MVT::i64) {
10487       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10488 
10489       Results.push_back(NewNode);
10490       Results.push_back(NewNode.getValue(1));
10491     }
10492     return;
10493   }
10494   case ISD::FP_TO_SINT:
10495   case ISD::FP_TO_UINT:
10496     // LowerFP_TO_INT() can only handle f32 and f64.
10497     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10498       return;
10499     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10500     return;
10501   case ISD::TRUNCATE: {
10502     EVT TrgVT = N->getValueType(0);
10503     EVT OpVT = N->getOperand(0).getValueType();
10504     if (TrgVT.isVector() &&
10505         isOperationCustom(N->getOpcode(), TrgVT) &&
10506         OpVT.getSizeInBits() <= 128 &&
10507         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10508       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10509     return;
10510   }
10511   case ISD::BITCAST:
10512     // Don't handle bitcast here.
10513     return;
10514   }
10515 }
10516 
10517 //===----------------------------------------------------------------------===//
10518 //  Other Lowering Code
10519 //===----------------------------------------------------------------------===//
10520 
10521 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10522   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10523   Function *Func = Intrinsic::getDeclaration(M, Id);
10524   return Builder.CreateCall(Func, {});
10525 }
10526 
10527 // The mappings for emitLeading/TrailingFence is taken from
10528 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10529 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10530                                                  Instruction *Inst,
10531                                                  AtomicOrdering Ord) const {
10532   if (Ord == AtomicOrdering::SequentiallyConsistent)
10533     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10534   if (isReleaseOrStronger(Ord))
10535     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10536   return nullptr;
10537 }
10538 
10539 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10540                                                   Instruction *Inst,
10541                                                   AtomicOrdering Ord) const {
10542   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10543     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10544     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10545     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10546     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10547       return Builder.CreateCall(
10548           Intrinsic::getDeclaration(
10549               Builder.GetInsertBlock()->getParent()->getParent(),
10550               Intrinsic::ppc_cfence, {Inst->getType()}),
10551           {Inst});
10552     // FIXME: Can use isync for rmw operation.
10553     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10554   }
10555   return nullptr;
10556 }
10557 
10558 MachineBasicBlock *
10559 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10560                                     unsigned AtomicSize,
10561                                     unsigned BinOpcode,
10562                                     unsigned CmpOpcode,
10563                                     unsigned CmpPred) const {
10564   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10565   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10566 
10567   auto LoadMnemonic = PPC::LDARX;
10568   auto StoreMnemonic = PPC::STDCX;
10569   switch (AtomicSize) {
10570   default:
10571     llvm_unreachable("Unexpected size of atomic entity");
10572   case 1:
10573     LoadMnemonic = PPC::LBARX;
10574     StoreMnemonic = PPC::STBCX;
10575     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10576     break;
10577   case 2:
10578     LoadMnemonic = PPC::LHARX;
10579     StoreMnemonic = PPC::STHCX;
10580     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10581     break;
10582   case 4:
10583     LoadMnemonic = PPC::LWARX;
10584     StoreMnemonic = PPC::STWCX;
10585     break;
10586   case 8:
10587     LoadMnemonic = PPC::LDARX;
10588     StoreMnemonic = PPC::STDCX;
10589     break;
10590   }
10591 
10592   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10593   MachineFunction *F = BB->getParent();
10594   MachineFunction::iterator It = ++BB->getIterator();
10595 
10596   Register dest = MI.getOperand(0).getReg();
10597   Register ptrA = MI.getOperand(1).getReg();
10598   Register ptrB = MI.getOperand(2).getReg();
10599   Register incr = MI.getOperand(3).getReg();
10600   DebugLoc dl = MI.getDebugLoc();
10601 
10602   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10603   MachineBasicBlock *loop2MBB =
10604     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10605   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10606   F->insert(It, loopMBB);
10607   if (CmpOpcode)
10608     F->insert(It, loop2MBB);
10609   F->insert(It, exitMBB);
10610   exitMBB->splice(exitMBB->begin(), BB,
10611                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10612   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10613 
10614   MachineRegisterInfo &RegInfo = F->getRegInfo();
10615   Register TmpReg = (!BinOpcode) ? incr :
10616     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10617                                            : &PPC::GPRCRegClass);
10618 
10619   //  thisMBB:
10620   //   ...
10621   //   fallthrough --> loopMBB
10622   BB->addSuccessor(loopMBB);
10623 
10624   //  loopMBB:
10625   //   l[wd]arx dest, ptr
10626   //   add r0, dest, incr
10627   //   st[wd]cx. r0, ptr
10628   //   bne- loopMBB
10629   //   fallthrough --> exitMBB
10630 
10631   // For max/min...
10632   //  loopMBB:
10633   //   l[wd]arx dest, ptr
10634   //   cmpl?[wd] incr, dest
10635   //   bgt exitMBB
10636   //  loop2MBB:
10637   //   st[wd]cx. dest, ptr
10638   //   bne- loopMBB
10639   //   fallthrough --> exitMBB
10640 
10641   BB = loopMBB;
10642   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10643     .addReg(ptrA).addReg(ptrB);
10644   if (BinOpcode)
10645     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10646   if (CmpOpcode) {
10647     // Signed comparisons of byte or halfword values must be sign-extended.
10648     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10649       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10650       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10651               ExtReg).addReg(dest);
10652       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10653         .addReg(incr).addReg(ExtReg);
10654     } else
10655       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10656         .addReg(incr).addReg(dest);
10657 
10658     BuildMI(BB, dl, TII->get(PPC::BCC))
10659       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10660     BB->addSuccessor(loop2MBB);
10661     BB->addSuccessor(exitMBB);
10662     BB = loop2MBB;
10663   }
10664   BuildMI(BB, dl, TII->get(StoreMnemonic))
10665     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10666   BuildMI(BB, dl, TII->get(PPC::BCC))
10667     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10668   BB->addSuccessor(loopMBB);
10669   BB->addSuccessor(exitMBB);
10670 
10671   //  exitMBB:
10672   //   ...
10673   BB = exitMBB;
10674   return BB;
10675 }
10676 
10677 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10678     MachineInstr &MI, MachineBasicBlock *BB,
10679     bool is8bit, // operation
10680     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10681   // If we support part-word atomic mnemonics, just use them
10682   if (Subtarget.hasPartwordAtomics())
10683     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10684                             CmpPred);
10685 
10686   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10687   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10688   // In 64 bit mode we have to use 64 bits for addresses, even though the
10689   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10690   // registers without caring whether they're 32 or 64, but here we're
10691   // doing actual arithmetic on the addresses.
10692   bool is64bit = Subtarget.isPPC64();
10693   bool isLittleEndian = Subtarget.isLittleEndian();
10694   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10695 
10696   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10697   MachineFunction *F = BB->getParent();
10698   MachineFunction::iterator It = ++BB->getIterator();
10699 
10700   Register dest = MI.getOperand(0).getReg();
10701   Register ptrA = MI.getOperand(1).getReg();
10702   Register ptrB = MI.getOperand(2).getReg();
10703   Register incr = MI.getOperand(3).getReg();
10704   DebugLoc dl = MI.getDebugLoc();
10705 
10706   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10707   MachineBasicBlock *loop2MBB =
10708       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10709   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10710   F->insert(It, loopMBB);
10711   if (CmpOpcode)
10712     F->insert(It, loop2MBB);
10713   F->insert(It, exitMBB);
10714   exitMBB->splice(exitMBB->begin(), BB,
10715                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10716   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10717 
10718   MachineRegisterInfo &RegInfo = F->getRegInfo();
10719   const TargetRegisterClass *RC =
10720       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10721   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10722 
10723   Register PtrReg = RegInfo.createVirtualRegister(RC);
10724   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10725   Register ShiftReg =
10726       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10727   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10728   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10729   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10730   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10731   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10732   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10733   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10734   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10735   Register Ptr1Reg;
10736   Register TmpReg =
10737       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10738 
10739   //  thisMBB:
10740   //   ...
10741   //   fallthrough --> loopMBB
10742   BB->addSuccessor(loopMBB);
10743 
10744   // The 4-byte load must be aligned, while a char or short may be
10745   // anywhere in the word.  Hence all this nasty bookkeeping code.
10746   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10747   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10748   //   xori shift, shift1, 24 [16]
10749   //   rlwinm ptr, ptr1, 0, 0, 29
10750   //   slw incr2, incr, shift
10751   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10752   //   slw mask, mask2, shift
10753   //  loopMBB:
10754   //   lwarx tmpDest, ptr
10755   //   add tmp, tmpDest, incr2
10756   //   andc tmp2, tmpDest, mask
10757   //   and tmp3, tmp, mask
10758   //   or tmp4, tmp3, tmp2
10759   //   stwcx. tmp4, ptr
10760   //   bne- loopMBB
10761   //   fallthrough --> exitMBB
10762   //   srw dest, tmpDest, shift
10763   if (ptrA != ZeroReg) {
10764     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10765     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10766         .addReg(ptrA)
10767         .addReg(ptrB);
10768   } else {
10769     Ptr1Reg = ptrB;
10770   }
10771   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10772   // mode.
10773   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10774       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10775       .addImm(3)
10776       .addImm(27)
10777       .addImm(is8bit ? 28 : 27);
10778   if (!isLittleEndian)
10779     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10780         .addReg(Shift1Reg)
10781         .addImm(is8bit ? 24 : 16);
10782   if (is64bit)
10783     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10784         .addReg(Ptr1Reg)
10785         .addImm(0)
10786         .addImm(61);
10787   else
10788     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10789         .addReg(Ptr1Reg)
10790         .addImm(0)
10791         .addImm(0)
10792         .addImm(29);
10793   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10794   if (is8bit)
10795     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10796   else {
10797     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10798     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10799         .addReg(Mask3Reg)
10800         .addImm(65535);
10801   }
10802   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10803       .addReg(Mask2Reg)
10804       .addReg(ShiftReg);
10805 
10806   BB = loopMBB;
10807   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10808       .addReg(ZeroReg)
10809       .addReg(PtrReg);
10810   if (BinOpcode)
10811     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10812         .addReg(Incr2Reg)
10813         .addReg(TmpDestReg);
10814   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10815       .addReg(TmpDestReg)
10816       .addReg(MaskReg);
10817   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10818   if (CmpOpcode) {
10819     // For unsigned comparisons, we can directly compare the shifted values.
10820     // For signed comparisons we shift and sign extend.
10821     Register SReg = RegInfo.createVirtualRegister(GPRC);
10822     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10823         .addReg(TmpDestReg)
10824         .addReg(MaskReg);
10825     unsigned ValueReg = SReg;
10826     unsigned CmpReg = Incr2Reg;
10827     if (CmpOpcode == PPC::CMPW) {
10828       ValueReg = RegInfo.createVirtualRegister(GPRC);
10829       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10830           .addReg(SReg)
10831           .addReg(ShiftReg);
10832       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10833       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10834           .addReg(ValueReg);
10835       ValueReg = ValueSReg;
10836       CmpReg = incr;
10837     }
10838     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10839         .addReg(CmpReg)
10840         .addReg(ValueReg);
10841     BuildMI(BB, dl, TII->get(PPC::BCC))
10842         .addImm(CmpPred)
10843         .addReg(PPC::CR0)
10844         .addMBB(exitMBB);
10845     BB->addSuccessor(loop2MBB);
10846     BB->addSuccessor(exitMBB);
10847     BB = loop2MBB;
10848   }
10849   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10850   BuildMI(BB, dl, TII->get(PPC::STWCX))
10851       .addReg(Tmp4Reg)
10852       .addReg(ZeroReg)
10853       .addReg(PtrReg);
10854   BuildMI(BB, dl, TII->get(PPC::BCC))
10855       .addImm(PPC::PRED_NE)
10856       .addReg(PPC::CR0)
10857       .addMBB(loopMBB);
10858   BB->addSuccessor(loopMBB);
10859   BB->addSuccessor(exitMBB);
10860 
10861   //  exitMBB:
10862   //   ...
10863   BB = exitMBB;
10864   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10865       .addReg(TmpDestReg)
10866       .addReg(ShiftReg);
10867   return BB;
10868 }
10869 
10870 llvm::MachineBasicBlock *
10871 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10872                                     MachineBasicBlock *MBB) const {
10873   DebugLoc DL = MI.getDebugLoc();
10874   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10875   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10876 
10877   MachineFunction *MF = MBB->getParent();
10878   MachineRegisterInfo &MRI = MF->getRegInfo();
10879 
10880   const BasicBlock *BB = MBB->getBasicBlock();
10881   MachineFunction::iterator I = ++MBB->getIterator();
10882 
10883   Register DstReg = MI.getOperand(0).getReg();
10884   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10885   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10886   Register mainDstReg = MRI.createVirtualRegister(RC);
10887   Register restoreDstReg = MRI.createVirtualRegister(RC);
10888 
10889   MVT PVT = getPointerTy(MF->getDataLayout());
10890   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10891          "Invalid Pointer Size!");
10892   // For v = setjmp(buf), we generate
10893   //
10894   // thisMBB:
10895   //  SjLjSetup mainMBB
10896   //  bl mainMBB
10897   //  v_restore = 1
10898   //  b sinkMBB
10899   //
10900   // mainMBB:
10901   //  buf[LabelOffset] = LR
10902   //  v_main = 0
10903   //
10904   // sinkMBB:
10905   //  v = phi(main, restore)
10906   //
10907 
10908   MachineBasicBlock *thisMBB = MBB;
10909   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10910   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10911   MF->insert(I, mainMBB);
10912   MF->insert(I, sinkMBB);
10913 
10914   MachineInstrBuilder MIB;
10915 
10916   // Transfer the remainder of BB and its successor edges to sinkMBB.
10917   sinkMBB->splice(sinkMBB->begin(), MBB,
10918                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10919   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10920 
10921   // Note that the structure of the jmp_buf used here is not compatible
10922   // with that used by libc, and is not designed to be. Specifically, it
10923   // stores only those 'reserved' registers that LLVM does not otherwise
10924   // understand how to spill. Also, by convention, by the time this
10925   // intrinsic is called, Clang has already stored the frame address in the
10926   // first slot of the buffer and stack address in the third. Following the
10927   // X86 target code, we'll store the jump address in the second slot. We also
10928   // need to save the TOC pointer (R2) to handle jumps between shared
10929   // libraries, and that will be stored in the fourth slot. The thread
10930   // identifier (R13) is not affected.
10931 
10932   // thisMBB:
10933   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10934   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10935   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10936 
10937   // Prepare IP either in reg.
10938   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10939   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10940   Register BufReg = MI.getOperand(1).getReg();
10941 
10942   if (Subtarget.is64BitELFABI()) {
10943     setUsesTOCBasePtr(*MBB->getParent());
10944     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10945               .addReg(PPC::X2)
10946               .addImm(TOCOffset)
10947               .addReg(BufReg)
10948               .cloneMemRefs(MI);
10949   }
10950 
10951   // Naked functions never have a base pointer, and so we use r1. For all
10952   // other functions, this decision must be delayed until during PEI.
10953   unsigned BaseReg;
10954   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10955     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10956   else
10957     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10958 
10959   MIB = BuildMI(*thisMBB, MI, DL,
10960                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10961             .addReg(BaseReg)
10962             .addImm(BPOffset)
10963             .addReg(BufReg)
10964             .cloneMemRefs(MI);
10965 
10966   // Setup
10967   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10968   MIB.addRegMask(TRI->getNoPreservedMask());
10969 
10970   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10971 
10972   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10973           .addMBB(mainMBB);
10974   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10975 
10976   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10977   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10978 
10979   // mainMBB:
10980   //  mainDstReg = 0
10981   MIB =
10982       BuildMI(mainMBB, DL,
10983               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10984 
10985   // Store IP
10986   if (Subtarget.isPPC64()) {
10987     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10988             .addReg(LabelReg)
10989             .addImm(LabelOffset)
10990             .addReg(BufReg);
10991   } else {
10992     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10993             .addReg(LabelReg)
10994             .addImm(LabelOffset)
10995             .addReg(BufReg);
10996   }
10997   MIB.cloneMemRefs(MI);
10998 
10999   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
11000   mainMBB->addSuccessor(sinkMBB);
11001 
11002   // sinkMBB:
11003   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
11004           TII->get(PPC::PHI), DstReg)
11005     .addReg(mainDstReg).addMBB(mainMBB)
11006     .addReg(restoreDstReg).addMBB(thisMBB);
11007 
11008   MI.eraseFromParent();
11009   return sinkMBB;
11010 }
11011 
11012 MachineBasicBlock *
11013 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
11014                                      MachineBasicBlock *MBB) const {
11015   DebugLoc DL = MI.getDebugLoc();
11016   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11017 
11018   MachineFunction *MF = MBB->getParent();
11019   MachineRegisterInfo &MRI = MF->getRegInfo();
11020 
11021   MVT PVT = getPointerTy(MF->getDataLayout());
11022   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
11023          "Invalid Pointer Size!");
11024 
11025   const TargetRegisterClass *RC =
11026     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11027   Register Tmp = MRI.createVirtualRegister(RC);
11028   // Since FP is only updated here but NOT referenced, it's treated as GPR.
11029   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
11030   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
11031   unsigned BP =
11032       (PVT == MVT::i64)
11033           ? PPC::X30
11034           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
11035                                                               : PPC::R30);
11036 
11037   MachineInstrBuilder MIB;
11038 
11039   const int64_t LabelOffset = 1 * PVT.getStoreSize();
11040   const int64_t SPOffset    = 2 * PVT.getStoreSize();
11041   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
11042   const int64_t BPOffset    = 4 * PVT.getStoreSize();
11043 
11044   Register BufReg = MI.getOperand(0).getReg();
11045 
11046   // Reload FP (the jumped-to function may not have had a
11047   // frame pointer, and if so, then its r31 will be restored
11048   // as necessary).
11049   if (PVT == MVT::i64) {
11050     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
11051             .addImm(0)
11052             .addReg(BufReg);
11053   } else {
11054     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
11055             .addImm(0)
11056             .addReg(BufReg);
11057   }
11058   MIB.cloneMemRefs(MI);
11059 
11060   // Reload IP
11061   if (PVT == MVT::i64) {
11062     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11063             .addImm(LabelOffset)
11064             .addReg(BufReg);
11065   } else {
11066     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11067             .addImm(LabelOffset)
11068             .addReg(BufReg);
11069   }
11070   MIB.cloneMemRefs(MI);
11071 
11072   // Reload SP
11073   if (PVT == MVT::i64) {
11074     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11075             .addImm(SPOffset)
11076             .addReg(BufReg);
11077   } else {
11078     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11079             .addImm(SPOffset)
11080             .addReg(BufReg);
11081   }
11082   MIB.cloneMemRefs(MI);
11083 
11084   // Reload BP
11085   if (PVT == MVT::i64) {
11086     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11087             .addImm(BPOffset)
11088             .addReg(BufReg);
11089   } else {
11090     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11091             .addImm(BPOffset)
11092             .addReg(BufReg);
11093   }
11094   MIB.cloneMemRefs(MI);
11095 
11096   // Reload TOC
11097   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11098     setUsesTOCBasePtr(*MBB->getParent());
11099     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11100               .addImm(TOCOffset)
11101               .addReg(BufReg)
11102               .cloneMemRefs(MI);
11103   }
11104 
11105   // Jump
11106   BuildMI(*MBB, MI, DL,
11107           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11108   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11109 
11110   MI.eraseFromParent();
11111   return MBB;
11112 }
11113 
11114 MachineBasicBlock *
11115 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11116                                                MachineBasicBlock *BB) const {
11117   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11118       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11119     if (Subtarget.is64BitELFABI() &&
11120         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11121       // Call lowering should have added an r2 operand to indicate a dependence
11122       // on the TOC base pointer value. It can't however, because there is no
11123       // way to mark the dependence as implicit there, and so the stackmap code
11124       // will confuse it with a regular operand. Instead, add the dependence
11125       // here.
11126       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11127     }
11128 
11129     return emitPatchPoint(MI, BB);
11130   }
11131 
11132   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11133       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11134     return emitEHSjLjSetJmp(MI, BB);
11135   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11136              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11137     return emitEHSjLjLongJmp(MI, BB);
11138   }
11139 
11140   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11141 
11142   // To "insert" these instructions we actually have to insert their
11143   // control-flow patterns.
11144   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11145   MachineFunction::iterator It = ++BB->getIterator();
11146 
11147   MachineFunction *F = BB->getParent();
11148 
11149   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11150       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11151       MI.getOpcode() == PPC::SELECT_I8) {
11152     SmallVector<MachineOperand, 2> Cond;
11153     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11154         MI.getOpcode() == PPC::SELECT_CC_I8)
11155       Cond.push_back(MI.getOperand(4));
11156     else
11157       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11158     Cond.push_back(MI.getOperand(1));
11159 
11160     DebugLoc dl = MI.getDebugLoc();
11161     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11162                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11163   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11164              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11165              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11166              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11167              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11168              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11169              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11170              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11171              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11172              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11173              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11174              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11175              MI.getOpcode() == PPC::SELECT_F4 ||
11176              MI.getOpcode() == PPC::SELECT_F8 ||
11177              MI.getOpcode() == PPC::SELECT_F16 ||
11178              MI.getOpcode() == PPC::SELECT_QFRC ||
11179              MI.getOpcode() == PPC::SELECT_QSRC ||
11180              MI.getOpcode() == PPC::SELECT_QBRC ||
11181              MI.getOpcode() == PPC::SELECT_SPE ||
11182              MI.getOpcode() == PPC::SELECT_SPE4 ||
11183              MI.getOpcode() == PPC::SELECT_VRRC ||
11184              MI.getOpcode() == PPC::SELECT_VSFRC ||
11185              MI.getOpcode() == PPC::SELECT_VSSRC ||
11186              MI.getOpcode() == PPC::SELECT_VSRC) {
11187     // The incoming instruction knows the destination vreg to set, the
11188     // condition code register to branch on, the true/false values to
11189     // select between, and a branch opcode to use.
11190 
11191     //  thisMBB:
11192     //  ...
11193     //   TrueVal = ...
11194     //   cmpTY ccX, r1, r2
11195     //   bCC copy1MBB
11196     //   fallthrough --> copy0MBB
11197     MachineBasicBlock *thisMBB = BB;
11198     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11199     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11200     DebugLoc dl = MI.getDebugLoc();
11201     F->insert(It, copy0MBB);
11202     F->insert(It, sinkMBB);
11203 
11204     // Transfer the remainder of BB and its successor edges to sinkMBB.
11205     sinkMBB->splice(sinkMBB->begin(), BB,
11206                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11207     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11208 
11209     // Next, add the true and fallthrough blocks as its successors.
11210     BB->addSuccessor(copy0MBB);
11211     BB->addSuccessor(sinkMBB);
11212 
11213     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11214         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11215         MI.getOpcode() == PPC::SELECT_F16 ||
11216         MI.getOpcode() == PPC::SELECT_SPE4 ||
11217         MI.getOpcode() == PPC::SELECT_SPE ||
11218         MI.getOpcode() == PPC::SELECT_QFRC ||
11219         MI.getOpcode() == PPC::SELECT_QSRC ||
11220         MI.getOpcode() == PPC::SELECT_QBRC ||
11221         MI.getOpcode() == PPC::SELECT_VRRC ||
11222         MI.getOpcode() == PPC::SELECT_VSFRC ||
11223         MI.getOpcode() == PPC::SELECT_VSSRC ||
11224         MI.getOpcode() == PPC::SELECT_VSRC) {
11225       BuildMI(BB, dl, TII->get(PPC::BC))
11226           .addReg(MI.getOperand(1).getReg())
11227           .addMBB(sinkMBB);
11228     } else {
11229       unsigned SelectPred = MI.getOperand(4).getImm();
11230       BuildMI(BB, dl, TII->get(PPC::BCC))
11231           .addImm(SelectPred)
11232           .addReg(MI.getOperand(1).getReg())
11233           .addMBB(sinkMBB);
11234     }
11235 
11236     //  copy0MBB:
11237     //   %FalseValue = ...
11238     //   # fallthrough to sinkMBB
11239     BB = copy0MBB;
11240 
11241     // Update machine-CFG edges
11242     BB->addSuccessor(sinkMBB);
11243 
11244     //  sinkMBB:
11245     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11246     //  ...
11247     BB = sinkMBB;
11248     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11249         .addReg(MI.getOperand(3).getReg())
11250         .addMBB(copy0MBB)
11251         .addReg(MI.getOperand(2).getReg())
11252         .addMBB(thisMBB);
11253   } else if (MI.getOpcode() == PPC::ReadTB) {
11254     // To read the 64-bit time-base register on a 32-bit target, we read the
11255     // two halves. Should the counter have wrapped while it was being read, we
11256     // need to try again.
11257     // ...
11258     // readLoop:
11259     // mfspr Rx,TBU # load from TBU
11260     // mfspr Ry,TB  # load from TB
11261     // mfspr Rz,TBU # load from TBU
11262     // cmpw crX,Rx,Rz # check if 'old'='new'
11263     // bne readLoop   # branch if they're not equal
11264     // ...
11265 
11266     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11267     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11268     DebugLoc dl = MI.getDebugLoc();
11269     F->insert(It, readMBB);
11270     F->insert(It, sinkMBB);
11271 
11272     // Transfer the remainder of BB and its successor edges to sinkMBB.
11273     sinkMBB->splice(sinkMBB->begin(), BB,
11274                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11275     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11276 
11277     BB->addSuccessor(readMBB);
11278     BB = readMBB;
11279 
11280     MachineRegisterInfo &RegInfo = F->getRegInfo();
11281     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11282     Register LoReg = MI.getOperand(0).getReg();
11283     Register HiReg = MI.getOperand(1).getReg();
11284 
11285     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11286     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11287     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11288 
11289     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11290 
11291     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11292         .addReg(HiReg)
11293         .addReg(ReadAgainReg);
11294     BuildMI(BB, dl, TII->get(PPC::BCC))
11295         .addImm(PPC::PRED_NE)
11296         .addReg(CmpReg)
11297         .addMBB(readMBB);
11298 
11299     BB->addSuccessor(readMBB);
11300     BB->addSuccessor(sinkMBB);
11301   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11302     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11304     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11305   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11306     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11308     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11309 
11310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11311     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11313     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11314   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11315     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11317     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11318 
11319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11320     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11322     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11323   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11324     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11326     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11327 
11328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11329     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11331     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11332   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11333     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11334   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11335     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11336 
11337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11338     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11339   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11340     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11341   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11342     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11343   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11344     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11345 
11346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11347     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11348   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11349     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11350   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11351     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11352   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11353     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11354 
11355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11356     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11357   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11358     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11359   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11360     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11361   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11362     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11363 
11364   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11365     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11366   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11367     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11368   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11369     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11370   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11371     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11372 
11373   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11374     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11375   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11376     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11377   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11378     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11379   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11380     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11381 
11382   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11383     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11384   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11385     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11386   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11387     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11388   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11389     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11390 
11391   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11392     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11393   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11394     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11395   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11396     BB = EmitAtomicBinary(MI, BB, 4, 0);
11397   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11398     BB = EmitAtomicBinary(MI, BB, 8, 0);
11399   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11400            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11401            (Subtarget.hasPartwordAtomics() &&
11402             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11403            (Subtarget.hasPartwordAtomics() &&
11404             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11405     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11406 
11407     auto LoadMnemonic = PPC::LDARX;
11408     auto StoreMnemonic = PPC::STDCX;
11409     switch (MI.getOpcode()) {
11410     default:
11411       llvm_unreachable("Compare and swap of unknown size");
11412     case PPC::ATOMIC_CMP_SWAP_I8:
11413       LoadMnemonic = PPC::LBARX;
11414       StoreMnemonic = PPC::STBCX;
11415       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11416       break;
11417     case PPC::ATOMIC_CMP_SWAP_I16:
11418       LoadMnemonic = PPC::LHARX;
11419       StoreMnemonic = PPC::STHCX;
11420       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11421       break;
11422     case PPC::ATOMIC_CMP_SWAP_I32:
11423       LoadMnemonic = PPC::LWARX;
11424       StoreMnemonic = PPC::STWCX;
11425       break;
11426     case PPC::ATOMIC_CMP_SWAP_I64:
11427       LoadMnemonic = PPC::LDARX;
11428       StoreMnemonic = PPC::STDCX;
11429       break;
11430     }
11431     Register dest = MI.getOperand(0).getReg();
11432     Register ptrA = MI.getOperand(1).getReg();
11433     Register ptrB = MI.getOperand(2).getReg();
11434     Register oldval = MI.getOperand(3).getReg();
11435     Register newval = MI.getOperand(4).getReg();
11436     DebugLoc dl = MI.getDebugLoc();
11437 
11438     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11439     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11440     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11441     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11442     F->insert(It, loop1MBB);
11443     F->insert(It, loop2MBB);
11444     F->insert(It, midMBB);
11445     F->insert(It, exitMBB);
11446     exitMBB->splice(exitMBB->begin(), BB,
11447                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11448     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11449 
11450     //  thisMBB:
11451     //   ...
11452     //   fallthrough --> loopMBB
11453     BB->addSuccessor(loop1MBB);
11454 
11455     // loop1MBB:
11456     //   l[bhwd]arx dest, ptr
11457     //   cmp[wd] dest, oldval
11458     //   bne- midMBB
11459     // loop2MBB:
11460     //   st[bhwd]cx. newval, ptr
11461     //   bne- loopMBB
11462     //   b exitBB
11463     // midMBB:
11464     //   st[bhwd]cx. dest, ptr
11465     // exitBB:
11466     BB = loop1MBB;
11467     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11468     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11469         .addReg(oldval)
11470         .addReg(dest);
11471     BuildMI(BB, dl, TII->get(PPC::BCC))
11472         .addImm(PPC::PRED_NE)
11473         .addReg(PPC::CR0)
11474         .addMBB(midMBB);
11475     BB->addSuccessor(loop2MBB);
11476     BB->addSuccessor(midMBB);
11477 
11478     BB = loop2MBB;
11479     BuildMI(BB, dl, TII->get(StoreMnemonic))
11480         .addReg(newval)
11481         .addReg(ptrA)
11482         .addReg(ptrB);
11483     BuildMI(BB, dl, TII->get(PPC::BCC))
11484         .addImm(PPC::PRED_NE)
11485         .addReg(PPC::CR0)
11486         .addMBB(loop1MBB);
11487     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11488     BB->addSuccessor(loop1MBB);
11489     BB->addSuccessor(exitMBB);
11490 
11491     BB = midMBB;
11492     BuildMI(BB, dl, TII->get(StoreMnemonic))
11493         .addReg(dest)
11494         .addReg(ptrA)
11495         .addReg(ptrB);
11496     BB->addSuccessor(exitMBB);
11497 
11498     //  exitMBB:
11499     //   ...
11500     BB = exitMBB;
11501   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11502              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11503     // We must use 64-bit registers for addresses when targeting 64-bit,
11504     // since we're actually doing arithmetic on them.  Other registers
11505     // can be 32-bit.
11506     bool is64bit = Subtarget.isPPC64();
11507     bool isLittleEndian = Subtarget.isLittleEndian();
11508     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11509 
11510     Register dest = MI.getOperand(0).getReg();
11511     Register ptrA = MI.getOperand(1).getReg();
11512     Register ptrB = MI.getOperand(2).getReg();
11513     Register oldval = MI.getOperand(3).getReg();
11514     Register newval = MI.getOperand(4).getReg();
11515     DebugLoc dl = MI.getDebugLoc();
11516 
11517     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11518     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11519     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11520     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11521     F->insert(It, loop1MBB);
11522     F->insert(It, loop2MBB);
11523     F->insert(It, midMBB);
11524     F->insert(It, exitMBB);
11525     exitMBB->splice(exitMBB->begin(), BB,
11526                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11527     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11528 
11529     MachineRegisterInfo &RegInfo = F->getRegInfo();
11530     const TargetRegisterClass *RC =
11531         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11532     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11533 
11534     Register PtrReg = RegInfo.createVirtualRegister(RC);
11535     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11536     Register ShiftReg =
11537         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11538     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11539     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11540     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11541     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11542     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11543     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11544     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11545     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11546     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11547     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11548     Register Ptr1Reg;
11549     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11550     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11551     //  thisMBB:
11552     //   ...
11553     //   fallthrough --> loopMBB
11554     BB->addSuccessor(loop1MBB);
11555 
11556     // The 4-byte load must be aligned, while a char or short may be
11557     // anywhere in the word.  Hence all this nasty bookkeeping code.
11558     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11559     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11560     //   xori shift, shift1, 24 [16]
11561     //   rlwinm ptr, ptr1, 0, 0, 29
11562     //   slw newval2, newval, shift
11563     //   slw oldval2, oldval,shift
11564     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11565     //   slw mask, mask2, shift
11566     //   and newval3, newval2, mask
11567     //   and oldval3, oldval2, mask
11568     // loop1MBB:
11569     //   lwarx tmpDest, ptr
11570     //   and tmp, tmpDest, mask
11571     //   cmpw tmp, oldval3
11572     //   bne- midMBB
11573     // loop2MBB:
11574     //   andc tmp2, tmpDest, mask
11575     //   or tmp4, tmp2, newval3
11576     //   stwcx. tmp4, ptr
11577     //   bne- loop1MBB
11578     //   b exitBB
11579     // midMBB:
11580     //   stwcx. tmpDest, ptr
11581     // exitBB:
11582     //   srw dest, tmpDest, shift
11583     if (ptrA != ZeroReg) {
11584       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11585       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11586           .addReg(ptrA)
11587           .addReg(ptrB);
11588     } else {
11589       Ptr1Reg = ptrB;
11590     }
11591 
11592     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11593     // mode.
11594     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11595         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11596         .addImm(3)
11597         .addImm(27)
11598         .addImm(is8bit ? 28 : 27);
11599     if (!isLittleEndian)
11600       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11601           .addReg(Shift1Reg)
11602           .addImm(is8bit ? 24 : 16);
11603     if (is64bit)
11604       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11605           .addReg(Ptr1Reg)
11606           .addImm(0)
11607           .addImm(61);
11608     else
11609       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11610           .addReg(Ptr1Reg)
11611           .addImm(0)
11612           .addImm(0)
11613           .addImm(29);
11614     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11615         .addReg(newval)
11616         .addReg(ShiftReg);
11617     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11618         .addReg(oldval)
11619         .addReg(ShiftReg);
11620     if (is8bit)
11621       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11622     else {
11623       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11624       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11625           .addReg(Mask3Reg)
11626           .addImm(65535);
11627     }
11628     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11629         .addReg(Mask2Reg)
11630         .addReg(ShiftReg);
11631     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11632         .addReg(NewVal2Reg)
11633         .addReg(MaskReg);
11634     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11635         .addReg(OldVal2Reg)
11636         .addReg(MaskReg);
11637 
11638     BB = loop1MBB;
11639     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11640         .addReg(ZeroReg)
11641         .addReg(PtrReg);
11642     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11643         .addReg(TmpDestReg)
11644         .addReg(MaskReg);
11645     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11646         .addReg(TmpReg)
11647         .addReg(OldVal3Reg);
11648     BuildMI(BB, dl, TII->get(PPC::BCC))
11649         .addImm(PPC::PRED_NE)
11650         .addReg(PPC::CR0)
11651         .addMBB(midMBB);
11652     BB->addSuccessor(loop2MBB);
11653     BB->addSuccessor(midMBB);
11654 
11655     BB = loop2MBB;
11656     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11657         .addReg(TmpDestReg)
11658         .addReg(MaskReg);
11659     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11660         .addReg(Tmp2Reg)
11661         .addReg(NewVal3Reg);
11662     BuildMI(BB, dl, TII->get(PPC::STWCX))
11663         .addReg(Tmp4Reg)
11664         .addReg(ZeroReg)
11665         .addReg(PtrReg);
11666     BuildMI(BB, dl, TII->get(PPC::BCC))
11667         .addImm(PPC::PRED_NE)
11668         .addReg(PPC::CR0)
11669         .addMBB(loop1MBB);
11670     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11671     BB->addSuccessor(loop1MBB);
11672     BB->addSuccessor(exitMBB);
11673 
11674     BB = midMBB;
11675     BuildMI(BB, dl, TII->get(PPC::STWCX))
11676         .addReg(TmpDestReg)
11677         .addReg(ZeroReg)
11678         .addReg(PtrReg);
11679     BB->addSuccessor(exitMBB);
11680 
11681     //  exitMBB:
11682     //   ...
11683     BB = exitMBB;
11684     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11685         .addReg(TmpReg)
11686         .addReg(ShiftReg);
11687   } else if (MI.getOpcode() == PPC::FADDrtz) {
11688     // This pseudo performs an FADD with rounding mode temporarily forced
11689     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11690     // is not modeled at the SelectionDAG level.
11691     Register Dest = MI.getOperand(0).getReg();
11692     Register Src1 = MI.getOperand(1).getReg();
11693     Register Src2 = MI.getOperand(2).getReg();
11694     DebugLoc dl = MI.getDebugLoc();
11695 
11696     MachineRegisterInfo &RegInfo = F->getRegInfo();
11697     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11698 
11699     // Save FPSCR value.
11700     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11701 
11702     // Set rounding mode to round-to-zero.
11703     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11704     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11705 
11706     // Perform addition.
11707     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11708 
11709     // Restore FPSCR value.
11710     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11711   } else if (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11712              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT ||
11713              MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11714              MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8) {
11715     unsigned Opcode = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8 ||
11716                        MI.getOpcode() == PPC::ANDI_rec_1_GT_BIT8)
11717                           ? PPC::ANDI8_rec
11718                           : PPC::ANDI_rec;
11719     bool IsEQ = (MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT ||
11720                  MI.getOpcode() == PPC::ANDI_rec_1_EQ_BIT8);
11721 
11722     MachineRegisterInfo &RegInfo = F->getRegInfo();
11723     Register Dest = RegInfo.createVirtualRegister(
11724         Opcode == PPC::ANDI_rec ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11725 
11726     DebugLoc Dl = MI.getDebugLoc();
11727     BuildMI(*BB, MI, Dl, TII->get(Opcode), Dest)
11728         .addReg(MI.getOperand(1).getReg())
11729         .addImm(1);
11730     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11731             MI.getOperand(0).getReg())
11732         .addReg(IsEQ ? PPC::CR0EQ : PPC::CR0GT);
11733   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11734     DebugLoc Dl = MI.getDebugLoc();
11735     MachineRegisterInfo &RegInfo = F->getRegInfo();
11736     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11737     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11738     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11739             MI.getOperand(0).getReg())
11740         .addReg(CRReg);
11741   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11742     DebugLoc Dl = MI.getDebugLoc();
11743     unsigned Imm = MI.getOperand(1).getImm();
11744     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11745     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11746             MI.getOperand(0).getReg())
11747         .addReg(PPC::CR0EQ);
11748   } else if (MI.getOpcode() == PPC::SETRNDi) {
11749     DebugLoc dl = MI.getDebugLoc();
11750     Register OldFPSCRReg = MI.getOperand(0).getReg();
11751 
11752     // Save FPSCR value.
11753     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11754 
11755     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11756     // the following settings:
11757     //   00 Round to nearest
11758     //   01 Round to 0
11759     //   10 Round to +inf
11760     //   11 Round to -inf
11761 
11762     // When the operand is immediate, using the two least significant bits of
11763     // the immediate to set the bits 62:63 of FPSCR.
11764     unsigned Mode = MI.getOperand(1).getImm();
11765     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11766       .addImm(31);
11767 
11768     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11769       .addImm(30);
11770   } else if (MI.getOpcode() == PPC::SETRND) {
11771     DebugLoc dl = MI.getDebugLoc();
11772 
11773     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11774     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11775     // If the target doesn't have DirectMove, we should use stack to do the
11776     // conversion, because the target doesn't have the instructions like mtvsrd
11777     // or mfvsrd to do this conversion directly.
11778     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11779       if (Subtarget.hasDirectMove()) {
11780         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11781           .addReg(SrcReg);
11782       } else {
11783         // Use stack to do the register copy.
11784         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11785         MachineRegisterInfo &RegInfo = F->getRegInfo();
11786         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11787         if (RC == &PPC::F8RCRegClass) {
11788           // Copy register from F8RCRegClass to G8RCRegclass.
11789           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11790                  "Unsupported RegClass.");
11791 
11792           StoreOp = PPC::STFD;
11793           LoadOp = PPC::LD;
11794         } else {
11795           // Copy register from G8RCRegClass to F8RCRegclass.
11796           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11797                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11798                  "Unsupported RegClass.");
11799         }
11800 
11801         MachineFrameInfo &MFI = F->getFrameInfo();
11802         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11803 
11804         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11805           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11806           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11807           MFI.getObjectAlignment(FrameIdx));
11808 
11809         // Store the SrcReg into the stack.
11810         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11811           .addReg(SrcReg)
11812           .addImm(0)
11813           .addFrameIndex(FrameIdx)
11814           .addMemOperand(MMOStore);
11815 
11816         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11817           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11818           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11819           MFI.getObjectAlignment(FrameIdx));
11820 
11821         // Load from the stack where SrcReg is stored, and save to DestReg,
11822         // so we have done the RegClass conversion from RegClass::SrcReg to
11823         // RegClass::DestReg.
11824         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11825           .addImm(0)
11826           .addFrameIndex(FrameIdx)
11827           .addMemOperand(MMOLoad);
11828       }
11829     };
11830 
11831     Register OldFPSCRReg = MI.getOperand(0).getReg();
11832 
11833     // Save FPSCR value.
11834     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11835 
11836     // When the operand is gprc register, use two least significant bits of the
11837     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11838     //
11839     // copy OldFPSCRTmpReg, OldFPSCRReg
11840     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11841     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11842     // copy NewFPSCRReg, NewFPSCRTmpReg
11843     // mtfsf 255, NewFPSCRReg
11844     MachineOperand SrcOp = MI.getOperand(1);
11845     MachineRegisterInfo &RegInfo = F->getRegInfo();
11846     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11847 
11848     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11849 
11850     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11851     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11852 
11853     // The first operand of INSERT_SUBREG should be a register which has
11854     // subregisters, we only care about its RegClass, so we should use an
11855     // IMPLICIT_DEF register.
11856     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11857     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11858       .addReg(ImDefReg)
11859       .add(SrcOp)
11860       .addImm(1);
11861 
11862     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11863     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11864       .addReg(OldFPSCRTmpReg)
11865       .addReg(ExtSrcReg)
11866       .addImm(0)
11867       .addImm(62);
11868 
11869     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11870     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11871 
11872     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11873     // bits of FPSCR.
11874     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11875       .addImm(255)
11876       .addReg(NewFPSCRReg)
11877       .addImm(0)
11878       .addImm(0);
11879   } else {
11880     llvm_unreachable("Unexpected instr type to insert");
11881   }
11882 
11883   MI.eraseFromParent(); // The pseudo instruction is gone now.
11884   return BB;
11885 }
11886 
11887 //===----------------------------------------------------------------------===//
11888 // Target Optimization Hooks
11889 //===----------------------------------------------------------------------===//
11890 
11891 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11892   // For the estimates, convergence is quadratic, so we essentially double the
11893   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11894   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11895   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11896   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11897   if (VT.getScalarType() == MVT::f64)
11898     RefinementSteps++;
11899   return RefinementSteps;
11900 }
11901 
11902 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11903                                            int Enabled, int &RefinementSteps,
11904                                            bool &UseOneConstNR,
11905                                            bool Reciprocal) const {
11906   EVT VT = Operand.getValueType();
11907   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11908       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11909       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11910       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11911       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11912       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11913     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11914       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11915 
11916     // The Newton-Raphson computation with a single constant does not provide
11917     // enough accuracy on some CPUs.
11918     UseOneConstNR = !Subtarget.needsTwoConstNR();
11919     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11920   }
11921   return SDValue();
11922 }
11923 
11924 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11925                                             int Enabled,
11926                                             int &RefinementSteps) const {
11927   EVT VT = Operand.getValueType();
11928   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11929       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11930       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11931       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11932       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11933       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11934     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11935       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11936     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11937   }
11938   return SDValue();
11939 }
11940 
11941 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11942   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11943   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11944   // enabled for division), this functionality is redundant with the default
11945   // combiner logic (once the division -> reciprocal/multiply transformation
11946   // has taken place). As a result, this matters more for older cores than for
11947   // newer ones.
11948 
11949   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11950   // reciprocal if there are two or more FDIVs (for embedded cores with only
11951   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11952   switch (Subtarget.getCPUDirective()) {
11953   default:
11954     return 3;
11955   case PPC::DIR_440:
11956   case PPC::DIR_A2:
11957   case PPC::DIR_E500:
11958   case PPC::DIR_E500mc:
11959   case PPC::DIR_E5500:
11960     return 2;
11961   }
11962 }
11963 
11964 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11965 // collapsed, and so we need to look through chains of them.
11966 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11967                                      int64_t& Offset, SelectionDAG &DAG) {
11968   if (DAG.isBaseWithConstantOffset(Loc)) {
11969     Base = Loc.getOperand(0);
11970     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11971 
11972     // The base might itself be a base plus an offset, and if so, accumulate
11973     // that as well.
11974     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11975   }
11976 }
11977 
11978 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11979                             unsigned Bytes, int Dist,
11980                             SelectionDAG &DAG) {
11981   if (VT.getSizeInBits() / 8 != Bytes)
11982     return false;
11983 
11984   SDValue BaseLoc = Base->getBasePtr();
11985   if (Loc.getOpcode() == ISD::FrameIndex) {
11986     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11987       return false;
11988     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11989     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11990     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11991     int FS  = MFI.getObjectSize(FI);
11992     int BFS = MFI.getObjectSize(BFI);
11993     if (FS != BFS || FS != (int)Bytes) return false;
11994     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11995   }
11996 
11997   SDValue Base1 = Loc, Base2 = BaseLoc;
11998   int64_t Offset1 = 0, Offset2 = 0;
11999   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
12000   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
12001   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
12002     return true;
12003 
12004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12005   const GlobalValue *GV1 = nullptr;
12006   const GlobalValue *GV2 = nullptr;
12007   Offset1 = 0;
12008   Offset2 = 0;
12009   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
12010   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
12011   if (isGA1 && isGA2 && GV1 == GV2)
12012     return Offset1 == (Offset2 + Dist*Bytes);
12013   return false;
12014 }
12015 
12016 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
12017 // not enforce equality of the chain operands.
12018 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
12019                             unsigned Bytes, int Dist,
12020                             SelectionDAG &DAG) {
12021   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
12022     EVT VT = LS->getMemoryVT();
12023     SDValue Loc = LS->getBasePtr();
12024     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
12025   }
12026 
12027   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
12028     EVT VT;
12029     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12030     default: return false;
12031     case Intrinsic::ppc_qpx_qvlfd:
12032     case Intrinsic::ppc_qpx_qvlfda:
12033       VT = MVT::v4f64;
12034       break;
12035     case Intrinsic::ppc_qpx_qvlfs:
12036     case Intrinsic::ppc_qpx_qvlfsa:
12037       VT = MVT::v4f32;
12038       break;
12039     case Intrinsic::ppc_qpx_qvlfcd:
12040     case Intrinsic::ppc_qpx_qvlfcda:
12041       VT = MVT::v2f64;
12042       break;
12043     case Intrinsic::ppc_qpx_qvlfcs:
12044     case Intrinsic::ppc_qpx_qvlfcsa:
12045       VT = MVT::v2f32;
12046       break;
12047     case Intrinsic::ppc_qpx_qvlfiwa:
12048     case Intrinsic::ppc_qpx_qvlfiwz:
12049     case Intrinsic::ppc_altivec_lvx:
12050     case Intrinsic::ppc_altivec_lvxl:
12051     case Intrinsic::ppc_vsx_lxvw4x:
12052     case Intrinsic::ppc_vsx_lxvw4x_be:
12053       VT = MVT::v4i32;
12054       break;
12055     case Intrinsic::ppc_vsx_lxvd2x:
12056     case Intrinsic::ppc_vsx_lxvd2x_be:
12057       VT = MVT::v2f64;
12058       break;
12059     case Intrinsic::ppc_altivec_lvebx:
12060       VT = MVT::i8;
12061       break;
12062     case Intrinsic::ppc_altivec_lvehx:
12063       VT = MVT::i16;
12064       break;
12065     case Intrinsic::ppc_altivec_lvewx:
12066       VT = MVT::i32;
12067       break;
12068     }
12069 
12070     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12071   }
12072 
12073   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12074     EVT VT;
12075     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12076     default: return false;
12077     case Intrinsic::ppc_qpx_qvstfd:
12078     case Intrinsic::ppc_qpx_qvstfda:
12079       VT = MVT::v4f64;
12080       break;
12081     case Intrinsic::ppc_qpx_qvstfs:
12082     case Intrinsic::ppc_qpx_qvstfsa:
12083       VT = MVT::v4f32;
12084       break;
12085     case Intrinsic::ppc_qpx_qvstfcd:
12086     case Intrinsic::ppc_qpx_qvstfcda:
12087       VT = MVT::v2f64;
12088       break;
12089     case Intrinsic::ppc_qpx_qvstfcs:
12090     case Intrinsic::ppc_qpx_qvstfcsa:
12091       VT = MVT::v2f32;
12092       break;
12093     case Intrinsic::ppc_qpx_qvstfiw:
12094     case Intrinsic::ppc_qpx_qvstfiwa:
12095     case Intrinsic::ppc_altivec_stvx:
12096     case Intrinsic::ppc_altivec_stvxl:
12097     case Intrinsic::ppc_vsx_stxvw4x:
12098       VT = MVT::v4i32;
12099       break;
12100     case Intrinsic::ppc_vsx_stxvd2x:
12101       VT = MVT::v2f64;
12102       break;
12103     case Intrinsic::ppc_vsx_stxvw4x_be:
12104       VT = MVT::v4i32;
12105       break;
12106     case Intrinsic::ppc_vsx_stxvd2x_be:
12107       VT = MVT::v2f64;
12108       break;
12109     case Intrinsic::ppc_altivec_stvebx:
12110       VT = MVT::i8;
12111       break;
12112     case Intrinsic::ppc_altivec_stvehx:
12113       VT = MVT::i16;
12114       break;
12115     case Intrinsic::ppc_altivec_stvewx:
12116       VT = MVT::i32;
12117       break;
12118     }
12119 
12120     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12121   }
12122 
12123   return false;
12124 }
12125 
12126 // Return true is there is a nearyby consecutive load to the one provided
12127 // (regardless of alignment). We search up and down the chain, looking though
12128 // token factors and other loads (but nothing else). As a result, a true result
12129 // indicates that it is safe to create a new consecutive load adjacent to the
12130 // load provided.
12131 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12132   SDValue Chain = LD->getChain();
12133   EVT VT = LD->getMemoryVT();
12134 
12135   SmallSet<SDNode *, 16> LoadRoots;
12136   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12137   SmallSet<SDNode *, 16> Visited;
12138 
12139   // First, search up the chain, branching to follow all token-factor operands.
12140   // If we find a consecutive load, then we're done, otherwise, record all
12141   // nodes just above the top-level loads and token factors.
12142   while (!Queue.empty()) {
12143     SDNode *ChainNext = Queue.pop_back_val();
12144     if (!Visited.insert(ChainNext).second)
12145       continue;
12146 
12147     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12148       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12149         return true;
12150 
12151       if (!Visited.count(ChainLD->getChain().getNode()))
12152         Queue.push_back(ChainLD->getChain().getNode());
12153     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12154       for (const SDUse &O : ChainNext->ops())
12155         if (!Visited.count(O.getNode()))
12156           Queue.push_back(O.getNode());
12157     } else
12158       LoadRoots.insert(ChainNext);
12159   }
12160 
12161   // Second, search down the chain, starting from the top-level nodes recorded
12162   // in the first phase. These top-level nodes are the nodes just above all
12163   // loads and token factors. Starting with their uses, recursively look though
12164   // all loads (just the chain uses) and token factors to find a consecutive
12165   // load.
12166   Visited.clear();
12167   Queue.clear();
12168 
12169   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12170        IE = LoadRoots.end(); I != IE; ++I) {
12171     Queue.push_back(*I);
12172 
12173     while (!Queue.empty()) {
12174       SDNode *LoadRoot = Queue.pop_back_val();
12175       if (!Visited.insert(LoadRoot).second)
12176         continue;
12177 
12178       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12179         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12180           return true;
12181 
12182       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12183            UE = LoadRoot->use_end(); UI != UE; ++UI)
12184         if (((isa<MemSDNode>(*UI) &&
12185             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12186             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12187           Queue.push_back(*UI);
12188     }
12189   }
12190 
12191   return false;
12192 }
12193 
12194 /// This function is called when we have proved that a SETCC node can be replaced
12195 /// by subtraction (and other supporting instructions) so that the result of
12196 /// comparison is kept in a GPR instead of CR. This function is purely for
12197 /// codegen purposes and has some flags to guide the codegen process.
12198 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12199                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12200   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12201 
12202   // Zero extend the operands to the largest legal integer. Originally, they
12203   // must be of a strictly smaller size.
12204   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12205                          DAG.getConstant(Size, DL, MVT::i32));
12206   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12207                          DAG.getConstant(Size, DL, MVT::i32));
12208 
12209   // Swap if needed. Depends on the condition code.
12210   if (Swap)
12211     std::swap(Op0, Op1);
12212 
12213   // Subtract extended integers.
12214   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12215 
12216   // Move the sign bit to the least significant position and zero out the rest.
12217   // Now the least significant bit carries the result of original comparison.
12218   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12219                              DAG.getConstant(Size - 1, DL, MVT::i32));
12220   auto Final = Shifted;
12221 
12222   // Complement the result if needed. Based on the condition code.
12223   if (Complement)
12224     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12225                         DAG.getConstant(1, DL, MVT::i64));
12226 
12227   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12228 }
12229 
12230 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12231                                                   DAGCombinerInfo &DCI) const {
12232   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12233 
12234   SelectionDAG &DAG = DCI.DAG;
12235   SDLoc DL(N);
12236 
12237   // Size of integers being compared has a critical role in the following
12238   // analysis, so we prefer to do this when all types are legal.
12239   if (!DCI.isAfterLegalizeDAG())
12240     return SDValue();
12241 
12242   // If all users of SETCC extend its value to a legal integer type
12243   // then we replace SETCC with a subtraction
12244   for (SDNode::use_iterator UI = N->use_begin(),
12245        UE = N->use_end(); UI != UE; ++UI) {
12246     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12247       return SDValue();
12248   }
12249 
12250   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12251   auto OpSize = N->getOperand(0).getValueSizeInBits();
12252 
12253   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12254 
12255   if (OpSize < Size) {
12256     switch (CC) {
12257     default: break;
12258     case ISD::SETULT:
12259       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12260     case ISD::SETULE:
12261       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12262     case ISD::SETUGT:
12263       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12264     case ISD::SETUGE:
12265       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12266     }
12267   }
12268 
12269   return SDValue();
12270 }
12271 
12272 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12273                                                   DAGCombinerInfo &DCI) const {
12274   SelectionDAG &DAG = DCI.DAG;
12275   SDLoc dl(N);
12276 
12277   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12278   // If we're tracking CR bits, we need to be careful that we don't have:
12279   //   trunc(binary-ops(zext(x), zext(y)))
12280   // or
12281   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12282   // such that we're unnecessarily moving things into GPRs when it would be
12283   // better to keep them in CR bits.
12284 
12285   // Note that trunc here can be an actual i1 trunc, or can be the effective
12286   // truncation that comes from a setcc or select_cc.
12287   if (N->getOpcode() == ISD::TRUNCATE &&
12288       N->getValueType(0) != MVT::i1)
12289     return SDValue();
12290 
12291   if (N->getOperand(0).getValueType() != MVT::i32 &&
12292       N->getOperand(0).getValueType() != MVT::i64)
12293     return SDValue();
12294 
12295   if (N->getOpcode() == ISD::SETCC ||
12296       N->getOpcode() == ISD::SELECT_CC) {
12297     // If we're looking at a comparison, then we need to make sure that the
12298     // high bits (all except for the first) don't matter the result.
12299     ISD::CondCode CC =
12300       cast<CondCodeSDNode>(N->getOperand(
12301         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12302     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12303 
12304     if (ISD::isSignedIntSetCC(CC)) {
12305       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12306           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12307         return SDValue();
12308     } else if (ISD::isUnsignedIntSetCC(CC)) {
12309       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12310                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12311           !DAG.MaskedValueIsZero(N->getOperand(1),
12312                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12313         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12314                                              : SDValue());
12315     } else {
12316       // This is neither a signed nor an unsigned comparison, just make sure
12317       // that the high bits are equal.
12318       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12319       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12320 
12321       // We don't really care about what is known about the first bit (if
12322       // anything), so clear it in all masks prior to comparing them.
12323       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12324       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12325 
12326       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12327         return SDValue();
12328     }
12329   }
12330 
12331   // We now know that the higher-order bits are irrelevant, we just need to
12332   // make sure that all of the intermediate operations are bit operations, and
12333   // all inputs are extensions.
12334   if (N->getOperand(0).getOpcode() != ISD::AND &&
12335       N->getOperand(0).getOpcode() != ISD::OR  &&
12336       N->getOperand(0).getOpcode() != ISD::XOR &&
12337       N->getOperand(0).getOpcode() != ISD::SELECT &&
12338       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12339       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12340       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12341       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12342       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12343     return SDValue();
12344 
12345   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12346       N->getOperand(1).getOpcode() != ISD::AND &&
12347       N->getOperand(1).getOpcode() != ISD::OR  &&
12348       N->getOperand(1).getOpcode() != ISD::XOR &&
12349       N->getOperand(1).getOpcode() != ISD::SELECT &&
12350       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12351       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12352       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12353       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12354       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12355     return SDValue();
12356 
12357   SmallVector<SDValue, 4> Inputs;
12358   SmallVector<SDValue, 8> BinOps, PromOps;
12359   SmallPtrSet<SDNode *, 16> Visited;
12360 
12361   for (unsigned i = 0; i < 2; ++i) {
12362     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12363           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12364           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12365           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12366         isa<ConstantSDNode>(N->getOperand(i)))
12367       Inputs.push_back(N->getOperand(i));
12368     else
12369       BinOps.push_back(N->getOperand(i));
12370 
12371     if (N->getOpcode() == ISD::TRUNCATE)
12372       break;
12373   }
12374 
12375   // Visit all inputs, collect all binary operations (and, or, xor and
12376   // select) that are all fed by extensions.
12377   while (!BinOps.empty()) {
12378     SDValue BinOp = BinOps.back();
12379     BinOps.pop_back();
12380 
12381     if (!Visited.insert(BinOp.getNode()).second)
12382       continue;
12383 
12384     PromOps.push_back(BinOp);
12385 
12386     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12387       // The condition of the select is not promoted.
12388       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12389         continue;
12390       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12391         continue;
12392 
12393       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12394             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12395             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12396            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12397           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12398         Inputs.push_back(BinOp.getOperand(i));
12399       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12400                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12401                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12402                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12403                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12404                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12405                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12406                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12407                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12408         BinOps.push_back(BinOp.getOperand(i));
12409       } else {
12410         // We have an input that is not an extension or another binary
12411         // operation; we'll abort this transformation.
12412         return SDValue();
12413       }
12414     }
12415   }
12416 
12417   // Make sure that this is a self-contained cluster of operations (which
12418   // is not quite the same thing as saying that everything has only one
12419   // use).
12420   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12421     if (isa<ConstantSDNode>(Inputs[i]))
12422       continue;
12423 
12424     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12425                               UE = Inputs[i].getNode()->use_end();
12426          UI != UE; ++UI) {
12427       SDNode *User = *UI;
12428       if (User != N && !Visited.count(User))
12429         return SDValue();
12430 
12431       // Make sure that we're not going to promote the non-output-value
12432       // operand(s) or SELECT or SELECT_CC.
12433       // FIXME: Although we could sometimes handle this, and it does occur in
12434       // practice that one of the condition inputs to the select is also one of
12435       // the outputs, we currently can't deal with this.
12436       if (User->getOpcode() == ISD::SELECT) {
12437         if (User->getOperand(0) == Inputs[i])
12438           return SDValue();
12439       } else if (User->getOpcode() == ISD::SELECT_CC) {
12440         if (User->getOperand(0) == Inputs[i] ||
12441             User->getOperand(1) == Inputs[i])
12442           return SDValue();
12443       }
12444     }
12445   }
12446 
12447   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12448     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12449                               UE = PromOps[i].getNode()->use_end();
12450          UI != UE; ++UI) {
12451       SDNode *User = *UI;
12452       if (User != N && !Visited.count(User))
12453         return SDValue();
12454 
12455       // Make sure that we're not going to promote the non-output-value
12456       // operand(s) or SELECT or SELECT_CC.
12457       // FIXME: Although we could sometimes handle this, and it does occur in
12458       // practice that one of the condition inputs to the select is also one of
12459       // the outputs, we currently can't deal with this.
12460       if (User->getOpcode() == ISD::SELECT) {
12461         if (User->getOperand(0) == PromOps[i])
12462           return SDValue();
12463       } else if (User->getOpcode() == ISD::SELECT_CC) {
12464         if (User->getOperand(0) == PromOps[i] ||
12465             User->getOperand(1) == PromOps[i])
12466           return SDValue();
12467       }
12468     }
12469   }
12470 
12471   // Replace all inputs with the extension operand.
12472   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12473     // Constants may have users outside the cluster of to-be-promoted nodes,
12474     // and so we need to replace those as we do the promotions.
12475     if (isa<ConstantSDNode>(Inputs[i]))
12476       continue;
12477     else
12478       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12479   }
12480 
12481   std::list<HandleSDNode> PromOpHandles;
12482   for (auto &PromOp : PromOps)
12483     PromOpHandles.emplace_back(PromOp);
12484 
12485   // Replace all operations (these are all the same, but have a different
12486   // (i1) return type). DAG.getNode will validate that the types of
12487   // a binary operator match, so go through the list in reverse so that
12488   // we've likely promoted both operands first. Any intermediate truncations or
12489   // extensions disappear.
12490   while (!PromOpHandles.empty()) {
12491     SDValue PromOp = PromOpHandles.back().getValue();
12492     PromOpHandles.pop_back();
12493 
12494     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12495         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12496         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12497         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12498       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12499           PromOp.getOperand(0).getValueType() != MVT::i1) {
12500         // The operand is not yet ready (see comment below).
12501         PromOpHandles.emplace_front(PromOp);
12502         continue;
12503       }
12504 
12505       SDValue RepValue = PromOp.getOperand(0);
12506       if (isa<ConstantSDNode>(RepValue))
12507         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12508 
12509       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12510       continue;
12511     }
12512 
12513     unsigned C;
12514     switch (PromOp.getOpcode()) {
12515     default:             C = 0; break;
12516     case ISD::SELECT:    C = 1; break;
12517     case ISD::SELECT_CC: C = 2; break;
12518     }
12519 
12520     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12521          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12522         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12523          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12524       // The to-be-promoted operands of this node have not yet been
12525       // promoted (this should be rare because we're going through the
12526       // list backward, but if one of the operands has several users in
12527       // this cluster of to-be-promoted nodes, it is possible).
12528       PromOpHandles.emplace_front(PromOp);
12529       continue;
12530     }
12531 
12532     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12533                                 PromOp.getNode()->op_end());
12534 
12535     // If there are any constant inputs, make sure they're replaced now.
12536     for (unsigned i = 0; i < 2; ++i)
12537       if (isa<ConstantSDNode>(Ops[C+i]))
12538         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12539 
12540     DAG.ReplaceAllUsesOfValueWith(PromOp,
12541       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12542   }
12543 
12544   // Now we're left with the initial truncation itself.
12545   if (N->getOpcode() == ISD::TRUNCATE)
12546     return N->getOperand(0);
12547 
12548   // Otherwise, this is a comparison. The operands to be compared have just
12549   // changed type (to i1), but everything else is the same.
12550   return SDValue(N, 0);
12551 }
12552 
12553 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12554                                                   DAGCombinerInfo &DCI) const {
12555   SelectionDAG &DAG = DCI.DAG;
12556   SDLoc dl(N);
12557 
12558   // If we're tracking CR bits, we need to be careful that we don't have:
12559   //   zext(binary-ops(trunc(x), trunc(y)))
12560   // or
12561   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12562   // such that we're unnecessarily moving things into CR bits that can more
12563   // efficiently stay in GPRs. Note that if we're not certain that the high
12564   // bits are set as required by the final extension, we still may need to do
12565   // some masking to get the proper behavior.
12566 
12567   // This same functionality is important on PPC64 when dealing with
12568   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12569   // the return values of functions. Because it is so similar, it is handled
12570   // here as well.
12571 
12572   if (N->getValueType(0) != MVT::i32 &&
12573       N->getValueType(0) != MVT::i64)
12574     return SDValue();
12575 
12576   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12577         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12578     return SDValue();
12579 
12580   if (N->getOperand(0).getOpcode() != ISD::AND &&
12581       N->getOperand(0).getOpcode() != ISD::OR  &&
12582       N->getOperand(0).getOpcode() != ISD::XOR &&
12583       N->getOperand(0).getOpcode() != ISD::SELECT &&
12584       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12585     return SDValue();
12586 
12587   SmallVector<SDValue, 4> Inputs;
12588   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12589   SmallPtrSet<SDNode *, 16> Visited;
12590 
12591   // Visit all inputs, collect all binary operations (and, or, xor and
12592   // select) that are all fed by truncations.
12593   while (!BinOps.empty()) {
12594     SDValue BinOp = BinOps.back();
12595     BinOps.pop_back();
12596 
12597     if (!Visited.insert(BinOp.getNode()).second)
12598       continue;
12599 
12600     PromOps.push_back(BinOp);
12601 
12602     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12603       // The condition of the select is not promoted.
12604       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12605         continue;
12606       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12607         continue;
12608 
12609       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12610           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12611         Inputs.push_back(BinOp.getOperand(i));
12612       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12613                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12614                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12615                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12616                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12617         BinOps.push_back(BinOp.getOperand(i));
12618       } else {
12619         // We have an input that is not a truncation or another binary
12620         // operation; we'll abort this transformation.
12621         return SDValue();
12622       }
12623     }
12624   }
12625 
12626   // The operands of a select that must be truncated when the select is
12627   // promoted because the operand is actually part of the to-be-promoted set.
12628   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12629 
12630   // Make sure that this is a self-contained cluster of operations (which
12631   // is not quite the same thing as saying that everything has only one
12632   // use).
12633   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12634     if (isa<ConstantSDNode>(Inputs[i]))
12635       continue;
12636 
12637     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12638                               UE = Inputs[i].getNode()->use_end();
12639          UI != UE; ++UI) {
12640       SDNode *User = *UI;
12641       if (User != N && !Visited.count(User))
12642         return SDValue();
12643 
12644       // If we're going to promote the non-output-value operand(s) or SELECT or
12645       // SELECT_CC, record them for truncation.
12646       if (User->getOpcode() == ISD::SELECT) {
12647         if (User->getOperand(0) == Inputs[i])
12648           SelectTruncOp[0].insert(std::make_pair(User,
12649                                     User->getOperand(0).getValueType()));
12650       } else if (User->getOpcode() == ISD::SELECT_CC) {
12651         if (User->getOperand(0) == Inputs[i])
12652           SelectTruncOp[0].insert(std::make_pair(User,
12653                                     User->getOperand(0).getValueType()));
12654         if (User->getOperand(1) == Inputs[i])
12655           SelectTruncOp[1].insert(std::make_pair(User,
12656                                     User->getOperand(1).getValueType()));
12657       }
12658     }
12659   }
12660 
12661   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12662     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12663                               UE = PromOps[i].getNode()->use_end();
12664          UI != UE; ++UI) {
12665       SDNode *User = *UI;
12666       if (User != N && !Visited.count(User))
12667         return SDValue();
12668 
12669       // If we're going to promote the non-output-value operand(s) or SELECT or
12670       // SELECT_CC, record them for truncation.
12671       if (User->getOpcode() == ISD::SELECT) {
12672         if (User->getOperand(0) == PromOps[i])
12673           SelectTruncOp[0].insert(std::make_pair(User,
12674                                     User->getOperand(0).getValueType()));
12675       } else if (User->getOpcode() == ISD::SELECT_CC) {
12676         if (User->getOperand(0) == PromOps[i])
12677           SelectTruncOp[0].insert(std::make_pair(User,
12678                                     User->getOperand(0).getValueType()));
12679         if (User->getOperand(1) == PromOps[i])
12680           SelectTruncOp[1].insert(std::make_pair(User,
12681                                     User->getOperand(1).getValueType()));
12682       }
12683     }
12684   }
12685 
12686   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12687   bool ReallyNeedsExt = false;
12688   if (N->getOpcode() != ISD::ANY_EXTEND) {
12689     // If all of the inputs are not already sign/zero extended, then
12690     // we'll still need to do that at the end.
12691     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12692       if (isa<ConstantSDNode>(Inputs[i]))
12693         continue;
12694 
12695       unsigned OpBits =
12696         Inputs[i].getOperand(0).getValueSizeInBits();
12697       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12698 
12699       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12700            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12701                                   APInt::getHighBitsSet(OpBits,
12702                                                         OpBits-PromBits))) ||
12703           (N->getOpcode() == ISD::SIGN_EXTEND &&
12704            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12705              (OpBits-(PromBits-1)))) {
12706         ReallyNeedsExt = true;
12707         break;
12708       }
12709     }
12710   }
12711 
12712   // Replace all inputs, either with the truncation operand, or a
12713   // truncation or extension to the final output type.
12714   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12715     // Constant inputs need to be replaced with the to-be-promoted nodes that
12716     // use them because they might have users outside of the cluster of
12717     // promoted nodes.
12718     if (isa<ConstantSDNode>(Inputs[i]))
12719       continue;
12720 
12721     SDValue InSrc = Inputs[i].getOperand(0);
12722     if (Inputs[i].getValueType() == N->getValueType(0))
12723       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12724     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12725       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12726         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12727     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12728       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12729         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12730     else
12731       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12732         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12733   }
12734 
12735   std::list<HandleSDNode> PromOpHandles;
12736   for (auto &PromOp : PromOps)
12737     PromOpHandles.emplace_back(PromOp);
12738 
12739   // Replace all operations (these are all the same, but have a different
12740   // (promoted) return type). DAG.getNode will validate that the types of
12741   // a binary operator match, so go through the list in reverse so that
12742   // we've likely promoted both operands first.
12743   while (!PromOpHandles.empty()) {
12744     SDValue PromOp = PromOpHandles.back().getValue();
12745     PromOpHandles.pop_back();
12746 
12747     unsigned C;
12748     switch (PromOp.getOpcode()) {
12749     default:             C = 0; break;
12750     case ISD::SELECT:    C = 1; break;
12751     case ISD::SELECT_CC: C = 2; break;
12752     }
12753 
12754     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12755          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12756         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12757          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12758       // The to-be-promoted operands of this node have not yet been
12759       // promoted (this should be rare because we're going through the
12760       // list backward, but if one of the operands has several users in
12761       // this cluster of to-be-promoted nodes, it is possible).
12762       PromOpHandles.emplace_front(PromOp);
12763       continue;
12764     }
12765 
12766     // For SELECT and SELECT_CC nodes, we do a similar check for any
12767     // to-be-promoted comparison inputs.
12768     if (PromOp.getOpcode() == ISD::SELECT ||
12769         PromOp.getOpcode() == ISD::SELECT_CC) {
12770       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12771            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12772           (SelectTruncOp[1].count(PromOp.getNode()) &&
12773            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12774         PromOpHandles.emplace_front(PromOp);
12775         continue;
12776       }
12777     }
12778 
12779     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12780                                 PromOp.getNode()->op_end());
12781 
12782     // If this node has constant inputs, then they'll need to be promoted here.
12783     for (unsigned i = 0; i < 2; ++i) {
12784       if (!isa<ConstantSDNode>(Ops[C+i]))
12785         continue;
12786       if (Ops[C+i].getValueType() == N->getValueType(0))
12787         continue;
12788 
12789       if (N->getOpcode() == ISD::SIGN_EXTEND)
12790         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12791       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12792         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12793       else
12794         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12795     }
12796 
12797     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12798     // truncate them again to the original value type.
12799     if (PromOp.getOpcode() == ISD::SELECT ||
12800         PromOp.getOpcode() == ISD::SELECT_CC) {
12801       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12802       if (SI0 != SelectTruncOp[0].end())
12803         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12804       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12805       if (SI1 != SelectTruncOp[1].end())
12806         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12807     }
12808 
12809     DAG.ReplaceAllUsesOfValueWith(PromOp,
12810       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12811   }
12812 
12813   // Now we're left with the initial extension itself.
12814   if (!ReallyNeedsExt)
12815     return N->getOperand(0);
12816 
12817   // To zero extend, just mask off everything except for the first bit (in the
12818   // i1 case).
12819   if (N->getOpcode() == ISD::ZERO_EXTEND)
12820     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12821                        DAG.getConstant(APInt::getLowBitsSet(
12822                                          N->getValueSizeInBits(0), PromBits),
12823                                        dl, N->getValueType(0)));
12824 
12825   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12826          "Invalid extension type");
12827   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12828   SDValue ShiftCst =
12829       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12830   return DAG.getNode(
12831       ISD::SRA, dl, N->getValueType(0),
12832       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12833       ShiftCst);
12834 }
12835 
12836 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12837                                         DAGCombinerInfo &DCI) const {
12838   assert(N->getOpcode() == ISD::SETCC &&
12839          "Should be called with a SETCC node");
12840 
12841   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12842   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12843     SDValue LHS = N->getOperand(0);
12844     SDValue RHS = N->getOperand(1);
12845 
12846     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12847     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12848         LHS.hasOneUse())
12849       std::swap(LHS, RHS);
12850 
12851     // x == 0-y --> x+y == 0
12852     // x != 0-y --> x+y != 0
12853     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12854         RHS.hasOneUse()) {
12855       SDLoc DL(N);
12856       SelectionDAG &DAG = DCI.DAG;
12857       EVT VT = N->getValueType(0);
12858       EVT OpVT = LHS.getValueType();
12859       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12860       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12861     }
12862   }
12863 
12864   return DAGCombineTruncBoolExt(N, DCI);
12865 }
12866 
12867 // Is this an extending load from an f32 to an f64?
12868 static bool isFPExtLoad(SDValue Op) {
12869   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12870     return LD->getExtensionType() == ISD::EXTLOAD &&
12871       Op.getValueType() == MVT::f64;
12872   return false;
12873 }
12874 
12875 /// Reduces the number of fp-to-int conversion when building a vector.
12876 ///
12877 /// If this vector is built out of floating to integer conversions,
12878 /// transform it to a vector built out of floating point values followed by a
12879 /// single floating to integer conversion of the vector.
12880 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12881 /// becomes (fptosi (build_vector ($A, $B, ...)))
12882 SDValue PPCTargetLowering::
12883 combineElementTruncationToVectorTruncation(SDNode *N,
12884                                            DAGCombinerInfo &DCI) const {
12885   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12886          "Should be called with a BUILD_VECTOR node");
12887 
12888   SelectionDAG &DAG = DCI.DAG;
12889   SDLoc dl(N);
12890 
12891   SDValue FirstInput = N->getOperand(0);
12892   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12893          "The input operand must be an fp-to-int conversion.");
12894 
12895   // This combine happens after legalization so the fp_to_[su]i nodes are
12896   // already converted to PPCSISD nodes.
12897   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12898   if (FirstConversion == PPCISD::FCTIDZ ||
12899       FirstConversion == PPCISD::FCTIDUZ ||
12900       FirstConversion == PPCISD::FCTIWZ ||
12901       FirstConversion == PPCISD::FCTIWUZ) {
12902     bool IsSplat = true;
12903     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12904       FirstConversion == PPCISD::FCTIWUZ;
12905     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12906     SmallVector<SDValue, 4> Ops;
12907     EVT TargetVT = N->getValueType(0);
12908     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12909       SDValue NextOp = N->getOperand(i);
12910       if (NextOp.getOpcode() != PPCISD::MFVSR)
12911         return SDValue();
12912       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12913       if (NextConversion != FirstConversion)
12914         return SDValue();
12915       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12916       // This is not valid if the input was originally double precision. It is
12917       // also not profitable to do unless this is an extending load in which
12918       // case doing this combine will allow us to combine consecutive loads.
12919       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12920         return SDValue();
12921       if (N->getOperand(i) != FirstInput)
12922         IsSplat = false;
12923     }
12924 
12925     // If this is a splat, we leave it as-is since there will be only a single
12926     // fp-to-int conversion followed by a splat of the integer. This is better
12927     // for 32-bit and smaller ints and neutral for 64-bit ints.
12928     if (IsSplat)
12929       return SDValue();
12930 
12931     // Now that we know we have the right type of node, get its operands
12932     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12933       SDValue In = N->getOperand(i).getOperand(0);
12934       if (Is32Bit) {
12935         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12936         // here, we know that all inputs are extending loads so this is safe).
12937         if (In.isUndef())
12938           Ops.push_back(DAG.getUNDEF(SrcVT));
12939         else {
12940           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12941                                       MVT::f32, In.getOperand(0),
12942                                       DAG.getIntPtrConstant(1, dl));
12943           Ops.push_back(Trunc);
12944         }
12945       } else
12946         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12947     }
12948 
12949     unsigned Opcode;
12950     if (FirstConversion == PPCISD::FCTIDZ ||
12951         FirstConversion == PPCISD::FCTIWZ)
12952       Opcode = ISD::FP_TO_SINT;
12953     else
12954       Opcode = ISD::FP_TO_UINT;
12955 
12956     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12957     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12958     return DAG.getNode(Opcode, dl, TargetVT, BV);
12959   }
12960   return SDValue();
12961 }
12962 
12963 /// Reduce the number of loads when building a vector.
12964 ///
12965 /// Building a vector out of multiple loads can be converted to a load
12966 /// of the vector type if the loads are consecutive. If the loads are
12967 /// consecutive but in descending order, a shuffle is added at the end
12968 /// to reorder the vector.
12969 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12970   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12971          "Should be called with a BUILD_VECTOR node");
12972 
12973   SDLoc dl(N);
12974 
12975   // Return early for non byte-sized type, as they can't be consecutive.
12976   if (!N->getValueType(0).getVectorElementType().isByteSized())
12977     return SDValue();
12978 
12979   bool InputsAreConsecutiveLoads = true;
12980   bool InputsAreReverseConsecutive = true;
12981   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12982   SDValue FirstInput = N->getOperand(0);
12983   bool IsRoundOfExtLoad = false;
12984 
12985   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12986       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12987     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12988     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12989   }
12990   // Not a build vector of (possibly fp_rounded) loads.
12991   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12992       N->getNumOperands() == 1)
12993     return SDValue();
12994 
12995   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12996     // If any inputs are fp_round(extload), they all must be.
12997     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12998       return SDValue();
12999 
13000     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
13001       N->getOperand(i);
13002     if (NextInput.getOpcode() != ISD::LOAD)
13003       return SDValue();
13004 
13005     SDValue PreviousInput =
13006       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
13007     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
13008     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
13009 
13010     // If any inputs are fp_round(extload), they all must be.
13011     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
13012       return SDValue();
13013 
13014     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
13015       InputsAreConsecutiveLoads = false;
13016     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
13017       InputsAreReverseConsecutive = false;
13018 
13019     // Exit early if the loads are neither consecutive nor reverse consecutive.
13020     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
13021       return SDValue();
13022   }
13023 
13024   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
13025          "The loads cannot be both consecutive and reverse consecutive.");
13026 
13027   SDValue FirstLoadOp =
13028     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
13029   SDValue LastLoadOp =
13030     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
13031                        N->getOperand(N->getNumOperands()-1);
13032 
13033   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
13034   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
13035   if (InputsAreConsecutiveLoads) {
13036     assert(LD1 && "Input needs to be a LoadSDNode.");
13037     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
13038                        LD1->getBasePtr(), LD1->getPointerInfo(),
13039                        LD1->getAlignment());
13040   }
13041   if (InputsAreReverseConsecutive) {
13042     assert(LDL && "Input needs to be a LoadSDNode.");
13043     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
13044                                LDL->getBasePtr(), LDL->getPointerInfo(),
13045                                LDL->getAlignment());
13046     SmallVector<int, 16> Ops;
13047     for (int i = N->getNumOperands() - 1; i >= 0; i--)
13048       Ops.push_back(i);
13049 
13050     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
13051                                 DAG.getUNDEF(N->getValueType(0)), Ops);
13052   }
13053   return SDValue();
13054 }
13055 
13056 // This function adds the required vector_shuffle needed to get
13057 // the elements of the vector extract in the correct position
13058 // as specified by the CorrectElems encoding.
13059 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13060                                       SDValue Input, uint64_t Elems,
13061                                       uint64_t CorrectElems) {
13062   SDLoc dl(N);
13063 
13064   unsigned NumElems = Input.getValueType().getVectorNumElements();
13065   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13066 
13067   // Knowing the element indices being extracted from the original
13068   // vector and the order in which they're being inserted, just put
13069   // them at element indices required for the instruction.
13070   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13071     if (DAG.getDataLayout().isLittleEndian())
13072       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13073     else
13074       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13075     CorrectElems = CorrectElems >> 8;
13076     Elems = Elems >> 8;
13077   }
13078 
13079   SDValue Shuffle =
13080       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13081                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13082 
13083   EVT Ty = N->getValueType(0);
13084   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
13085   return BV;
13086 }
13087 
13088 // Look for build vector patterns where input operands come from sign
13089 // extended vector_extract elements of specific indices. If the correct indices
13090 // aren't used, add a vector shuffle to fix up the indices and create a new
13091 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13092 // during instruction selection.
13093 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13094   // This array encodes the indices that the vector sign extend instructions
13095   // extract from when extending from one type to another for both BE and LE.
13096   // The right nibble of each byte corresponds to the LE incides.
13097   // and the left nibble of each byte corresponds to the BE incides.
13098   // For example: 0x3074B8FC  byte->word
13099   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13100   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13101   // For example: 0x000070F8  byte->double word
13102   // For LE: the allowed indices are: 0x0,0x8
13103   // For BE: the allowed indices are: 0x7,0xF
13104   uint64_t TargetElems[] = {
13105       0x3074B8FC, // b->w
13106       0x000070F8, // b->d
13107       0x10325476, // h->w
13108       0x00003074, // h->d
13109       0x00001032, // w->d
13110   };
13111 
13112   uint64_t Elems = 0;
13113   int Index;
13114   SDValue Input;
13115 
13116   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13117     if (!Op)
13118       return false;
13119     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13120         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13121       return false;
13122 
13123     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13124     // of the right width.
13125     SDValue Extract = Op.getOperand(0);
13126     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13127       Extract = Extract.getOperand(0);
13128     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13129       return false;
13130 
13131     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13132     if (!ExtOp)
13133       return false;
13134 
13135     Index = ExtOp->getZExtValue();
13136     if (Input && Input != Extract.getOperand(0))
13137       return false;
13138 
13139     if (!Input)
13140       Input = Extract.getOperand(0);
13141 
13142     Elems = Elems << 8;
13143     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13144     Elems |= Index;
13145 
13146     return true;
13147   };
13148 
13149   // If the build vector operands aren't sign extended vector extracts,
13150   // of the same input vector, then return.
13151   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13152     if (!isSExtOfVecExtract(N->getOperand(i))) {
13153       return SDValue();
13154     }
13155   }
13156 
13157   // If the vector extract indicies are not correct, add the appropriate
13158   // vector_shuffle.
13159   int TgtElemArrayIdx;
13160   int InputSize = Input.getValueType().getScalarSizeInBits();
13161   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13162   if (InputSize + OutputSize == 40)
13163     TgtElemArrayIdx = 0;
13164   else if (InputSize + OutputSize == 72)
13165     TgtElemArrayIdx = 1;
13166   else if (InputSize + OutputSize == 48)
13167     TgtElemArrayIdx = 2;
13168   else if (InputSize + OutputSize == 80)
13169     TgtElemArrayIdx = 3;
13170   else if (InputSize + OutputSize == 96)
13171     TgtElemArrayIdx = 4;
13172   else
13173     return SDValue();
13174 
13175   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13176   CorrectElems = DAG.getDataLayout().isLittleEndian()
13177                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13178                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13179   if (Elems != CorrectElems) {
13180     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13181   }
13182 
13183   // Regular lowering will catch cases where a shuffle is not needed.
13184   return SDValue();
13185 }
13186 
13187 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13188                                                  DAGCombinerInfo &DCI) const {
13189   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13190          "Should be called with a BUILD_VECTOR node");
13191 
13192   SelectionDAG &DAG = DCI.DAG;
13193   SDLoc dl(N);
13194 
13195   if (!Subtarget.hasVSX())
13196     return SDValue();
13197 
13198   // The target independent DAG combiner will leave a build_vector of
13199   // float-to-int conversions intact. We can generate MUCH better code for
13200   // a float-to-int conversion of a vector of floats.
13201   SDValue FirstInput = N->getOperand(0);
13202   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13203     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13204     if (Reduced)
13205       return Reduced;
13206   }
13207 
13208   // If we're building a vector out of consecutive loads, just load that
13209   // vector type.
13210   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13211   if (Reduced)
13212     return Reduced;
13213 
13214   // If we're building a vector out of extended elements from another vector
13215   // we have P9 vector integer extend instructions. The code assumes legal
13216   // input types (i.e. it can't handle things like v4i16) so do not run before
13217   // legalization.
13218   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13219     Reduced = combineBVOfVecSExt(N, DAG);
13220     if (Reduced)
13221       return Reduced;
13222   }
13223 
13224 
13225   if (N->getValueType(0) != MVT::v2f64)
13226     return SDValue();
13227 
13228   // Looking for:
13229   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13230   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13231       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13232     return SDValue();
13233   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13234       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13235     return SDValue();
13236   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13237     return SDValue();
13238 
13239   SDValue Ext1 = FirstInput.getOperand(0);
13240   SDValue Ext2 = N->getOperand(1).getOperand(0);
13241   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13242      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13243     return SDValue();
13244 
13245   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13246   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13247   if (!Ext1Op || !Ext2Op)
13248     return SDValue();
13249   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13250       Ext1.getOperand(0) != Ext2.getOperand(0))
13251     return SDValue();
13252 
13253   int FirstElem = Ext1Op->getZExtValue();
13254   int SecondElem = Ext2Op->getZExtValue();
13255   int SubvecIdx;
13256   if (FirstElem == 0 && SecondElem == 1)
13257     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13258   else if (FirstElem == 2 && SecondElem == 3)
13259     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13260   else
13261     return SDValue();
13262 
13263   SDValue SrcVec = Ext1.getOperand(0);
13264   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13265     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13266   return DAG.getNode(NodeType, dl, MVT::v2f64,
13267                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13268 }
13269 
13270 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13271                                               DAGCombinerInfo &DCI) const {
13272   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13273           N->getOpcode() == ISD::UINT_TO_FP) &&
13274          "Need an int -> FP conversion node here");
13275 
13276   if (useSoftFloat() || !Subtarget.has64BitSupport())
13277     return SDValue();
13278 
13279   SelectionDAG &DAG = DCI.DAG;
13280   SDLoc dl(N);
13281   SDValue Op(N, 0);
13282 
13283   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13284   // from the hardware.
13285   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13286     return SDValue();
13287   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13288       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13289     return SDValue();
13290 
13291   SDValue FirstOperand(Op.getOperand(0));
13292   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13293     (FirstOperand.getValueType() == MVT::i8 ||
13294      FirstOperand.getValueType() == MVT::i16);
13295   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13296     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13297     bool DstDouble = Op.getValueType() == MVT::f64;
13298     unsigned ConvOp = Signed ?
13299       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13300       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13301     SDValue WidthConst =
13302       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13303                             dl, false);
13304     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13305     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13306     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13307                                          DAG.getVTList(MVT::f64, MVT::Other),
13308                                          Ops, MVT::i8, LDN->getMemOperand());
13309 
13310     // For signed conversion, we need to sign-extend the value in the VSR
13311     if (Signed) {
13312       SDValue ExtOps[] = { Ld, WidthConst };
13313       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13314       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13315     } else
13316       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13317   }
13318 
13319 
13320   // For i32 intermediate values, unfortunately, the conversion functions
13321   // leave the upper 32 bits of the value are undefined. Within the set of
13322   // scalar instructions, we have no method for zero- or sign-extending the
13323   // value. Thus, we cannot handle i32 intermediate values here.
13324   if (Op.getOperand(0).getValueType() == MVT::i32)
13325     return SDValue();
13326 
13327   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13328          "UINT_TO_FP is supported only with FPCVT");
13329 
13330   // If we have FCFIDS, then use it when converting to single-precision.
13331   // Otherwise, convert to double-precision and then round.
13332   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13333                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13334                                                             : PPCISD::FCFIDS)
13335                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13336                                                             : PPCISD::FCFID);
13337   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13338                   ? MVT::f32
13339                   : MVT::f64;
13340 
13341   // If we're converting from a float, to an int, and back to a float again,
13342   // then we don't need the store/load pair at all.
13343   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13344        Subtarget.hasFPCVT()) ||
13345       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13346     SDValue Src = Op.getOperand(0).getOperand(0);
13347     if (Src.getValueType() == MVT::f32) {
13348       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13349       DCI.AddToWorklist(Src.getNode());
13350     } else if (Src.getValueType() != MVT::f64) {
13351       // Make sure that we don't pick up a ppc_fp128 source value.
13352       return SDValue();
13353     }
13354 
13355     unsigned FCTOp =
13356       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13357                                                         PPCISD::FCTIDUZ;
13358 
13359     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13360     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13361 
13362     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13363       FP = DAG.getNode(ISD::FP_ROUND, dl,
13364                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13365       DCI.AddToWorklist(FP.getNode());
13366     }
13367 
13368     return FP;
13369   }
13370 
13371   return SDValue();
13372 }
13373 
13374 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13375 // builtins) into loads with swaps.
13376 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13377                                               DAGCombinerInfo &DCI) const {
13378   SelectionDAG &DAG = DCI.DAG;
13379   SDLoc dl(N);
13380   SDValue Chain;
13381   SDValue Base;
13382   MachineMemOperand *MMO;
13383 
13384   switch (N->getOpcode()) {
13385   default:
13386     llvm_unreachable("Unexpected opcode for little endian VSX load");
13387   case ISD::LOAD: {
13388     LoadSDNode *LD = cast<LoadSDNode>(N);
13389     Chain = LD->getChain();
13390     Base = LD->getBasePtr();
13391     MMO = LD->getMemOperand();
13392     // If the MMO suggests this isn't a load of a full vector, leave
13393     // things alone.  For a built-in, we have to make the change for
13394     // correctness, so if there is a size problem that will be a bug.
13395     if (MMO->getSize() < 16)
13396       return SDValue();
13397     break;
13398   }
13399   case ISD::INTRINSIC_W_CHAIN: {
13400     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13401     Chain = Intrin->getChain();
13402     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13403     // us what we want. Get operand 2 instead.
13404     Base = Intrin->getOperand(2);
13405     MMO = Intrin->getMemOperand();
13406     break;
13407   }
13408   }
13409 
13410   MVT VecTy = N->getValueType(0).getSimpleVT();
13411 
13412   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13413   // aligned and the type is a vector with elements up to 4 bytes
13414   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13415       && VecTy.getScalarSizeInBits() <= 32 ) {
13416     return SDValue();
13417   }
13418 
13419   SDValue LoadOps[] = { Chain, Base };
13420   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13421                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13422                                          LoadOps, MVT::v2f64, MMO);
13423 
13424   DCI.AddToWorklist(Load.getNode());
13425   Chain = Load.getValue(1);
13426   SDValue Swap = DAG.getNode(
13427       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13428   DCI.AddToWorklist(Swap.getNode());
13429 
13430   // Add a bitcast if the resulting load type doesn't match v2f64.
13431   if (VecTy != MVT::v2f64) {
13432     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13433     DCI.AddToWorklist(N.getNode());
13434     // Package {bitcast value, swap's chain} to match Load's shape.
13435     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13436                        N, Swap.getValue(1));
13437   }
13438 
13439   return Swap;
13440 }
13441 
13442 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13443 // builtins) into stores with swaps.
13444 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13445                                                DAGCombinerInfo &DCI) const {
13446   SelectionDAG &DAG = DCI.DAG;
13447   SDLoc dl(N);
13448   SDValue Chain;
13449   SDValue Base;
13450   unsigned SrcOpnd;
13451   MachineMemOperand *MMO;
13452 
13453   switch (N->getOpcode()) {
13454   default:
13455     llvm_unreachable("Unexpected opcode for little endian VSX store");
13456   case ISD::STORE: {
13457     StoreSDNode *ST = cast<StoreSDNode>(N);
13458     Chain = ST->getChain();
13459     Base = ST->getBasePtr();
13460     MMO = ST->getMemOperand();
13461     SrcOpnd = 1;
13462     // If the MMO suggests this isn't a store of a full vector, leave
13463     // things alone.  For a built-in, we have to make the change for
13464     // correctness, so if there is a size problem that will be a bug.
13465     if (MMO->getSize() < 16)
13466       return SDValue();
13467     break;
13468   }
13469   case ISD::INTRINSIC_VOID: {
13470     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13471     Chain = Intrin->getChain();
13472     // Intrin->getBasePtr() oddly does not get what we want.
13473     Base = Intrin->getOperand(3);
13474     MMO = Intrin->getMemOperand();
13475     SrcOpnd = 2;
13476     break;
13477   }
13478   }
13479 
13480   SDValue Src = N->getOperand(SrcOpnd);
13481   MVT VecTy = Src.getValueType().getSimpleVT();
13482 
13483   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13484   // aligned and the type is a vector with elements up to 4 bytes
13485   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13486       && VecTy.getScalarSizeInBits() <= 32 ) {
13487     return SDValue();
13488   }
13489 
13490   // All stores are done as v2f64 and possible bit cast.
13491   if (VecTy != MVT::v2f64) {
13492     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13493     DCI.AddToWorklist(Src.getNode());
13494   }
13495 
13496   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13497                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13498   DCI.AddToWorklist(Swap.getNode());
13499   Chain = Swap.getValue(1);
13500   SDValue StoreOps[] = { Chain, Swap, Base };
13501   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13502                                           DAG.getVTList(MVT::Other),
13503                                           StoreOps, VecTy, MMO);
13504   DCI.AddToWorklist(Store.getNode());
13505   return Store;
13506 }
13507 
13508 // Handle DAG combine for STORE (FP_TO_INT F).
13509 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13510                                                DAGCombinerInfo &DCI) const {
13511 
13512   SelectionDAG &DAG = DCI.DAG;
13513   SDLoc dl(N);
13514   unsigned Opcode = N->getOperand(1).getOpcode();
13515 
13516   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13517          && "Not a FP_TO_INT Instruction!");
13518 
13519   SDValue Val = N->getOperand(1).getOperand(0);
13520   EVT Op1VT = N->getOperand(1).getValueType();
13521   EVT ResVT = Val.getValueType();
13522 
13523   // Floating point types smaller than 32 bits are not legal on Power.
13524   if (ResVT.getScalarSizeInBits() < 32)
13525     return SDValue();
13526 
13527   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13528   bool ValidTypeForStoreFltAsInt =
13529         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13530          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13531 
13532   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13533       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13534     return SDValue();
13535 
13536   // Extend f32 values to f64
13537   if (ResVT.getScalarSizeInBits() == 32) {
13538     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13539     DCI.AddToWorklist(Val.getNode());
13540   }
13541 
13542   // Set signed or unsigned conversion opcode.
13543   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13544                           PPCISD::FP_TO_SINT_IN_VSR :
13545                           PPCISD::FP_TO_UINT_IN_VSR;
13546 
13547   Val = DAG.getNode(ConvOpcode,
13548                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13549   DCI.AddToWorklist(Val.getNode());
13550 
13551   // Set number of bytes being converted.
13552   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13553   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13554                     DAG.getIntPtrConstant(ByteSize, dl, false),
13555                     DAG.getValueType(Op1VT) };
13556 
13557   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13558           DAG.getVTList(MVT::Other), Ops,
13559           cast<StoreSDNode>(N)->getMemoryVT(),
13560           cast<StoreSDNode>(N)->getMemOperand());
13561 
13562   DCI.AddToWorklist(Val.getNode());
13563   return Val;
13564 }
13565 
13566 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13567                                                 LSBaseSDNode *LSBase,
13568                                                 DAGCombinerInfo &DCI) const {
13569   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13570         "Not a reverse memop pattern!");
13571 
13572   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13573     auto Mask = SVN->getMask();
13574     int i = 0;
13575     auto I = Mask.rbegin();
13576     auto E = Mask.rend();
13577 
13578     for (; I != E; ++I) {
13579       if (*I != i)
13580         return false;
13581       i++;
13582     }
13583     return true;
13584   };
13585 
13586   SelectionDAG &DAG = DCI.DAG;
13587   EVT VT = SVN->getValueType(0);
13588 
13589   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13590     return SDValue();
13591 
13592   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13593   // See comment in PPCVSXSwapRemoval.cpp.
13594   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13595   if (!Subtarget.hasP9Vector())
13596     return SDValue();
13597 
13598   if(!IsElementReverse(SVN))
13599     return SDValue();
13600 
13601   if (LSBase->getOpcode() == ISD::LOAD) {
13602     SDLoc dl(SVN);
13603     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13604     return DAG.getMemIntrinsicNode(
13605         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13606         LSBase->getMemoryVT(), LSBase->getMemOperand());
13607   }
13608 
13609   if (LSBase->getOpcode() == ISD::STORE) {
13610     SDLoc dl(LSBase);
13611     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13612                           LSBase->getBasePtr()};
13613     return DAG.getMemIntrinsicNode(
13614         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13615         LSBase->getMemoryVT(), LSBase->getMemOperand());
13616   }
13617 
13618   llvm_unreachable("Expected a load or store node here");
13619 }
13620 
13621 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13622                                              DAGCombinerInfo &DCI) const {
13623   SelectionDAG &DAG = DCI.DAG;
13624   SDLoc dl(N);
13625   switch (N->getOpcode()) {
13626   default: break;
13627   case ISD::ADD:
13628     return combineADD(N, DCI);
13629   case ISD::SHL:
13630     return combineSHL(N, DCI);
13631   case ISD::SRA:
13632     return combineSRA(N, DCI);
13633   case ISD::SRL:
13634     return combineSRL(N, DCI);
13635   case ISD::MUL:
13636     return combineMUL(N, DCI);
13637   case PPCISD::SHL:
13638     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13639         return N->getOperand(0);
13640     break;
13641   case PPCISD::SRL:
13642     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13643         return N->getOperand(0);
13644     break;
13645   case PPCISD::SRA:
13646     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13647       if (C->isNullValue() ||   //  0 >>s V -> 0.
13648           C->isAllOnesValue())    // -1 >>s V -> -1.
13649         return N->getOperand(0);
13650     }
13651     break;
13652   case ISD::SIGN_EXTEND:
13653   case ISD::ZERO_EXTEND:
13654   case ISD::ANY_EXTEND:
13655     return DAGCombineExtBoolTrunc(N, DCI);
13656   case ISD::TRUNCATE:
13657     return combineTRUNCATE(N, DCI);
13658   case ISD::SETCC:
13659     if (SDValue CSCC = combineSetCC(N, DCI))
13660       return CSCC;
13661     LLVM_FALLTHROUGH;
13662   case ISD::SELECT_CC:
13663     return DAGCombineTruncBoolExt(N, DCI);
13664   case ISD::SINT_TO_FP:
13665   case ISD::UINT_TO_FP:
13666     return combineFPToIntToFP(N, DCI);
13667   case ISD::VECTOR_SHUFFLE:
13668     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13669       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13670       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13671     }
13672     break;
13673   case ISD::STORE: {
13674 
13675     EVT Op1VT = N->getOperand(1).getValueType();
13676     unsigned Opcode = N->getOperand(1).getOpcode();
13677 
13678     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13679       SDValue Val= combineStoreFPToInt(N, DCI);
13680       if (Val)
13681         return Val;
13682     }
13683 
13684     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13685       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13686       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13687       if (Val)
13688         return Val;
13689     }
13690 
13691     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13692     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13693         N->getOperand(1).getNode()->hasOneUse() &&
13694         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13695          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13696 
13697       // STBRX can only handle simple types and it makes no sense to store less
13698       // two bytes in byte-reversed order.
13699       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13700       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13701         break;
13702 
13703       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13704       // Do an any-extend to 32-bits if this is a half-word input.
13705       if (BSwapOp.getValueType() == MVT::i16)
13706         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13707 
13708       // If the type of BSWAP operand is wider than stored memory width
13709       // it need to be shifted to the right side before STBRX.
13710       if (Op1VT.bitsGT(mVT)) {
13711         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13712         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13713                               DAG.getConstant(Shift, dl, MVT::i32));
13714         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13715         if (Op1VT == MVT::i64)
13716           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13717       }
13718 
13719       SDValue Ops[] = {
13720         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13721       };
13722       return
13723         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13724                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13725                                 cast<StoreSDNode>(N)->getMemOperand());
13726     }
13727 
13728     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13729     // So it can increase the chance of CSE constant construction.
13730     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13731         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13732       // Need to sign-extended to 64-bits to handle negative values.
13733       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13734       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13735                                     MemVT.getSizeInBits());
13736       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13737 
13738       // DAG.getTruncStore() can't be used here because it doesn't accept
13739       // the general (base + offset) addressing mode.
13740       // So we use UpdateNodeOperands and setTruncatingStore instead.
13741       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13742                              N->getOperand(3));
13743       cast<StoreSDNode>(N)->setTruncatingStore(true);
13744       return SDValue(N, 0);
13745     }
13746 
13747     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13748     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13749     if (Op1VT.isSimple()) {
13750       MVT StoreVT = Op1VT.getSimpleVT();
13751       if (Subtarget.needsSwapsForVSXMemOps() &&
13752           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13753            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13754         return expandVSXStoreForLE(N, DCI);
13755     }
13756     break;
13757   }
13758   case ISD::LOAD: {
13759     LoadSDNode *LD = cast<LoadSDNode>(N);
13760     EVT VT = LD->getValueType(0);
13761 
13762     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13763     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13764     if (VT.isSimple()) {
13765       MVT LoadVT = VT.getSimpleVT();
13766       if (Subtarget.needsSwapsForVSXMemOps() &&
13767           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13768            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13769         return expandVSXLoadForLE(N, DCI);
13770     }
13771 
13772     // We sometimes end up with a 64-bit integer load, from which we extract
13773     // two single-precision floating-point numbers. This happens with
13774     // std::complex<float>, and other similar structures, because of the way we
13775     // canonicalize structure copies. However, if we lack direct moves,
13776     // then the final bitcasts from the extracted integer values to the
13777     // floating-point numbers turn into store/load pairs. Even with direct moves,
13778     // just loading the two floating-point numbers is likely better.
13779     auto ReplaceTwoFloatLoad = [&]() {
13780       if (VT != MVT::i64)
13781         return false;
13782 
13783       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13784           LD->isVolatile())
13785         return false;
13786 
13787       //  We're looking for a sequence like this:
13788       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13789       //      t16: i64 = srl t13, Constant:i32<32>
13790       //    t17: i32 = truncate t16
13791       //  t18: f32 = bitcast t17
13792       //    t19: i32 = truncate t13
13793       //  t20: f32 = bitcast t19
13794 
13795       if (!LD->hasNUsesOfValue(2, 0))
13796         return false;
13797 
13798       auto UI = LD->use_begin();
13799       while (UI.getUse().getResNo() != 0) ++UI;
13800       SDNode *Trunc = *UI++;
13801       while (UI.getUse().getResNo() != 0) ++UI;
13802       SDNode *RightShift = *UI;
13803       if (Trunc->getOpcode() != ISD::TRUNCATE)
13804         std::swap(Trunc, RightShift);
13805 
13806       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13807           Trunc->getValueType(0) != MVT::i32 ||
13808           !Trunc->hasOneUse())
13809         return false;
13810       if (RightShift->getOpcode() != ISD::SRL ||
13811           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13812           RightShift->getConstantOperandVal(1) != 32 ||
13813           !RightShift->hasOneUse())
13814         return false;
13815 
13816       SDNode *Trunc2 = *RightShift->use_begin();
13817       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13818           Trunc2->getValueType(0) != MVT::i32 ||
13819           !Trunc2->hasOneUse())
13820         return false;
13821 
13822       SDNode *Bitcast = *Trunc->use_begin();
13823       SDNode *Bitcast2 = *Trunc2->use_begin();
13824 
13825       if (Bitcast->getOpcode() != ISD::BITCAST ||
13826           Bitcast->getValueType(0) != MVT::f32)
13827         return false;
13828       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13829           Bitcast2->getValueType(0) != MVT::f32)
13830         return false;
13831 
13832       if (Subtarget.isLittleEndian())
13833         std::swap(Bitcast, Bitcast2);
13834 
13835       // Bitcast has the second float (in memory-layout order) and Bitcast2
13836       // has the first one.
13837 
13838       SDValue BasePtr = LD->getBasePtr();
13839       if (LD->isIndexed()) {
13840         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13841                "Non-pre-inc AM on PPC?");
13842         BasePtr =
13843           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13844                       LD->getOffset());
13845       }
13846 
13847       auto MMOFlags =
13848           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13849       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13850                                       LD->getPointerInfo(), LD->getAlignment(),
13851                                       MMOFlags, LD->getAAInfo());
13852       SDValue AddPtr =
13853         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13854                     BasePtr, DAG.getIntPtrConstant(4, dl));
13855       SDValue FloatLoad2 = DAG.getLoad(
13856           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13857           LD->getPointerInfo().getWithOffset(4),
13858           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13859 
13860       if (LD->isIndexed()) {
13861         // Note that DAGCombine should re-form any pre-increment load(s) from
13862         // what is produced here if that makes sense.
13863         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13864       }
13865 
13866       DCI.CombineTo(Bitcast2, FloatLoad);
13867       DCI.CombineTo(Bitcast, FloatLoad2);
13868 
13869       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13870                                     SDValue(FloatLoad2.getNode(), 1));
13871       return true;
13872     };
13873 
13874     if (ReplaceTwoFloatLoad())
13875       return SDValue(N, 0);
13876 
13877     EVT MemVT = LD->getMemoryVT();
13878     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13879     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13880     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13881     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13882     if (LD->isUnindexed() && VT.isVector() &&
13883         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13884           // P8 and later hardware should just use LOAD.
13885           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13886                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13887          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13888           LD->getAlignment() >= ScalarABIAlignment)) &&
13889         LD->getAlignment() < ABIAlignment) {
13890       // This is a type-legal unaligned Altivec or QPX load.
13891       SDValue Chain = LD->getChain();
13892       SDValue Ptr = LD->getBasePtr();
13893       bool isLittleEndian = Subtarget.isLittleEndian();
13894 
13895       // This implements the loading of unaligned vectors as described in
13896       // the venerable Apple Velocity Engine overview. Specifically:
13897       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13898       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13899       //
13900       // The general idea is to expand a sequence of one or more unaligned
13901       // loads into an alignment-based permutation-control instruction (lvsl
13902       // or lvsr), a series of regular vector loads (which always truncate
13903       // their input address to an aligned address), and a series of
13904       // permutations.  The results of these permutations are the requested
13905       // loaded values.  The trick is that the last "extra" load is not taken
13906       // from the address you might suspect (sizeof(vector) bytes after the
13907       // last requested load), but rather sizeof(vector) - 1 bytes after the
13908       // last requested vector. The point of this is to avoid a page fault if
13909       // the base address happened to be aligned. This works because if the
13910       // base address is aligned, then adding less than a full vector length
13911       // will cause the last vector in the sequence to be (re)loaded.
13912       // Otherwise, the next vector will be fetched as you might suspect was
13913       // necessary.
13914 
13915       // We might be able to reuse the permutation generation from
13916       // a different base address offset from this one by an aligned amount.
13917       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13918       // optimization later.
13919       Intrinsic::ID Intr, IntrLD, IntrPerm;
13920       MVT PermCntlTy, PermTy, LDTy;
13921       if (Subtarget.hasAltivec()) {
13922         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13923                                  Intrinsic::ppc_altivec_lvsl;
13924         IntrLD = Intrinsic::ppc_altivec_lvx;
13925         IntrPerm = Intrinsic::ppc_altivec_vperm;
13926         PermCntlTy = MVT::v16i8;
13927         PermTy = MVT::v4i32;
13928         LDTy = MVT::v4i32;
13929       } else {
13930         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13931                                        Intrinsic::ppc_qpx_qvlpcls;
13932         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13933                                        Intrinsic::ppc_qpx_qvlfs;
13934         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13935         PermCntlTy = MVT::v4f64;
13936         PermTy = MVT::v4f64;
13937         LDTy = MemVT.getSimpleVT();
13938       }
13939 
13940       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13941 
13942       // Create the new MMO for the new base load. It is like the original MMO,
13943       // but represents an area in memory almost twice the vector size centered
13944       // on the original address. If the address is unaligned, we might start
13945       // reading up to (sizeof(vector)-1) bytes below the address of the
13946       // original unaligned load.
13947       MachineFunction &MF = DAG.getMachineFunction();
13948       MachineMemOperand *BaseMMO =
13949         MF.getMachineMemOperand(LD->getMemOperand(),
13950                                 -(long)MemVT.getStoreSize()+1,
13951                                 2*MemVT.getStoreSize()-1);
13952 
13953       // Create the new base load.
13954       SDValue LDXIntID =
13955           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13956       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13957       SDValue BaseLoad =
13958         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13959                                 DAG.getVTList(PermTy, MVT::Other),
13960                                 BaseLoadOps, LDTy, BaseMMO);
13961 
13962       // Note that the value of IncOffset (which is provided to the next
13963       // load's pointer info offset value, and thus used to calculate the
13964       // alignment), and the value of IncValue (which is actually used to
13965       // increment the pointer value) are different! This is because we
13966       // require the next load to appear to be aligned, even though it
13967       // is actually offset from the base pointer by a lesser amount.
13968       int IncOffset = VT.getSizeInBits() / 8;
13969       int IncValue = IncOffset;
13970 
13971       // Walk (both up and down) the chain looking for another load at the real
13972       // (aligned) offset (the alignment of the other load does not matter in
13973       // this case). If found, then do not use the offset reduction trick, as
13974       // that will prevent the loads from being later combined (as they would
13975       // otherwise be duplicates).
13976       if (!findConsecutiveLoad(LD, DAG))
13977         --IncValue;
13978 
13979       SDValue Increment =
13980           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13981       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13982 
13983       MachineMemOperand *ExtraMMO =
13984         MF.getMachineMemOperand(LD->getMemOperand(),
13985                                 1, 2*MemVT.getStoreSize()-1);
13986       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13987       SDValue ExtraLoad =
13988         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13989                                 DAG.getVTList(PermTy, MVT::Other),
13990                                 ExtraLoadOps, LDTy, ExtraMMO);
13991 
13992       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13993         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13994 
13995       // Because vperm has a big-endian bias, we must reverse the order
13996       // of the input vectors and complement the permute control vector
13997       // when generating little endian code.  We have already handled the
13998       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13999       // and ExtraLoad here.
14000       SDValue Perm;
14001       if (isLittleEndian)
14002         Perm = BuildIntrinsicOp(IntrPerm,
14003                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
14004       else
14005         Perm = BuildIntrinsicOp(IntrPerm,
14006                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
14007 
14008       if (VT != PermTy)
14009         Perm = Subtarget.hasAltivec() ?
14010                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
14011                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
14012                                DAG.getTargetConstant(1, dl, MVT::i64));
14013                                // second argument is 1 because this rounding
14014                                // is always exact.
14015 
14016       // The output of the permutation is our loaded result, the TokenFactor is
14017       // our new chain.
14018       DCI.CombineTo(N, Perm, TF);
14019       return SDValue(N, 0);
14020     }
14021     }
14022     break;
14023     case ISD::INTRINSIC_WO_CHAIN: {
14024       bool isLittleEndian = Subtarget.isLittleEndian();
14025       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
14026       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
14027                                            : Intrinsic::ppc_altivec_lvsl);
14028       if ((IID == Intr ||
14029            IID == Intrinsic::ppc_qpx_qvlpcld  ||
14030            IID == Intrinsic::ppc_qpx_qvlpcls) &&
14031         N->getOperand(1)->getOpcode() == ISD::ADD) {
14032         SDValue Add = N->getOperand(1);
14033 
14034         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
14035                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
14036 
14037         if (DAG.MaskedValueIsZero(Add->getOperand(1),
14038                                   APInt::getAllOnesValue(Bits /* alignment */)
14039                                       .zext(Add.getScalarValueSizeInBits()))) {
14040           SDNode *BasePtr = Add->getOperand(0).getNode();
14041           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14042                                     UE = BasePtr->use_end();
14043                UI != UE; ++UI) {
14044             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14045                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
14046               // We've found another LVSL/LVSR, and this address is an aligned
14047               // multiple of that one. The results will be the same, so use the
14048               // one we've just found instead.
14049 
14050               return SDValue(*UI, 0);
14051             }
14052           }
14053         }
14054 
14055         if (isa<ConstantSDNode>(Add->getOperand(1))) {
14056           SDNode *BasePtr = Add->getOperand(0).getNode();
14057           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14058                UE = BasePtr->use_end(); UI != UE; ++UI) {
14059             if (UI->getOpcode() == ISD::ADD &&
14060                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14061                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14062                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14063                 (1ULL << Bits) == 0) {
14064               SDNode *OtherAdd = *UI;
14065               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14066                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14067                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14068                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14069                   return SDValue(*VI, 0);
14070                 }
14071               }
14072             }
14073           }
14074         }
14075       }
14076 
14077       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14078       // Expose the vabsduw/h/b opportunity for down stream
14079       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14080           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14081            IID == Intrinsic::ppc_altivec_vmaxsh ||
14082            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14083         SDValue V1 = N->getOperand(1);
14084         SDValue V2 = N->getOperand(2);
14085         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14086              V1.getSimpleValueType() == MVT::v8i16 ||
14087              V1.getSimpleValueType() == MVT::v16i8) &&
14088             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14089           // (0-a, a)
14090           if (V1.getOpcode() == ISD::SUB &&
14091               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14092               V1.getOperand(1) == V2) {
14093             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14094           }
14095           // (a, 0-a)
14096           if (V2.getOpcode() == ISD::SUB &&
14097               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14098               V2.getOperand(1) == V1) {
14099             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14100           }
14101           // (x-y, y-x)
14102           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14103               V1.getOperand(0) == V2.getOperand(1) &&
14104               V1.getOperand(1) == V2.getOperand(0)) {
14105             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14106           }
14107         }
14108       }
14109     }
14110 
14111     break;
14112   case ISD::INTRINSIC_W_CHAIN:
14113     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14114     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14115     if (Subtarget.needsSwapsForVSXMemOps()) {
14116       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14117       default:
14118         break;
14119       case Intrinsic::ppc_vsx_lxvw4x:
14120       case Intrinsic::ppc_vsx_lxvd2x:
14121         return expandVSXLoadForLE(N, DCI);
14122       }
14123     }
14124     break;
14125   case ISD::INTRINSIC_VOID:
14126     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14127     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14128     if (Subtarget.needsSwapsForVSXMemOps()) {
14129       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14130       default:
14131         break;
14132       case Intrinsic::ppc_vsx_stxvw4x:
14133       case Intrinsic::ppc_vsx_stxvd2x:
14134         return expandVSXStoreForLE(N, DCI);
14135       }
14136     }
14137     break;
14138   case ISD::BSWAP:
14139     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14140     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14141         N->getOperand(0).hasOneUse() &&
14142         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14143          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14144           N->getValueType(0) == MVT::i64))) {
14145       SDValue Load = N->getOperand(0);
14146       LoadSDNode *LD = cast<LoadSDNode>(Load);
14147       // Create the byte-swapping load.
14148       SDValue Ops[] = {
14149         LD->getChain(),    // Chain
14150         LD->getBasePtr(),  // Ptr
14151         DAG.getValueType(N->getValueType(0)) // VT
14152       };
14153       SDValue BSLoad =
14154         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14155                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14156                                               MVT::i64 : MVT::i32, MVT::Other),
14157                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14158 
14159       // If this is an i16 load, insert the truncate.
14160       SDValue ResVal = BSLoad;
14161       if (N->getValueType(0) == MVT::i16)
14162         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14163 
14164       // First, combine the bswap away.  This makes the value produced by the
14165       // load dead.
14166       DCI.CombineTo(N, ResVal);
14167 
14168       // Next, combine the load away, we give it a bogus result value but a real
14169       // chain result.  The result value is dead because the bswap is dead.
14170       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14171 
14172       // Return N so it doesn't get rechecked!
14173       return SDValue(N, 0);
14174     }
14175     break;
14176   case PPCISD::VCMP:
14177     // If a VCMPo node already exists with exactly the same operands as this
14178     // node, use its result instead of this node (VCMPo computes both a CR6 and
14179     // a normal output).
14180     //
14181     if (!N->getOperand(0).hasOneUse() &&
14182         !N->getOperand(1).hasOneUse() &&
14183         !N->getOperand(2).hasOneUse()) {
14184 
14185       // Scan all of the users of the LHS, looking for VCMPo's that match.
14186       SDNode *VCMPoNode = nullptr;
14187 
14188       SDNode *LHSN = N->getOperand(0).getNode();
14189       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14190            UI != E; ++UI)
14191         if (UI->getOpcode() == PPCISD::VCMPo &&
14192             UI->getOperand(1) == N->getOperand(1) &&
14193             UI->getOperand(2) == N->getOperand(2) &&
14194             UI->getOperand(0) == N->getOperand(0)) {
14195           VCMPoNode = *UI;
14196           break;
14197         }
14198 
14199       // If there is no VCMPo node, or if the flag value has a single use, don't
14200       // transform this.
14201       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14202         break;
14203 
14204       // Look at the (necessarily single) use of the flag value.  If it has a
14205       // chain, this transformation is more complex.  Note that multiple things
14206       // could use the value result, which we should ignore.
14207       SDNode *FlagUser = nullptr;
14208       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14209            FlagUser == nullptr; ++UI) {
14210         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14211         SDNode *User = *UI;
14212         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14213           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14214             FlagUser = User;
14215             break;
14216           }
14217         }
14218       }
14219 
14220       // If the user is a MFOCRF instruction, we know this is safe.
14221       // Otherwise we give up for right now.
14222       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14223         return SDValue(VCMPoNode, 0);
14224     }
14225     break;
14226   case ISD::BRCOND: {
14227     SDValue Cond = N->getOperand(1);
14228     SDValue Target = N->getOperand(2);
14229 
14230     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14231         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14232           Intrinsic::loop_decrement) {
14233 
14234       // We now need to make the intrinsic dead (it cannot be instruction
14235       // selected).
14236       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14237       assert(Cond.getNode()->hasOneUse() &&
14238              "Counter decrement has more than one use");
14239 
14240       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14241                          N->getOperand(0), Target);
14242     }
14243   }
14244   break;
14245   case ISD::BR_CC: {
14246     // If this is a branch on an altivec predicate comparison, lower this so
14247     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14248     // lowering is done pre-legalize, because the legalizer lowers the predicate
14249     // compare down to code that is difficult to reassemble.
14250     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14251     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14252 
14253     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14254     // value. If so, pass-through the AND to get to the intrinsic.
14255     if (LHS.getOpcode() == ISD::AND &&
14256         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14257         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14258           Intrinsic::loop_decrement &&
14259         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14260         !isNullConstant(LHS.getOperand(1)))
14261       LHS = LHS.getOperand(0);
14262 
14263     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14264         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14265           Intrinsic::loop_decrement &&
14266         isa<ConstantSDNode>(RHS)) {
14267       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14268              "Counter decrement comparison is not EQ or NE");
14269 
14270       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14271       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14272                     (CC == ISD::SETNE && !Val);
14273 
14274       // We now need to make the intrinsic dead (it cannot be instruction
14275       // selected).
14276       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14277       assert(LHS.getNode()->hasOneUse() &&
14278              "Counter decrement has more than one use");
14279 
14280       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14281                          N->getOperand(0), N->getOperand(4));
14282     }
14283 
14284     int CompareOpc;
14285     bool isDot;
14286 
14287     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14288         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14289         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14290       assert(isDot && "Can't compare against a vector result!");
14291 
14292       // If this is a comparison against something other than 0/1, then we know
14293       // that the condition is never/always true.
14294       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14295       if (Val != 0 && Val != 1) {
14296         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14297           return N->getOperand(0);
14298         // Always !=, turn it into an unconditional branch.
14299         return DAG.getNode(ISD::BR, dl, MVT::Other,
14300                            N->getOperand(0), N->getOperand(4));
14301       }
14302 
14303       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14304 
14305       // Create the PPCISD altivec 'dot' comparison node.
14306       SDValue Ops[] = {
14307         LHS.getOperand(2),  // LHS of compare
14308         LHS.getOperand(3),  // RHS of compare
14309         DAG.getConstant(CompareOpc, dl, MVT::i32)
14310       };
14311       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14312       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14313 
14314       // Unpack the result based on how the target uses it.
14315       PPC::Predicate CompOpc;
14316       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14317       default:  // Can't happen, don't crash on invalid number though.
14318       case 0:   // Branch on the value of the EQ bit of CR6.
14319         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14320         break;
14321       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14322         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14323         break;
14324       case 2:   // Branch on the value of the LT bit of CR6.
14325         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14326         break;
14327       case 3:   // Branch on the inverted value of the LT bit of CR6.
14328         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14329         break;
14330       }
14331 
14332       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14333                          DAG.getConstant(CompOpc, dl, MVT::i32),
14334                          DAG.getRegister(PPC::CR6, MVT::i32),
14335                          N->getOperand(4), CompNode.getValue(1));
14336     }
14337     break;
14338   }
14339   case ISD::BUILD_VECTOR:
14340     return DAGCombineBuildVector(N, DCI);
14341   case ISD::ABS:
14342     return combineABS(N, DCI);
14343   case ISD::VSELECT:
14344     return combineVSelect(N, DCI);
14345   }
14346 
14347   return SDValue();
14348 }
14349 
14350 SDValue
14351 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14352                                  SelectionDAG &DAG,
14353                                  SmallVectorImpl<SDNode *> &Created) const {
14354   // fold (sdiv X, pow2)
14355   EVT VT = N->getValueType(0);
14356   if (VT == MVT::i64 && !Subtarget.isPPC64())
14357     return SDValue();
14358   if ((VT != MVT::i32 && VT != MVT::i64) ||
14359       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14360     return SDValue();
14361 
14362   SDLoc DL(N);
14363   SDValue N0 = N->getOperand(0);
14364 
14365   bool IsNegPow2 = (-Divisor).isPowerOf2();
14366   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14367   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14368 
14369   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14370   Created.push_back(Op.getNode());
14371 
14372   if (IsNegPow2) {
14373     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14374     Created.push_back(Op.getNode());
14375   }
14376 
14377   return Op;
14378 }
14379 
14380 //===----------------------------------------------------------------------===//
14381 // Inline Assembly Support
14382 //===----------------------------------------------------------------------===//
14383 
14384 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14385                                                       KnownBits &Known,
14386                                                       const APInt &DemandedElts,
14387                                                       const SelectionDAG &DAG,
14388                                                       unsigned Depth) const {
14389   Known.resetAll();
14390   switch (Op.getOpcode()) {
14391   default: break;
14392   case PPCISD::LBRX: {
14393     // lhbrx is known to have the top bits cleared out.
14394     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14395       Known.Zero = 0xFFFF0000;
14396     break;
14397   }
14398   case ISD::INTRINSIC_WO_CHAIN: {
14399     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14400     default: break;
14401     case Intrinsic::ppc_altivec_vcmpbfp_p:
14402     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14403     case Intrinsic::ppc_altivec_vcmpequb_p:
14404     case Intrinsic::ppc_altivec_vcmpequh_p:
14405     case Intrinsic::ppc_altivec_vcmpequw_p:
14406     case Intrinsic::ppc_altivec_vcmpequd_p:
14407     case Intrinsic::ppc_altivec_vcmpgefp_p:
14408     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14409     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14410     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14411     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14412     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14413     case Intrinsic::ppc_altivec_vcmpgtub_p:
14414     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14415     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14416     case Intrinsic::ppc_altivec_vcmpgtud_p:
14417       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14418       break;
14419     }
14420   }
14421   }
14422 }
14423 
14424 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14425   switch (Subtarget.getCPUDirective()) {
14426   default: break;
14427   case PPC::DIR_970:
14428   case PPC::DIR_PWR4:
14429   case PPC::DIR_PWR5:
14430   case PPC::DIR_PWR5X:
14431   case PPC::DIR_PWR6:
14432   case PPC::DIR_PWR6X:
14433   case PPC::DIR_PWR7:
14434   case PPC::DIR_PWR8:
14435   case PPC::DIR_PWR9:
14436   case PPC::DIR_PWR_FUTURE: {
14437     if (!ML)
14438       break;
14439 
14440     if (!DisableInnermostLoopAlign32) {
14441       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14442       // so that we can decrease cache misses and branch-prediction misses.
14443       // Actual alignment of the loop will depend on the hotness check and other
14444       // logic in alignBlocks.
14445       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14446         return Align(32);
14447     }
14448 
14449     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14450 
14451     // For small loops (between 5 and 8 instructions), align to a 32-byte
14452     // boundary so that the entire loop fits in one instruction-cache line.
14453     uint64_t LoopSize = 0;
14454     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14455       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14456         LoopSize += TII->getInstSizeInBytes(*J);
14457         if (LoopSize > 32)
14458           break;
14459       }
14460 
14461     if (LoopSize > 16 && LoopSize <= 32)
14462       return Align(32);
14463 
14464     break;
14465   }
14466   }
14467 
14468   return TargetLowering::getPrefLoopAlignment(ML);
14469 }
14470 
14471 /// getConstraintType - Given a constraint, return the type of
14472 /// constraint it is for this target.
14473 PPCTargetLowering::ConstraintType
14474 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14475   if (Constraint.size() == 1) {
14476     switch (Constraint[0]) {
14477     default: break;
14478     case 'b':
14479     case 'r':
14480     case 'f':
14481     case 'd':
14482     case 'v':
14483     case 'y':
14484       return C_RegisterClass;
14485     case 'Z':
14486       // FIXME: While Z does indicate a memory constraint, it specifically
14487       // indicates an r+r address (used in conjunction with the 'y' modifier
14488       // in the replacement string). Currently, we're forcing the base
14489       // register to be r0 in the asm printer (which is interpreted as zero)
14490       // and forming the complete address in the second register. This is
14491       // suboptimal.
14492       return C_Memory;
14493     }
14494   } else if (Constraint == "wc") { // individual CR bits.
14495     return C_RegisterClass;
14496   } else if (Constraint == "wa" || Constraint == "wd" ||
14497              Constraint == "wf" || Constraint == "ws" ||
14498              Constraint == "wi" || Constraint == "ww") {
14499     return C_RegisterClass; // VSX registers.
14500   }
14501   return TargetLowering::getConstraintType(Constraint);
14502 }
14503 
14504 /// Examine constraint type and operand type and determine a weight value.
14505 /// This object must already have been set up with the operand type
14506 /// and the current alternative constraint selected.
14507 TargetLowering::ConstraintWeight
14508 PPCTargetLowering::getSingleConstraintMatchWeight(
14509     AsmOperandInfo &info, const char *constraint) const {
14510   ConstraintWeight weight = CW_Invalid;
14511   Value *CallOperandVal = info.CallOperandVal;
14512     // If we don't have a value, we can't do a match,
14513     // but allow it at the lowest weight.
14514   if (!CallOperandVal)
14515     return CW_Default;
14516   Type *type = CallOperandVal->getType();
14517 
14518   // Look at the constraint type.
14519   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14520     return CW_Register; // an individual CR bit.
14521   else if ((StringRef(constraint) == "wa" ||
14522             StringRef(constraint) == "wd" ||
14523             StringRef(constraint) == "wf") &&
14524            type->isVectorTy())
14525     return CW_Register;
14526   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14527     return CW_Register; // just hold 64-bit integers data.
14528   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14529     return CW_Register;
14530   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14531     return CW_Register;
14532 
14533   switch (*constraint) {
14534   default:
14535     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14536     break;
14537   case 'b':
14538     if (type->isIntegerTy())
14539       weight = CW_Register;
14540     break;
14541   case 'f':
14542     if (type->isFloatTy())
14543       weight = CW_Register;
14544     break;
14545   case 'd':
14546     if (type->isDoubleTy())
14547       weight = CW_Register;
14548     break;
14549   case 'v':
14550     if (type->isVectorTy())
14551       weight = CW_Register;
14552     break;
14553   case 'y':
14554     weight = CW_Register;
14555     break;
14556   case 'Z':
14557     weight = CW_Memory;
14558     break;
14559   }
14560   return weight;
14561 }
14562 
14563 std::pair<unsigned, const TargetRegisterClass *>
14564 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14565                                                 StringRef Constraint,
14566                                                 MVT VT) const {
14567   if (Constraint.size() == 1) {
14568     // GCC RS6000 Constraint Letters
14569     switch (Constraint[0]) {
14570     case 'b':   // R1-R31
14571       if (VT == MVT::i64 && Subtarget.isPPC64())
14572         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14573       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14574     case 'r':   // R0-R31
14575       if (VT == MVT::i64 && Subtarget.isPPC64())
14576         return std::make_pair(0U, &PPC::G8RCRegClass);
14577       return std::make_pair(0U, &PPC::GPRCRegClass);
14578     // 'd' and 'f' constraints are both defined to be "the floating point
14579     // registers", where one is for 32-bit and the other for 64-bit. We don't
14580     // really care overly much here so just give them all the same reg classes.
14581     case 'd':
14582     case 'f':
14583       if (Subtarget.hasSPE()) {
14584         if (VT == MVT::f32 || VT == MVT::i32)
14585           return std::make_pair(0U, &PPC::GPRCRegClass);
14586         if (VT == MVT::f64 || VT == MVT::i64)
14587           return std::make_pair(0U, &PPC::SPERCRegClass);
14588       } else {
14589         if (VT == MVT::f32 || VT == MVT::i32)
14590           return std::make_pair(0U, &PPC::F4RCRegClass);
14591         if (VT == MVT::f64 || VT == MVT::i64)
14592           return std::make_pair(0U, &PPC::F8RCRegClass);
14593         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14594           return std::make_pair(0U, &PPC::QFRCRegClass);
14595         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14596           return std::make_pair(0U, &PPC::QSRCRegClass);
14597       }
14598       break;
14599     case 'v':
14600       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14601         return std::make_pair(0U, &PPC::QFRCRegClass);
14602       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14603         return std::make_pair(0U, &PPC::QSRCRegClass);
14604       if (Subtarget.hasAltivec())
14605         return std::make_pair(0U, &PPC::VRRCRegClass);
14606       break;
14607     case 'y':   // crrc
14608       return std::make_pair(0U, &PPC::CRRCRegClass);
14609     }
14610   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14611     // An individual CR bit.
14612     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14613   } else if ((Constraint == "wa" || Constraint == "wd" ||
14614              Constraint == "wf" || Constraint == "wi") &&
14615              Subtarget.hasVSX()) {
14616     return std::make_pair(0U, &PPC::VSRCRegClass);
14617   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14618     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14619       return std::make_pair(0U, &PPC::VSSRCRegClass);
14620     else
14621       return std::make_pair(0U, &PPC::VSFRCRegClass);
14622   }
14623 
14624   // If we name a VSX register, we can't defer to the base class because it
14625   // will not recognize the correct register (their names will be VSL{0-31}
14626   // and V{0-31} so they won't match). So we match them here.
14627   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14628     int VSNum = atoi(Constraint.data() + 3);
14629     assert(VSNum >= 0 && VSNum <= 63 &&
14630            "Attempted to access a vsr out of range");
14631     if (VSNum < 32)
14632       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14633     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14634   }
14635   std::pair<unsigned, const TargetRegisterClass *> R =
14636       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14637 
14638   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14639   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14640   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14641   // register.
14642   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14643   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14644   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14645       PPC::GPRCRegClass.contains(R.first))
14646     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14647                             PPC::sub_32, &PPC::G8RCRegClass),
14648                           &PPC::G8RCRegClass);
14649 
14650   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14651   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14652     R.first = PPC::CR0;
14653     R.second = &PPC::CRRCRegClass;
14654   }
14655 
14656   return R;
14657 }
14658 
14659 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14660 /// vector.  If it is invalid, don't add anything to Ops.
14661 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14662                                                      std::string &Constraint,
14663                                                      std::vector<SDValue>&Ops,
14664                                                      SelectionDAG &DAG) const {
14665   SDValue Result;
14666 
14667   // Only support length 1 constraints.
14668   if (Constraint.length() > 1) return;
14669 
14670   char Letter = Constraint[0];
14671   switch (Letter) {
14672   default: break;
14673   case 'I':
14674   case 'J':
14675   case 'K':
14676   case 'L':
14677   case 'M':
14678   case 'N':
14679   case 'O':
14680   case 'P': {
14681     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14682     if (!CST) return; // Must be an immediate to match.
14683     SDLoc dl(Op);
14684     int64_t Value = CST->getSExtValue();
14685     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14686                          // numbers are printed as such.
14687     switch (Letter) {
14688     default: llvm_unreachable("Unknown constraint letter!");
14689     case 'I':  // "I" is a signed 16-bit constant.
14690       if (isInt<16>(Value))
14691         Result = DAG.getTargetConstant(Value, dl, TCVT);
14692       break;
14693     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14694       if (isShiftedUInt<16, 16>(Value))
14695         Result = DAG.getTargetConstant(Value, dl, TCVT);
14696       break;
14697     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14698       if (isShiftedInt<16, 16>(Value))
14699         Result = DAG.getTargetConstant(Value, dl, TCVT);
14700       break;
14701     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14702       if (isUInt<16>(Value))
14703         Result = DAG.getTargetConstant(Value, dl, TCVT);
14704       break;
14705     case 'M':  // "M" is a constant that is greater than 31.
14706       if (Value > 31)
14707         Result = DAG.getTargetConstant(Value, dl, TCVT);
14708       break;
14709     case 'N':  // "N" is a positive constant that is an exact power of two.
14710       if (Value > 0 && isPowerOf2_64(Value))
14711         Result = DAG.getTargetConstant(Value, dl, TCVT);
14712       break;
14713     case 'O':  // "O" is the constant zero.
14714       if (Value == 0)
14715         Result = DAG.getTargetConstant(Value, dl, TCVT);
14716       break;
14717     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14718       if (isInt<16>(-Value))
14719         Result = DAG.getTargetConstant(Value, dl, TCVT);
14720       break;
14721     }
14722     break;
14723   }
14724   }
14725 
14726   if (Result.getNode()) {
14727     Ops.push_back(Result);
14728     return;
14729   }
14730 
14731   // Handle standard constraint letters.
14732   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14733 }
14734 
14735 // isLegalAddressingMode - Return true if the addressing mode represented
14736 // by AM is legal for this target, for a load/store of the specified type.
14737 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14738                                               const AddrMode &AM, Type *Ty,
14739                                               unsigned AS, Instruction *I) const {
14740   // PPC does not allow r+i addressing modes for vectors!
14741   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14742     return false;
14743 
14744   // PPC allows a sign-extended 16-bit immediate field.
14745   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14746     return false;
14747 
14748   // No global is ever allowed as a base.
14749   if (AM.BaseGV)
14750     return false;
14751 
14752   // PPC only support r+r,
14753   switch (AM.Scale) {
14754   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14755     break;
14756   case 1:
14757     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14758       return false;
14759     // Otherwise we have r+r or r+i.
14760     break;
14761   case 2:
14762     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14763       return false;
14764     // Allow 2*r as r+r.
14765     break;
14766   default:
14767     // No other scales are supported.
14768     return false;
14769   }
14770 
14771   return true;
14772 }
14773 
14774 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14775                                            SelectionDAG &DAG) const {
14776   MachineFunction &MF = DAG.getMachineFunction();
14777   MachineFrameInfo &MFI = MF.getFrameInfo();
14778   MFI.setReturnAddressIsTaken(true);
14779 
14780   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14781     return SDValue();
14782 
14783   SDLoc dl(Op);
14784   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14785 
14786   // Make sure the function does not optimize away the store of the RA to
14787   // the stack.
14788   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14789   FuncInfo->setLRStoreRequired();
14790   bool isPPC64 = Subtarget.isPPC64();
14791   auto PtrVT = getPointerTy(MF.getDataLayout());
14792 
14793   if (Depth > 0) {
14794     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14795     SDValue Offset =
14796         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14797                         isPPC64 ? MVT::i64 : MVT::i32);
14798     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14799                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14800                        MachinePointerInfo());
14801   }
14802 
14803   // Just load the return address off the stack.
14804   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14805   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14806                      MachinePointerInfo());
14807 }
14808 
14809 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14810                                           SelectionDAG &DAG) const {
14811   SDLoc dl(Op);
14812   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14813 
14814   MachineFunction &MF = DAG.getMachineFunction();
14815   MachineFrameInfo &MFI = MF.getFrameInfo();
14816   MFI.setFrameAddressIsTaken(true);
14817 
14818   EVT PtrVT = getPointerTy(MF.getDataLayout());
14819   bool isPPC64 = PtrVT == MVT::i64;
14820 
14821   // Naked functions never have a frame pointer, and so we use r1. For all
14822   // other functions, this decision must be delayed until during PEI.
14823   unsigned FrameReg;
14824   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14825     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14826   else
14827     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14828 
14829   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14830                                          PtrVT);
14831   while (Depth--)
14832     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14833                             FrameAddr, MachinePointerInfo());
14834   return FrameAddr;
14835 }
14836 
14837 // FIXME? Maybe this could be a TableGen attribute on some registers and
14838 // this table could be generated automatically from RegInfo.
14839 Register PPCTargetLowering::getRegisterByName(const char* RegName, LLT VT,
14840                                               const MachineFunction &MF) const {
14841   bool isPPC64 = Subtarget.isPPC64();
14842 
14843   bool is64Bit = isPPC64 && VT == LLT::scalar(64);
14844   if (!is64Bit && VT != LLT::scalar(32))
14845     report_fatal_error("Invalid register global variable type");
14846 
14847   Register Reg = StringSwitch<Register>(RegName)
14848                      .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14849                      .Case("r2", isPPC64 ? Register() : PPC::R2)
14850                      .Case("r13", (is64Bit ? PPC::X13 : PPC::R13))
14851                      .Default(Register());
14852 
14853   if (Reg)
14854     return Reg;
14855   report_fatal_error("Invalid register name global variable");
14856 }
14857 
14858 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14859   // 32-bit SVR4 ABI access everything as got-indirect.
14860   if (Subtarget.is32BitELFABI())
14861     return true;
14862 
14863   // AIX accesses everything indirectly through the TOC, which is similar to
14864   // the GOT.
14865   if (Subtarget.isAIXABI())
14866     return true;
14867 
14868   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14869   // If it is small or large code model, module locals are accessed
14870   // indirectly by loading their address from .toc/.got.
14871   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14872     return true;
14873 
14874   // JumpTable and BlockAddress are accessed as got-indirect.
14875   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14876     return true;
14877 
14878   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14879     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14880 
14881   return false;
14882 }
14883 
14884 bool
14885 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14886   // The PowerPC target isn't yet aware of offsets.
14887   return false;
14888 }
14889 
14890 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14891                                            const CallInst &I,
14892                                            MachineFunction &MF,
14893                                            unsigned Intrinsic) const {
14894   switch (Intrinsic) {
14895   case Intrinsic::ppc_qpx_qvlfd:
14896   case Intrinsic::ppc_qpx_qvlfs:
14897   case Intrinsic::ppc_qpx_qvlfcd:
14898   case Intrinsic::ppc_qpx_qvlfcs:
14899   case Intrinsic::ppc_qpx_qvlfiwa:
14900   case Intrinsic::ppc_qpx_qvlfiwz:
14901   case Intrinsic::ppc_altivec_lvx:
14902   case Intrinsic::ppc_altivec_lvxl:
14903   case Intrinsic::ppc_altivec_lvebx:
14904   case Intrinsic::ppc_altivec_lvehx:
14905   case Intrinsic::ppc_altivec_lvewx:
14906   case Intrinsic::ppc_vsx_lxvd2x:
14907   case Intrinsic::ppc_vsx_lxvw4x: {
14908     EVT VT;
14909     switch (Intrinsic) {
14910     case Intrinsic::ppc_altivec_lvebx:
14911       VT = MVT::i8;
14912       break;
14913     case Intrinsic::ppc_altivec_lvehx:
14914       VT = MVT::i16;
14915       break;
14916     case Intrinsic::ppc_altivec_lvewx:
14917       VT = MVT::i32;
14918       break;
14919     case Intrinsic::ppc_vsx_lxvd2x:
14920       VT = MVT::v2f64;
14921       break;
14922     case Intrinsic::ppc_qpx_qvlfd:
14923       VT = MVT::v4f64;
14924       break;
14925     case Intrinsic::ppc_qpx_qvlfs:
14926       VT = MVT::v4f32;
14927       break;
14928     case Intrinsic::ppc_qpx_qvlfcd:
14929       VT = MVT::v2f64;
14930       break;
14931     case Intrinsic::ppc_qpx_qvlfcs:
14932       VT = MVT::v2f32;
14933       break;
14934     default:
14935       VT = MVT::v4i32;
14936       break;
14937     }
14938 
14939     Info.opc = ISD::INTRINSIC_W_CHAIN;
14940     Info.memVT = VT;
14941     Info.ptrVal = I.getArgOperand(0);
14942     Info.offset = -VT.getStoreSize()+1;
14943     Info.size = 2*VT.getStoreSize()-1;
14944     Info.align = Align(1);
14945     Info.flags = MachineMemOperand::MOLoad;
14946     return true;
14947   }
14948   case Intrinsic::ppc_qpx_qvlfda:
14949   case Intrinsic::ppc_qpx_qvlfsa:
14950   case Intrinsic::ppc_qpx_qvlfcda:
14951   case Intrinsic::ppc_qpx_qvlfcsa:
14952   case Intrinsic::ppc_qpx_qvlfiwaa:
14953   case Intrinsic::ppc_qpx_qvlfiwza: {
14954     EVT VT;
14955     switch (Intrinsic) {
14956     case Intrinsic::ppc_qpx_qvlfda:
14957       VT = MVT::v4f64;
14958       break;
14959     case Intrinsic::ppc_qpx_qvlfsa:
14960       VT = MVT::v4f32;
14961       break;
14962     case Intrinsic::ppc_qpx_qvlfcda:
14963       VT = MVT::v2f64;
14964       break;
14965     case Intrinsic::ppc_qpx_qvlfcsa:
14966       VT = MVT::v2f32;
14967       break;
14968     default:
14969       VT = MVT::v4i32;
14970       break;
14971     }
14972 
14973     Info.opc = ISD::INTRINSIC_W_CHAIN;
14974     Info.memVT = VT;
14975     Info.ptrVal = I.getArgOperand(0);
14976     Info.offset = 0;
14977     Info.size = VT.getStoreSize();
14978     Info.align = Align(1);
14979     Info.flags = MachineMemOperand::MOLoad;
14980     return true;
14981   }
14982   case Intrinsic::ppc_qpx_qvstfd:
14983   case Intrinsic::ppc_qpx_qvstfs:
14984   case Intrinsic::ppc_qpx_qvstfcd:
14985   case Intrinsic::ppc_qpx_qvstfcs:
14986   case Intrinsic::ppc_qpx_qvstfiw:
14987   case Intrinsic::ppc_altivec_stvx:
14988   case Intrinsic::ppc_altivec_stvxl:
14989   case Intrinsic::ppc_altivec_stvebx:
14990   case Intrinsic::ppc_altivec_stvehx:
14991   case Intrinsic::ppc_altivec_stvewx:
14992   case Intrinsic::ppc_vsx_stxvd2x:
14993   case Intrinsic::ppc_vsx_stxvw4x: {
14994     EVT VT;
14995     switch (Intrinsic) {
14996     case Intrinsic::ppc_altivec_stvebx:
14997       VT = MVT::i8;
14998       break;
14999     case Intrinsic::ppc_altivec_stvehx:
15000       VT = MVT::i16;
15001       break;
15002     case Intrinsic::ppc_altivec_stvewx:
15003       VT = MVT::i32;
15004       break;
15005     case Intrinsic::ppc_vsx_stxvd2x:
15006       VT = MVT::v2f64;
15007       break;
15008     case Intrinsic::ppc_qpx_qvstfd:
15009       VT = MVT::v4f64;
15010       break;
15011     case Intrinsic::ppc_qpx_qvstfs:
15012       VT = MVT::v4f32;
15013       break;
15014     case Intrinsic::ppc_qpx_qvstfcd:
15015       VT = MVT::v2f64;
15016       break;
15017     case Intrinsic::ppc_qpx_qvstfcs:
15018       VT = MVT::v2f32;
15019       break;
15020     default:
15021       VT = MVT::v4i32;
15022       break;
15023     }
15024 
15025     Info.opc = ISD::INTRINSIC_VOID;
15026     Info.memVT = VT;
15027     Info.ptrVal = I.getArgOperand(1);
15028     Info.offset = -VT.getStoreSize()+1;
15029     Info.size = 2*VT.getStoreSize()-1;
15030     Info.align = Align(1);
15031     Info.flags = MachineMemOperand::MOStore;
15032     return true;
15033   }
15034   case Intrinsic::ppc_qpx_qvstfda:
15035   case Intrinsic::ppc_qpx_qvstfsa:
15036   case Intrinsic::ppc_qpx_qvstfcda:
15037   case Intrinsic::ppc_qpx_qvstfcsa:
15038   case Intrinsic::ppc_qpx_qvstfiwa: {
15039     EVT VT;
15040     switch (Intrinsic) {
15041     case Intrinsic::ppc_qpx_qvstfda:
15042       VT = MVT::v4f64;
15043       break;
15044     case Intrinsic::ppc_qpx_qvstfsa:
15045       VT = MVT::v4f32;
15046       break;
15047     case Intrinsic::ppc_qpx_qvstfcda:
15048       VT = MVT::v2f64;
15049       break;
15050     case Intrinsic::ppc_qpx_qvstfcsa:
15051       VT = MVT::v2f32;
15052       break;
15053     default:
15054       VT = MVT::v4i32;
15055       break;
15056     }
15057 
15058     Info.opc = ISD::INTRINSIC_VOID;
15059     Info.memVT = VT;
15060     Info.ptrVal = I.getArgOperand(1);
15061     Info.offset = 0;
15062     Info.size = VT.getStoreSize();
15063     Info.align = Align(1);
15064     Info.flags = MachineMemOperand::MOStore;
15065     return true;
15066   }
15067   default:
15068     break;
15069   }
15070 
15071   return false;
15072 }
15073 
15074 /// It returns EVT::Other if the type should be determined using generic
15075 /// target-independent logic.
15076 EVT PPCTargetLowering::getOptimalMemOpType(
15077     const MemOp &Op, const AttributeList &FuncAttributes) const {
15078   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15079     // When expanding a memset, require at least two QPX instructions to cover
15080     // the cost of loading the value to be stored from the constant pool.
15081     if (Subtarget.hasQPX() && Op.size() >= 32 &&
15082         (!Op.isMemset() || Op.size() >= 64) &&
15083         (!Op.getSrcAlign() || Op.getSrcAlign() >= 32) &&
15084         (!Op.getDstAlign() || Op.getDstAlign() >= 32) &&
15085         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15086       return MVT::v4f64;
15087     }
15088 
15089     // We should use Altivec/VSX loads and stores when available. For unaligned
15090     // addresses, unaligned VSX loads are only fast starting with the P8.
15091     if (Subtarget.hasAltivec() && Op.size() >= 16 &&
15092         (((!Op.getSrcAlign() || Op.getSrcAlign() >= 16) &&
15093           (!Op.getDstAlign() || Op.getDstAlign() >= 16)) ||
15094          ((Op.isMemset() && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15095       return MVT::v4i32;
15096   }
15097 
15098   if (Subtarget.isPPC64()) {
15099     return MVT::i64;
15100   }
15101 
15102   return MVT::i32;
15103 }
15104 
15105 /// Returns true if it is beneficial to convert a load of a constant
15106 /// to just the constant itself.
15107 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15108                                                           Type *Ty) const {
15109   assert(Ty->isIntegerTy());
15110 
15111   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15112   return !(BitSize == 0 || BitSize > 64);
15113 }
15114 
15115 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15116   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15117     return false;
15118   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15119   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15120   return NumBits1 == 64 && NumBits2 == 32;
15121 }
15122 
15123 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15124   if (!VT1.isInteger() || !VT2.isInteger())
15125     return false;
15126   unsigned NumBits1 = VT1.getSizeInBits();
15127   unsigned NumBits2 = VT2.getSizeInBits();
15128   return NumBits1 == 64 && NumBits2 == 32;
15129 }
15130 
15131 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15132   // Generally speaking, zexts are not free, but they are free when they can be
15133   // folded with other operations.
15134   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15135     EVT MemVT = LD->getMemoryVT();
15136     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15137          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15138         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15139          LD->getExtensionType() == ISD::ZEXTLOAD))
15140       return true;
15141   }
15142 
15143   // FIXME: Add other cases...
15144   //  - 32-bit shifts with a zext to i64
15145   //  - zext after ctlz, bswap, etc.
15146   //  - zext after and by a constant mask
15147 
15148   return TargetLowering::isZExtFree(Val, VT2);
15149 }
15150 
15151 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15152   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15153          "invalid fpext types");
15154   // Extending to float128 is not free.
15155   if (DestVT == MVT::f128)
15156     return false;
15157   return true;
15158 }
15159 
15160 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15161   return isInt<16>(Imm) || isUInt<16>(Imm);
15162 }
15163 
15164 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15165   return isInt<16>(Imm) || isUInt<16>(Imm);
15166 }
15167 
15168 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15169                                                        unsigned,
15170                                                        unsigned,
15171                                                        MachineMemOperand::Flags,
15172                                                        bool *Fast) const {
15173   if (DisablePPCUnaligned)
15174     return false;
15175 
15176   // PowerPC supports unaligned memory access for simple non-vector types.
15177   // Although accessing unaligned addresses is not as efficient as accessing
15178   // aligned addresses, it is generally more efficient than manual expansion,
15179   // and generally only traps for software emulation when crossing page
15180   // boundaries.
15181 
15182   if (!VT.isSimple())
15183     return false;
15184 
15185   if (VT.isFloatingPoint() && !Subtarget.allowsUnalignedFPAccess())
15186     return false;
15187 
15188   if (VT.getSimpleVT().isVector()) {
15189     if (Subtarget.hasVSX()) {
15190       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15191           VT != MVT::v4f32 && VT != MVT::v4i32)
15192         return false;
15193     } else {
15194       return false;
15195     }
15196   }
15197 
15198   if (VT == MVT::ppcf128)
15199     return false;
15200 
15201   if (Fast)
15202     *Fast = true;
15203 
15204   return true;
15205 }
15206 
15207 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15208                                                    EVT VT) const {
15209   VT = VT.getScalarType();
15210 
15211   if (!VT.isSimple())
15212     return false;
15213 
15214   switch (VT.getSimpleVT().SimpleTy) {
15215   case MVT::f32:
15216   case MVT::f64:
15217     return true;
15218   case MVT::f128:
15219     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15220   default:
15221     break;
15222   }
15223 
15224   return false;
15225 }
15226 
15227 const MCPhysReg *
15228 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15229   // LR is a callee-save register, but we must treat it as clobbered by any call
15230   // site. Hence we include LR in the scratch registers, which are in turn added
15231   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15232   // to CTR, which is used by any indirect call.
15233   static const MCPhysReg ScratchRegs[] = {
15234     PPC::X12, PPC::LR8, PPC::CTR8, 0
15235   };
15236 
15237   return ScratchRegs;
15238 }
15239 
15240 unsigned PPCTargetLowering::getExceptionPointerRegister(
15241     const Constant *PersonalityFn) const {
15242   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15243 }
15244 
15245 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15246     const Constant *PersonalityFn) const {
15247   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15248 }
15249 
15250 bool
15251 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15252                      EVT VT , unsigned DefinedValues) const {
15253   if (VT == MVT::v2i64)
15254     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15255 
15256   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15257     return true;
15258 
15259   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15260 }
15261 
15262 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15263   if (DisableILPPref || Subtarget.enableMachineScheduler())
15264     return TargetLowering::getSchedulingPreference(N);
15265 
15266   return Sched::ILP;
15267 }
15268 
15269 // Create a fast isel object.
15270 FastISel *
15271 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15272                                   const TargetLibraryInfo *LibInfo) const {
15273   return PPC::createFastISel(FuncInfo, LibInfo);
15274 }
15275 
15276 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15277   if (!Subtarget.isPPC64()) return;
15278 
15279   // Update IsSplitCSR in PPCFunctionInfo
15280   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15281   PFI->setIsSplitCSR(true);
15282 }
15283 
15284 void PPCTargetLowering::insertCopiesSplitCSR(
15285   MachineBasicBlock *Entry,
15286   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15287   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15288   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15289   if (!IStart)
15290     return;
15291 
15292   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15293   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15294   MachineBasicBlock::iterator MBBI = Entry->begin();
15295   for (const MCPhysReg *I = IStart; *I; ++I) {
15296     const TargetRegisterClass *RC = nullptr;
15297     if (PPC::G8RCRegClass.contains(*I))
15298       RC = &PPC::G8RCRegClass;
15299     else if (PPC::F8RCRegClass.contains(*I))
15300       RC = &PPC::F8RCRegClass;
15301     else if (PPC::CRRCRegClass.contains(*I))
15302       RC = &PPC::CRRCRegClass;
15303     else if (PPC::VRRCRegClass.contains(*I))
15304       RC = &PPC::VRRCRegClass;
15305     else
15306       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15307 
15308     Register NewVR = MRI->createVirtualRegister(RC);
15309     // Create copy from CSR to a virtual register.
15310     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15311     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15312     // nounwind. If we want to generalize this later, we may need to emit
15313     // CFI pseudo-instructions.
15314     assert(Entry->getParent()->getFunction().hasFnAttribute(
15315              Attribute::NoUnwind) &&
15316            "Function should be nounwind in insertCopiesSplitCSR!");
15317     Entry->addLiveIn(*I);
15318     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15319       .addReg(*I);
15320 
15321     // Insert the copy-back instructions right before the terminator.
15322     for (auto *Exit : Exits)
15323       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15324               TII->get(TargetOpcode::COPY), *I)
15325         .addReg(NewVR);
15326   }
15327 }
15328 
15329 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15330 bool PPCTargetLowering::useLoadStackGuardNode() const {
15331   if (!Subtarget.isTargetLinux())
15332     return TargetLowering::useLoadStackGuardNode();
15333   return true;
15334 }
15335 
15336 // Override to disable global variable loading on Linux.
15337 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15338   if (!Subtarget.isTargetLinux())
15339     return TargetLowering::insertSSPDeclarations(M);
15340 }
15341 
15342 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15343                                      bool ForCodeSize) const {
15344   if (!VT.isSimple() || !Subtarget.hasVSX())
15345     return false;
15346 
15347   switch(VT.getSimpleVT().SimpleTy) {
15348   default:
15349     // For FP types that are currently not supported by PPC backend, return
15350     // false. Examples: f16, f80.
15351     return false;
15352   case MVT::f32:
15353   case MVT::f64:
15354   case MVT::ppcf128:
15355     return Imm.isPosZero();
15356   }
15357 }
15358 
15359 // For vector shift operation op, fold
15360 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15361 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15362                                   SelectionDAG &DAG) {
15363   SDValue N0 = N->getOperand(0);
15364   SDValue N1 = N->getOperand(1);
15365   EVT VT = N0.getValueType();
15366   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15367   unsigned Opcode = N->getOpcode();
15368   unsigned TargetOpcode;
15369 
15370   switch (Opcode) {
15371   default:
15372     llvm_unreachable("Unexpected shift operation");
15373   case ISD::SHL:
15374     TargetOpcode = PPCISD::SHL;
15375     break;
15376   case ISD::SRL:
15377     TargetOpcode = PPCISD::SRL;
15378     break;
15379   case ISD::SRA:
15380     TargetOpcode = PPCISD::SRA;
15381     break;
15382   }
15383 
15384   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15385       N1->getOpcode() == ISD::AND)
15386     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15387       if (Mask->getZExtValue() == OpSizeInBits - 1)
15388         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15389 
15390   return SDValue();
15391 }
15392 
15393 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15394   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15395     return Value;
15396 
15397   SDValue N0 = N->getOperand(0);
15398   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15399   if (!Subtarget.isISA3_0() ||
15400       N0.getOpcode() != ISD::SIGN_EXTEND ||
15401       N0.getOperand(0).getValueType() != MVT::i32 ||
15402       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15403     return SDValue();
15404 
15405   // We can't save an operation here if the value is already extended, and
15406   // the existing shift is easier to combine.
15407   SDValue ExtsSrc = N0.getOperand(0);
15408   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15409       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15410     return SDValue();
15411 
15412   SDLoc DL(N0);
15413   SDValue ShiftBy = SDValue(CN1, 0);
15414   // We want the shift amount to be i32 on the extswli, but the shift could
15415   // have an i64.
15416   if (ShiftBy.getValueType() == MVT::i64)
15417     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15418 
15419   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15420                          ShiftBy);
15421 }
15422 
15423 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15424   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15425     return Value;
15426 
15427   return SDValue();
15428 }
15429 
15430 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15431   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15432     return Value;
15433 
15434   return SDValue();
15435 }
15436 
15437 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15438 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15439 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15440 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15441 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15442                                  const PPCSubtarget &Subtarget) {
15443   if (!Subtarget.isPPC64())
15444     return SDValue();
15445 
15446   SDValue LHS = N->getOperand(0);
15447   SDValue RHS = N->getOperand(1);
15448 
15449   auto isZextOfCompareWithConstant = [](SDValue Op) {
15450     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15451         Op.getValueType() != MVT::i64)
15452       return false;
15453 
15454     SDValue Cmp = Op.getOperand(0);
15455     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15456         Cmp.getOperand(0).getValueType() != MVT::i64)
15457       return false;
15458 
15459     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15460       int64_t NegConstant = 0 - Constant->getSExtValue();
15461       // Due to the limitations of the addi instruction,
15462       // -C is required to be [-32768, 32767].
15463       return isInt<16>(NegConstant);
15464     }
15465 
15466     return false;
15467   };
15468 
15469   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15470   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15471 
15472   // If there is a pattern, canonicalize a zext operand to the RHS.
15473   if (LHSHasPattern && !RHSHasPattern)
15474     std::swap(LHS, RHS);
15475   else if (!LHSHasPattern && !RHSHasPattern)
15476     return SDValue();
15477 
15478   SDLoc DL(N);
15479   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15480   SDValue Cmp = RHS.getOperand(0);
15481   SDValue Z = Cmp.getOperand(0);
15482   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15483 
15484   assert(Constant && "Constant Should not be a null pointer.");
15485   int64_t NegConstant = 0 - Constant->getSExtValue();
15486 
15487   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15488   default: break;
15489   case ISD::SETNE: {
15490     //                                 when C == 0
15491     //                             --> addze X, (addic Z, -1).carry
15492     //                            /
15493     // add X, (zext(setne Z, C))--
15494     //                            \    when -32768 <= -C <= 32767 && C != 0
15495     //                             --> addze X, (addic (addi Z, -C), -1).carry
15496     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15497                               DAG.getConstant(NegConstant, DL, MVT::i64));
15498     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15499     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15500                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15501     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15502                        SDValue(Addc.getNode(), 1));
15503     }
15504   case ISD::SETEQ: {
15505     //                                 when C == 0
15506     //                             --> addze X, (subfic Z, 0).carry
15507     //                            /
15508     // add X, (zext(sete  Z, C))--
15509     //                            \    when -32768 <= -C <= 32767 && C != 0
15510     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15511     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15512                               DAG.getConstant(NegConstant, DL, MVT::i64));
15513     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15514     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15515                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15516     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15517                        SDValue(Subc.getNode(), 1));
15518     }
15519   }
15520 
15521   return SDValue();
15522 }
15523 
15524 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15525   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15526     return Value;
15527 
15528   return SDValue();
15529 }
15530 
15531 // Detect TRUNCATE operations on bitcasts of float128 values.
15532 // What we are looking for here is the situtation where we extract a subset
15533 // of bits from a 128 bit float.
15534 // This can be of two forms:
15535 // 1) BITCAST of f128 feeding TRUNCATE
15536 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15537 // The reason this is required is because we do not have a legal i128 type
15538 // and so we want to prevent having to store the f128 and then reload part
15539 // of it.
15540 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15541                                            DAGCombinerInfo &DCI) const {
15542   // If we are using CRBits then try that first.
15543   if (Subtarget.useCRBits()) {
15544     // Check if CRBits did anything and return that if it did.
15545     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15546       return CRTruncValue;
15547   }
15548 
15549   SDLoc dl(N);
15550   SDValue Op0 = N->getOperand(0);
15551 
15552   // Looking for a truncate of i128 to i64.
15553   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15554     return SDValue();
15555 
15556   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15557 
15558   // SRL feeding TRUNCATE.
15559   if (Op0.getOpcode() == ISD::SRL) {
15560     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15561     // The right shift has to be by 64 bits.
15562     if (!ConstNode || ConstNode->getZExtValue() != 64)
15563       return SDValue();
15564 
15565     // Switch the element number to extract.
15566     EltToExtract = EltToExtract ? 0 : 1;
15567     // Update Op0 past the SRL.
15568     Op0 = Op0.getOperand(0);
15569   }
15570 
15571   // BITCAST feeding a TRUNCATE possibly via SRL.
15572   if (Op0.getOpcode() == ISD::BITCAST &&
15573       Op0.getValueType() == MVT::i128 &&
15574       Op0.getOperand(0).getValueType() == MVT::f128) {
15575     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15576     return DCI.DAG.getNode(
15577         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15578         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15579   }
15580   return SDValue();
15581 }
15582 
15583 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15584   SelectionDAG &DAG = DCI.DAG;
15585 
15586   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15587   if (!ConstOpOrElement)
15588     return SDValue();
15589 
15590   // An imul is usually smaller than the alternative sequence for legal type.
15591   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15592       isOperationLegal(ISD::MUL, N->getValueType(0)))
15593     return SDValue();
15594 
15595   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15596     switch (this->Subtarget.getCPUDirective()) {
15597     default:
15598       // TODO: enhance the condition for subtarget before pwr8
15599       return false;
15600     case PPC::DIR_PWR8:
15601       //  type        mul     add    shl
15602       // scalar        4       1      1
15603       // vector        7       2      2
15604       return true;
15605     case PPC::DIR_PWR9:
15606     case PPC::DIR_PWR_FUTURE:
15607       //  type        mul     add    shl
15608       // scalar        5       2      2
15609       // vector        7       2      2
15610 
15611       // The cycle RATIO of related operations are showed as a table above.
15612       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15613       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15614       // are 4, it is always profitable; but for 3 instrs patterns
15615       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15616       // So we should only do it for vector type.
15617       return IsAddOne && IsNeg ? VT.isVector() : true;
15618     }
15619   };
15620 
15621   EVT VT = N->getValueType(0);
15622   SDLoc DL(N);
15623 
15624   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15625   bool IsNeg = MulAmt.isNegative();
15626   APInt MulAmtAbs = MulAmt.abs();
15627 
15628   if ((MulAmtAbs - 1).isPowerOf2()) {
15629     // (mul x, 2^N + 1) => (add (shl x, N), x)
15630     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15631 
15632     if (!IsProfitable(IsNeg, true, VT))
15633       return SDValue();
15634 
15635     SDValue Op0 = N->getOperand(0);
15636     SDValue Op1 =
15637         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15638                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15639     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15640 
15641     if (!IsNeg)
15642       return Res;
15643 
15644     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15645   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15646     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15647     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15648 
15649     if (!IsProfitable(IsNeg, false, VT))
15650       return SDValue();
15651 
15652     SDValue Op0 = N->getOperand(0);
15653     SDValue Op1 =
15654         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15655                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15656 
15657     if (!IsNeg)
15658       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15659     else
15660       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15661 
15662   } else {
15663     return SDValue();
15664   }
15665 }
15666 
15667 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15668   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15669   if (!Subtarget.is64BitELFABI())
15670     return false;
15671 
15672   // If not a tail call then no need to proceed.
15673   if (!CI->isTailCall())
15674     return false;
15675 
15676   // If sibling calls have been disabled and tail-calls aren't guaranteed
15677   // there is no reason to duplicate.
15678   auto &TM = getTargetMachine();
15679   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15680     return false;
15681 
15682   // Can't tail call a function called indirectly, or if it has variadic args.
15683   const Function *Callee = CI->getCalledFunction();
15684   if (!Callee || Callee->isVarArg())
15685     return false;
15686 
15687   // Make sure the callee and caller calling conventions are eligible for tco.
15688   const Function *Caller = CI->getParent()->getParent();
15689   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15690                                            CI->getCallingConv()))
15691       return false;
15692 
15693   // If the function is local then we have a good chance at tail-calling it
15694   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15695 }
15696 
15697 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15698   if (!Subtarget.hasVSX())
15699     return false;
15700   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15701     return true;
15702   return VT == MVT::f32 || VT == MVT::f64 ||
15703     VT == MVT::v4f32 || VT == MVT::v2f64;
15704 }
15705 
15706 bool PPCTargetLowering::
15707 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15708   const Value *Mask = AndI.getOperand(1);
15709   // If the mask is suitable for andi. or andis. we should sink the and.
15710   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15711     // Can't handle constants wider than 64-bits.
15712     if (CI->getBitWidth() > 64)
15713       return false;
15714     int64_t ConstVal = CI->getZExtValue();
15715     return isUInt<16>(ConstVal) ||
15716       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15717   }
15718 
15719   // For non-constant masks, we can always use the record-form and.
15720   return true;
15721 }
15722 
15723 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15724 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15725 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15726 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15727 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15728 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15729   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15730   assert(Subtarget.hasP9Altivec() &&
15731          "Only combine this when P9 altivec supported!");
15732   EVT VT = N->getValueType(0);
15733   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15734     return SDValue();
15735 
15736   SelectionDAG &DAG = DCI.DAG;
15737   SDLoc dl(N);
15738   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15739     // Even for signed integers, if it's known to be positive (as signed
15740     // integer) due to zero-extended inputs.
15741     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15742     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15743     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15744          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15745         (SubOpcd1 == ISD::ZERO_EXTEND ||
15746          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15747       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15748                          N->getOperand(0)->getOperand(0),
15749                          N->getOperand(0)->getOperand(1),
15750                          DAG.getTargetConstant(0, dl, MVT::i32));
15751     }
15752 
15753     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15754     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15755         N->getOperand(0).hasOneUse()) {
15756       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15757                          N->getOperand(0)->getOperand(0),
15758                          N->getOperand(0)->getOperand(1),
15759                          DAG.getTargetConstant(1, dl, MVT::i32));
15760     }
15761   }
15762 
15763   return SDValue();
15764 }
15765 
15766 // For type v4i32/v8ii16/v16i8, transform
15767 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15768 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15769 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15770 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15771 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15772                                           DAGCombinerInfo &DCI) const {
15773   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15774   assert(Subtarget.hasP9Altivec() &&
15775          "Only combine this when P9 altivec supported!");
15776 
15777   SelectionDAG &DAG = DCI.DAG;
15778   SDLoc dl(N);
15779   SDValue Cond = N->getOperand(0);
15780   SDValue TrueOpnd = N->getOperand(1);
15781   SDValue FalseOpnd = N->getOperand(2);
15782   EVT VT = N->getOperand(1).getValueType();
15783 
15784   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15785       FalseOpnd.getOpcode() != ISD::SUB)
15786     return SDValue();
15787 
15788   // ABSD only available for type v4i32/v8i16/v16i8
15789   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15790     return SDValue();
15791 
15792   // At least to save one more dependent computation
15793   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15794     return SDValue();
15795 
15796   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15797 
15798   // Can only handle unsigned comparison here
15799   switch (CC) {
15800   default:
15801     return SDValue();
15802   case ISD::SETUGT:
15803   case ISD::SETUGE:
15804     break;
15805   case ISD::SETULT:
15806   case ISD::SETULE:
15807     std::swap(TrueOpnd, FalseOpnd);
15808     break;
15809   }
15810 
15811   SDValue CmpOpnd1 = Cond.getOperand(0);
15812   SDValue CmpOpnd2 = Cond.getOperand(1);
15813 
15814   // SETCC CmpOpnd1 CmpOpnd2 cond
15815   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15816   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15817   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15818       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15819       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15820       FalseOpnd.getOperand(1) == CmpOpnd1) {
15821     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15822                        CmpOpnd1, CmpOpnd2,
15823                        DAG.getTargetConstant(0, dl, MVT::i32));
15824   }
15825 
15826   return SDValue();
15827 }
15828