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   // Use _setjmp/_longjmp instead of setjmp/longjmp.
141   setUseUnderscoreSetJmp(true);
142   setUseUnderscoreLongJmp(true);
143 
144   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
145   // arguments are at least 4/8 bytes aligned.
146   bool isPPC64 = Subtarget.isPPC64();
147   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
148 
149   // Set up the register classes.
150   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
151   if (!useSoftFloat()) {
152     if (hasSPE()) {
153       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
154       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
155     } else {
156       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
157       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
158     }
159   }
160 
161   // Match BITREVERSE to customized fast code sequence in the td file.
162   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
163   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
164 
165   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
166   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
167 
168   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
169   for (MVT VT : MVT::integer_valuetypes()) {
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
171     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
172   }
173 
174   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
175 
176   // PowerPC has pre-inc load and store's.
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
178   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
179   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
180   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
181   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
183   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
184   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
185   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
186   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
187   if (!Subtarget.hasSPE()) {
188     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
189     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
190     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
191     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
192   }
193 
194   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
195   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
196   for (MVT VT : ScalarIntVTs) {
197     setOperationAction(ISD::ADDC, VT, Legal);
198     setOperationAction(ISD::ADDE, VT, Legal);
199     setOperationAction(ISD::SUBC, VT, Legal);
200     setOperationAction(ISD::SUBE, VT, Legal);
201   }
202 
203   if (Subtarget.useCRBits()) {
204     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
205 
206     if (isPPC64 || Subtarget.hasFPCVT()) {
207       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
208       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
209                          isPPC64 ? MVT::i64 : MVT::i32);
210       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
211       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
212                         isPPC64 ? MVT::i64 : MVT::i32);
213     } else {
214       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
215       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
216     }
217 
218     // PowerPC does not support direct load/store of condition registers.
219     setOperationAction(ISD::LOAD, MVT::i1, Custom);
220     setOperationAction(ISD::STORE, MVT::i1, Custom);
221 
222     // FIXME: Remove this once the ANDI glue bug is fixed:
223     if (ANDIGlueBug)
224       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
225 
226     for (MVT VT : MVT::integer_valuetypes()) {
227       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
228       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
229       setTruncStoreAction(VT, MVT::i1, Expand);
230     }
231 
232     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
233   }
234 
235   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
236   // PPC (the libcall is not available).
237   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
238   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
239 
240   // We do not currently implement these libm ops for PowerPC.
241   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
242   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
243   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
244   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
245   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
246   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
247 
248   // PowerPC has no SREM/UREM instructions unless we are on P9
249   // On P9 we may use a hardware instruction to compute the remainder.
250   // The instructions are not legalized directly because in the cases where the
251   // result of both the remainder and the division is required it is more
252   // efficient to compute the remainder from the result of the division rather
253   // than use the remainder instruction.
254   if (Subtarget.isISA3_0()) {
255     setOperationAction(ISD::SREM, MVT::i32, Custom);
256     setOperationAction(ISD::UREM, MVT::i32, Custom);
257     setOperationAction(ISD::SREM, MVT::i64, Custom);
258     setOperationAction(ISD::UREM, MVT::i64, Custom);
259   } else {
260     setOperationAction(ISD::SREM, MVT::i32, Expand);
261     setOperationAction(ISD::UREM, MVT::i32, Expand);
262     setOperationAction(ISD::SREM, MVT::i64, Expand);
263     setOperationAction(ISD::UREM, MVT::i64, Expand);
264   }
265 
266   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
267   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
268   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
269   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
270   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
271   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
272   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
273   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
274   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
275 
276   // We don't support sin/cos/sqrt/fmod/pow
277   setOperationAction(ISD::FSIN , MVT::f64, Expand);
278   setOperationAction(ISD::FCOS , MVT::f64, Expand);
279   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
280   setOperationAction(ISD::FREM , MVT::f64, Expand);
281   setOperationAction(ISD::FPOW , MVT::f64, Expand);
282   setOperationAction(ISD::FSIN , MVT::f32, Expand);
283   setOperationAction(ISD::FCOS , MVT::f32, Expand);
284   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
285   setOperationAction(ISD::FREM , MVT::f32, Expand);
286   setOperationAction(ISD::FPOW , MVT::f32, Expand);
287   if (Subtarget.hasSPE()) {
288     setOperationAction(ISD::FMA  , MVT::f64, Expand);
289     setOperationAction(ISD::FMA  , MVT::f32, Expand);
290   } else {
291     setOperationAction(ISD::FMA  , MVT::f64, Legal);
292     setOperationAction(ISD::FMA  , MVT::f32, Legal);
293   }
294 
295   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
296 
297   // If we're enabling GP optimizations, use hardware square root
298   if (!Subtarget.hasFSQRT() &&
299       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
300         Subtarget.hasFRE()))
301     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
302 
303   if (!Subtarget.hasFSQRT() &&
304       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
305         Subtarget.hasFRES()))
306     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
307 
308   if (Subtarget.hasFCPSGN()) {
309     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
310     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
311   } else {
312     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
313     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
314   }
315 
316   if (Subtarget.hasFPRND()) {
317     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
318     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
319     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
320     setOperationAction(ISD::FROUND, MVT::f64, Legal);
321 
322     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
323     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
324     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
325     setOperationAction(ISD::FROUND, MVT::f32, Legal);
326   }
327 
328   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
329   // to speed up scalar BSWAP64.
330   // CTPOP or CTTZ were introduced in P8/P9 respectively
331   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
332   if (Subtarget.hasP9Vector())
333     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
334   else
335     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
336   if (Subtarget.isISA3_0()) {
337     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
338     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
339   } else {
340     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
341     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
342   }
343 
344   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
345     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
346     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
347   } else {
348     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
349     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
350   }
351 
352   // PowerPC does not have ROTR
353   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
354   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
355 
356   if (!Subtarget.useCRBits()) {
357     // PowerPC does not have Select
358     setOperationAction(ISD::SELECT, MVT::i32, Expand);
359     setOperationAction(ISD::SELECT, MVT::i64, Expand);
360     setOperationAction(ISD::SELECT, MVT::f32, Expand);
361     setOperationAction(ISD::SELECT, MVT::f64, Expand);
362   }
363 
364   // PowerPC wants to turn select_cc of FP into fsel when possible.
365   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
366   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
367 
368   // PowerPC wants to optimize integer setcc a bit
369   if (!Subtarget.useCRBits())
370     setOperationAction(ISD::SETCC, MVT::i32, Custom);
371 
372   // PowerPC does not have BRCOND which requires SetCC
373   if (!Subtarget.useCRBits())
374     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
375 
376   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
377 
378   if (Subtarget.hasSPE()) {
379     // SPE has built-in conversions
380     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
381     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
382     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
383   } else {
384     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
385     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
386 
387     // PowerPC does not have [U|S]INT_TO_FP
388     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
389     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
390   }
391 
392   if (Subtarget.hasDirectMove() && isPPC64) {
393     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
394     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
395     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
396     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
397   } else {
398     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
399     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
400     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
401     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
402   }
403 
404   // We cannot sextinreg(i1).  Expand to shifts.
405   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
406 
407   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
408   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
409   // support continuation, user-level threading, and etc.. As a result, no
410   // other SjLj exception interfaces are implemented and please don't build
411   // your own exception handling based on them.
412   // LLVM/Clang supports zero-cost DWARF exception handling.
413   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
414   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
415 
416   // We want to legalize GlobalAddress and ConstantPool nodes into the
417   // appropriate instructions to materialize the address.
418   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
419   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
420   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
421   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
422   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
423   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
424   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
425   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
426   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
427   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
428 
429   // TRAP is legal.
430   setOperationAction(ISD::TRAP, MVT::Other, Legal);
431 
432   // TRAMPOLINE is custom lowered.
433   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
434   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
435 
436   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
437   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
438 
439   if (Subtarget.is64BitELFABI()) {
440     // VAARG always uses double-word chunks, so promote anything smaller.
441     setOperationAction(ISD::VAARG, MVT::i1, Promote);
442     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
443     setOperationAction(ISD::VAARG, MVT::i8, Promote);
444     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
445     setOperationAction(ISD::VAARG, MVT::i16, Promote);
446     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
447     setOperationAction(ISD::VAARG, MVT::i32, Promote);
448     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
449     setOperationAction(ISD::VAARG, MVT::Other, Expand);
450   } else if (Subtarget.is32BitELFABI()) {
451     // VAARG is custom lowered with the 32-bit SVR4 ABI.
452     setOperationAction(ISD::VAARG, MVT::Other, Custom);
453     setOperationAction(ISD::VAARG, MVT::i64, Custom);
454   } else
455     setOperationAction(ISD::VAARG, MVT::Other, Expand);
456 
457   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
458   if (Subtarget.is32BitELFABI())
459     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
460   else
461     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
462 
463   // Use the default implementation.
464   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
465   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
466   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
467   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
468   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
469   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
470   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
471   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
472   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
473 
474   // We want to custom lower some of our intrinsics.
475   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
476 
477   // To handle counter-based loop conditions.
478   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
479 
480   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
481   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
482   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
483   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
484 
485   // Comparisons that require checking two conditions.
486   if (Subtarget.hasSPE()) {
487     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
488     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
489     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
490     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
491   }
492   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
493   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
494   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
495   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
496   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
497   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
498   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
499   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
500   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
501   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
502   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
503   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
504 
505   if (Subtarget.has64BitSupport()) {
506     // They also have instructions for converting between i64 and fp.
507     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
508     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
509     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
510     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
511     // This is just the low 32 bits of a (signed) fp->i64 conversion.
512     // We cannot do this with Promote because i64 is not a legal type.
513     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
514 
515     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
516       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
517   } else {
518     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
519     if (Subtarget.hasSPE())
520       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
521     else
522       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
523   }
524 
525   // With the instructions enabled under FPCVT, we can do everything.
526   if (Subtarget.hasFPCVT()) {
527     if (Subtarget.has64BitSupport()) {
528       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
529       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
530       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
531       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
532     }
533 
534     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
535     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
536     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
537     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
538   }
539 
540   if (Subtarget.use64BitRegs()) {
541     // 64-bit PowerPC implementations can support i64 types directly
542     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
543     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
544     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
545     // 64-bit PowerPC wants to expand i128 shifts itself.
546     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
547     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
548     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
549   } else {
550     // 32-bit PowerPC wants to expand i64 shifts itself.
551     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
552     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
553     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
554   }
555 
556   if (Subtarget.hasVSX()) {
557     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
558     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
559     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
560     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
561   }
562 
563   if (Subtarget.hasAltivec()) {
564     // First set operation action for all vector types to expand. Then we
565     // will selectively turn on ones that can be effectively codegen'd.
566     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
567       // add/sub are legal for all supported vector VT's.
568       setOperationAction(ISD::ADD, VT, Legal);
569       setOperationAction(ISD::SUB, VT, Legal);
570 
571       // For v2i64, these are only valid with P8Vector. This is corrected after
572       // the loop.
573       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
574         setOperationAction(ISD::SMAX, VT, Legal);
575         setOperationAction(ISD::SMIN, VT, Legal);
576         setOperationAction(ISD::UMAX, VT, Legal);
577         setOperationAction(ISD::UMIN, VT, Legal);
578       }
579       else {
580         setOperationAction(ISD::SMAX, VT, Expand);
581         setOperationAction(ISD::SMIN, VT, Expand);
582         setOperationAction(ISD::UMAX, VT, Expand);
583         setOperationAction(ISD::UMIN, VT, Expand);
584       }
585 
586       if (Subtarget.hasVSX()) {
587         setOperationAction(ISD::FMAXNUM, VT, Legal);
588         setOperationAction(ISD::FMINNUM, VT, Legal);
589       }
590 
591       // Vector instructions introduced in P8
592       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
593         setOperationAction(ISD::CTPOP, VT, Legal);
594         setOperationAction(ISD::CTLZ, VT, Legal);
595       }
596       else {
597         setOperationAction(ISD::CTPOP, VT, Expand);
598         setOperationAction(ISD::CTLZ, VT, Expand);
599       }
600 
601       // Vector instructions introduced in P9
602       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
603         setOperationAction(ISD::CTTZ, VT, Legal);
604       else
605         setOperationAction(ISD::CTTZ, VT, Expand);
606 
607       // We promote all shuffles to v16i8.
608       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
609       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
610 
611       // We promote all non-typed operations to v4i32.
612       setOperationAction(ISD::AND   , VT, Promote);
613       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
614       setOperationAction(ISD::OR    , VT, Promote);
615       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
616       setOperationAction(ISD::XOR   , VT, Promote);
617       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
618       setOperationAction(ISD::LOAD  , VT, Promote);
619       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
620       setOperationAction(ISD::SELECT, VT, Promote);
621       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
622       setOperationAction(ISD::VSELECT, VT, Legal);
623       setOperationAction(ISD::SELECT_CC, VT, Promote);
624       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
625       setOperationAction(ISD::STORE, VT, Promote);
626       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
627 
628       // No other operations are legal.
629       setOperationAction(ISD::MUL , VT, Expand);
630       setOperationAction(ISD::SDIV, VT, Expand);
631       setOperationAction(ISD::SREM, VT, Expand);
632       setOperationAction(ISD::UDIV, VT, Expand);
633       setOperationAction(ISD::UREM, VT, Expand);
634       setOperationAction(ISD::FDIV, VT, Expand);
635       setOperationAction(ISD::FREM, VT, Expand);
636       setOperationAction(ISD::FNEG, VT, Expand);
637       setOperationAction(ISD::FSQRT, VT, Expand);
638       setOperationAction(ISD::FLOG, VT, Expand);
639       setOperationAction(ISD::FLOG10, VT, Expand);
640       setOperationAction(ISD::FLOG2, VT, Expand);
641       setOperationAction(ISD::FEXP, VT, Expand);
642       setOperationAction(ISD::FEXP2, VT, Expand);
643       setOperationAction(ISD::FSIN, VT, Expand);
644       setOperationAction(ISD::FCOS, VT, Expand);
645       setOperationAction(ISD::FABS, VT, Expand);
646       setOperationAction(ISD::FFLOOR, VT, Expand);
647       setOperationAction(ISD::FCEIL,  VT, Expand);
648       setOperationAction(ISD::FTRUNC, VT, Expand);
649       setOperationAction(ISD::FRINT,  VT, Expand);
650       setOperationAction(ISD::FNEARBYINT, VT, Expand);
651       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
652       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
653       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
654       setOperationAction(ISD::MULHU, VT, Expand);
655       setOperationAction(ISD::MULHS, VT, Expand);
656       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
657       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
658       setOperationAction(ISD::UDIVREM, VT, Expand);
659       setOperationAction(ISD::SDIVREM, VT, Expand);
660       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
661       setOperationAction(ISD::FPOW, VT, Expand);
662       setOperationAction(ISD::BSWAP, VT, Expand);
663       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
664       setOperationAction(ISD::ROTL, VT, Expand);
665       setOperationAction(ISD::ROTR, VT, Expand);
666 
667       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
668         setTruncStoreAction(VT, InnerVT, Expand);
669         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
670         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
671         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
672       }
673     }
674     if (!Subtarget.hasP8Vector()) {
675       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
676       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
677       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
678       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
679     }
680 
681     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
682       setOperationAction(ISD::ABS, VT, Custom);
683 
684     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
685     // with merges, splats, etc.
686     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
687 
688     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
689     // are cheap, so handle them before they get expanded to scalar.
690     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
691     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
692     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
693     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
694     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
695 
696     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
697     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
698     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
699     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
700     setOperationAction(ISD::SELECT, MVT::v4i32,
701                        Subtarget.useCRBits() ? Legal : Expand);
702     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
703     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
704     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
705     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
706     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
707     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
708     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
709     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
710     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
711 
712     // Without hasP8Altivec set, v2i64 SMAX isn't available.
713     // But ABS custom lowering requires SMAX support.
714     if (!Subtarget.hasP8Altivec())
715       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
716 
717     // With hasAltivec set, we can lower ISD::ROTL to vrl(b|h|w).
718     if (Subtarget.hasAltivec())
719       for (auto VT : {MVT::v4i32, MVT::v8i16, MVT::v16i8})
720         setOperationAction(ISD::ROTL, VT, Legal);
721     // With hasP8Altivec set, we can lower ISD::ROTL to vrld.
722     if (Subtarget.hasP8Altivec())
723       setOperationAction(ISD::ROTL, MVT::v2i64, Legal);
724 
725     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
726     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
727     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
728     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
729 
730     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
731     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
732 
733     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
734       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
735       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
736     }
737 
738     if (Subtarget.hasP8Altivec())
739       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
740     else
741       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
742 
743     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
744     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
745 
746     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
747     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
748 
749     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
750     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
751     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
752     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
753 
754     // Altivec does not contain unordered floating-point compare instructions
755     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
756     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
757     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
758     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
759 
760     if (Subtarget.hasVSX()) {
761       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
762       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
763       if (Subtarget.hasP8Vector()) {
764         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
765         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
766       }
767       if (Subtarget.hasDirectMove() && isPPC64) {
768         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
769         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
770         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
771         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
772         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
773         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
774         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
775         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
776       }
777       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
778 
779       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
780       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
781       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
782       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
783       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
784 
785       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
786 
787       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
788       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
789 
790       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
791       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
792 
793       // Share the Altivec comparison restrictions.
794       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
795       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
796       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
797       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
798 
799       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
800       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
801 
802       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
803 
804       if (Subtarget.hasP8Vector())
805         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
806 
807       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
808 
809       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
810       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
811       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
812 
813       if (Subtarget.hasP8Altivec()) {
814         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
815         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
816         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
817 
818         // 128 bit shifts can be accomplished via 3 instructions for SHL and
819         // SRL, but not for SRA because of the instructions available:
820         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
821         // doing
822         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
823         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
824         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
825 
826         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
827       }
828       else {
829         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
830         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
831         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
832 
833         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
834 
835         // VSX v2i64 only supports non-arithmetic operations.
836         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
837         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
838       }
839 
840       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
841       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
842       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
843       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
844 
845       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
846 
847       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
848       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
849       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
850       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
851 
852       // Custom handling for partial vectors of integers converted to
853       // floating point. We already have optimal handling for v2i32 through
854       // the DAG combine, so those aren't necessary.
855       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
856       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
857       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
858       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
859       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
860       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
861       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
862       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
863 
864       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
865       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
866       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
867       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
868       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
869       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
870 
871       if (Subtarget.hasDirectMove())
872         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
873       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
874 
875       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
876     }
877 
878     if (Subtarget.hasP8Altivec()) {
879       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
880       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
881     }
882 
883     if (Subtarget.hasP9Vector()) {
884       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
885       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
886 
887       // 128 bit shifts can be accomplished via 3 instructions for SHL and
888       // SRL, but not for SRA because of the instructions available:
889       // VS{RL} and VS{RL}O.
890       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
891       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
892       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
893 
894       if (EnableQuadPrecision) {
895         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
896         setOperationAction(ISD::FADD, MVT::f128, Legal);
897         setOperationAction(ISD::FSUB, MVT::f128, Legal);
898         setOperationAction(ISD::FDIV, MVT::f128, Legal);
899         setOperationAction(ISD::FMUL, MVT::f128, Legal);
900         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
901         // No extending loads to f128 on PPC.
902         for (MVT FPT : MVT::fp_valuetypes())
903           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
904         setOperationAction(ISD::FMA, MVT::f128, Legal);
905         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
906         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
907         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
908         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
909         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
910         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
911 
912         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
913         setOperationAction(ISD::FRINT, MVT::f128, Legal);
914         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
915         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
916         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
917         setOperationAction(ISD::FROUND, MVT::f128, Legal);
918 
919         setOperationAction(ISD::SELECT, MVT::f128, Expand);
920         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
921         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
922         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
923         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
924         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
925         // No implementation for these ops for PowerPC.
926         setOperationAction(ISD::FSIN , MVT::f128, Expand);
927         setOperationAction(ISD::FCOS , MVT::f128, Expand);
928         setOperationAction(ISD::FPOW, MVT::f128, Expand);
929         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
930         setOperationAction(ISD::FREM, MVT::f128, Expand);
931       }
932       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
933       setOperationAction(ISD::BSWAP, MVT::v8i16, Legal);
934       setOperationAction(ISD::BSWAP, MVT::v4i32, Legal);
935       setOperationAction(ISD::BSWAP, MVT::v2i64, Legal);
936       setOperationAction(ISD::BSWAP, MVT::v1i128, Legal);
937     }
938 
939     if (Subtarget.hasP9Altivec()) {
940       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
941       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
942 
943       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
944       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
945       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
946       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
947       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
948       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
949       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
950     }
951   }
952 
953   if (Subtarget.hasQPX()) {
954     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
955     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
956     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
957     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
958 
959     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
960     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
961 
962     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
963     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
964 
965     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
966     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
967 
968     if (!Subtarget.useCRBits())
969       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
970     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
971 
972     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
973     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
974     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
975     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
976     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
977     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
978     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
979 
980     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
981     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
982 
983     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
984     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
985 
986     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
987     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
988     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
989     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
990     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
991     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
992     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
993     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
994     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
995     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
996 
997     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
998     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
999 
1000     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
1001     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
1002 
1003     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
1004 
1005     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
1006     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
1007     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
1008     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
1009 
1010     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
1011     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1012 
1013     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1014     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1015 
1016     if (!Subtarget.useCRBits())
1017       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1018     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1019 
1020     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1021     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1022     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1023     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1024     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1025     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1026     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1027 
1028     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1029     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1030 
1031     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1032     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1033     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1034     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1035     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1036     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1037     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1038     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1039     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1040     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1041 
1042     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1043     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1044 
1045     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1046     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1047 
1048     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1049 
1050     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1051     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1052     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1053 
1054     if (!Subtarget.useCRBits())
1055       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1056     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1057 
1058     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1059     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1060 
1061     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1062     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1063     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1064     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1065     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1066     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1067     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1068 
1069     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1070     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1071 
1072     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1073 
1074     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1075     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1076     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1077     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1078 
1079     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1080     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1081     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1082     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1083 
1084     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1085     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1086 
1087     // These need to set FE_INEXACT, and so cannot be vectorized here.
1088     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1089     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1090 
1091     if (TM.Options.UnsafeFPMath) {
1092       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1093       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1094 
1095       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1096       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1097     } else {
1098       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1099       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1100 
1101       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1102       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1103     }
1104   }
1105 
1106   if (Subtarget.has64BitSupport())
1107     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1108 
1109   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1110 
1111   if (!isPPC64) {
1112     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1113     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1114   }
1115 
1116   setBooleanContents(ZeroOrOneBooleanContent);
1117 
1118   if (Subtarget.hasAltivec()) {
1119     // Altivec instructions set fields to all zeros or all ones.
1120     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1121   }
1122 
1123   if (!isPPC64) {
1124     // These libcalls are not available in 32-bit.
1125     setLibcallName(RTLIB::SHL_I128, nullptr);
1126     setLibcallName(RTLIB::SRL_I128, nullptr);
1127     setLibcallName(RTLIB::SRA_I128, nullptr);
1128   }
1129 
1130   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1131 
1132   // We have target-specific dag combine patterns for the following nodes:
1133   setTargetDAGCombine(ISD::ADD);
1134   setTargetDAGCombine(ISD::SHL);
1135   setTargetDAGCombine(ISD::SRA);
1136   setTargetDAGCombine(ISD::SRL);
1137   setTargetDAGCombine(ISD::MUL);
1138   setTargetDAGCombine(ISD::SINT_TO_FP);
1139   setTargetDAGCombine(ISD::BUILD_VECTOR);
1140   if (Subtarget.hasFPCVT())
1141     setTargetDAGCombine(ISD::UINT_TO_FP);
1142   setTargetDAGCombine(ISD::LOAD);
1143   setTargetDAGCombine(ISD::STORE);
1144   setTargetDAGCombine(ISD::BR_CC);
1145   if (Subtarget.useCRBits())
1146     setTargetDAGCombine(ISD::BRCOND);
1147   setTargetDAGCombine(ISD::BSWAP);
1148   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1149   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1150   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1151 
1152   setTargetDAGCombine(ISD::SIGN_EXTEND);
1153   setTargetDAGCombine(ISD::ZERO_EXTEND);
1154   setTargetDAGCombine(ISD::ANY_EXTEND);
1155 
1156   setTargetDAGCombine(ISD::TRUNCATE);
1157   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1158 
1159 
1160   if (Subtarget.useCRBits()) {
1161     setTargetDAGCombine(ISD::TRUNCATE);
1162     setTargetDAGCombine(ISD::SETCC);
1163     setTargetDAGCombine(ISD::SELECT_CC);
1164   }
1165 
1166   // Use reciprocal estimates.
1167   if (TM.Options.UnsafeFPMath) {
1168     setTargetDAGCombine(ISD::FDIV);
1169     setTargetDAGCombine(ISD::FSQRT);
1170   }
1171 
1172   if (Subtarget.hasP9Altivec()) {
1173     setTargetDAGCombine(ISD::ABS);
1174     setTargetDAGCombine(ISD::VSELECT);
1175   }
1176 
1177   // Darwin long double math library functions have $LDBL128 appended.
1178   if (Subtarget.isDarwin()) {
1179     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1180     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1181     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1182     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1183     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1184     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1185     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1186     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1187     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1188     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1189   }
1190 
1191   if (EnableQuadPrecision) {
1192     setLibcallName(RTLIB::LOG_F128, "logf128");
1193     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1194     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1195     setLibcallName(RTLIB::EXP_F128, "expf128");
1196     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1197     setLibcallName(RTLIB::SIN_F128, "sinf128");
1198     setLibcallName(RTLIB::COS_F128, "cosf128");
1199     setLibcallName(RTLIB::POW_F128, "powf128");
1200     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1201     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1202     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1203     setLibcallName(RTLIB::REM_F128, "fmodf128");
1204   }
1205 
1206   // With 32 condition bits, we don't need to sink (and duplicate) compares
1207   // aggressively in CodeGenPrep.
1208   if (Subtarget.useCRBits()) {
1209     setHasMultipleConditionRegisters();
1210     setJumpIsExpensive();
1211   }
1212 
1213   setMinFunctionAlignment(Align(4));
1214   if (Subtarget.isDarwin())
1215     setPrefFunctionAlignment(Align(16));
1216 
1217   switch (Subtarget.getCPUDirective()) {
1218   default: break;
1219   case PPC::DIR_970:
1220   case PPC::DIR_A2:
1221   case PPC::DIR_E500:
1222   case PPC::DIR_E500mc:
1223   case PPC::DIR_E5500:
1224   case PPC::DIR_PWR4:
1225   case PPC::DIR_PWR5:
1226   case PPC::DIR_PWR5X:
1227   case PPC::DIR_PWR6:
1228   case PPC::DIR_PWR6X:
1229   case PPC::DIR_PWR7:
1230   case PPC::DIR_PWR8:
1231   case PPC::DIR_PWR9:
1232   case PPC::DIR_PWR_FUTURE:
1233     setPrefLoopAlignment(Align(16));
1234     setPrefFunctionAlignment(Align(16));
1235     break;
1236   }
1237 
1238   if (Subtarget.enableMachineScheduler())
1239     setSchedulingPreference(Sched::Source);
1240   else
1241     setSchedulingPreference(Sched::Hybrid);
1242 
1243   computeRegisterProperties(STI.getRegisterInfo());
1244 
1245   // The Freescale cores do better with aggressive inlining of memcpy and
1246   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1247   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1248       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1249     MaxStoresPerMemset = 32;
1250     MaxStoresPerMemsetOptSize = 16;
1251     MaxStoresPerMemcpy = 32;
1252     MaxStoresPerMemcpyOptSize = 8;
1253     MaxStoresPerMemmove = 32;
1254     MaxStoresPerMemmoveOptSize = 8;
1255   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1256     // The A2 also benefits from (very) aggressive inlining of memcpy and
1257     // friends. The overhead of a the function call, even when warm, can be
1258     // over one hundred cycles.
1259     MaxStoresPerMemset = 128;
1260     MaxStoresPerMemcpy = 128;
1261     MaxStoresPerMemmove = 128;
1262     MaxLoadsPerMemcmp = 128;
1263   } else {
1264     MaxLoadsPerMemcmp = 8;
1265     MaxLoadsPerMemcmpOptSize = 4;
1266   }
1267 }
1268 
1269 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1270 /// the desired ByVal argument alignment.
1271 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1272                              unsigned MaxMaxAlign) {
1273   if (MaxAlign == MaxMaxAlign)
1274     return;
1275   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1276     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1277       MaxAlign = 32;
1278     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1279       MaxAlign = 16;
1280   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1281     unsigned EltAlign = 0;
1282     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1283     if (EltAlign > MaxAlign)
1284       MaxAlign = EltAlign;
1285   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1286     for (auto *EltTy : STy->elements()) {
1287       unsigned EltAlign = 0;
1288       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1289       if (EltAlign > MaxAlign)
1290         MaxAlign = EltAlign;
1291       if (MaxAlign == MaxMaxAlign)
1292         break;
1293     }
1294   }
1295 }
1296 
1297 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1298 /// function arguments in the caller parameter area.
1299 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1300                                                   const DataLayout &DL) const {
1301   // Darwin passes everything on 4 byte boundary.
1302   if (Subtarget.isDarwin())
1303     return 4;
1304 
1305   // 16byte and wider vectors are passed on 16byte boundary.
1306   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1307   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1308   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1309     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1310   return Align;
1311 }
1312 
1313 bool PPCTargetLowering::useSoftFloat() const {
1314   return Subtarget.useSoftFloat();
1315 }
1316 
1317 bool PPCTargetLowering::hasSPE() const {
1318   return Subtarget.hasSPE();
1319 }
1320 
1321 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1322   return VT.isScalarInteger();
1323 }
1324 
1325 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1326   switch ((PPCISD::NodeType)Opcode) {
1327   case PPCISD::FIRST_NUMBER:    break;
1328   case PPCISD::FSEL:            return "PPCISD::FSEL";
1329   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1330   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1331   case PPCISD::FCFID:           return "PPCISD::FCFID";
1332   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1333   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1334   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1335   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1336   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1337   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1338   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1339   case PPCISD::FP_TO_UINT_IN_VSR:
1340                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1341   case PPCISD::FP_TO_SINT_IN_VSR:
1342                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1343   case PPCISD::FRE:             return "PPCISD::FRE";
1344   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1345   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1346   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1347   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1348   case PPCISD::VPERM:           return "PPCISD::VPERM";
1349   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1350   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1351   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1352   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1353   case PPCISD::CMPB:            return "PPCISD::CMPB";
1354   case PPCISD::Hi:              return "PPCISD::Hi";
1355   case PPCISD::Lo:              return "PPCISD::Lo";
1356   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1357   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1358   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1359   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1360   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1361   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1362   case PPCISD::SRL:             return "PPCISD::SRL";
1363   case PPCISD::SRA:             return "PPCISD::SRA";
1364   case PPCISD::SHL:             return "PPCISD::SHL";
1365   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1366   case PPCISD::CALL:            return "PPCISD::CALL";
1367   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1368   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1369   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1370   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1371   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1372   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1373   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1374   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1375   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1376   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1377   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1378   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1379   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1380   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1381   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1382   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1383   case PPCISD::VCMP:            return "PPCISD::VCMP";
1384   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1385   case PPCISD::LBRX:            return "PPCISD::LBRX";
1386   case PPCISD::STBRX:           return "PPCISD::STBRX";
1387   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1388   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1389   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1390   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1391   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1392   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1393   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1394   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1395   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1396   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1397   case PPCISD::ST_VSR_SCAL_INT:
1398                                 return "PPCISD::ST_VSR_SCAL_INT";
1399   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1400   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1401   case PPCISD::BDZ:             return "PPCISD::BDZ";
1402   case PPCISD::MFFS:            return "PPCISD::MFFS";
1403   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1404   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1405   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1406   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1407   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1408   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1409   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1410   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1411   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1412   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1413   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1414   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1415   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1416   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1417   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1418   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1419   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1420   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1421   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1422   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1423   case PPCISD::SC:              return "PPCISD::SC";
1424   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1425   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1426   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1427   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1428   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1429   case PPCISD::VABSD:           return "PPCISD::VABSD";
1430   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1431   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1432   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1433   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1434   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1435   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1436   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1437   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1438   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1439   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1440   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1441   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1442   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1443   }
1444   return nullptr;
1445 }
1446 
1447 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1448                                           EVT VT) const {
1449   if (!VT.isVector())
1450     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1451 
1452   if (Subtarget.hasQPX())
1453     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1454 
1455   return VT.changeVectorElementTypeToInteger();
1456 }
1457 
1458 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1459   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1460   return true;
1461 }
1462 
1463 //===----------------------------------------------------------------------===//
1464 // Node matching predicates, for use by the tblgen matching code.
1465 //===----------------------------------------------------------------------===//
1466 
1467 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1468 static bool isFloatingPointZero(SDValue Op) {
1469   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1470     return CFP->getValueAPF().isZero();
1471   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1472     // Maybe this has already been legalized into the constant pool?
1473     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1474       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1475         return CFP->getValueAPF().isZero();
1476   }
1477   return false;
1478 }
1479 
1480 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1481 /// true if Op is undef or if it matches the specified value.
1482 static bool isConstantOrUndef(int Op, int Val) {
1483   return Op < 0 || Op == Val;
1484 }
1485 
1486 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1487 /// VPKUHUM instruction.
1488 /// The ShuffleKind distinguishes between big-endian operations with
1489 /// two different inputs (0), either-endian operations with two identical
1490 /// inputs (1), and little-endian operations with two different inputs (2).
1491 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1492 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1493                                SelectionDAG &DAG) {
1494   bool IsLE = DAG.getDataLayout().isLittleEndian();
1495   if (ShuffleKind == 0) {
1496     if (IsLE)
1497       return false;
1498     for (unsigned i = 0; i != 16; ++i)
1499       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1500         return false;
1501   } else if (ShuffleKind == 2) {
1502     if (!IsLE)
1503       return false;
1504     for (unsigned i = 0; i != 16; ++i)
1505       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1506         return false;
1507   } else if (ShuffleKind == 1) {
1508     unsigned j = IsLE ? 0 : 1;
1509     for (unsigned i = 0; i != 8; ++i)
1510       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1511           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1512         return false;
1513   }
1514   return true;
1515 }
1516 
1517 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1518 /// VPKUWUM instruction.
1519 /// The ShuffleKind distinguishes between big-endian operations with
1520 /// two different inputs (0), either-endian operations with two identical
1521 /// inputs (1), and little-endian operations with two different inputs (2).
1522 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1523 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1524                                SelectionDAG &DAG) {
1525   bool IsLE = DAG.getDataLayout().isLittleEndian();
1526   if (ShuffleKind == 0) {
1527     if (IsLE)
1528       return false;
1529     for (unsigned i = 0; i != 16; i += 2)
1530       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1531           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1532         return false;
1533   } else if (ShuffleKind == 2) {
1534     if (!IsLE)
1535       return false;
1536     for (unsigned i = 0; i != 16; i += 2)
1537       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1538           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1539         return false;
1540   } else if (ShuffleKind == 1) {
1541     unsigned j = IsLE ? 0 : 2;
1542     for (unsigned i = 0; i != 8; i += 2)
1543       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1544           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1545           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1546           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1547         return false;
1548   }
1549   return true;
1550 }
1551 
1552 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1553 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1554 /// current subtarget.
1555 ///
1556 /// The ShuffleKind distinguishes between big-endian operations with
1557 /// two different inputs (0), either-endian operations with two identical
1558 /// inputs (1), and little-endian operations with two different inputs (2).
1559 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1560 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1561                                SelectionDAG &DAG) {
1562   const PPCSubtarget& Subtarget =
1563       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1564   if (!Subtarget.hasP8Vector())
1565     return false;
1566 
1567   bool IsLE = DAG.getDataLayout().isLittleEndian();
1568   if (ShuffleKind == 0) {
1569     if (IsLE)
1570       return false;
1571     for (unsigned i = 0; i != 16; i += 4)
1572       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1573           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1574           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1575           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1576         return false;
1577   } else if (ShuffleKind == 2) {
1578     if (!IsLE)
1579       return false;
1580     for (unsigned i = 0; i != 16; i += 4)
1581       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1582           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1583           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1584           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1585         return false;
1586   } else if (ShuffleKind == 1) {
1587     unsigned j = IsLE ? 0 : 4;
1588     for (unsigned i = 0; i != 8; i += 4)
1589       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1590           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1591           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1592           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1593           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1594           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1595           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1596           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1597         return false;
1598   }
1599   return true;
1600 }
1601 
1602 /// isVMerge - Common function, used to match vmrg* shuffles.
1603 ///
1604 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1605                      unsigned LHSStart, unsigned RHSStart) {
1606   if (N->getValueType(0) != MVT::v16i8)
1607     return false;
1608   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1609          "Unsupported merge size!");
1610 
1611   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1612     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1613       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1614                              LHSStart+j+i*UnitSize) ||
1615           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1616                              RHSStart+j+i*UnitSize))
1617         return false;
1618     }
1619   return true;
1620 }
1621 
1622 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1623 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1624 /// The ShuffleKind distinguishes between big-endian merges with two
1625 /// different inputs (0), either-endian merges with two identical inputs (1),
1626 /// and little-endian merges with two different inputs (2).  For the latter,
1627 /// the input operands are swapped (see PPCInstrAltivec.td).
1628 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1629                              unsigned ShuffleKind, SelectionDAG &DAG) {
1630   if (DAG.getDataLayout().isLittleEndian()) {
1631     if (ShuffleKind == 1) // unary
1632       return isVMerge(N, UnitSize, 0, 0);
1633     else if (ShuffleKind == 2) // swapped
1634       return isVMerge(N, UnitSize, 0, 16);
1635     else
1636       return false;
1637   } else {
1638     if (ShuffleKind == 1) // unary
1639       return isVMerge(N, UnitSize, 8, 8);
1640     else if (ShuffleKind == 0) // normal
1641       return isVMerge(N, UnitSize, 8, 24);
1642     else
1643       return false;
1644   }
1645 }
1646 
1647 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1648 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1649 /// The ShuffleKind distinguishes between big-endian merges with two
1650 /// different inputs (0), either-endian merges with two identical inputs (1),
1651 /// and little-endian merges with two different inputs (2).  For the latter,
1652 /// the input operands are swapped (see PPCInstrAltivec.td).
1653 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1654                              unsigned ShuffleKind, SelectionDAG &DAG) {
1655   if (DAG.getDataLayout().isLittleEndian()) {
1656     if (ShuffleKind == 1) // unary
1657       return isVMerge(N, UnitSize, 8, 8);
1658     else if (ShuffleKind == 2) // swapped
1659       return isVMerge(N, UnitSize, 8, 24);
1660     else
1661       return false;
1662   } else {
1663     if (ShuffleKind == 1) // unary
1664       return isVMerge(N, UnitSize, 0, 0);
1665     else if (ShuffleKind == 0) // normal
1666       return isVMerge(N, UnitSize, 0, 16);
1667     else
1668       return false;
1669   }
1670 }
1671 
1672 /**
1673  * Common function used to match vmrgew and vmrgow shuffles
1674  *
1675  * The indexOffset determines whether to look for even or odd words in
1676  * the shuffle mask. This is based on the of the endianness of the target
1677  * machine.
1678  *   - Little Endian:
1679  *     - Use offset of 0 to check for odd elements
1680  *     - Use offset of 4 to check for even elements
1681  *   - Big Endian:
1682  *     - Use offset of 0 to check for even elements
1683  *     - Use offset of 4 to check for odd elements
1684  * A detailed description of the vector element ordering for little endian and
1685  * big endian can be found at
1686  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1687  * Targeting your applications - what little endian and big endian IBM XL C/C++
1688  * compiler differences mean to you
1689  *
1690  * The mask to the shuffle vector instruction specifies the indices of the
1691  * elements from the two input vectors to place in the result. The elements are
1692  * numbered in array-access order, starting with the first vector. These vectors
1693  * are always of type v16i8, thus each vector will contain 16 elements of size
1694  * 8. More info on the shuffle vector can be found in the
1695  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1696  * Language Reference.
1697  *
1698  * The RHSStartValue indicates whether the same input vectors are used (unary)
1699  * or two different input vectors are used, based on the following:
1700  *   - If the instruction uses the same vector for both inputs, the range of the
1701  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1702  *     be 0.
1703  *   - If the instruction has two different vectors then the range of the
1704  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1705  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1706  *     to 31 specify elements in the second vector).
1707  *
1708  * \param[in] N The shuffle vector SD Node to analyze
1709  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1710  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1711  * vector to the shuffle_vector instruction
1712  * \return true iff this shuffle vector represents an even or odd word merge
1713  */
1714 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1715                      unsigned RHSStartValue) {
1716   if (N->getValueType(0) != MVT::v16i8)
1717     return false;
1718 
1719   for (unsigned i = 0; i < 2; ++i)
1720     for (unsigned j = 0; j < 4; ++j)
1721       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1722                              i*RHSStartValue+j+IndexOffset) ||
1723           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1724                              i*RHSStartValue+j+IndexOffset+8))
1725         return false;
1726   return true;
1727 }
1728 
1729 /**
1730  * Determine if the specified shuffle mask is suitable for the vmrgew or
1731  * vmrgow instructions.
1732  *
1733  * \param[in] N The shuffle vector SD Node to analyze
1734  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1735  * \param[in] ShuffleKind Identify the type of merge:
1736  *   - 0 = big-endian merge with two different inputs;
1737  *   - 1 = either-endian merge with two identical inputs;
1738  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1739  *     little-endian merges).
1740  * \param[in] DAG The current SelectionDAG
1741  * \return true iff this shuffle mask
1742  */
1743 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1744                               unsigned ShuffleKind, SelectionDAG &DAG) {
1745   if (DAG.getDataLayout().isLittleEndian()) {
1746     unsigned indexOffset = CheckEven ? 4 : 0;
1747     if (ShuffleKind == 1) // Unary
1748       return isVMerge(N, indexOffset, 0);
1749     else if (ShuffleKind == 2) // swapped
1750       return isVMerge(N, indexOffset, 16);
1751     else
1752       return false;
1753   }
1754   else {
1755     unsigned indexOffset = CheckEven ? 0 : 4;
1756     if (ShuffleKind == 1) // Unary
1757       return isVMerge(N, indexOffset, 0);
1758     else if (ShuffleKind == 0) // Normal
1759       return isVMerge(N, indexOffset, 16);
1760     else
1761       return false;
1762   }
1763   return false;
1764 }
1765 
1766 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1767 /// amount, otherwise return -1.
1768 /// The ShuffleKind distinguishes between big-endian operations with two
1769 /// different inputs (0), either-endian operations with two identical inputs
1770 /// (1), and little-endian operations with two different inputs (2).  For the
1771 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1772 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1773                              SelectionDAG &DAG) {
1774   if (N->getValueType(0) != MVT::v16i8)
1775     return -1;
1776 
1777   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1778 
1779   // Find the first non-undef value in the shuffle mask.
1780   unsigned i;
1781   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1782     /*search*/;
1783 
1784   if (i == 16) return -1;  // all undef.
1785 
1786   // Otherwise, check to see if the rest of the elements are consecutively
1787   // numbered from this value.
1788   unsigned ShiftAmt = SVOp->getMaskElt(i);
1789   if (ShiftAmt < i) return -1;
1790 
1791   ShiftAmt -= i;
1792   bool isLE = DAG.getDataLayout().isLittleEndian();
1793 
1794   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1795     // Check the rest of the elements to see if they are consecutive.
1796     for (++i; i != 16; ++i)
1797       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1798         return -1;
1799   } else if (ShuffleKind == 1) {
1800     // Check the rest of the elements to see if they are consecutive.
1801     for (++i; i != 16; ++i)
1802       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1803         return -1;
1804   } else
1805     return -1;
1806 
1807   if (isLE)
1808     ShiftAmt = 16 - ShiftAmt;
1809 
1810   return ShiftAmt;
1811 }
1812 
1813 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1814 /// specifies a splat of a single element that is suitable for input to
1815 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1816 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1817   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1818          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1819 
1820   // The consecutive indices need to specify an element, not part of two
1821   // different elements.  So abandon ship early if this isn't the case.
1822   if (N->getMaskElt(0) % EltSize != 0)
1823     return false;
1824 
1825   // This is a splat operation if each element of the permute is the same, and
1826   // if the value doesn't reference the second vector.
1827   unsigned ElementBase = N->getMaskElt(0);
1828 
1829   // FIXME: Handle UNDEF elements too!
1830   if (ElementBase >= 16)
1831     return false;
1832 
1833   // Check that the indices are consecutive, in the case of a multi-byte element
1834   // splatted with a v16i8 mask.
1835   for (unsigned i = 1; i != EltSize; ++i)
1836     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1837       return false;
1838 
1839   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1840     if (N->getMaskElt(i) < 0) continue;
1841     for (unsigned j = 0; j != EltSize; ++j)
1842       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1843         return false;
1844   }
1845   return true;
1846 }
1847 
1848 /// Check that the mask is shuffling N byte elements. Within each N byte
1849 /// element of the mask, the indices could be either in increasing or
1850 /// decreasing order as long as they are consecutive.
1851 /// \param[in] N the shuffle vector SD Node to analyze
1852 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1853 /// Word/DoubleWord/QuadWord).
1854 /// \param[in] StepLen the delta indices number among the N byte element, if
1855 /// the mask is in increasing/decreasing order then it is 1/-1.
1856 /// \return true iff the mask is shuffling N byte elements.
1857 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1858                                    int StepLen) {
1859   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1860          "Unexpected element width.");
1861   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1862 
1863   unsigned NumOfElem = 16 / Width;
1864   unsigned MaskVal[16]; //  Width is never greater than 16
1865   for (unsigned i = 0; i < NumOfElem; ++i) {
1866     MaskVal[0] = N->getMaskElt(i * Width);
1867     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1868       return false;
1869     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1870       return false;
1871     }
1872 
1873     for (unsigned int j = 1; j < Width; ++j) {
1874       MaskVal[j] = N->getMaskElt(i * Width + j);
1875       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1876         return false;
1877       }
1878     }
1879   }
1880 
1881   return true;
1882 }
1883 
1884 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1885                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1886   if (!isNByteElemShuffleMask(N, 4, 1))
1887     return false;
1888 
1889   // Now we look at mask elements 0,4,8,12
1890   unsigned M0 = N->getMaskElt(0) / 4;
1891   unsigned M1 = N->getMaskElt(4) / 4;
1892   unsigned M2 = N->getMaskElt(8) / 4;
1893   unsigned M3 = N->getMaskElt(12) / 4;
1894   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1895   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1896 
1897   // Below, let H and L be arbitrary elements of the shuffle mask
1898   // where H is in the range [4,7] and L is in the range [0,3].
1899   // H, 1, 2, 3 or L, 5, 6, 7
1900   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1901       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1902     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1903     InsertAtByte = IsLE ? 12 : 0;
1904     Swap = M0 < 4;
1905     return true;
1906   }
1907   // 0, H, 2, 3 or 4, L, 6, 7
1908   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1909       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1910     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1911     InsertAtByte = IsLE ? 8 : 4;
1912     Swap = M1 < 4;
1913     return true;
1914   }
1915   // 0, 1, H, 3 or 4, 5, L, 7
1916   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1917       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1918     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1919     InsertAtByte = IsLE ? 4 : 8;
1920     Swap = M2 < 4;
1921     return true;
1922   }
1923   // 0, 1, 2, H or 4, 5, 6, L
1924   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1925       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1926     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1927     InsertAtByte = IsLE ? 0 : 12;
1928     Swap = M3 < 4;
1929     return true;
1930   }
1931 
1932   // If both vector operands for the shuffle are the same vector, the mask will
1933   // contain only elements from the first one and the second one will be undef.
1934   if (N->getOperand(1).isUndef()) {
1935     ShiftElts = 0;
1936     Swap = true;
1937     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1938     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1939       InsertAtByte = IsLE ? 12 : 0;
1940       return true;
1941     }
1942     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1943       InsertAtByte = IsLE ? 8 : 4;
1944       return true;
1945     }
1946     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1947       InsertAtByte = IsLE ? 4 : 8;
1948       return true;
1949     }
1950     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1951       InsertAtByte = IsLE ? 0 : 12;
1952       return true;
1953     }
1954   }
1955 
1956   return false;
1957 }
1958 
1959 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1960                                bool &Swap, bool IsLE) {
1961   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1962   // Ensure each byte index of the word is consecutive.
1963   if (!isNByteElemShuffleMask(N, 4, 1))
1964     return false;
1965 
1966   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1967   unsigned M0 = N->getMaskElt(0) / 4;
1968   unsigned M1 = N->getMaskElt(4) / 4;
1969   unsigned M2 = N->getMaskElt(8) / 4;
1970   unsigned M3 = N->getMaskElt(12) / 4;
1971 
1972   // If both vector operands for the shuffle are the same vector, the mask will
1973   // contain only elements from the first one and the second one will be undef.
1974   if (N->getOperand(1).isUndef()) {
1975     assert(M0 < 4 && "Indexing into an undef vector?");
1976     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1977       return false;
1978 
1979     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1980     Swap = false;
1981     return true;
1982   }
1983 
1984   // Ensure each word index of the ShuffleVector Mask is consecutive.
1985   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1986     return false;
1987 
1988   if (IsLE) {
1989     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1990       // Input vectors don't need to be swapped if the leading element
1991       // of the result is one of the 3 left elements of the second vector
1992       // (or if there is no shift to be done at all).
1993       Swap = false;
1994       ShiftElts = (8 - M0) % 8;
1995     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1996       // Input vectors need to be swapped if the leading element
1997       // of the result is one of the 3 left elements of the first vector
1998       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1999       Swap = true;
2000       ShiftElts = (4 - M0) % 4;
2001     }
2002 
2003     return true;
2004   } else {                                          // BE
2005     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
2006       // Input vectors don't need to be swapped if the leading element
2007       // of the result is one of the 4 elements of the first vector.
2008       Swap = false;
2009       ShiftElts = M0;
2010     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2011       // Input vectors need to be swapped if the leading element
2012       // of the result is one of the 4 elements of the right vector.
2013       Swap = true;
2014       ShiftElts = M0 - 4;
2015     }
2016 
2017     return true;
2018   }
2019 }
2020 
2021 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2022   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2023 
2024   if (!isNByteElemShuffleMask(N, Width, -1))
2025     return false;
2026 
2027   for (int i = 0; i < 16; i += Width)
2028     if (N->getMaskElt(i) != i + Width - 1)
2029       return false;
2030 
2031   return true;
2032 }
2033 
2034 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2035   return isXXBRShuffleMaskHelper(N, 2);
2036 }
2037 
2038 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2039   return isXXBRShuffleMaskHelper(N, 4);
2040 }
2041 
2042 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2043   return isXXBRShuffleMaskHelper(N, 8);
2044 }
2045 
2046 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2047   return isXXBRShuffleMaskHelper(N, 16);
2048 }
2049 
2050 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2051 /// if the inputs to the instruction should be swapped and set \p DM to the
2052 /// value for the immediate.
2053 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2054 /// AND element 0 of the result comes from the first input (LE) or second input
2055 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2056 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2057 /// mask.
2058 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2059                                bool &Swap, bool IsLE) {
2060   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2061 
2062   // Ensure each byte index of the double word is consecutive.
2063   if (!isNByteElemShuffleMask(N, 8, 1))
2064     return false;
2065 
2066   unsigned M0 = N->getMaskElt(0) / 8;
2067   unsigned M1 = N->getMaskElt(8) / 8;
2068   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2069 
2070   // If both vector operands for the shuffle are the same vector, the mask will
2071   // contain only elements from the first one and the second one will be undef.
2072   if (N->getOperand(1).isUndef()) {
2073     if ((M0 | M1) < 2) {
2074       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2075       Swap = false;
2076       return true;
2077     } else
2078       return false;
2079   }
2080 
2081   if (IsLE) {
2082     if (M0 > 1 && M1 < 2) {
2083       Swap = false;
2084     } else if (M0 < 2 && M1 > 1) {
2085       M0 = (M0 + 2) % 4;
2086       M1 = (M1 + 2) % 4;
2087       Swap = true;
2088     } else
2089       return false;
2090 
2091     // Note: if control flow comes here that means Swap is already set above
2092     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2093     return true;
2094   } else { // BE
2095     if (M0 < 2 && M1 > 1) {
2096       Swap = false;
2097     } else if (M0 > 1 && M1 < 2) {
2098       M0 = (M0 + 2) % 4;
2099       M1 = (M1 + 2) % 4;
2100       Swap = true;
2101     } else
2102       return false;
2103 
2104     // Note: if control flow comes here that means Swap is already set above
2105     DM = (M0 << 1) + (M1 & 1);
2106     return true;
2107   }
2108 }
2109 
2110 
2111 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2112 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2113 /// elements are counted from the left of the vector register).
2114 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2115                                          SelectionDAG &DAG) {
2116   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2117   assert(isSplatShuffleMask(SVOp, EltSize));
2118   if (DAG.getDataLayout().isLittleEndian())
2119     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2120   else
2121     return SVOp->getMaskElt(0) / EltSize;
2122 }
2123 
2124 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2125 /// by using a vspltis[bhw] instruction of the specified element size, return
2126 /// the constant being splatted.  The ByteSize field indicates the number of
2127 /// bytes of each element [124] -> [bhw].
2128 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2129   SDValue OpVal(nullptr, 0);
2130 
2131   // If ByteSize of the splat is bigger than the element size of the
2132   // build_vector, then we have a case where we are checking for a splat where
2133   // multiple elements of the buildvector are folded together into a single
2134   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2135   unsigned EltSize = 16/N->getNumOperands();
2136   if (EltSize < ByteSize) {
2137     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2138     SDValue UniquedVals[4];
2139     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2140 
2141     // See if all of the elements in the buildvector agree across.
2142     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2143       if (N->getOperand(i).isUndef()) continue;
2144       // If the element isn't a constant, bail fully out.
2145       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2146 
2147       if (!UniquedVals[i&(Multiple-1)].getNode())
2148         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2149       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2150         return SDValue();  // no match.
2151     }
2152 
2153     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2154     // either constant or undef values that are identical for each chunk.  See
2155     // if these chunks can form into a larger vspltis*.
2156 
2157     // Check to see if all of the leading entries are either 0 or -1.  If
2158     // neither, then this won't fit into the immediate field.
2159     bool LeadingZero = true;
2160     bool LeadingOnes = true;
2161     for (unsigned i = 0; i != Multiple-1; ++i) {
2162       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2163 
2164       LeadingZero &= isNullConstant(UniquedVals[i]);
2165       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2166     }
2167     // Finally, check the least significant entry.
2168     if (LeadingZero) {
2169       if (!UniquedVals[Multiple-1].getNode())
2170         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2171       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2172       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2173         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2174     }
2175     if (LeadingOnes) {
2176       if (!UniquedVals[Multiple-1].getNode())
2177         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2178       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2179       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2180         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2181     }
2182 
2183     return SDValue();
2184   }
2185 
2186   // Check to see if this buildvec has a single non-undef value in its elements.
2187   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2188     if (N->getOperand(i).isUndef()) continue;
2189     if (!OpVal.getNode())
2190       OpVal = N->getOperand(i);
2191     else if (OpVal != N->getOperand(i))
2192       return SDValue();
2193   }
2194 
2195   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2196 
2197   unsigned ValSizeInBytes = EltSize;
2198   uint64_t Value = 0;
2199   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2200     Value = CN->getZExtValue();
2201   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2202     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2203     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2204   }
2205 
2206   // If the splat value is larger than the element value, then we can never do
2207   // this splat.  The only case that we could fit the replicated bits into our
2208   // immediate field for would be zero, and we prefer to use vxor for it.
2209   if (ValSizeInBytes < ByteSize) return SDValue();
2210 
2211   // If the element value is larger than the splat value, check if it consists
2212   // of a repeated bit pattern of size ByteSize.
2213   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2214     return SDValue();
2215 
2216   // Properly sign extend the value.
2217   int MaskVal = SignExtend32(Value, ByteSize * 8);
2218 
2219   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2220   if (MaskVal == 0) return SDValue();
2221 
2222   // Finally, if this value fits in a 5 bit sext field, return it
2223   if (SignExtend32<5>(MaskVal) == MaskVal)
2224     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2225   return SDValue();
2226 }
2227 
2228 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2229 /// amount, otherwise return -1.
2230 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2231   EVT VT = N->getValueType(0);
2232   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2233     return -1;
2234 
2235   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2236 
2237   // Find the first non-undef value in the shuffle mask.
2238   unsigned i;
2239   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2240     /*search*/;
2241 
2242   if (i == 4) return -1;  // all undef.
2243 
2244   // Otherwise, check to see if the rest of the elements are consecutively
2245   // numbered from this value.
2246   unsigned ShiftAmt = SVOp->getMaskElt(i);
2247   if (ShiftAmt < i) return -1;
2248   ShiftAmt -= i;
2249 
2250   // Check the rest of the elements to see if they are consecutive.
2251   for (++i; i != 4; ++i)
2252     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2253       return -1;
2254 
2255   return ShiftAmt;
2256 }
2257 
2258 //===----------------------------------------------------------------------===//
2259 //  Addressing Mode Selection
2260 //===----------------------------------------------------------------------===//
2261 
2262 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2263 /// or 64-bit immediate, and if the value can be accurately represented as a
2264 /// sign extension from a 16-bit value.  If so, this returns true and the
2265 /// immediate.
2266 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2267   if (!isa<ConstantSDNode>(N))
2268     return false;
2269 
2270   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2271   if (N->getValueType(0) == MVT::i32)
2272     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2273   else
2274     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2275 }
2276 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2277   return isIntS16Immediate(Op.getNode(), Imm);
2278 }
2279 
2280 
2281 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2282 /// be represented as an indexed [r+r] operation.
2283 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2284                                                SDValue &Index,
2285                                                SelectionDAG &DAG) const {
2286   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2287       UI != E; ++UI) {
2288     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2289       if (Memop->getMemoryVT() == MVT::f64) {
2290           Base = N.getOperand(0);
2291           Index = N.getOperand(1);
2292           return true;
2293       }
2294     }
2295   }
2296   return false;
2297 }
2298 
2299 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2300 /// can be represented as an indexed [r+r] operation.  Returns false if it
2301 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2302 /// non-zero and N can be represented by a base register plus a signed 16-bit
2303 /// displacement, make a more precise judgement by checking (displacement % \p
2304 /// EncodingAlignment).
2305 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2306                                             SDValue &Index, SelectionDAG &DAG,
2307                                             unsigned EncodingAlignment) const {
2308   int16_t imm = 0;
2309   if (N.getOpcode() == ISD::ADD) {
2310     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2311     // SPE load/store can only handle 8-bit offsets.
2312     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2313         return true;
2314     if (isIntS16Immediate(N.getOperand(1), imm) &&
2315         (!EncodingAlignment || !(imm % EncodingAlignment)))
2316       return false; // r+i
2317     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2318       return false;    // r+i
2319 
2320     Base = N.getOperand(0);
2321     Index = N.getOperand(1);
2322     return true;
2323   } else if (N.getOpcode() == ISD::OR) {
2324     if (isIntS16Immediate(N.getOperand(1), imm) &&
2325         (!EncodingAlignment || !(imm % EncodingAlignment)))
2326       return false; // r+i can fold it if we can.
2327 
2328     // If this is an or of disjoint bitfields, we can codegen this as an add
2329     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2330     // disjoint.
2331     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2332 
2333     if (LHSKnown.Zero.getBoolValue()) {
2334       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2335       // If all of the bits are known zero on the LHS or RHS, the add won't
2336       // carry.
2337       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2338         Base = N.getOperand(0);
2339         Index = N.getOperand(1);
2340         return true;
2341       }
2342     }
2343   }
2344 
2345   return false;
2346 }
2347 
2348 // If we happen to be doing an i64 load or store into a stack slot that has
2349 // less than a 4-byte alignment, then the frame-index elimination may need to
2350 // use an indexed load or store instruction (because the offset may not be a
2351 // multiple of 4). The extra register needed to hold the offset comes from the
2352 // register scavenger, and it is possible that the scavenger will need to use
2353 // an emergency spill slot. As a result, we need to make sure that a spill slot
2354 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2355 // stack slot.
2356 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2357   // FIXME: This does not handle the LWA case.
2358   if (VT != MVT::i64)
2359     return;
2360 
2361   // NOTE: We'll exclude negative FIs here, which come from argument
2362   // lowering, because there are no known test cases triggering this problem
2363   // using packed structures (or similar). We can remove this exclusion if
2364   // we find such a test case. The reason why this is so test-case driven is
2365   // because this entire 'fixup' is only to prevent crashes (from the
2366   // register scavenger) on not-really-valid inputs. For example, if we have:
2367   //   %a = alloca i1
2368   //   %b = bitcast i1* %a to i64*
2369   //   store i64* a, i64 b
2370   // then the store should really be marked as 'align 1', but is not. If it
2371   // were marked as 'align 1' then the indexed form would have been
2372   // instruction-selected initially, and the problem this 'fixup' is preventing
2373   // won't happen regardless.
2374   if (FrameIdx < 0)
2375     return;
2376 
2377   MachineFunction &MF = DAG.getMachineFunction();
2378   MachineFrameInfo &MFI = MF.getFrameInfo();
2379 
2380   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2381   if (Align >= 4)
2382     return;
2383 
2384   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2385   FuncInfo->setHasNonRISpills();
2386 }
2387 
2388 /// Returns true if the address N can be represented by a base register plus
2389 /// a signed 16-bit displacement [r+imm], and if it is not better
2390 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2391 /// displacements that are multiples of that value.
2392 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2393                                             SDValue &Base,
2394                                             SelectionDAG &DAG,
2395                                             unsigned EncodingAlignment) const {
2396   // FIXME dl should come from parent load or store, not from address
2397   SDLoc dl(N);
2398   // If this can be more profitably realized as r+r, fail.
2399   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2400     return false;
2401 
2402   if (N.getOpcode() == ISD::ADD) {
2403     int16_t imm = 0;
2404     if (isIntS16Immediate(N.getOperand(1), imm) &&
2405         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2406       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2407       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2408         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2409         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2410       } else {
2411         Base = N.getOperand(0);
2412       }
2413       return true; // [r+i]
2414     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2415       // Match LOAD (ADD (X, Lo(G))).
2416       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2417              && "Cannot handle constant offsets yet!");
2418       Disp = N.getOperand(1).getOperand(0);  // The global address.
2419       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2420              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2421              Disp.getOpcode() == ISD::TargetConstantPool ||
2422              Disp.getOpcode() == ISD::TargetJumpTable);
2423       Base = N.getOperand(0);
2424       return true;  // [&g+r]
2425     }
2426   } else if (N.getOpcode() == ISD::OR) {
2427     int16_t imm = 0;
2428     if (isIntS16Immediate(N.getOperand(1), imm) &&
2429         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2430       // If this is an or of disjoint bitfields, we can codegen this as an add
2431       // (for better address arithmetic) if the LHS and RHS of the OR are
2432       // provably disjoint.
2433       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2434 
2435       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2436         // If all of the bits are known zero on the LHS or RHS, the add won't
2437         // carry.
2438         if (FrameIndexSDNode *FI =
2439               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2440           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2441           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2442         } else {
2443           Base = N.getOperand(0);
2444         }
2445         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2446         return true;
2447       }
2448     }
2449   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2450     // Loading from a constant address.
2451 
2452     // If this address fits entirely in a 16-bit sext immediate field, codegen
2453     // this as "d, 0"
2454     int16_t Imm;
2455     if (isIntS16Immediate(CN, Imm) &&
2456         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2457       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2458       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2459                              CN->getValueType(0));
2460       return true;
2461     }
2462 
2463     // Handle 32-bit sext immediates with LIS + addr mode.
2464     if ((CN->getValueType(0) == MVT::i32 ||
2465          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2466         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2467       int Addr = (int)CN->getZExtValue();
2468 
2469       // Otherwise, break this down into an LIS + disp.
2470       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2471 
2472       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2473                                    MVT::i32);
2474       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2475       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2476       return true;
2477     }
2478   }
2479 
2480   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2481   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2482     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2483     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2484   } else
2485     Base = N;
2486   return true;      // [r+0]
2487 }
2488 
2489 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2490 /// represented as an indexed [r+r] operation.
2491 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2492                                                 SDValue &Index,
2493                                                 SelectionDAG &DAG) const {
2494   // Check to see if we can easily represent this as an [r+r] address.  This
2495   // will fail if it thinks that the address is more profitably represented as
2496   // reg+imm, e.g. where imm = 0.
2497   if (SelectAddressRegReg(N, Base, Index, DAG))
2498     return true;
2499 
2500   // If the address is the result of an add, we will utilize the fact that the
2501   // address calculation includes an implicit add.  However, we can reduce
2502   // register pressure if we do not materialize a constant just for use as the
2503   // index register.  We only get rid of the add if it is not an add of a
2504   // value and a 16-bit signed constant and both have a single use.
2505   int16_t imm = 0;
2506   if (N.getOpcode() == ISD::ADD &&
2507       (!isIntS16Immediate(N.getOperand(1), imm) ||
2508        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2509     Base = N.getOperand(0);
2510     Index = N.getOperand(1);
2511     return true;
2512   }
2513 
2514   // Otherwise, do it the hard way, using R0 as the base register.
2515   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2516                          N.getValueType());
2517   Index = N;
2518   return true;
2519 }
2520 
2521 /// Returns true if we should use a direct load into vector instruction
2522 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2523 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2524 
2525   // If there are any other uses other than scalar to vector, then we should
2526   // keep it as a scalar load -> direct move pattern to prevent multiple
2527   // loads.
2528   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2529   if (!LD)
2530     return false;
2531 
2532   EVT MemVT = LD->getMemoryVT();
2533   if (!MemVT.isSimple())
2534     return false;
2535   switch(MemVT.getSimpleVT().SimpleTy) {
2536   case MVT::i64:
2537     break;
2538   case MVT::i32:
2539     if (!ST.hasP8Vector())
2540       return false;
2541     break;
2542   case MVT::i16:
2543   case MVT::i8:
2544     if (!ST.hasP9Vector())
2545       return false;
2546     break;
2547   default:
2548     return false;
2549   }
2550 
2551   SDValue LoadedVal(N, 0);
2552   if (!LoadedVal.hasOneUse())
2553     return false;
2554 
2555   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2556        UI != UE; ++UI)
2557     if (UI.getUse().get().getResNo() == 0 &&
2558         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2559       return false;
2560 
2561   return true;
2562 }
2563 
2564 /// getPreIndexedAddressParts - returns true by value, base pointer and
2565 /// offset pointer and addressing mode by reference if the node's address
2566 /// can be legally represented as pre-indexed load / store address.
2567 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2568                                                   SDValue &Offset,
2569                                                   ISD::MemIndexedMode &AM,
2570                                                   SelectionDAG &DAG) const {
2571   if (DisablePPCPreinc) return false;
2572 
2573   bool isLoad = true;
2574   SDValue Ptr;
2575   EVT VT;
2576   unsigned Alignment;
2577   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2578     Ptr = LD->getBasePtr();
2579     VT = LD->getMemoryVT();
2580     Alignment = LD->getAlignment();
2581   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2582     Ptr = ST->getBasePtr();
2583     VT  = ST->getMemoryVT();
2584     Alignment = ST->getAlignment();
2585     isLoad = false;
2586   } else
2587     return false;
2588 
2589   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2590   // instructions because we can fold these into a more efficient instruction
2591   // instead, (such as LXSD).
2592   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2593     return false;
2594   }
2595 
2596   // PowerPC doesn't have preinc load/store instructions for vectors (except
2597   // for QPX, which does have preinc r+r forms).
2598   if (VT.isVector()) {
2599     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2600       return false;
2601     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2602       AM = ISD::PRE_INC;
2603       return true;
2604     }
2605   }
2606 
2607   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2608     // Common code will reject creating a pre-inc form if the base pointer
2609     // is a frame index, or if N is a store and the base pointer is either
2610     // the same as or a predecessor of the value being stored.  Check for
2611     // those situations here, and try with swapped Base/Offset instead.
2612     bool Swap = false;
2613 
2614     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2615       Swap = true;
2616     else if (!isLoad) {
2617       SDValue Val = cast<StoreSDNode>(N)->getValue();
2618       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2619         Swap = true;
2620     }
2621 
2622     if (Swap)
2623       std::swap(Base, Offset);
2624 
2625     AM = ISD::PRE_INC;
2626     return true;
2627   }
2628 
2629   // LDU/STU can only handle immediates that are a multiple of 4.
2630   if (VT != MVT::i64) {
2631     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2632       return false;
2633   } else {
2634     // LDU/STU need an address with at least 4-byte alignment.
2635     if (Alignment < 4)
2636       return false;
2637 
2638     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2639       return false;
2640   }
2641 
2642   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2643     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2644     // sext i32 to i64 when addr mode is r+i.
2645     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2646         LD->getExtensionType() == ISD::SEXTLOAD &&
2647         isa<ConstantSDNode>(Offset))
2648       return false;
2649   }
2650 
2651   AM = ISD::PRE_INC;
2652   return true;
2653 }
2654 
2655 //===----------------------------------------------------------------------===//
2656 //  LowerOperation implementation
2657 //===----------------------------------------------------------------------===//
2658 
2659 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2660 /// and LoOpFlags to the target MO flags.
2661 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2662                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2663                                const GlobalValue *GV = nullptr) {
2664   HiOpFlags = PPCII::MO_HA;
2665   LoOpFlags = PPCII::MO_LO;
2666 
2667   // Don't use the pic base if not in PIC relocation model.
2668   if (IsPIC) {
2669     HiOpFlags |= PPCII::MO_PIC_FLAG;
2670     LoOpFlags |= PPCII::MO_PIC_FLAG;
2671   }
2672 
2673   // If this is a reference to a global value that requires a non-lazy-ptr, make
2674   // sure that instruction lowering adds it.
2675   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2676     HiOpFlags |= PPCII::MO_NLP_FLAG;
2677     LoOpFlags |= PPCII::MO_NLP_FLAG;
2678 
2679     if (GV->hasHiddenVisibility()) {
2680       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2681       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2682     }
2683   }
2684 }
2685 
2686 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2687                              SelectionDAG &DAG) {
2688   SDLoc DL(HiPart);
2689   EVT PtrVT = HiPart.getValueType();
2690   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2691 
2692   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2693   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2694 
2695   // With PIC, the first instruction is actually "GR+hi(&G)".
2696   if (isPIC)
2697     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2698                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2699 
2700   // Generate non-pic code that has direct accesses to the constant pool.
2701   // The address of the global is just (hi(&g)+lo(&g)).
2702   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2703 }
2704 
2705 static void setUsesTOCBasePtr(MachineFunction &MF) {
2706   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2707   FuncInfo->setUsesTOCBasePtr();
2708 }
2709 
2710 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2711   setUsesTOCBasePtr(DAG.getMachineFunction());
2712 }
2713 
2714 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2715                                        SDValue GA) const {
2716   const bool Is64Bit = Subtarget.isPPC64();
2717   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2718   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2719                         : Subtarget.isAIXABI()
2720                               ? DAG.getRegister(PPC::R2, VT)
2721                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2722   SDValue Ops[] = { GA, Reg };
2723   return DAG.getMemIntrinsicNode(
2724       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2725       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2726       MachineMemOperand::MOLoad);
2727 }
2728 
2729 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2730                                              SelectionDAG &DAG) const {
2731   EVT PtrVT = Op.getValueType();
2732   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2733   const Constant *C = CP->getConstVal();
2734 
2735   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2736   // The actual address of the GlobalValue is stored in the TOC.
2737   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2738     setUsesTOCBasePtr(DAG);
2739     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2740     return getTOCEntry(DAG, SDLoc(CP), GA);
2741   }
2742 
2743   unsigned MOHiFlag, MOLoFlag;
2744   bool IsPIC = isPositionIndependent();
2745   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2746 
2747   if (IsPIC && Subtarget.isSVR4ABI()) {
2748     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2749                                            PPCII::MO_PIC_FLAG);
2750     return getTOCEntry(DAG, SDLoc(CP), GA);
2751   }
2752 
2753   SDValue CPIHi =
2754     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2755   SDValue CPILo =
2756     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2757   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2758 }
2759 
2760 // For 64-bit PowerPC, prefer the more compact relative encodings.
2761 // This trades 32 bits per jump table entry for one or two instructions
2762 // on the jump site.
2763 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2764   if (isJumpTableRelative())
2765     return MachineJumpTableInfo::EK_LabelDifference32;
2766 
2767   return TargetLowering::getJumpTableEncoding();
2768 }
2769 
2770 bool PPCTargetLowering::isJumpTableRelative() const {
2771   if (UseAbsoluteJumpTables)
2772     return false;
2773   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2774     return true;
2775   return TargetLowering::isJumpTableRelative();
2776 }
2777 
2778 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2779                                                     SelectionDAG &DAG) const {
2780   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2781     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2782 
2783   switch (getTargetMachine().getCodeModel()) {
2784   case CodeModel::Small:
2785   case CodeModel::Medium:
2786     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2787   default:
2788     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2789                        getPointerTy(DAG.getDataLayout()));
2790   }
2791 }
2792 
2793 const MCExpr *
2794 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2795                                                 unsigned JTI,
2796                                                 MCContext &Ctx) const {
2797   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2798     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2799 
2800   switch (getTargetMachine().getCodeModel()) {
2801   case CodeModel::Small:
2802   case CodeModel::Medium:
2803     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2804   default:
2805     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2806   }
2807 }
2808 
2809 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2810   EVT PtrVT = Op.getValueType();
2811   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2812 
2813   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2814   // The actual address of the GlobalValue is stored in the TOC.
2815   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2816     setUsesTOCBasePtr(DAG);
2817     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2818     return getTOCEntry(DAG, SDLoc(JT), GA);
2819   }
2820 
2821   unsigned MOHiFlag, MOLoFlag;
2822   bool IsPIC = isPositionIndependent();
2823   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2824 
2825   if (IsPIC && Subtarget.isSVR4ABI()) {
2826     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2827                                         PPCII::MO_PIC_FLAG);
2828     return getTOCEntry(DAG, SDLoc(GA), GA);
2829   }
2830 
2831   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2832   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2833   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2834 }
2835 
2836 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2837                                              SelectionDAG &DAG) const {
2838   EVT PtrVT = Op.getValueType();
2839   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2840   const BlockAddress *BA = BASDN->getBlockAddress();
2841 
2842   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2843   // The actual BlockAddress is stored in the TOC.
2844   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2845     setUsesTOCBasePtr(DAG);
2846     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2847     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2848   }
2849 
2850   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2851   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2852     return getTOCEntry(
2853         DAG, SDLoc(BASDN),
2854         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2855 
2856   unsigned MOHiFlag, MOLoFlag;
2857   bool IsPIC = isPositionIndependent();
2858   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2859   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2860   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2861   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2862 }
2863 
2864 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2865                                               SelectionDAG &DAG) const {
2866   // FIXME: TLS addresses currently use medium model code sequences,
2867   // which is the most useful form.  Eventually support for small and
2868   // large models could be added if users need it, at the cost of
2869   // additional complexity.
2870   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2871   if (DAG.getTarget().useEmulatedTLS())
2872     return LowerToTLSEmulatedModel(GA, DAG);
2873 
2874   SDLoc dl(GA);
2875   const GlobalValue *GV = GA->getGlobal();
2876   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2877   bool is64bit = Subtarget.isPPC64();
2878   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2879   PICLevel::Level picLevel = M->getPICLevel();
2880 
2881   const TargetMachine &TM = getTargetMachine();
2882   TLSModel::Model Model = TM.getTLSModel(GV);
2883 
2884   if (Model == TLSModel::LocalExec) {
2885     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2886                                                PPCII::MO_TPREL_HA);
2887     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2888                                                PPCII::MO_TPREL_LO);
2889     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2890                              : DAG.getRegister(PPC::R2, MVT::i32);
2891 
2892     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2893     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2894   }
2895 
2896   if (Model == TLSModel::InitialExec) {
2897     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2898     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2899                                                 PPCII::MO_TLS);
2900     SDValue GOTPtr;
2901     if (is64bit) {
2902       setUsesTOCBasePtr(DAG);
2903       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2904       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2905                            PtrVT, GOTReg, TGA);
2906     } else {
2907       if (!TM.isPositionIndependent())
2908         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2909       else if (picLevel == PICLevel::SmallPIC)
2910         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2911       else
2912         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2913     }
2914     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2915                                    PtrVT, TGA, GOTPtr);
2916     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2917   }
2918 
2919   if (Model == TLSModel::GeneralDynamic) {
2920     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2921     SDValue GOTPtr;
2922     if (is64bit) {
2923       setUsesTOCBasePtr(DAG);
2924       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2925       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2926                                    GOTReg, TGA);
2927     } else {
2928       if (picLevel == PICLevel::SmallPIC)
2929         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2930       else
2931         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2932     }
2933     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2934                        GOTPtr, TGA, TGA);
2935   }
2936 
2937   if (Model == TLSModel::LocalDynamic) {
2938     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2939     SDValue GOTPtr;
2940     if (is64bit) {
2941       setUsesTOCBasePtr(DAG);
2942       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2943       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2944                            GOTReg, TGA);
2945     } else {
2946       if (picLevel == PICLevel::SmallPIC)
2947         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2948       else
2949         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2950     }
2951     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2952                                   PtrVT, GOTPtr, TGA, TGA);
2953     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2954                                       PtrVT, TLSAddr, TGA);
2955     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2956   }
2957 
2958   llvm_unreachable("Unknown TLS model!");
2959 }
2960 
2961 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2962                                               SelectionDAG &DAG) const {
2963   EVT PtrVT = Op.getValueType();
2964   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2965   SDLoc DL(GSDN);
2966   const GlobalValue *GV = GSDN->getGlobal();
2967 
2968   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2969   // The actual address of the GlobalValue is stored in the TOC.
2970   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2971     setUsesTOCBasePtr(DAG);
2972     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2973     return getTOCEntry(DAG, DL, GA);
2974   }
2975 
2976   unsigned MOHiFlag, MOLoFlag;
2977   bool IsPIC = isPositionIndependent();
2978   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2979 
2980   if (IsPIC && Subtarget.isSVR4ABI()) {
2981     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2982                                             GSDN->getOffset(),
2983                                             PPCII::MO_PIC_FLAG);
2984     return getTOCEntry(DAG, DL, GA);
2985   }
2986 
2987   SDValue GAHi =
2988     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2989   SDValue GALo =
2990     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2991 
2992   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2993 
2994   // If the global reference is actually to a non-lazy-pointer, we have to do an
2995   // extra load to get the address of the global.
2996   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2997     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2998   return Ptr;
2999 }
3000 
3001 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3002   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3003   SDLoc dl(Op);
3004 
3005   if (Op.getValueType() == MVT::v2i64) {
3006     // When the operands themselves are v2i64 values, we need to do something
3007     // special because VSX has no underlying comparison operations for these.
3008     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
3009       // Equality can be handled by casting to the legal type for Altivec
3010       // comparisons, everything else needs to be expanded.
3011       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3012         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3013                  DAG.getSetCC(dl, MVT::v4i32,
3014                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3015                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3016                    CC));
3017       }
3018 
3019       return SDValue();
3020     }
3021 
3022     // We handle most of these in the usual way.
3023     return Op;
3024   }
3025 
3026   // If we're comparing for equality to zero, expose the fact that this is
3027   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3028   // fold the new nodes.
3029   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3030     return V;
3031 
3032   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3033     // Leave comparisons against 0 and -1 alone for now, since they're usually
3034     // optimized.  FIXME: revisit this when we can custom lower all setcc
3035     // optimizations.
3036     if (C->isAllOnesValue() || C->isNullValue())
3037       return SDValue();
3038   }
3039 
3040   // If we have an integer seteq/setne, turn it into a compare against zero
3041   // by xor'ing the rhs with the lhs, which is faster than setting a
3042   // condition register, reading it back out, and masking the correct bit.  The
3043   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3044   // the result to other bit-twiddling opportunities.
3045   EVT LHSVT = Op.getOperand(0).getValueType();
3046   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3047     EVT VT = Op.getValueType();
3048     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3049                                 Op.getOperand(1));
3050     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3051   }
3052   return SDValue();
3053 }
3054 
3055 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3056   SDNode *Node = Op.getNode();
3057   EVT VT = Node->getValueType(0);
3058   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3059   SDValue InChain = Node->getOperand(0);
3060   SDValue VAListPtr = Node->getOperand(1);
3061   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3062   SDLoc dl(Node);
3063 
3064   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3065 
3066   // gpr_index
3067   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3068                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3069   InChain = GprIndex.getValue(1);
3070 
3071   if (VT == MVT::i64) {
3072     // Check if GprIndex is even
3073     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3074                                  DAG.getConstant(1, dl, MVT::i32));
3075     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3076                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3077     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3078                                           DAG.getConstant(1, dl, MVT::i32));
3079     // Align GprIndex to be even if it isn't
3080     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3081                            GprIndex);
3082   }
3083 
3084   // fpr index is 1 byte after gpr
3085   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3086                                DAG.getConstant(1, dl, MVT::i32));
3087 
3088   // fpr
3089   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3090                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3091   InChain = FprIndex.getValue(1);
3092 
3093   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3094                                        DAG.getConstant(8, dl, MVT::i32));
3095 
3096   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3097                                         DAG.getConstant(4, dl, MVT::i32));
3098 
3099   // areas
3100   SDValue OverflowArea =
3101       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3102   InChain = OverflowArea.getValue(1);
3103 
3104   SDValue RegSaveArea =
3105       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3106   InChain = RegSaveArea.getValue(1);
3107 
3108   // select overflow_area if index > 8
3109   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3110                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3111 
3112   // adjustment constant gpr_index * 4/8
3113   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3114                                     VT.isInteger() ? GprIndex : FprIndex,
3115                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3116                                                     MVT::i32));
3117 
3118   // OurReg = RegSaveArea + RegConstant
3119   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3120                                RegConstant);
3121 
3122   // Floating types are 32 bytes into RegSaveArea
3123   if (VT.isFloatingPoint())
3124     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3125                          DAG.getConstant(32, dl, MVT::i32));
3126 
3127   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3128   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3129                                    VT.isInteger() ? GprIndex : FprIndex,
3130                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3131                                                    MVT::i32));
3132 
3133   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3134                               VT.isInteger() ? VAListPtr : FprPtr,
3135                               MachinePointerInfo(SV), MVT::i8);
3136 
3137   // determine if we should load from reg_save_area or overflow_area
3138   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3139 
3140   // increase overflow_area by 4/8 if gpr/fpr > 8
3141   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3142                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3143                                           dl, MVT::i32));
3144 
3145   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3146                              OverflowAreaPlusN);
3147 
3148   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3149                               MachinePointerInfo(), MVT::i32);
3150 
3151   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3152 }
3153 
3154 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3155   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3156 
3157   // We have to copy the entire va_list struct:
3158   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3159   return DAG.getMemcpy(Op.getOperand(0), Op,
3160                        Op.getOperand(1), Op.getOperand(2),
3161                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3162                        false, MachinePointerInfo(), MachinePointerInfo());
3163 }
3164 
3165 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3166                                                   SelectionDAG &DAG) const {
3167   if (Subtarget.isAIXABI())
3168     report_fatal_error("ADJUST_TRAMPOLINE operation is not supported on AIX.");
3169 
3170   return Op.getOperand(0);
3171 }
3172 
3173 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3174                                                 SelectionDAG &DAG) const {
3175   if (Subtarget.isAIXABI())
3176     report_fatal_error("INIT_TRAMPOLINE operation is not supported on AIX.");
3177 
3178   SDValue Chain = Op.getOperand(0);
3179   SDValue Trmp = Op.getOperand(1); // trampoline
3180   SDValue FPtr = Op.getOperand(2); // nested function
3181   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3182   SDLoc dl(Op);
3183 
3184   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3185   bool isPPC64 = (PtrVT == MVT::i64);
3186   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3187 
3188   TargetLowering::ArgListTy Args;
3189   TargetLowering::ArgListEntry Entry;
3190 
3191   Entry.Ty = IntPtrTy;
3192   Entry.Node = Trmp; Args.push_back(Entry);
3193 
3194   // TrampSize == (isPPC64 ? 48 : 40);
3195   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3196                                isPPC64 ? MVT::i64 : MVT::i32);
3197   Args.push_back(Entry);
3198 
3199   Entry.Node = FPtr; Args.push_back(Entry);
3200   Entry.Node = Nest; Args.push_back(Entry);
3201 
3202   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3203   TargetLowering::CallLoweringInfo CLI(DAG);
3204   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3205       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3206       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3207 
3208   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3209   return CallResult.second;
3210 }
3211 
3212 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3213   MachineFunction &MF = DAG.getMachineFunction();
3214   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3215   EVT PtrVT = getPointerTy(MF.getDataLayout());
3216 
3217   SDLoc dl(Op);
3218 
3219   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3220     // vastart just stores the address of the VarArgsFrameIndex slot into the
3221     // memory location argument.
3222     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3223     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3224     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3225                         MachinePointerInfo(SV));
3226   }
3227 
3228   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3229   // We suppose the given va_list is already allocated.
3230   //
3231   // typedef struct {
3232   //  char gpr;     /* index into the array of 8 GPRs
3233   //                 * stored in the register save area
3234   //                 * gpr=0 corresponds to r3,
3235   //                 * gpr=1 to r4, etc.
3236   //                 */
3237   //  char fpr;     /* index into the array of 8 FPRs
3238   //                 * stored in the register save area
3239   //                 * fpr=0 corresponds to f1,
3240   //                 * fpr=1 to f2, etc.
3241   //                 */
3242   //  char *overflow_arg_area;
3243   //                /* location on stack that holds
3244   //                 * the next overflow argument
3245   //                 */
3246   //  char *reg_save_area;
3247   //               /* where r3:r10 and f1:f8 (if saved)
3248   //                * are stored
3249   //                */
3250   // } va_list[1];
3251 
3252   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3253   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3254   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3255                                             PtrVT);
3256   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3257                                  PtrVT);
3258 
3259   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3260   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3261 
3262   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3263   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3264 
3265   uint64_t FPROffset = 1;
3266   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3267 
3268   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3269 
3270   // Store first byte : number of int regs
3271   SDValue firstStore =
3272       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3273                         MachinePointerInfo(SV), MVT::i8);
3274   uint64_t nextOffset = FPROffset;
3275   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3276                                   ConstFPROffset);
3277 
3278   // Store second byte : number of float regs
3279   SDValue secondStore =
3280       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3281                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3282   nextOffset += StackOffset;
3283   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3284 
3285   // Store second word : arguments given on stack
3286   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3287                                     MachinePointerInfo(SV, nextOffset));
3288   nextOffset += FrameOffset;
3289   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3290 
3291   // Store third word : arguments given in registers
3292   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3293                       MachinePointerInfo(SV, nextOffset));
3294 }
3295 
3296 /// FPR - The set of FP registers that should be allocated for arguments
3297 /// on Darwin and AIX.
3298 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3299                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3300                                 PPC::F11, PPC::F12, PPC::F13};
3301 
3302 /// QFPR - The set of QPX registers that should be allocated for arguments.
3303 static const MCPhysReg QFPR[] = {
3304     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3305     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3306 
3307 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3308 /// the stack.
3309 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3310                                        unsigned PtrByteSize) {
3311   unsigned ArgSize = ArgVT.getStoreSize();
3312   if (Flags.isByVal())
3313     ArgSize = Flags.getByValSize();
3314 
3315   // Round up to multiples of the pointer size, except for array members,
3316   // which are always packed.
3317   if (!Flags.isInConsecutiveRegs())
3318     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3319 
3320   return ArgSize;
3321 }
3322 
3323 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3324 /// on the stack.
3325 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3326                                             ISD::ArgFlagsTy Flags,
3327                                             unsigned PtrByteSize) {
3328   unsigned Align = PtrByteSize;
3329 
3330   // Altivec parameters are padded to a 16 byte boundary.
3331   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3332       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3333       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3334       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3335     Align = 16;
3336   // QPX vector types stored in double-precision are padded to a 32 byte
3337   // boundary.
3338   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3339     Align = 32;
3340 
3341   // ByVal parameters are aligned as requested.
3342   if (Flags.isByVal()) {
3343     unsigned BVAlign = Flags.getByValAlign();
3344     if (BVAlign > PtrByteSize) {
3345       if (BVAlign % PtrByteSize != 0)
3346           llvm_unreachable(
3347             "ByVal alignment is not a multiple of the pointer size");
3348 
3349       Align = BVAlign;
3350     }
3351   }
3352 
3353   // Array members are always packed to their original alignment.
3354   if (Flags.isInConsecutiveRegs()) {
3355     // If the array member was split into multiple registers, the first
3356     // needs to be aligned to the size of the full type.  (Except for
3357     // ppcf128, which is only aligned as its f64 components.)
3358     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3359       Align = OrigVT.getStoreSize();
3360     else
3361       Align = ArgVT.getStoreSize();
3362   }
3363 
3364   return Align;
3365 }
3366 
3367 /// CalculateStackSlotUsed - Return whether this argument will use its
3368 /// stack slot (instead of being passed in registers).  ArgOffset,
3369 /// AvailableFPRs, and AvailableVRs must hold the current argument
3370 /// position, and will be updated to account for this argument.
3371 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3372                                    ISD::ArgFlagsTy Flags,
3373                                    unsigned PtrByteSize,
3374                                    unsigned LinkageSize,
3375                                    unsigned ParamAreaSize,
3376                                    unsigned &ArgOffset,
3377                                    unsigned &AvailableFPRs,
3378                                    unsigned &AvailableVRs, bool HasQPX) {
3379   bool UseMemory = false;
3380 
3381   // Respect alignment of argument on the stack.
3382   unsigned Align =
3383     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3384   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3385   // If there's no space left in the argument save area, we must
3386   // use memory (this check also catches zero-sized arguments).
3387   if (ArgOffset >= LinkageSize + ParamAreaSize)
3388     UseMemory = true;
3389 
3390   // Allocate argument on the stack.
3391   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3392   if (Flags.isInConsecutiveRegsLast())
3393     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3394   // If we overran the argument save area, we must use memory
3395   // (this check catches arguments passed partially in memory)
3396   if (ArgOffset > LinkageSize + ParamAreaSize)
3397     UseMemory = true;
3398 
3399   // However, if the argument is actually passed in an FPR or a VR,
3400   // we don't use memory after all.
3401   if (!Flags.isByVal()) {
3402     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3403         // QPX registers overlap with the scalar FP registers.
3404         (HasQPX && (ArgVT == MVT::v4f32 ||
3405                     ArgVT == MVT::v4f64 ||
3406                     ArgVT == MVT::v4i1)))
3407       if (AvailableFPRs > 0) {
3408         --AvailableFPRs;
3409         return false;
3410       }
3411     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3412         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3413         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3414         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3415       if (AvailableVRs > 0) {
3416         --AvailableVRs;
3417         return false;
3418       }
3419   }
3420 
3421   return UseMemory;
3422 }
3423 
3424 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3425 /// ensure minimum alignment required for target.
3426 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3427                                      unsigned NumBytes) {
3428   unsigned TargetAlign = Lowering->getStackAlignment();
3429   unsigned AlignMask = TargetAlign - 1;
3430   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3431   return NumBytes;
3432 }
3433 
3434 SDValue PPCTargetLowering::LowerFormalArguments(
3435     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3436     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3437     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3438   if (Subtarget.isAIXABI())
3439     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3440                                     InVals);
3441   if (Subtarget.is64BitELFABI())
3442     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3443                                        InVals);
3444   if (Subtarget.is32BitELFABI())
3445     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3446                                        InVals);
3447 
3448   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3449                                      InVals);
3450 }
3451 
3452 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3453     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3454     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3455     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3456 
3457   // 32-bit SVR4 ABI Stack Frame Layout:
3458   //              +-----------------------------------+
3459   //        +-->  |            Back chain             |
3460   //        |     +-----------------------------------+
3461   //        |     | Floating-point register save area |
3462   //        |     +-----------------------------------+
3463   //        |     |    General register save area     |
3464   //        |     +-----------------------------------+
3465   //        |     |          CR save word             |
3466   //        |     +-----------------------------------+
3467   //        |     |         VRSAVE save word          |
3468   //        |     +-----------------------------------+
3469   //        |     |         Alignment padding         |
3470   //        |     +-----------------------------------+
3471   //        |     |     Vector register save area     |
3472   //        |     +-----------------------------------+
3473   //        |     |       Local variable space        |
3474   //        |     +-----------------------------------+
3475   //        |     |        Parameter list area        |
3476   //        |     +-----------------------------------+
3477   //        |     |           LR save word            |
3478   //        |     +-----------------------------------+
3479   // SP-->  +---  |            Back chain             |
3480   //              +-----------------------------------+
3481   //
3482   // Specifications:
3483   //   System V Application Binary Interface PowerPC Processor Supplement
3484   //   AltiVec Technology Programming Interface Manual
3485 
3486   MachineFunction &MF = DAG.getMachineFunction();
3487   MachineFrameInfo &MFI = MF.getFrameInfo();
3488   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3489 
3490   EVT PtrVT = getPointerTy(MF.getDataLayout());
3491   // Potential tail calls could cause overwriting of argument stack slots.
3492   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3493                        (CallConv == CallingConv::Fast));
3494   unsigned PtrByteSize = 4;
3495 
3496   // Assign locations to all of the incoming arguments.
3497   SmallVector<CCValAssign, 16> ArgLocs;
3498   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3499                  *DAG.getContext());
3500 
3501   // Reserve space for the linkage area on the stack.
3502   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3503   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3504   if (useSoftFloat())
3505     CCInfo.PreAnalyzeFormalArguments(Ins);
3506 
3507   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3508   CCInfo.clearWasPPCF128();
3509 
3510   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3511     CCValAssign &VA = ArgLocs[i];
3512 
3513     // Arguments stored in registers.
3514     if (VA.isRegLoc()) {
3515       const TargetRegisterClass *RC;
3516       EVT ValVT = VA.getValVT();
3517 
3518       switch (ValVT.getSimpleVT().SimpleTy) {
3519         default:
3520           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3521         case MVT::i1:
3522         case MVT::i32:
3523           RC = &PPC::GPRCRegClass;
3524           break;
3525         case MVT::f32:
3526           if (Subtarget.hasP8Vector())
3527             RC = &PPC::VSSRCRegClass;
3528           else if (Subtarget.hasSPE())
3529             RC = &PPC::GPRCRegClass;
3530           else
3531             RC = &PPC::F4RCRegClass;
3532           break;
3533         case MVT::f64:
3534           if (Subtarget.hasVSX())
3535             RC = &PPC::VSFRCRegClass;
3536           else if (Subtarget.hasSPE())
3537             // SPE passes doubles in GPR pairs.
3538             RC = &PPC::GPRCRegClass;
3539           else
3540             RC = &PPC::F8RCRegClass;
3541           break;
3542         case MVT::v16i8:
3543         case MVT::v8i16:
3544         case MVT::v4i32:
3545           RC = &PPC::VRRCRegClass;
3546           break;
3547         case MVT::v4f32:
3548           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3549           break;
3550         case MVT::v2f64:
3551         case MVT::v2i64:
3552           RC = &PPC::VRRCRegClass;
3553           break;
3554         case MVT::v4f64:
3555           RC = &PPC::QFRCRegClass;
3556           break;
3557         case MVT::v4i1:
3558           RC = &PPC::QBRCRegClass;
3559           break;
3560       }
3561 
3562       SDValue ArgValue;
3563       // Transform the arguments stored in physical registers into
3564       // virtual ones.
3565       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3566         assert(i + 1 < e && "No second half of double precision argument");
3567         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3568         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3569         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3570         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3571         if (!Subtarget.isLittleEndian())
3572           std::swap (ArgValueLo, ArgValueHi);
3573         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3574                                ArgValueHi);
3575       } else {
3576         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3577         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3578                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3579         if (ValVT == MVT::i1)
3580           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3581       }
3582 
3583       InVals.push_back(ArgValue);
3584     } else {
3585       // Argument stored in memory.
3586       assert(VA.isMemLoc());
3587 
3588       // Get the extended size of the argument type in stack
3589       unsigned ArgSize = VA.getLocVT().getStoreSize();
3590       // Get the actual size of the argument type
3591       unsigned ObjSize = VA.getValVT().getStoreSize();
3592       unsigned ArgOffset = VA.getLocMemOffset();
3593       // Stack objects in PPC32 are right justified.
3594       ArgOffset += ArgSize - ObjSize;
3595       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3596 
3597       // Create load nodes to retrieve arguments from the stack.
3598       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3599       InVals.push_back(
3600           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3601     }
3602   }
3603 
3604   // Assign locations to all of the incoming aggregate by value arguments.
3605   // Aggregates passed by value are stored in the local variable space of the
3606   // caller's stack frame, right above the parameter list area.
3607   SmallVector<CCValAssign, 16> ByValArgLocs;
3608   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3609                       ByValArgLocs, *DAG.getContext());
3610 
3611   // Reserve stack space for the allocations in CCInfo.
3612   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3613 
3614   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3615 
3616   // Area that is at least reserved in the caller of this function.
3617   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3618   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3619 
3620   // Set the size that is at least reserved in caller of this function.  Tail
3621   // call optimized function's reserved stack space needs to be aligned so that
3622   // taking the difference between two stack areas will result in an aligned
3623   // stack.
3624   MinReservedArea =
3625       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3626   FuncInfo->setMinReservedArea(MinReservedArea);
3627 
3628   SmallVector<SDValue, 8> MemOps;
3629 
3630   // If the function takes variable number of arguments, make a frame index for
3631   // the start of the first vararg value... for expansion of llvm.va_start.
3632   if (isVarArg) {
3633     static const MCPhysReg GPArgRegs[] = {
3634       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3635       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3636     };
3637     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3638 
3639     static const MCPhysReg FPArgRegs[] = {
3640       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3641       PPC::F8
3642     };
3643     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3644 
3645     if (useSoftFloat() || hasSPE())
3646        NumFPArgRegs = 0;
3647 
3648     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3649     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3650 
3651     // Make room for NumGPArgRegs and NumFPArgRegs.
3652     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3653                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3654 
3655     FuncInfo->setVarArgsStackOffset(
3656       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3657                             CCInfo.getNextStackOffset(), true));
3658 
3659     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3660     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3661 
3662     // The fixed integer arguments of a variadic function are stored to the
3663     // VarArgsFrameIndex on the stack so that they may be loaded by
3664     // dereferencing the result of va_next.
3665     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3666       // Get an existing live-in vreg, or add a new one.
3667       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3668       if (!VReg)
3669         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3670 
3671       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3672       SDValue Store =
3673           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3674       MemOps.push_back(Store);
3675       // Increment the address by four for the next argument to store
3676       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3677       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3678     }
3679 
3680     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3681     // is set.
3682     // The double arguments are stored to the VarArgsFrameIndex
3683     // on the stack.
3684     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3685       // Get an existing live-in vreg, or add a new one.
3686       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3687       if (!VReg)
3688         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3689 
3690       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3691       SDValue Store =
3692           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3693       MemOps.push_back(Store);
3694       // Increment the address by eight for the next argument to store
3695       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3696                                          PtrVT);
3697       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3698     }
3699   }
3700 
3701   if (!MemOps.empty())
3702     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3703 
3704   return Chain;
3705 }
3706 
3707 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3708 // value to MVT::i64 and then truncate to the correct register size.
3709 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3710                                              EVT ObjectVT, SelectionDAG &DAG,
3711                                              SDValue ArgVal,
3712                                              const SDLoc &dl) const {
3713   if (Flags.isSExt())
3714     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3715                          DAG.getValueType(ObjectVT));
3716   else if (Flags.isZExt())
3717     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3718                          DAG.getValueType(ObjectVT));
3719 
3720   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3721 }
3722 
3723 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3724     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3725     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3726     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3727   // TODO: add description of PPC stack frame format, or at least some docs.
3728   //
3729   bool isELFv2ABI = Subtarget.isELFv2ABI();
3730   bool isLittleEndian = Subtarget.isLittleEndian();
3731   MachineFunction &MF = DAG.getMachineFunction();
3732   MachineFrameInfo &MFI = MF.getFrameInfo();
3733   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3734 
3735   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3736          "fastcc not supported on varargs functions");
3737 
3738   EVT PtrVT = getPointerTy(MF.getDataLayout());
3739   // Potential tail calls could cause overwriting of argument stack slots.
3740   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3741                        (CallConv == CallingConv::Fast));
3742   unsigned PtrByteSize = 8;
3743   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3744 
3745   static const MCPhysReg GPR[] = {
3746     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3747     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3748   };
3749   static const MCPhysReg VR[] = {
3750     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3751     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3752   };
3753 
3754   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3755   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3756   const unsigned Num_VR_Regs  = array_lengthof(VR);
3757   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3758 
3759   // Do a first pass over the arguments to determine whether the ABI
3760   // guarantees that our caller has allocated the parameter save area
3761   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3762   // in the ELFv2 ABI, it is true if this is a vararg function or if
3763   // any parameter is located in a stack slot.
3764 
3765   bool HasParameterArea = !isELFv2ABI || isVarArg;
3766   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3767   unsigned NumBytes = LinkageSize;
3768   unsigned AvailableFPRs = Num_FPR_Regs;
3769   unsigned AvailableVRs = Num_VR_Regs;
3770   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3771     if (Ins[i].Flags.isNest())
3772       continue;
3773 
3774     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3775                                PtrByteSize, LinkageSize, ParamAreaSize,
3776                                NumBytes, AvailableFPRs, AvailableVRs,
3777                                Subtarget.hasQPX()))
3778       HasParameterArea = true;
3779   }
3780 
3781   // Add DAG nodes to load the arguments or copy them out of registers.  On
3782   // entry to a function on PPC, the arguments start after the linkage area,
3783   // although the first ones are often in registers.
3784 
3785   unsigned ArgOffset = LinkageSize;
3786   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3787   unsigned &QFPR_idx = FPR_idx;
3788   SmallVector<SDValue, 8> MemOps;
3789   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3790   unsigned CurArgIdx = 0;
3791   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3792     SDValue ArgVal;
3793     bool needsLoad = false;
3794     EVT ObjectVT = Ins[ArgNo].VT;
3795     EVT OrigVT = Ins[ArgNo].ArgVT;
3796     unsigned ObjSize = ObjectVT.getStoreSize();
3797     unsigned ArgSize = ObjSize;
3798     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3799     if (Ins[ArgNo].isOrigArg()) {
3800       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3801       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3802     }
3803     // We re-align the argument offset for each argument, except when using the
3804     // fast calling convention, when we need to make sure we do that only when
3805     // we'll actually use a stack slot.
3806     unsigned CurArgOffset, Align;
3807     auto ComputeArgOffset = [&]() {
3808       /* Respect alignment of argument on the stack.  */
3809       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3810       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3811       CurArgOffset = ArgOffset;
3812     };
3813 
3814     if (CallConv != CallingConv::Fast) {
3815       ComputeArgOffset();
3816 
3817       /* Compute GPR index associated with argument offset.  */
3818       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3819       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3820     }
3821 
3822     // FIXME the codegen can be much improved in some cases.
3823     // We do not have to keep everything in memory.
3824     if (Flags.isByVal()) {
3825       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3826 
3827       if (CallConv == CallingConv::Fast)
3828         ComputeArgOffset();
3829 
3830       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3831       ObjSize = Flags.getByValSize();
3832       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3833       // Empty aggregate parameters do not take up registers.  Examples:
3834       //   struct { } a;
3835       //   union  { } b;
3836       //   int c[0];
3837       // etc.  However, we have to provide a place-holder in InVals, so
3838       // pretend we have an 8-byte item at the current address for that
3839       // purpose.
3840       if (!ObjSize) {
3841         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3842         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3843         InVals.push_back(FIN);
3844         continue;
3845       }
3846 
3847       // Create a stack object covering all stack doublewords occupied
3848       // by the argument.  If the argument is (fully or partially) on
3849       // the stack, or if the argument is fully in registers but the
3850       // caller has allocated the parameter save anyway, we can refer
3851       // directly to the caller's stack frame.  Otherwise, create a
3852       // local copy in our own frame.
3853       int FI;
3854       if (HasParameterArea ||
3855           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3856         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3857       else
3858         FI = MFI.CreateStackObject(ArgSize, Align, false);
3859       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3860 
3861       // Handle aggregates smaller than 8 bytes.
3862       if (ObjSize < PtrByteSize) {
3863         // The value of the object is its address, which differs from the
3864         // address of the enclosing doubleword on big-endian systems.
3865         SDValue Arg = FIN;
3866         if (!isLittleEndian) {
3867           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3868           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3869         }
3870         InVals.push_back(Arg);
3871 
3872         if (GPR_idx != Num_GPR_Regs) {
3873           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3874           FuncInfo->addLiveInAttr(VReg, Flags);
3875           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3876           SDValue Store;
3877 
3878           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3879             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3880                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3881             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3882                                       MachinePointerInfo(&*FuncArg), ObjType);
3883           } else {
3884             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3885             // store the whole register as-is to the parameter save area
3886             // slot.
3887             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3888                                  MachinePointerInfo(&*FuncArg));
3889           }
3890 
3891           MemOps.push_back(Store);
3892         }
3893         // Whether we copied from a register or not, advance the offset
3894         // into the parameter save area by a full doubleword.
3895         ArgOffset += PtrByteSize;
3896         continue;
3897       }
3898 
3899       // The value of the object is its address, which is the address of
3900       // its first stack doubleword.
3901       InVals.push_back(FIN);
3902 
3903       // Store whatever pieces of the object are in registers to memory.
3904       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3905         if (GPR_idx == Num_GPR_Regs)
3906           break;
3907 
3908         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3909         FuncInfo->addLiveInAttr(VReg, Flags);
3910         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3911         SDValue Addr = FIN;
3912         if (j) {
3913           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3914           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3915         }
3916         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3917                                      MachinePointerInfo(&*FuncArg, j));
3918         MemOps.push_back(Store);
3919         ++GPR_idx;
3920       }
3921       ArgOffset += ArgSize;
3922       continue;
3923     }
3924 
3925     switch (ObjectVT.getSimpleVT().SimpleTy) {
3926     default: llvm_unreachable("Unhandled argument type!");
3927     case MVT::i1:
3928     case MVT::i32:
3929     case MVT::i64:
3930       if (Flags.isNest()) {
3931         // The 'nest' parameter, if any, is passed in R11.
3932         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3933         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3934 
3935         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3936           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3937 
3938         break;
3939       }
3940 
3941       // These can be scalar arguments or elements of an integer array type
3942       // passed directly.  Clang may use those instead of "byval" aggregate
3943       // types to avoid forcing arguments to memory unnecessarily.
3944       if (GPR_idx != Num_GPR_Regs) {
3945         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3946         FuncInfo->addLiveInAttr(VReg, Flags);
3947         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3948 
3949         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3950           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3951           // value to MVT::i64 and then truncate to the correct register size.
3952           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3953       } else {
3954         if (CallConv == CallingConv::Fast)
3955           ComputeArgOffset();
3956 
3957         needsLoad = true;
3958         ArgSize = PtrByteSize;
3959       }
3960       if (CallConv != CallingConv::Fast || needsLoad)
3961         ArgOffset += 8;
3962       break;
3963 
3964     case MVT::f32:
3965     case MVT::f64:
3966       // These can be scalar arguments or elements of a float array type
3967       // passed directly.  The latter are used to implement ELFv2 homogenous
3968       // float aggregates.
3969       if (FPR_idx != Num_FPR_Regs) {
3970         unsigned VReg;
3971 
3972         if (ObjectVT == MVT::f32)
3973           VReg = MF.addLiveIn(FPR[FPR_idx],
3974                               Subtarget.hasP8Vector()
3975                                   ? &PPC::VSSRCRegClass
3976                                   : &PPC::F4RCRegClass);
3977         else
3978           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3979                                                 ? &PPC::VSFRCRegClass
3980                                                 : &PPC::F8RCRegClass);
3981 
3982         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3983         ++FPR_idx;
3984       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3985         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3986         // once we support fp <-> gpr moves.
3987 
3988         // This can only ever happen in the presence of f32 array types,
3989         // since otherwise we never run out of FPRs before running out
3990         // of GPRs.
3991         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3992         FuncInfo->addLiveInAttr(VReg, Flags);
3993         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3994 
3995         if (ObjectVT == MVT::f32) {
3996           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3997             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3998                                  DAG.getConstant(32, dl, MVT::i32));
3999           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
4000         }
4001 
4002         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
4003       } else {
4004         if (CallConv == CallingConv::Fast)
4005           ComputeArgOffset();
4006 
4007         needsLoad = true;
4008       }
4009 
4010       // When passing an array of floats, the array occupies consecutive
4011       // space in the argument area; only round up to the next doubleword
4012       // at the end of the array.  Otherwise, each float takes 8 bytes.
4013       if (CallConv != CallingConv::Fast || needsLoad) {
4014         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
4015         ArgOffset += ArgSize;
4016         if (Flags.isInConsecutiveRegsLast())
4017           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4018       }
4019       break;
4020     case MVT::v4f32:
4021     case MVT::v4i32:
4022     case MVT::v8i16:
4023     case MVT::v16i8:
4024     case MVT::v2f64:
4025     case MVT::v2i64:
4026     case MVT::v1i128:
4027     case MVT::f128:
4028       if (!Subtarget.hasQPX()) {
4029         // These can be scalar arguments or elements of a vector array type
4030         // passed directly.  The latter are used to implement ELFv2 homogenous
4031         // vector aggregates.
4032         if (VR_idx != Num_VR_Regs) {
4033           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4034           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4035           ++VR_idx;
4036         } else {
4037           if (CallConv == CallingConv::Fast)
4038             ComputeArgOffset();
4039           needsLoad = true;
4040         }
4041         if (CallConv != CallingConv::Fast || needsLoad)
4042           ArgOffset += 16;
4043         break;
4044       } // not QPX
4045 
4046       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4047              "Invalid QPX parameter type");
4048       LLVM_FALLTHROUGH;
4049 
4050     case MVT::v4f64:
4051     case MVT::v4i1:
4052       // QPX vectors are treated like their scalar floating-point subregisters
4053       // (except that they're larger).
4054       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4055       if (QFPR_idx != Num_QFPR_Regs) {
4056         const TargetRegisterClass *RC;
4057         switch (ObjectVT.getSimpleVT().SimpleTy) {
4058         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4059         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4060         default:         RC = &PPC::QBRCRegClass; break;
4061         }
4062 
4063         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4064         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4065         ++QFPR_idx;
4066       } else {
4067         if (CallConv == CallingConv::Fast)
4068           ComputeArgOffset();
4069         needsLoad = true;
4070       }
4071       if (CallConv != CallingConv::Fast || needsLoad)
4072         ArgOffset += Sz;
4073       break;
4074     }
4075 
4076     // We need to load the argument to a virtual register if we determined
4077     // above that we ran out of physical registers of the appropriate type.
4078     if (needsLoad) {
4079       if (ObjSize < ArgSize && !isLittleEndian)
4080         CurArgOffset += ArgSize - ObjSize;
4081       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4082       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4083       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4084     }
4085 
4086     InVals.push_back(ArgVal);
4087   }
4088 
4089   // Area that is at least reserved in the caller of this function.
4090   unsigned MinReservedArea;
4091   if (HasParameterArea)
4092     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4093   else
4094     MinReservedArea = LinkageSize;
4095 
4096   // Set the size that is at least reserved in caller of this function.  Tail
4097   // call optimized functions' reserved stack space needs to be aligned so that
4098   // taking the difference between two stack areas will result in an aligned
4099   // stack.
4100   MinReservedArea =
4101       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4102   FuncInfo->setMinReservedArea(MinReservedArea);
4103 
4104   // If the function takes variable number of arguments, make a frame index for
4105   // the start of the first vararg value... for expansion of llvm.va_start.
4106   if (isVarArg) {
4107     int Depth = ArgOffset;
4108 
4109     FuncInfo->setVarArgsFrameIndex(
4110       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4111     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4112 
4113     // If this function is vararg, store any remaining integer argument regs
4114     // to their spots on the stack so that they may be loaded by dereferencing
4115     // the result of va_next.
4116     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4117          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4118       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4119       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4120       SDValue Store =
4121           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4122       MemOps.push_back(Store);
4123       // Increment the address by four for the next argument to store
4124       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4125       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4126     }
4127   }
4128 
4129   if (!MemOps.empty())
4130     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4131 
4132   return Chain;
4133 }
4134 
4135 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4136     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4137     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4138     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4139   // TODO: add description of PPC stack frame format, or at least some docs.
4140   //
4141   MachineFunction &MF = DAG.getMachineFunction();
4142   MachineFrameInfo &MFI = MF.getFrameInfo();
4143   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4144 
4145   EVT PtrVT = getPointerTy(MF.getDataLayout());
4146   bool isPPC64 = PtrVT == MVT::i64;
4147   // Potential tail calls could cause overwriting of argument stack slots.
4148   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4149                        (CallConv == CallingConv::Fast));
4150   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4151   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4152   unsigned ArgOffset = LinkageSize;
4153   // Area that is at least reserved in caller of this function.
4154   unsigned MinReservedArea = ArgOffset;
4155 
4156   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4157     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4158     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4159   };
4160   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4161     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4162     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4163   };
4164   static const MCPhysReg VR[] = {
4165     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4166     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4167   };
4168 
4169   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4170   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4171   const unsigned Num_VR_Regs  = array_lengthof( VR);
4172 
4173   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4174 
4175   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4176 
4177   // In 32-bit non-varargs functions, the stack space for vectors is after the
4178   // stack space for non-vectors.  We do not use this space unless we have
4179   // too many vectors to fit in registers, something that only occurs in
4180   // constructed examples:), but we have to walk the arglist to figure
4181   // that out...for the pathological case, compute VecArgOffset as the
4182   // start of the vector parameter area.  Computing VecArgOffset is the
4183   // entire point of the following loop.
4184   unsigned VecArgOffset = ArgOffset;
4185   if (!isVarArg && !isPPC64) {
4186     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4187          ++ArgNo) {
4188       EVT ObjectVT = Ins[ArgNo].VT;
4189       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4190 
4191       if (Flags.isByVal()) {
4192         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4193         unsigned ObjSize = Flags.getByValSize();
4194         unsigned ArgSize =
4195                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4196         VecArgOffset += ArgSize;
4197         continue;
4198       }
4199 
4200       switch(ObjectVT.getSimpleVT().SimpleTy) {
4201       default: llvm_unreachable("Unhandled argument type!");
4202       case MVT::i1:
4203       case MVT::i32:
4204       case MVT::f32:
4205         VecArgOffset += 4;
4206         break;
4207       case MVT::i64:  // PPC64
4208       case MVT::f64:
4209         // FIXME: We are guaranteed to be !isPPC64 at this point.
4210         // Does MVT::i64 apply?
4211         VecArgOffset += 8;
4212         break;
4213       case MVT::v4f32:
4214       case MVT::v4i32:
4215       case MVT::v8i16:
4216       case MVT::v16i8:
4217         // Nothing to do, we're only looking at Nonvector args here.
4218         break;
4219       }
4220     }
4221   }
4222   // We've found where the vector parameter area in memory is.  Skip the
4223   // first 12 parameters; these don't use that memory.
4224   VecArgOffset = ((VecArgOffset+15)/16)*16;
4225   VecArgOffset += 12*16;
4226 
4227   // Add DAG nodes to load the arguments or copy them out of registers.  On
4228   // entry to a function on PPC, the arguments start after the linkage area,
4229   // although the first ones are often in registers.
4230 
4231   SmallVector<SDValue, 8> MemOps;
4232   unsigned nAltivecParamsAtEnd = 0;
4233   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4234   unsigned CurArgIdx = 0;
4235   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4236     SDValue ArgVal;
4237     bool needsLoad = false;
4238     EVT ObjectVT = Ins[ArgNo].VT;
4239     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4240     unsigned ArgSize = ObjSize;
4241     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4242     if (Ins[ArgNo].isOrigArg()) {
4243       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4244       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4245     }
4246     unsigned CurArgOffset = ArgOffset;
4247 
4248     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4249     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4250         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4251       if (isVarArg || isPPC64) {
4252         MinReservedArea = ((MinReservedArea+15)/16)*16;
4253         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4254                                                   Flags,
4255                                                   PtrByteSize);
4256       } else  nAltivecParamsAtEnd++;
4257     } else
4258       // Calculate min reserved area.
4259       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4260                                                 Flags,
4261                                                 PtrByteSize);
4262 
4263     // FIXME the codegen can be much improved in some cases.
4264     // We do not have to keep everything in memory.
4265     if (Flags.isByVal()) {
4266       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4267 
4268       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4269       ObjSize = Flags.getByValSize();
4270       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4271       // Objects of size 1 and 2 are right justified, everything else is
4272       // left justified.  This means the memory address is adjusted forwards.
4273       if (ObjSize==1 || ObjSize==2) {
4274         CurArgOffset = CurArgOffset + (4 - ObjSize);
4275       }
4276       // The value of the object is its address.
4277       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4278       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4279       InVals.push_back(FIN);
4280       if (ObjSize==1 || ObjSize==2) {
4281         if (GPR_idx != Num_GPR_Regs) {
4282           unsigned VReg;
4283           if (isPPC64)
4284             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4285           else
4286             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4287           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4288           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4289           SDValue Store =
4290               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4291                                 MachinePointerInfo(&*FuncArg), ObjType);
4292           MemOps.push_back(Store);
4293           ++GPR_idx;
4294         }
4295 
4296         ArgOffset += PtrByteSize;
4297 
4298         continue;
4299       }
4300       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4301         // Store whatever pieces of the object are in registers
4302         // to memory.  ArgOffset will be the address of the beginning
4303         // of the object.
4304         if (GPR_idx != Num_GPR_Regs) {
4305           unsigned VReg;
4306           if (isPPC64)
4307             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4308           else
4309             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4310           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4311           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4312           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4313           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4314                                        MachinePointerInfo(&*FuncArg, j));
4315           MemOps.push_back(Store);
4316           ++GPR_idx;
4317           ArgOffset += PtrByteSize;
4318         } else {
4319           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4320           break;
4321         }
4322       }
4323       continue;
4324     }
4325 
4326     switch (ObjectVT.getSimpleVT().SimpleTy) {
4327     default: llvm_unreachable("Unhandled argument type!");
4328     case MVT::i1:
4329     case MVT::i32:
4330       if (!isPPC64) {
4331         if (GPR_idx != Num_GPR_Regs) {
4332           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4333           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4334 
4335           if (ObjectVT == MVT::i1)
4336             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4337 
4338           ++GPR_idx;
4339         } else {
4340           needsLoad = true;
4341           ArgSize = PtrByteSize;
4342         }
4343         // All int arguments reserve stack space in the Darwin ABI.
4344         ArgOffset += PtrByteSize;
4345         break;
4346       }
4347       LLVM_FALLTHROUGH;
4348     case MVT::i64:  // PPC64
4349       if (GPR_idx != Num_GPR_Regs) {
4350         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4351         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4352 
4353         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4354           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4355           // value to MVT::i64 and then truncate to the correct register size.
4356           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4357 
4358         ++GPR_idx;
4359       } else {
4360         needsLoad = true;
4361         ArgSize = PtrByteSize;
4362       }
4363       // All int arguments reserve stack space in the Darwin ABI.
4364       ArgOffset += 8;
4365       break;
4366 
4367     case MVT::f32:
4368     case MVT::f64:
4369       // Every 4 bytes of argument space consumes one of the GPRs available for
4370       // argument passing.
4371       if (GPR_idx != Num_GPR_Regs) {
4372         ++GPR_idx;
4373         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4374           ++GPR_idx;
4375       }
4376       if (FPR_idx != Num_FPR_Regs) {
4377         unsigned VReg;
4378 
4379         if (ObjectVT == MVT::f32)
4380           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4381         else
4382           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4383 
4384         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4385         ++FPR_idx;
4386       } else {
4387         needsLoad = true;
4388       }
4389 
4390       // All FP arguments reserve stack space in the Darwin ABI.
4391       ArgOffset += isPPC64 ? 8 : ObjSize;
4392       break;
4393     case MVT::v4f32:
4394     case MVT::v4i32:
4395     case MVT::v8i16:
4396     case MVT::v16i8:
4397       // Note that vector arguments in registers don't reserve stack space,
4398       // except in varargs functions.
4399       if (VR_idx != Num_VR_Regs) {
4400         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4401         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4402         if (isVarArg) {
4403           while ((ArgOffset % 16) != 0) {
4404             ArgOffset += PtrByteSize;
4405             if (GPR_idx != Num_GPR_Regs)
4406               GPR_idx++;
4407           }
4408           ArgOffset += 16;
4409           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4410         }
4411         ++VR_idx;
4412       } else {
4413         if (!isVarArg && !isPPC64) {
4414           // Vectors go after all the nonvectors.
4415           CurArgOffset = VecArgOffset;
4416           VecArgOffset += 16;
4417         } else {
4418           // Vectors are aligned.
4419           ArgOffset = ((ArgOffset+15)/16)*16;
4420           CurArgOffset = ArgOffset;
4421           ArgOffset += 16;
4422         }
4423         needsLoad = true;
4424       }
4425       break;
4426     }
4427 
4428     // We need to load the argument to a virtual register if we determined above
4429     // that we ran out of physical registers of the appropriate type.
4430     if (needsLoad) {
4431       int FI = MFI.CreateFixedObject(ObjSize,
4432                                      CurArgOffset + (ArgSize - ObjSize),
4433                                      isImmutable);
4434       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4435       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4436     }
4437 
4438     InVals.push_back(ArgVal);
4439   }
4440 
4441   // Allow for Altivec parameters at the end, if needed.
4442   if (nAltivecParamsAtEnd) {
4443     MinReservedArea = ((MinReservedArea+15)/16)*16;
4444     MinReservedArea += 16*nAltivecParamsAtEnd;
4445   }
4446 
4447   // Area that is at least reserved in the caller of this function.
4448   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4449 
4450   // Set the size that is at least reserved in caller of this function.  Tail
4451   // call optimized functions' reserved stack space needs to be aligned so that
4452   // taking the difference between two stack areas will result in an aligned
4453   // stack.
4454   MinReservedArea =
4455       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4456   FuncInfo->setMinReservedArea(MinReservedArea);
4457 
4458   // If the function takes variable number of arguments, make a frame index for
4459   // the start of the first vararg value... for expansion of llvm.va_start.
4460   if (isVarArg) {
4461     int Depth = ArgOffset;
4462 
4463     FuncInfo->setVarArgsFrameIndex(
4464       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4465                             Depth, true));
4466     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4467 
4468     // If this function is vararg, store any remaining integer argument regs
4469     // to their spots on the stack so that they may be loaded by dereferencing
4470     // the result of va_next.
4471     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4472       unsigned VReg;
4473 
4474       if (isPPC64)
4475         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4476       else
4477         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4478 
4479       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4480       SDValue Store =
4481           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4482       MemOps.push_back(Store);
4483       // Increment the address by four for the next argument to store
4484       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4485       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4486     }
4487   }
4488 
4489   if (!MemOps.empty())
4490     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4491 
4492   return Chain;
4493 }
4494 
4495 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4496 /// adjusted to accommodate the arguments for the tailcall.
4497 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4498                                    unsigned ParamSize) {
4499 
4500   if (!isTailCall) return 0;
4501 
4502   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4503   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4504   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4505   // Remember only if the new adjustment is bigger.
4506   if (SPDiff < FI->getTailCallSPDelta())
4507     FI->setTailCallSPDelta(SPDiff);
4508 
4509   return SPDiff;
4510 }
4511 
4512 static bool isFunctionGlobalAddress(SDValue Callee);
4513 
4514 static bool
4515 callsShareTOCBase(const Function *Caller, SDValue Callee,
4516                     const TargetMachine &TM) {
4517    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4518    // don't have enough information to determine if the caller and calle share
4519    // the same  TOC base, so we have to pessimistically assume they don't for
4520    // correctness.
4521    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4522    if (!G)
4523      return false;
4524 
4525    const GlobalValue *GV = G->getGlobal();
4526   // The medium and large code models are expected to provide a sufficiently
4527   // large TOC to provide all data addressing needs of a module with a
4528   // single TOC. Since each module will be addressed with a single TOC then we
4529   // only need to check that caller and callee don't cross dso boundaries.
4530   if (CodeModel::Medium == TM.getCodeModel() ||
4531       CodeModel::Large == TM.getCodeModel())
4532     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4533 
4534   // Otherwise we need to ensure callee and caller are in the same section,
4535   // since the linker may allocate multiple TOCs, and we don't know which
4536   // sections will belong to the same TOC base.
4537 
4538   if (!GV->isStrongDefinitionForLinker())
4539     return false;
4540 
4541   // Any explicitly-specified sections and section prefixes must also match.
4542   // Also, if we're using -ffunction-sections, then each function is always in
4543   // a different section (the same is true for COMDAT functions).
4544   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4545       GV->getSection() != Caller->getSection())
4546     return false;
4547   if (const auto *F = dyn_cast<Function>(GV)) {
4548     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4549       return false;
4550   }
4551 
4552   // If the callee might be interposed, then we can't assume the ultimate call
4553   // target will be in the same section. Even in cases where we can assume that
4554   // interposition won't happen, in any case where the linker might insert a
4555   // stub to allow for interposition, we must generate code as though
4556   // interposition might occur. To understand why this matters, consider a
4557   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4558   // in the same section, but a is in a different module (i.e. has a different
4559   // TOC base pointer). If the linker allows for interposition between b and c,
4560   // then it will generate a stub for the call edge between b and c which will
4561   // save the TOC pointer into the designated stack slot allocated by b. If we
4562   // return true here, and therefore allow a tail call between b and c, that
4563   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4564   // pointer into the stack slot allocated by a (where the a -> b stub saved
4565   // a's TOC base pointer). If we're not considering a tail call, but rather,
4566   // whether a nop is needed after the call instruction in b, because the linker
4567   // will insert a stub, it might complain about a missing nop if we omit it
4568   // (although many don't complain in this case).
4569   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4570     return false;
4571 
4572   return true;
4573 }
4574 
4575 static bool
4576 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4577                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4578   assert(Subtarget.is64BitELFABI());
4579 
4580   const unsigned PtrByteSize = 8;
4581   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4582 
4583   static const MCPhysReg GPR[] = {
4584     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4585     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4586   };
4587   static const MCPhysReg VR[] = {
4588     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4589     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4590   };
4591 
4592   const unsigned NumGPRs = array_lengthof(GPR);
4593   const unsigned NumFPRs = 13;
4594   const unsigned NumVRs = array_lengthof(VR);
4595   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4596 
4597   unsigned NumBytes = LinkageSize;
4598   unsigned AvailableFPRs = NumFPRs;
4599   unsigned AvailableVRs = NumVRs;
4600 
4601   for (const ISD::OutputArg& Param : Outs) {
4602     if (Param.Flags.isNest()) continue;
4603 
4604     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4605                                PtrByteSize, LinkageSize, ParamAreaSize,
4606                                NumBytes, AvailableFPRs, AvailableVRs,
4607                                Subtarget.hasQPX()))
4608       return true;
4609   }
4610   return false;
4611 }
4612 
4613 static bool
4614 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4615   if (CS.arg_size() != CallerFn->arg_size())
4616     return false;
4617 
4618   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4619   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4620   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4621 
4622   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4623     const Value* CalleeArg = *CalleeArgIter;
4624     const Value* CallerArg = &(*CallerArgIter);
4625     if (CalleeArg == CallerArg)
4626       continue;
4627 
4628     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4629     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4630     //      }
4631     // 1st argument of callee is undef and has the same type as caller.
4632     if (CalleeArg->getType() == CallerArg->getType() &&
4633         isa<UndefValue>(CalleeArg))
4634       continue;
4635 
4636     return false;
4637   }
4638 
4639   return true;
4640 }
4641 
4642 // Returns true if TCO is possible between the callers and callees
4643 // calling conventions.
4644 static bool
4645 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4646                                     CallingConv::ID CalleeCC) {
4647   // Tail calls are possible with fastcc and ccc.
4648   auto isTailCallableCC  = [] (CallingConv::ID CC){
4649       return  CC == CallingConv::C || CC == CallingConv::Fast;
4650   };
4651   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4652     return false;
4653 
4654   // We can safely tail call both fastcc and ccc callees from a c calling
4655   // convention caller. If the caller is fastcc, we may have less stack space
4656   // than a non-fastcc caller with the same signature so disable tail-calls in
4657   // that case.
4658   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4659 }
4660 
4661 bool
4662 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4663                                     SDValue Callee,
4664                                     CallingConv::ID CalleeCC,
4665                                     ImmutableCallSite CS,
4666                                     bool isVarArg,
4667                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4668                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4669                                     SelectionDAG& DAG) const {
4670   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4671 
4672   if (DisableSCO && !TailCallOpt) return false;
4673 
4674   // Variadic argument functions are not supported.
4675   if (isVarArg) return false;
4676 
4677   auto &Caller = DAG.getMachineFunction().getFunction();
4678   // Check that the calling conventions are compatible for tco.
4679   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4680     return false;
4681 
4682   // Caller contains any byval parameter is not supported.
4683   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4684     return false;
4685 
4686   // Callee contains any byval parameter is not supported, too.
4687   // Note: This is a quick work around, because in some cases, e.g.
4688   // caller's stack size > callee's stack size, we are still able to apply
4689   // sibling call optimization. For example, gcc is able to do SCO for caller1
4690   // in the following example, but not for caller2.
4691   //   struct test {
4692   //     long int a;
4693   //     char ary[56];
4694   //   } gTest;
4695   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4696   //     b->a = v.a;
4697   //     return 0;
4698   //   }
4699   //   void caller1(struct test a, struct test c, struct test *b) {
4700   //     callee(gTest, b); }
4701   //   void caller2(struct test *b) { callee(gTest, b); }
4702   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4703     return false;
4704 
4705   // If callee and caller use different calling conventions, we cannot pass
4706   // parameters on stack since offsets for the parameter area may be different.
4707   if (Caller.getCallingConv() != CalleeCC &&
4708       needStackSlotPassParameters(Subtarget, Outs))
4709     return false;
4710 
4711   // No TCO/SCO on indirect call because Caller have to restore its TOC
4712   if (!isFunctionGlobalAddress(Callee) &&
4713       !isa<ExternalSymbolSDNode>(Callee))
4714     return false;
4715 
4716   // If the caller and callee potentially have different TOC bases then we
4717   // cannot tail call since we need to restore the TOC pointer after the call.
4718   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4719   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4720     return false;
4721 
4722   // TCO allows altering callee ABI, so we don't have to check further.
4723   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4724     return true;
4725 
4726   if (DisableSCO) return false;
4727 
4728   // If callee use the same argument list that caller is using, then we can
4729   // apply SCO on this case. If it is not, then we need to check if callee needs
4730   // stack for passing arguments.
4731   if (!hasSameArgumentList(&Caller, CS) &&
4732       needStackSlotPassParameters(Subtarget, Outs)) {
4733     return false;
4734   }
4735 
4736   return true;
4737 }
4738 
4739 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4740 /// for tail call optimization. Targets which want to do tail call
4741 /// optimization should implement this function.
4742 bool
4743 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4744                                                      CallingConv::ID CalleeCC,
4745                                                      bool isVarArg,
4746                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4747                                                      SelectionDAG& DAG) const {
4748   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4749     return false;
4750 
4751   // Variable argument functions are not supported.
4752   if (isVarArg)
4753     return false;
4754 
4755   MachineFunction &MF = DAG.getMachineFunction();
4756   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4757   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4758     // Functions containing by val parameters are not supported.
4759     for (unsigned i = 0; i != Ins.size(); i++) {
4760        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4761        if (Flags.isByVal()) return false;
4762     }
4763 
4764     // Non-PIC/GOT tail calls are supported.
4765     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4766       return true;
4767 
4768     // At the moment we can only do local tail calls (in same module, hidden
4769     // or protected) if we are generating PIC.
4770     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4771       return G->getGlobal()->hasHiddenVisibility()
4772           || G->getGlobal()->hasProtectedVisibility();
4773   }
4774 
4775   return false;
4776 }
4777 
4778 /// isCallCompatibleAddress - Return the immediate to use if the specified
4779 /// 32-bit value is representable in the immediate field of a BxA instruction.
4780 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4781   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4782   if (!C) return nullptr;
4783 
4784   int Addr = C->getZExtValue();
4785   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4786       SignExtend32<26>(Addr) != Addr)
4787     return nullptr;  // Top 6 bits have to be sext of immediate.
4788 
4789   return DAG
4790       .getConstant(
4791           (int)C->getZExtValue() >> 2, SDLoc(Op),
4792           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4793       .getNode();
4794 }
4795 
4796 namespace {
4797 
4798 struct TailCallArgumentInfo {
4799   SDValue Arg;
4800   SDValue FrameIdxOp;
4801   int FrameIdx = 0;
4802 
4803   TailCallArgumentInfo() = default;
4804 };
4805 
4806 } // end anonymous namespace
4807 
4808 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4809 static void StoreTailCallArgumentsToStackSlot(
4810     SelectionDAG &DAG, SDValue Chain,
4811     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4812     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4813   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4814     SDValue Arg = TailCallArgs[i].Arg;
4815     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4816     int FI = TailCallArgs[i].FrameIdx;
4817     // Store relative to framepointer.
4818     MemOpChains.push_back(DAG.getStore(
4819         Chain, dl, Arg, FIN,
4820         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4821   }
4822 }
4823 
4824 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4825 /// the appropriate stack slot for the tail call optimized function call.
4826 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4827                                              SDValue OldRetAddr, SDValue OldFP,
4828                                              int SPDiff, const SDLoc &dl) {
4829   if (SPDiff) {
4830     // Calculate the new stack slot for the return address.
4831     MachineFunction &MF = DAG.getMachineFunction();
4832     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4833     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4834     bool isPPC64 = Subtarget.isPPC64();
4835     int SlotSize = isPPC64 ? 8 : 4;
4836     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4837     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4838                                                          NewRetAddrLoc, true);
4839     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4840     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4841     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4842                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4843 
4844     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4845     // slot as the FP is never overwritten.
4846     if (Subtarget.isDarwinABI()) {
4847       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4848       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4849                                                          true);
4850       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4851       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4852                            MachinePointerInfo::getFixedStack(
4853                                DAG.getMachineFunction(), NewFPIdx));
4854     }
4855   }
4856   return Chain;
4857 }
4858 
4859 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4860 /// the position of the argument.
4861 static void
4862 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4863                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4864                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4865   int Offset = ArgOffset + SPDiff;
4866   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4867   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4868   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4869   SDValue FIN = DAG.getFrameIndex(FI, VT);
4870   TailCallArgumentInfo Info;
4871   Info.Arg = Arg;
4872   Info.FrameIdxOp = FIN;
4873   Info.FrameIdx = FI;
4874   TailCallArguments.push_back(Info);
4875 }
4876 
4877 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4878 /// stack slot. Returns the chain as result and the loaded frame pointers in
4879 /// LROpOut/FPOpout. Used when tail calling.
4880 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4881     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4882     SDValue &FPOpOut, const SDLoc &dl) const {
4883   if (SPDiff) {
4884     // Load the LR and FP stack slot for later adjusting.
4885     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4886     LROpOut = getReturnAddrFrameIndex(DAG);
4887     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4888     Chain = SDValue(LROpOut.getNode(), 1);
4889 
4890     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4891     // slot as the FP is never overwritten.
4892     if (Subtarget.isDarwinABI()) {
4893       FPOpOut = getFramePointerFrameIndex(DAG);
4894       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4895       Chain = SDValue(FPOpOut.getNode(), 1);
4896     }
4897   }
4898   return Chain;
4899 }
4900 
4901 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4902 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4903 /// specified by the specific parameter attribute. The copy will be passed as
4904 /// a byval function parameter.
4905 /// Sometimes what we are copying is the end of a larger object, the part that
4906 /// does not fit in registers.
4907 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4908                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4909                                          SelectionDAG &DAG, const SDLoc &dl) {
4910   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4911   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4912                        false, false, false, MachinePointerInfo(),
4913                        MachinePointerInfo());
4914 }
4915 
4916 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4917 /// tail calls.
4918 static void LowerMemOpCallTo(
4919     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4920     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4921     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4922     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4923   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4924   if (!isTailCall) {
4925     if (isVector) {
4926       SDValue StackPtr;
4927       if (isPPC64)
4928         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4929       else
4930         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4931       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4932                            DAG.getConstant(ArgOffset, dl, PtrVT));
4933     }
4934     MemOpChains.push_back(
4935         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4936     // Calculate and remember argument location.
4937   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4938                                   TailCallArguments);
4939 }
4940 
4941 static void
4942 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4943                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4944                 SDValue FPOp,
4945                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4946   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4947   // might overwrite each other in case of tail call optimization.
4948   SmallVector<SDValue, 8> MemOpChains2;
4949   // Do not flag preceding copytoreg stuff together with the following stuff.
4950   InFlag = SDValue();
4951   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4952                                     MemOpChains2, dl);
4953   if (!MemOpChains2.empty())
4954     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4955 
4956   // Store the return address to the appropriate stack slot.
4957   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4958 
4959   // Emit callseq_end just before tailcall node.
4960   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4961                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4962   InFlag = Chain.getValue(1);
4963 }
4964 
4965 // Is this global address that of a function that can be called by name? (as
4966 // opposed to something that must hold a descriptor for an indirect call).
4967 static bool isFunctionGlobalAddress(SDValue Callee) {
4968   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4969     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4970         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4971       return false;
4972 
4973     return G->getGlobal()->getValueType()->isFunctionTy();
4974   }
4975 
4976   return false;
4977 }
4978 
4979 SDValue PPCTargetLowering::LowerCallResult(
4980     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4981     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4982     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4983   SmallVector<CCValAssign, 16> RVLocs;
4984   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4985                     *DAG.getContext());
4986 
4987   CCRetInfo.AnalyzeCallResult(
4988       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4989                ? RetCC_PPC_Cold
4990                : RetCC_PPC);
4991 
4992   // Copy all of the result registers out of their specified physreg.
4993   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4994     CCValAssign &VA = RVLocs[i];
4995     assert(VA.isRegLoc() && "Can only return in registers!");
4996 
4997     SDValue Val;
4998 
4999     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
5000       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5001                                       InFlag);
5002       Chain = Lo.getValue(1);
5003       InFlag = Lo.getValue(2);
5004       VA = RVLocs[++i]; // skip ahead to next loc
5005       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
5006                                       InFlag);
5007       Chain = Hi.getValue(1);
5008       InFlag = Hi.getValue(2);
5009       if (!Subtarget.isLittleEndian())
5010         std::swap (Lo, Hi);
5011       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
5012     } else {
5013       Val = DAG.getCopyFromReg(Chain, dl,
5014                                VA.getLocReg(), VA.getLocVT(), InFlag);
5015       Chain = Val.getValue(1);
5016       InFlag = Val.getValue(2);
5017     }
5018 
5019     switch (VA.getLocInfo()) {
5020     default: llvm_unreachable("Unknown loc info!");
5021     case CCValAssign::Full: break;
5022     case CCValAssign::AExt:
5023       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5024       break;
5025     case CCValAssign::ZExt:
5026       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5027                         DAG.getValueType(VA.getValVT()));
5028       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5029       break;
5030     case CCValAssign::SExt:
5031       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5032                         DAG.getValueType(VA.getValVT()));
5033       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5034       break;
5035     }
5036 
5037     InVals.push_back(Val);
5038   }
5039 
5040   return Chain;
5041 }
5042 
5043 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5044                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5045   // PatchPoint calls are not indirect.
5046   if (isPatchPoint)
5047     return false;
5048 
5049   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5050     return false;
5051 
5052   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5053   // becuase the immediate function pointer points to a descriptor instead of
5054   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5055   // pointer immediate points to the global entry point, while the BLA would
5056   // need to jump to the local entry point (see rL211174).
5057   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5058       isBLACompatibleAddress(Callee, DAG))
5059     return false;
5060 
5061   return true;
5062 }
5063 
5064 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint,
5065                               bool isTailCall, const Function &Caller,
5066                               const SDValue &Callee,
5067                               const PPCSubtarget &Subtarget,
5068                               const TargetMachine &TM) {
5069   if (isTailCall)
5070     return PPCISD::TC_RETURN;
5071 
5072   // This is a call through a function pointer.
5073   if (isIndirectCall) {
5074     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5075     // indirect calls. The save of the caller's TOC pointer to the stack will be
5076     // inserted into the DAG as part of call lowering. The restore of the TOC
5077     // pointer is modeled by using a pseudo instruction for the call opcode that
5078     // represents the 2 instruction sequence of an indirect branch and link,
5079     // immediately followed by a load of the TOC pointer from the the stack save
5080     // slot into gpr2.
5081     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5082       return PPCISD::BCTRL_LOAD_TOC;
5083 
5084     // An indirect call that does not need a TOC restore.
5085     return PPCISD::BCTRL;
5086   }
5087 
5088   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5089   // immediately following the call instruction if the caller and callee may
5090   // have different TOC bases. At link time if the linker determines the calls
5091   // may not share a TOC base, the call is redirected to a trampoline inserted
5092   // by the linker. The trampoline will (among other things) save the callers
5093   // TOC pointer at an ABI designated offset in the linkage area and the linker
5094   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5095   // into gpr2.
5096   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5097     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5098                                                   : PPCISD::CALL_NOP;
5099 
5100   return PPCISD::CALL;
5101 }
5102 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5103                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5104   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5105     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5106       return SDValue(Dest, 0);
5107 
5108   // Returns true if the callee is local, and false otherwise.
5109   auto isLocalCallee = [&]() {
5110     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5111     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5112     const GlobalValue *GV = G ? G->getGlobal() : nullptr;
5113 
5114     return DAG.getTarget().shouldAssumeDSOLocal(*Mod, GV) &&
5115            !dyn_cast_or_null<GlobalIFunc>(GV);
5116   };
5117 
5118   // The PLT is only used in 32-bit ELF PIC mode.  Attempting to use the PLT in
5119   // a static relocation model causes some versions of GNU LD (2.17.50, at
5120   // least) to force BSS-PLT, instead of secure-PLT, even if all objects are
5121   // built with secure-PLT.
5122   bool UsePlt =
5123       Subtarget.is32BitELFABI() && !isLocalCallee() &&
5124       Subtarget.getTargetMachine().getRelocationModel() == Reloc::PIC_;
5125 
5126   if (isFunctionGlobalAddress(Callee)) {
5127     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5128     if (!Subtarget.isAIXABI())
5129       return DAG.getTargetGlobalAddress(G->getGlobal(), dl,
5130                                         Callee.getValueType(), 0,
5131                                         UsePlt ? PPCII::MO_PLT : 0);
5132 
5133     // On AIX, direct function calls reference the symbol for the function's
5134     // entry point, which is named by prepending a "." before the function's
5135     // C-linkage name.
5136     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5137 
5138     const GlobalObject *GO = cast<GlobalObject>(G->getGlobal());
5139     MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5140         Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName())));
5141 
5142     if (GO && GO->isDeclaration() && !S->hasContainingCsect()) {
5143       // On AIX, an undefined symbol needs to be associated with a
5144       // MCSectionXCOFF to get the correct storage mapping class.
5145       // In this case, XCOFF::XMC_PR.
5146       const XCOFF::StorageClass SC =
5147           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5148       MCSectionXCOFF *Sec =
5149           Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5150                                   SC, SectionKind::getMetadata());
5151       S->setContainingCsect(Sec);
5152     }
5153 
5154     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5155     return DAG.getMCSymbol(S, PtrVT);
5156   }
5157 
5158   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
5159     return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
5160                                        UsePlt ? PPCII::MO_PLT : 0);
5161 
5162   // No transformation needed.
5163   assert(Callee.getNode() && "What no callee?");
5164   return Callee;
5165 }
5166 
5167 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5168   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5169          "Expected a CALLSEQ_STARTSDNode.");
5170 
5171   // The last operand is the chain, except when the node has glue. If the node
5172   // has glue, then the last operand is the glue, and the chain is the second
5173   // last operand.
5174   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5175   if (LastValue.getValueType() != MVT::Glue)
5176     return LastValue;
5177 
5178   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5179 }
5180 
5181 // Creates the node that moves a functions address into the count register
5182 // to prepare for an indirect call instruction.
5183 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5184                                 SDValue &Glue, SDValue &Chain,
5185                                 const SDLoc &dl) {
5186   SDValue MTCTROps[] = {Chain, Callee, Glue};
5187   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5188   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5189                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5190   // The glue is the second value produced.
5191   Glue = Chain.getValue(1);
5192 }
5193 
5194 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5195                                           SDValue &Glue, SDValue &Chain,
5196                                           SDValue CallSeqStart,
5197                                           ImmutableCallSite CS, const SDLoc &dl,
5198                                           bool hasNest,
5199                                           const PPCSubtarget &Subtarget) {
5200   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5201   // entry point, but to the function descriptor (the function entry point
5202   // address is part of the function descriptor though).
5203   // The function descriptor is a three doubleword structure with the
5204   // following fields: function entry point, TOC base address and
5205   // environment pointer.
5206   // Thus for a call through a function pointer, the following actions need
5207   // to be performed:
5208   //   1. Save the TOC of the caller in the TOC save area of its stack
5209   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5210   //   2. Load the address of the function entry point from the function
5211   //      descriptor.
5212   //   3. Load the TOC of the callee from the function descriptor into r2.
5213   //   4. Load the environment pointer from the function descriptor into
5214   //      r11.
5215   //   5. Branch to the function entry point address.
5216   //   6. On return of the callee, the TOC of the caller needs to be
5217   //      restored (this is done in FinishCall()).
5218   //
5219   // The loads are scheduled at the beginning of the call sequence, and the
5220   // register copies are flagged together to ensure that no other
5221   // operations can be scheduled in between. E.g. without flagging the
5222   // copies together, a TOC access in the caller could be scheduled between
5223   // the assignment of the callee TOC and the branch to the callee, which leads
5224   // to incorrect code.
5225 
5226   // Start by loading the function address from the descriptor.
5227   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5228   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5229                       ? (MachineMemOperand::MODereferenceable |
5230                          MachineMemOperand::MOInvariant)
5231                       : MachineMemOperand::MONone;
5232 
5233   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5234 
5235   // Registers used in building the DAG.
5236   const MCRegister EnvPtrReg = Subtarget.getEnvironmentPointerRegister();
5237   const MCRegister TOCReg = Subtarget.getTOCPointerRegister();
5238 
5239   // Offsets of descriptor members.
5240   const unsigned TOCAnchorOffset = Subtarget.descriptorTOCAnchorOffset();
5241   const unsigned EnvPtrOffset = Subtarget.descriptorEnvironmentPointerOffset();
5242 
5243   const MVT RegVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
5244   const unsigned Alignment = Subtarget.isPPC64() ? 8 : 4;
5245 
5246   // One load for the functions entry point address.
5247   SDValue LoadFuncPtr = DAG.getLoad(RegVT, dl, LDChain, Callee, MPI,
5248                                     Alignment, MMOFlags);
5249 
5250   // One for loading the TOC anchor for the module that contains the called
5251   // function.
5252   SDValue TOCOff = DAG.getIntPtrConstant(TOCAnchorOffset, dl);
5253   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, Callee, TOCOff);
5254   SDValue TOCPtr =
5255       DAG.getLoad(RegVT, dl, LDChain, AddTOC,
5256                   MPI.getWithOffset(TOCAnchorOffset), Alignment, MMOFlags);
5257 
5258   // One for loading the environment pointer.
5259   SDValue PtrOff = DAG.getIntPtrConstant(EnvPtrOffset, dl);
5260   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, RegVT, Callee, PtrOff);
5261   SDValue LoadEnvPtr =
5262       DAG.getLoad(RegVT, dl, LDChain, AddPtr,
5263                   MPI.getWithOffset(EnvPtrOffset), Alignment, MMOFlags);
5264 
5265 
5266   // Then copy the newly loaded TOC anchor to the TOC pointer.
5267   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, TOCReg, TOCPtr, Glue);
5268   Chain = TOCVal.getValue(0);
5269   Glue = TOCVal.getValue(1);
5270 
5271   // If the function call has an explicit 'nest' parameter, it takes the
5272   // place of the environment pointer.
5273   assert((!hasNest || !Subtarget.isAIXABI()) &&
5274          "Nest parameter is not supported on AIX.");
5275   if (!hasNest) {
5276     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, EnvPtrReg, LoadEnvPtr, Glue);
5277     Chain = EnvVal.getValue(0);
5278     Glue = EnvVal.getValue(1);
5279   }
5280 
5281   // The rest of the indirect call sequence is the same as the non-descriptor
5282   // DAG.
5283   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5284 }
5285 
5286 static void
5287 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv,
5288                   const SDLoc &dl, bool isTailCall, bool isVarArg,
5289                   bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5290                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5291                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5292                   const PPCSubtarget &Subtarget, bool isIndirect) {
5293   const bool IsPPC64 = Subtarget.isPPC64();
5294   // MVT for a general purpose register.
5295   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5296 
5297   // First operand is always the chain.
5298   Ops.push_back(Chain);
5299 
5300   // If it's a direct call pass the callee as the second operand.
5301   if (!isIndirect)
5302     Ops.push_back(Callee);
5303   else {
5304     assert(!isPatchPoint && "Patch point call are not indirect.");
5305 
5306     // For the TOC based ABIs, we have saved the TOC pointer to the linkage area
5307     // on the stack (this would have been done in `LowerCall_64SVR4` or
5308     // `LowerCall_AIX`). The call instruction is a pseudo instruction that
5309     // represents both the indirect branch and a load that restores the TOC
5310     // pointer from the linkage area. The operand for the TOC restore is an add
5311     // of the TOC save offset to the stack pointer. This must be the second
5312     // operand: after the chain input but before any other variadic arguments.
5313     if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
5314       const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
5315 
5316       SDValue StackPtr = DAG.getRegister(StackPtrReg, RegVT);
5317       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5318       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5319       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, RegVT, StackPtr, TOCOff);
5320       Ops.push_back(AddTOC);
5321     }
5322 
5323     // Add the register used for the environment pointer.
5324     if (Subtarget.usesFunctionDescriptors() && !hasNest)
5325       Ops.push_back(DAG.getRegister(Subtarget.getEnvironmentPointerRegister(),
5326                                     RegVT));
5327 
5328 
5329     // Add CTR register as callee so a bctr can be emitted later.
5330     if (isTailCall)
5331       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5332   }
5333 
5334   // If this is a tail call add stack pointer delta.
5335   if (isTailCall)
5336     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5337 
5338   // Add argument registers to the end of the list so that they are known live
5339   // into the call.
5340   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5341     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5342                                   RegsToPass[i].second.getValueType()));
5343 
5344   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5345   // no way to mark dependencies as implicit here.
5346   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5347   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint)
5348     Ops.push_back(DAG.getRegister(Subtarget.getTOCPointerRegister(), RegVT));
5349 
5350   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5351   if (isVarArg && Subtarget.is32BitELFABI())
5352     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5353 
5354   // Add a register mask operand representing the call-preserved registers.
5355   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5356   const uint32_t *Mask =
5357       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5358   assert(Mask && "Missing call preserved mask for calling convention");
5359   Ops.push_back(DAG.getRegisterMask(Mask));
5360 
5361   // If the glue is valid, it is the last operand.
5362   if (Glue.getNode())
5363     Ops.push_back(Glue);
5364 }
5365 
5366 SDValue PPCTargetLowering::FinishCall(
5367     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5368     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5369     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5370     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5371     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5372     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5373 
5374   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5375     setUsesTOCBasePtr(DAG);
5376 
5377   const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint);
5378   unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall,
5379                                    DAG.getMachineFunction().getFunction(),
5380                                    Callee, Subtarget, DAG.getTarget());
5381 
5382   if (!isIndirect)
5383     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5384   else if (Subtarget.usesFunctionDescriptors())
5385     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5386                                   dl, hasNest, Subtarget);
5387   else
5388     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5389 
5390   // Build the operand list for the call instruction.
5391   SmallVector<SDValue, 8> Ops;
5392   buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5393                     hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff,
5394                     Subtarget, isIndirect);
5395 
5396   // Emit tail call.
5397   if (isTailCall) {
5398     assert(((Callee.getOpcode() == ISD::Register &&
5399              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5400             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5401             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5402             isa<ConstantSDNode>(Callee)) &&
5403            "Expecting a global address, external symbol, absolute value or "
5404            "register");
5405     assert(CallOpc == PPCISD::TC_RETURN &&
5406            "Unexpected call opcode for a tail call.");
5407     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5408     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5409   }
5410 
5411   std::array<EVT, 2> ReturnTypes = {{MVT::Other, MVT::Glue}};
5412   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5413   Glue = Chain.getValue(1);
5414 
5415   // When performing tail call optimization the callee pops its arguments off
5416   // the stack. Account for this here so these bytes can be pushed back on in
5417   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5418   int BytesCalleePops = (CallConv == CallingConv::Fast &&
5419                          getTargetMachine().Options.GuaranteedTailCallOpt)
5420                             ? NumBytes
5421                             : 0;
5422 
5423   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5424                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5425                              Glue, dl);
5426   Glue = Chain.getValue(1);
5427 
5428   return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals);
5429 }
5430 
5431 SDValue
5432 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5433                              SmallVectorImpl<SDValue> &InVals) const {
5434   SelectionDAG &DAG                     = CLI.DAG;
5435   SDLoc &dl                             = CLI.DL;
5436   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5437   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5438   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5439   SDValue Chain                         = CLI.Chain;
5440   SDValue Callee                        = CLI.Callee;
5441   bool &isTailCall                      = CLI.IsTailCall;
5442   CallingConv::ID CallConv              = CLI.CallConv;
5443   bool isVarArg                         = CLI.IsVarArg;
5444   bool isPatchPoint                     = CLI.IsPatchPoint;
5445   ImmutableCallSite CS                  = CLI.CS;
5446 
5447   if (isTailCall) {
5448     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5449       isTailCall = false;
5450     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5451       isTailCall =
5452         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5453                                                  isVarArg, Outs, Ins, DAG);
5454     else
5455       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5456                                                      Ins, DAG);
5457     if (isTailCall) {
5458       ++NumTailCalls;
5459       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5460         ++NumSiblingCalls;
5461 
5462       assert(isa<GlobalAddressSDNode>(Callee) &&
5463              "Callee should be an llvm::Function object.");
5464       LLVM_DEBUG(
5465           const GlobalValue *GV =
5466               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5467           const unsigned Width =
5468               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5469           dbgs() << "TCO caller: "
5470                  << left_justify(DAG.getMachineFunction().getName(), Width)
5471                  << ", callee linkage: " << GV->getVisibility() << ", "
5472                  << GV->getLinkage() << "\n");
5473     }
5474   }
5475 
5476   if (!isTailCall && CS && CS.isMustTailCall())
5477     report_fatal_error("failed to perform tail call elimination on a call "
5478                        "site marked musttail");
5479 
5480   // When long calls (i.e. indirect calls) are always used, calls are always
5481   // made via function pointer. If we have a function name, first translate it
5482   // into a pointer.
5483   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5484       !isTailCall)
5485     Callee = LowerGlobalAddress(Callee, DAG);
5486 
5487   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5488     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5489                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5490                             dl, DAG, InVals, CS);
5491 
5492   if (Subtarget.isSVR4ABI())
5493     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5494                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5495                             dl, DAG, InVals, CS);
5496 
5497   if (Subtarget.isAIXABI())
5498     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5499                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5500                          dl, DAG, InVals, CS);
5501 
5502   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5503                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5504                           dl, DAG, InVals, CS);
5505 }
5506 
5507 SDValue PPCTargetLowering::LowerCall_32SVR4(
5508     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5509     bool isTailCall, bool isPatchPoint,
5510     const SmallVectorImpl<ISD::OutputArg> &Outs,
5511     const SmallVectorImpl<SDValue> &OutVals,
5512     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5513     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5514     ImmutableCallSite CS) const {
5515   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5516   // of the 32-bit SVR4 ABI stack frame layout.
5517 
5518   assert((CallConv == CallingConv::C ||
5519           CallConv == CallingConv::Cold ||
5520           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5521 
5522   unsigned PtrByteSize = 4;
5523 
5524   MachineFunction &MF = DAG.getMachineFunction();
5525 
5526   // Mark this function as potentially containing a function that contains a
5527   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5528   // and restoring the callers stack pointer in this functions epilog. This is
5529   // done because by tail calling the called function might overwrite the value
5530   // in this function's (MF) stack pointer stack slot 0(SP).
5531   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5532       CallConv == CallingConv::Fast)
5533     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5534 
5535   // Count how many bytes are to be pushed on the stack, including the linkage
5536   // area, parameter list area and the part of the local variable space which
5537   // contains copies of aggregates which are passed by value.
5538 
5539   // Assign locations to all of the outgoing arguments.
5540   SmallVector<CCValAssign, 16> ArgLocs;
5541   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5542 
5543   // Reserve space for the linkage area on the stack.
5544   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5545                        PtrByteSize);
5546   if (useSoftFloat())
5547     CCInfo.PreAnalyzeCallOperands(Outs);
5548 
5549   if (isVarArg) {
5550     // Handle fixed and variable vector arguments differently.
5551     // Fixed vector arguments go into registers as long as registers are
5552     // available. Variable vector arguments always go into memory.
5553     unsigned NumArgs = Outs.size();
5554 
5555     for (unsigned i = 0; i != NumArgs; ++i) {
5556       MVT ArgVT = Outs[i].VT;
5557       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5558       bool Result;
5559 
5560       if (Outs[i].IsFixed) {
5561         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5562                                CCInfo);
5563       } else {
5564         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5565                                       ArgFlags, CCInfo);
5566       }
5567 
5568       if (Result) {
5569 #ifndef NDEBUG
5570         errs() << "Call operand #" << i << " has unhandled type "
5571              << EVT(ArgVT).getEVTString() << "\n";
5572 #endif
5573         llvm_unreachable(nullptr);
5574       }
5575     }
5576   } else {
5577     // All arguments are treated the same.
5578     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5579   }
5580   CCInfo.clearWasPPCF128();
5581 
5582   // Assign locations to all of the outgoing aggregate by value arguments.
5583   SmallVector<CCValAssign, 16> ByValArgLocs;
5584   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5585 
5586   // Reserve stack space for the allocations in CCInfo.
5587   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5588 
5589   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5590 
5591   // Size of the linkage area, parameter list area and the part of the local
5592   // space variable where copies of aggregates which are passed by value are
5593   // stored.
5594   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5595 
5596   // Calculate by how many bytes the stack has to be adjusted in case of tail
5597   // call optimization.
5598   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5599 
5600   // Adjust the stack pointer for the new arguments...
5601   // These operations are automatically eliminated by the prolog/epilog pass
5602   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5603   SDValue CallSeqStart = Chain;
5604 
5605   // Load the return address and frame pointer so it can be moved somewhere else
5606   // later.
5607   SDValue LROp, FPOp;
5608   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5609 
5610   // Set up a copy of the stack pointer for use loading and storing any
5611   // arguments that may not fit in the registers available for argument
5612   // passing.
5613   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5614 
5615   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5616   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5617   SmallVector<SDValue, 8> MemOpChains;
5618 
5619   bool seenFloatArg = false;
5620   // Walk the register/memloc assignments, inserting copies/loads.
5621   // i - Tracks the index into the list of registers allocated for the call
5622   // RealArgIdx - Tracks the index into the list of actual function arguments
5623   // j - Tracks the index into the list of byval arguments
5624   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5625        i != e;
5626        ++i, ++RealArgIdx) {
5627     CCValAssign &VA = ArgLocs[i];
5628     SDValue Arg = OutVals[RealArgIdx];
5629     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5630 
5631     if (Flags.isByVal()) {
5632       // Argument is an aggregate which is passed by value, thus we need to
5633       // create a copy of it in the local variable space of the current stack
5634       // frame (which is the stack frame of the caller) and pass the address of
5635       // this copy to the callee.
5636       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5637       CCValAssign &ByValVA = ByValArgLocs[j++];
5638       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5639 
5640       // Memory reserved in the local variable space of the callers stack frame.
5641       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5642 
5643       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5644       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5645                            StackPtr, PtrOff);
5646 
5647       // Create a copy of the argument in the local area of the current
5648       // stack frame.
5649       SDValue MemcpyCall =
5650         CreateCopyOfByValArgument(Arg, PtrOff,
5651                                   CallSeqStart.getNode()->getOperand(0),
5652                                   Flags, DAG, dl);
5653 
5654       // This must go outside the CALLSEQ_START..END.
5655       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5656                                                      SDLoc(MemcpyCall));
5657       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5658                              NewCallSeqStart.getNode());
5659       Chain = CallSeqStart = NewCallSeqStart;
5660 
5661       // Pass the address of the aggregate copy on the stack either in a
5662       // physical register or in the parameter list area of the current stack
5663       // frame to the callee.
5664       Arg = PtrOff;
5665     }
5666 
5667     // When useCRBits() is true, there can be i1 arguments.
5668     // It is because getRegisterType(MVT::i1) => MVT::i1,
5669     // and for other integer types getRegisterType() => MVT::i32.
5670     // Extend i1 and ensure callee will get i32.
5671     if (Arg.getValueType() == MVT::i1)
5672       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5673                         dl, MVT::i32, Arg);
5674 
5675     if (VA.isRegLoc()) {
5676       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5677       // Put argument in a physical register.
5678       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5679         bool IsLE = Subtarget.isLittleEndian();
5680         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5681                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5682         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5683         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5684                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5685         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5686                              SVal.getValue(0)));
5687       } else
5688         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5689     } else {
5690       // Put argument in the parameter list area of the current stack frame.
5691       assert(VA.isMemLoc());
5692       unsigned LocMemOffset = VA.getLocMemOffset();
5693 
5694       if (!isTailCall) {
5695         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5696         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5697                              StackPtr, PtrOff);
5698 
5699         MemOpChains.push_back(
5700             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5701       } else {
5702         // Calculate and remember argument location.
5703         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5704                                  TailCallArguments);
5705       }
5706     }
5707   }
5708 
5709   if (!MemOpChains.empty())
5710     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5711 
5712   // Build a sequence of copy-to-reg nodes chained together with token chain
5713   // and flag operands which copy the outgoing args into the appropriate regs.
5714   SDValue InFlag;
5715   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5716     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5717                              RegsToPass[i].second, InFlag);
5718     InFlag = Chain.getValue(1);
5719   }
5720 
5721   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5722   // registers.
5723   if (isVarArg) {
5724     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5725     SDValue Ops[] = { Chain, InFlag };
5726 
5727     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5728                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5729 
5730     InFlag = Chain.getValue(1);
5731   }
5732 
5733   if (isTailCall)
5734     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5735                     TailCallArguments);
5736 
5737   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5738                     /* unused except on PPC64 ELFv1 */ false, DAG,
5739                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5740                     NumBytes, Ins, InVals, CS);
5741 }
5742 
5743 // Copy an argument into memory, being careful to do this outside the
5744 // call sequence for the call to which the argument belongs.
5745 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5746     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5747     SelectionDAG &DAG, const SDLoc &dl) const {
5748   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5749                         CallSeqStart.getNode()->getOperand(0),
5750                         Flags, DAG, dl);
5751   // The MEMCPY must go outside the CALLSEQ_START..END.
5752   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5753   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5754                                                  SDLoc(MemcpyCall));
5755   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5756                          NewCallSeqStart.getNode());
5757   return NewCallSeqStart;
5758 }
5759 
5760 SDValue PPCTargetLowering::LowerCall_64SVR4(
5761     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5762     bool isTailCall, bool isPatchPoint,
5763     const SmallVectorImpl<ISD::OutputArg> &Outs,
5764     const SmallVectorImpl<SDValue> &OutVals,
5765     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5766     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5767     ImmutableCallSite CS) const {
5768   bool isELFv2ABI = Subtarget.isELFv2ABI();
5769   bool isLittleEndian = Subtarget.isLittleEndian();
5770   unsigned NumOps = Outs.size();
5771   bool hasNest = false;
5772   bool IsSibCall = false;
5773 
5774   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5775   unsigned PtrByteSize = 8;
5776 
5777   MachineFunction &MF = DAG.getMachineFunction();
5778 
5779   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5780     IsSibCall = true;
5781 
5782   // Mark this function as potentially containing a function that contains a
5783   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5784   // and restoring the callers stack pointer in this functions epilog. This is
5785   // done because by tail calling the called function might overwrite the value
5786   // in this function's (MF) stack pointer stack slot 0(SP).
5787   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5788       CallConv == CallingConv::Fast)
5789     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5790 
5791   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5792          "fastcc not supported on varargs functions");
5793 
5794   // Count how many bytes are to be pushed on the stack, including the linkage
5795   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5796   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5797   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5798   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5799   unsigned NumBytes = LinkageSize;
5800   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5801   unsigned &QFPR_idx = FPR_idx;
5802 
5803   static const MCPhysReg GPR[] = {
5804     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5805     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5806   };
5807   static const MCPhysReg VR[] = {
5808     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5809     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5810   };
5811 
5812   const unsigned NumGPRs = array_lengthof(GPR);
5813   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5814   const unsigned NumVRs  = array_lengthof(VR);
5815   const unsigned NumQFPRs = NumFPRs;
5816 
5817   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5818   // can be passed to the callee in registers.
5819   // For the fast calling convention, there is another check below.
5820   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5821   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5822   if (!HasParameterArea) {
5823     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5824     unsigned AvailableFPRs = NumFPRs;
5825     unsigned AvailableVRs = NumVRs;
5826     unsigned NumBytesTmp = NumBytes;
5827     for (unsigned i = 0; i != NumOps; ++i) {
5828       if (Outs[i].Flags.isNest()) continue;
5829       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5830                                 PtrByteSize, LinkageSize, ParamAreaSize,
5831                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5832                                 Subtarget.hasQPX()))
5833         HasParameterArea = true;
5834     }
5835   }
5836 
5837   // When using the fast calling convention, we don't provide backing for
5838   // arguments that will be in registers.
5839   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5840 
5841   // Avoid allocating parameter area for fastcc functions if all the arguments
5842   // can be passed in the registers.
5843   if (CallConv == CallingConv::Fast)
5844     HasParameterArea = false;
5845 
5846   // Add up all the space actually used.
5847   for (unsigned i = 0; i != NumOps; ++i) {
5848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5849     EVT ArgVT = Outs[i].VT;
5850     EVT OrigVT = Outs[i].ArgVT;
5851 
5852     if (Flags.isNest())
5853       continue;
5854 
5855     if (CallConv == CallingConv::Fast) {
5856       if (Flags.isByVal()) {
5857         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5858         if (NumGPRsUsed > NumGPRs)
5859           HasParameterArea = true;
5860       } else {
5861         switch (ArgVT.getSimpleVT().SimpleTy) {
5862         default: llvm_unreachable("Unexpected ValueType for argument!");
5863         case MVT::i1:
5864         case MVT::i32:
5865         case MVT::i64:
5866           if (++NumGPRsUsed <= NumGPRs)
5867             continue;
5868           break;
5869         case MVT::v4i32:
5870         case MVT::v8i16:
5871         case MVT::v16i8:
5872         case MVT::v2f64:
5873         case MVT::v2i64:
5874         case MVT::v1i128:
5875         case MVT::f128:
5876           if (++NumVRsUsed <= NumVRs)
5877             continue;
5878           break;
5879         case MVT::v4f32:
5880           // When using QPX, this is handled like a FP register, otherwise, it
5881           // is an Altivec register.
5882           if (Subtarget.hasQPX()) {
5883             if (++NumFPRsUsed <= NumFPRs)
5884               continue;
5885           } else {
5886             if (++NumVRsUsed <= NumVRs)
5887               continue;
5888           }
5889           break;
5890         case MVT::f32:
5891         case MVT::f64:
5892         case MVT::v4f64: // QPX
5893         case MVT::v4i1:  // QPX
5894           if (++NumFPRsUsed <= NumFPRs)
5895             continue;
5896           break;
5897         }
5898         HasParameterArea = true;
5899       }
5900     }
5901 
5902     /* Respect alignment of argument on the stack.  */
5903     unsigned Align =
5904       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5905     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5906 
5907     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5908     if (Flags.isInConsecutiveRegsLast())
5909       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5910   }
5911 
5912   unsigned NumBytesActuallyUsed = NumBytes;
5913 
5914   // In the old ELFv1 ABI,
5915   // the prolog code of the callee may store up to 8 GPR argument registers to
5916   // the stack, allowing va_start to index over them in memory if its varargs.
5917   // Because we cannot tell if this is needed on the caller side, we have to
5918   // conservatively assume that it is needed.  As such, make sure we have at
5919   // least enough stack space for the caller to store the 8 GPRs.
5920   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5921   // really requires memory operands, e.g. a vararg function.
5922   if (HasParameterArea)
5923     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5924   else
5925     NumBytes = LinkageSize;
5926 
5927   // Tail call needs the stack to be aligned.
5928   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5929       CallConv == CallingConv::Fast)
5930     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5931 
5932   int SPDiff = 0;
5933 
5934   // Calculate by how many bytes the stack has to be adjusted in case of tail
5935   // call optimization.
5936   if (!IsSibCall)
5937     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5938 
5939   // To protect arguments on the stack from being clobbered in a tail call,
5940   // force all the loads to happen before doing any other lowering.
5941   if (isTailCall)
5942     Chain = DAG.getStackArgumentTokenFactor(Chain);
5943 
5944   // Adjust the stack pointer for the new arguments...
5945   // These operations are automatically eliminated by the prolog/epilog pass
5946   if (!IsSibCall)
5947     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5948   SDValue CallSeqStart = Chain;
5949 
5950   // Load the return address and frame pointer so it can be move somewhere else
5951   // later.
5952   SDValue LROp, FPOp;
5953   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5954 
5955   // Set up a copy of the stack pointer for use loading and storing any
5956   // arguments that may not fit in the registers available for argument
5957   // passing.
5958   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5959 
5960   // Figure out which arguments are going to go in registers, and which in
5961   // memory.  Also, if this is a vararg function, floating point operations
5962   // must be stored to our stack, and loaded into integer regs as well, if
5963   // any integer regs are available for argument passing.
5964   unsigned ArgOffset = LinkageSize;
5965 
5966   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5967   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5968 
5969   SmallVector<SDValue, 8> MemOpChains;
5970   for (unsigned i = 0; i != NumOps; ++i) {
5971     SDValue Arg = OutVals[i];
5972     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5973     EVT ArgVT = Outs[i].VT;
5974     EVT OrigVT = Outs[i].ArgVT;
5975 
5976     // PtrOff will be used to store the current argument to the stack if a
5977     // register cannot be found for it.
5978     SDValue PtrOff;
5979 
5980     // We re-align the argument offset for each argument, except when using the
5981     // fast calling convention, when we need to make sure we do that only when
5982     // we'll actually use a stack slot.
5983     auto ComputePtrOff = [&]() {
5984       /* Respect alignment of argument on the stack.  */
5985       unsigned Align =
5986         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5987       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5988 
5989       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5990 
5991       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5992     };
5993 
5994     if (CallConv != CallingConv::Fast) {
5995       ComputePtrOff();
5996 
5997       /* Compute GPR index associated with argument offset.  */
5998       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5999       GPR_idx = std::min(GPR_idx, NumGPRs);
6000     }
6001 
6002     // Promote integers to 64-bit values.
6003     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
6004       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6005       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6006       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6007     }
6008 
6009     // FIXME memcpy is used way more than necessary.  Correctness first.
6010     // Note: "by value" is code for passing a structure by value, not
6011     // basic types.
6012     if (Flags.isByVal()) {
6013       // Note: Size includes alignment padding, so
6014       //   struct x { short a; char b; }
6015       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
6016       // These are the proper values we need for right-justifying the
6017       // aggregate in a parameter register.
6018       unsigned Size = Flags.getByValSize();
6019 
6020       // An empty aggregate parameter takes up no storage and no
6021       // registers.
6022       if (Size == 0)
6023         continue;
6024 
6025       if (CallConv == CallingConv::Fast)
6026         ComputePtrOff();
6027 
6028       // All aggregates smaller than 8 bytes must be passed right-justified.
6029       if (Size==1 || Size==2 || Size==4) {
6030         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
6031         if (GPR_idx != NumGPRs) {
6032           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6033                                         MachinePointerInfo(), VT);
6034           MemOpChains.push_back(Load.getValue(1));
6035           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6036 
6037           ArgOffset += PtrByteSize;
6038           continue;
6039         }
6040       }
6041 
6042       if (GPR_idx == NumGPRs && Size < 8) {
6043         SDValue AddPtr = PtrOff;
6044         if (!isLittleEndian) {
6045           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6046                                           PtrOff.getValueType());
6047           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6048         }
6049         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6050                                                           CallSeqStart,
6051                                                           Flags, DAG, dl);
6052         ArgOffset += PtrByteSize;
6053         continue;
6054       }
6055       // Copy entire object into memory.  There are cases where gcc-generated
6056       // code assumes it is there, even if it could be put entirely into
6057       // registers.  (This is not what the doc says.)
6058 
6059       // FIXME: The above statement is likely due to a misunderstanding of the
6060       // documents.  All arguments must be copied into the parameter area BY
6061       // THE CALLEE in the event that the callee takes the address of any
6062       // formal argument.  That has not yet been implemented.  However, it is
6063       // reasonable to use the stack area as a staging area for the register
6064       // load.
6065 
6066       // Skip this for small aggregates, as we will use the same slot for a
6067       // right-justified copy, below.
6068       if (Size >= 8)
6069         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6070                                                           CallSeqStart,
6071                                                           Flags, DAG, dl);
6072 
6073       // When a register is available, pass a small aggregate right-justified.
6074       if (Size < 8 && GPR_idx != NumGPRs) {
6075         // The easiest way to get this right-justified in a register
6076         // is to copy the structure into the rightmost portion of a
6077         // local variable slot, then load the whole slot into the
6078         // register.
6079         // FIXME: The memcpy seems to produce pretty awful code for
6080         // small aggregates, particularly for packed ones.
6081         // FIXME: It would be preferable to use the slot in the
6082         // parameter save area instead of a new local variable.
6083         SDValue AddPtr = PtrOff;
6084         if (!isLittleEndian) {
6085           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6086           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6087         }
6088         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6089                                                           CallSeqStart,
6090                                                           Flags, DAG, dl);
6091 
6092         // Load the slot into the register.
6093         SDValue Load =
6094             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6095         MemOpChains.push_back(Load.getValue(1));
6096         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6097 
6098         // Done with this argument.
6099         ArgOffset += PtrByteSize;
6100         continue;
6101       }
6102 
6103       // For aggregates larger than PtrByteSize, copy the pieces of the
6104       // object that fit into registers from the parameter save area.
6105       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6106         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6107         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6108         if (GPR_idx != NumGPRs) {
6109           SDValue Load =
6110               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6111           MemOpChains.push_back(Load.getValue(1));
6112           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6113           ArgOffset += PtrByteSize;
6114         } else {
6115           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6116           break;
6117         }
6118       }
6119       continue;
6120     }
6121 
6122     switch (Arg.getSimpleValueType().SimpleTy) {
6123     default: llvm_unreachable("Unexpected ValueType for argument!");
6124     case MVT::i1:
6125     case MVT::i32:
6126     case MVT::i64:
6127       if (Flags.isNest()) {
6128         // The 'nest' parameter, if any, is passed in R11.
6129         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6130         hasNest = true;
6131         break;
6132       }
6133 
6134       // These can be scalar arguments or elements of an integer array type
6135       // passed directly.  Clang may use those instead of "byval" aggregate
6136       // types to avoid forcing arguments to memory unnecessarily.
6137       if (GPR_idx != NumGPRs) {
6138         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6139       } else {
6140         if (CallConv == CallingConv::Fast)
6141           ComputePtrOff();
6142 
6143         assert(HasParameterArea &&
6144                "Parameter area must exist to pass an argument in memory.");
6145         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6146                          true, isTailCall, false, MemOpChains,
6147                          TailCallArguments, dl);
6148         if (CallConv == CallingConv::Fast)
6149           ArgOffset += PtrByteSize;
6150       }
6151       if (CallConv != CallingConv::Fast)
6152         ArgOffset += PtrByteSize;
6153       break;
6154     case MVT::f32:
6155     case MVT::f64: {
6156       // These can be scalar arguments or elements of a float array type
6157       // passed directly.  The latter are used to implement ELFv2 homogenous
6158       // float aggregates.
6159 
6160       // Named arguments go into FPRs first, and once they overflow, the
6161       // remaining arguments go into GPRs and then the parameter save area.
6162       // Unnamed arguments for vararg functions always go to GPRs and
6163       // then the parameter save area.  For now, put all arguments to vararg
6164       // routines always in both locations (FPR *and* GPR or stack slot).
6165       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6166       bool NeededLoad = false;
6167 
6168       // First load the argument into the next available FPR.
6169       if (FPR_idx != NumFPRs)
6170         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6171 
6172       // Next, load the argument into GPR or stack slot if needed.
6173       if (!NeedGPROrStack)
6174         ;
6175       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6176         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6177         // once we support fp <-> gpr moves.
6178 
6179         // In the non-vararg case, this can only ever happen in the
6180         // presence of f32 array types, since otherwise we never run
6181         // out of FPRs before running out of GPRs.
6182         SDValue ArgVal;
6183 
6184         // Double values are always passed in a single GPR.
6185         if (Arg.getValueType() != MVT::f32) {
6186           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6187 
6188         // Non-array float values are extended and passed in a GPR.
6189         } else if (!Flags.isInConsecutiveRegs()) {
6190           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6191           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6192 
6193         // If we have an array of floats, we collect every odd element
6194         // together with its predecessor into one GPR.
6195         } else if (ArgOffset % PtrByteSize != 0) {
6196           SDValue Lo, Hi;
6197           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6198           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6199           if (!isLittleEndian)
6200             std::swap(Lo, Hi);
6201           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6202 
6203         // The final element, if even, goes into the first half of a GPR.
6204         } else if (Flags.isInConsecutiveRegsLast()) {
6205           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6206           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6207           if (!isLittleEndian)
6208             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6209                                  DAG.getConstant(32, dl, MVT::i32));
6210 
6211         // Non-final even elements are skipped; they will be handled
6212         // together the with subsequent argument on the next go-around.
6213         } else
6214           ArgVal = SDValue();
6215 
6216         if (ArgVal.getNode())
6217           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6218       } else {
6219         if (CallConv == CallingConv::Fast)
6220           ComputePtrOff();
6221 
6222         // Single-precision floating-point values are mapped to the
6223         // second (rightmost) word of the stack doubleword.
6224         if (Arg.getValueType() == MVT::f32 &&
6225             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6226           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6227           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6228         }
6229 
6230         assert(HasParameterArea &&
6231                "Parameter area must exist to pass an argument in memory.");
6232         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6233                          true, isTailCall, false, MemOpChains,
6234                          TailCallArguments, dl);
6235 
6236         NeededLoad = true;
6237       }
6238       // When passing an array of floats, the array occupies consecutive
6239       // space in the argument area; only round up to the next doubleword
6240       // at the end of the array.  Otherwise, each float takes 8 bytes.
6241       if (CallConv != CallingConv::Fast || NeededLoad) {
6242         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6243                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6244         if (Flags.isInConsecutiveRegsLast())
6245           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6246       }
6247       break;
6248     }
6249     case MVT::v4f32:
6250     case MVT::v4i32:
6251     case MVT::v8i16:
6252     case MVT::v16i8:
6253     case MVT::v2f64:
6254     case MVT::v2i64:
6255     case MVT::v1i128:
6256     case MVT::f128:
6257       if (!Subtarget.hasQPX()) {
6258       // These can be scalar arguments or elements of a vector array type
6259       // passed directly.  The latter are used to implement ELFv2 homogenous
6260       // vector aggregates.
6261 
6262       // For a varargs call, named arguments go into VRs or on the stack as
6263       // usual; unnamed arguments always go to the stack or the corresponding
6264       // GPRs when within range.  For now, we always put the value in both
6265       // locations (or even all three).
6266       if (isVarArg) {
6267         assert(HasParameterArea &&
6268                "Parameter area must exist if we have a varargs call.");
6269         // We could elide this store in the case where the object fits
6270         // entirely in R registers.  Maybe later.
6271         SDValue Store =
6272             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6273         MemOpChains.push_back(Store);
6274         if (VR_idx != NumVRs) {
6275           SDValue Load =
6276               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6277           MemOpChains.push_back(Load.getValue(1));
6278           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6279         }
6280         ArgOffset += 16;
6281         for (unsigned i=0; i<16; i+=PtrByteSize) {
6282           if (GPR_idx == NumGPRs)
6283             break;
6284           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6285                                    DAG.getConstant(i, dl, PtrVT));
6286           SDValue Load =
6287               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6288           MemOpChains.push_back(Load.getValue(1));
6289           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6290         }
6291         break;
6292       }
6293 
6294       // Non-varargs Altivec params go into VRs or on the stack.
6295       if (VR_idx != NumVRs) {
6296         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6297       } else {
6298         if (CallConv == CallingConv::Fast)
6299           ComputePtrOff();
6300 
6301         assert(HasParameterArea &&
6302                "Parameter area must exist to pass an argument in memory.");
6303         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6304                          true, isTailCall, true, MemOpChains,
6305                          TailCallArguments, dl);
6306         if (CallConv == CallingConv::Fast)
6307           ArgOffset += 16;
6308       }
6309 
6310       if (CallConv != CallingConv::Fast)
6311         ArgOffset += 16;
6312       break;
6313       } // not QPX
6314 
6315       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6316              "Invalid QPX parameter type");
6317 
6318       LLVM_FALLTHROUGH;
6319     case MVT::v4f64:
6320     case MVT::v4i1: {
6321       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6322       if (isVarArg) {
6323         assert(HasParameterArea &&
6324                "Parameter area must exist if we have a varargs call.");
6325         // We could elide this store in the case where the object fits
6326         // entirely in R registers.  Maybe later.
6327         SDValue Store =
6328             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6329         MemOpChains.push_back(Store);
6330         if (QFPR_idx != NumQFPRs) {
6331           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6332                                      PtrOff, MachinePointerInfo());
6333           MemOpChains.push_back(Load.getValue(1));
6334           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6335         }
6336         ArgOffset += (IsF32 ? 16 : 32);
6337         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6338           if (GPR_idx == NumGPRs)
6339             break;
6340           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6341                                    DAG.getConstant(i, dl, PtrVT));
6342           SDValue Load =
6343               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6344           MemOpChains.push_back(Load.getValue(1));
6345           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6346         }
6347         break;
6348       }
6349 
6350       // Non-varargs QPX params go into registers or on the stack.
6351       if (QFPR_idx != NumQFPRs) {
6352         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6353       } else {
6354         if (CallConv == CallingConv::Fast)
6355           ComputePtrOff();
6356 
6357         assert(HasParameterArea &&
6358                "Parameter area must exist to pass an argument in memory.");
6359         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6360                          true, isTailCall, true, MemOpChains,
6361                          TailCallArguments, dl);
6362         if (CallConv == CallingConv::Fast)
6363           ArgOffset += (IsF32 ? 16 : 32);
6364       }
6365 
6366       if (CallConv != CallingConv::Fast)
6367         ArgOffset += (IsF32 ? 16 : 32);
6368       break;
6369       }
6370     }
6371   }
6372 
6373   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6374          "mismatch in size of parameter area");
6375   (void)NumBytesActuallyUsed;
6376 
6377   if (!MemOpChains.empty())
6378     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6379 
6380   // Check if this is an indirect call (MTCTR/BCTRL).
6381   // See prepareDescriptorIndirectCall and buildCallOperands for more
6382   // information about calls through function pointers in the 64-bit SVR4 ABI.
6383   if (!isTailCall && !isPatchPoint &&
6384       !isFunctionGlobalAddress(Callee) &&
6385       !isa<ExternalSymbolSDNode>(Callee)) {
6386     // Load r2 into a virtual register and store it to the TOC save area.
6387     setUsesTOCBasePtr(DAG);
6388     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6389     // TOC save area offset.
6390     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6391     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6392     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6393     Chain = DAG.getStore(
6394         Val.getValue(1), dl, Val, AddPtr,
6395         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6396     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6397     // This does not mean the MTCTR instruction must use R12; it's easier
6398     // to model this as an extra parameter, so do that.
6399     if (isELFv2ABI && !isPatchPoint)
6400       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6401   }
6402 
6403   // Build a sequence of copy-to-reg nodes chained together with token chain
6404   // and flag operands which copy the outgoing args into the appropriate regs.
6405   SDValue InFlag;
6406   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6407     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6408                              RegsToPass[i].second, InFlag);
6409     InFlag = Chain.getValue(1);
6410   }
6411 
6412   if (isTailCall && !IsSibCall)
6413     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6414                     TailCallArguments);
6415 
6416   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6417                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6418                     SPDiff, NumBytes, Ins, InVals, CS);
6419 }
6420 
6421 SDValue PPCTargetLowering::LowerCall_Darwin(
6422     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6423     bool isTailCall, bool isPatchPoint,
6424     const SmallVectorImpl<ISD::OutputArg> &Outs,
6425     const SmallVectorImpl<SDValue> &OutVals,
6426     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6427     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6428     ImmutableCallSite CS) const {
6429   unsigned NumOps = Outs.size();
6430 
6431   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6432   bool isPPC64 = PtrVT == MVT::i64;
6433   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6434 
6435   MachineFunction &MF = DAG.getMachineFunction();
6436 
6437   // Mark this function as potentially containing a function that contains a
6438   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6439   // and restoring the callers stack pointer in this functions epilog. This is
6440   // done because by tail calling the called function might overwrite the value
6441   // in this function's (MF) stack pointer stack slot 0(SP).
6442   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6443       CallConv == CallingConv::Fast)
6444     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6445 
6446   // Count how many bytes are to be pushed on the stack, including the linkage
6447   // area, and parameter passing area.  We start with 24/48 bytes, which is
6448   // prereserved space for [SP][CR][LR][3 x unused].
6449   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6450   unsigned NumBytes = LinkageSize;
6451 
6452   // Add up all the space actually used.
6453   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6454   // they all go in registers, but we must reserve stack space for them for
6455   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6456   // assigned stack space in order, with padding so Altivec parameters are
6457   // 16-byte aligned.
6458   unsigned nAltivecParamsAtEnd = 0;
6459   for (unsigned i = 0; i != NumOps; ++i) {
6460     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6461     EVT ArgVT = Outs[i].VT;
6462     // Varargs Altivec parameters are padded to a 16 byte boundary.
6463     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6464         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6465         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6466       if (!isVarArg && !isPPC64) {
6467         // Non-varargs Altivec parameters go after all the non-Altivec
6468         // parameters; handle those later so we know how much padding we need.
6469         nAltivecParamsAtEnd++;
6470         continue;
6471       }
6472       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6473       NumBytes = ((NumBytes+15)/16)*16;
6474     }
6475     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6476   }
6477 
6478   // Allow for Altivec parameters at the end, if needed.
6479   if (nAltivecParamsAtEnd) {
6480     NumBytes = ((NumBytes+15)/16)*16;
6481     NumBytes += 16*nAltivecParamsAtEnd;
6482   }
6483 
6484   // The prolog code of the callee may store up to 8 GPR argument registers to
6485   // the stack, allowing va_start to index over them in memory if its varargs.
6486   // Because we cannot tell if this is needed on the caller side, we have to
6487   // conservatively assume that it is needed.  As such, make sure we have at
6488   // least enough stack space for the caller to store the 8 GPRs.
6489   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6490 
6491   // Tail call needs the stack to be aligned.
6492   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6493       CallConv == CallingConv::Fast)
6494     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6495 
6496   // Calculate by how many bytes the stack has to be adjusted in case of tail
6497   // call optimization.
6498   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6499 
6500   // To protect arguments on the stack from being clobbered in a tail call,
6501   // force all the loads to happen before doing any other lowering.
6502   if (isTailCall)
6503     Chain = DAG.getStackArgumentTokenFactor(Chain);
6504 
6505   // Adjust the stack pointer for the new arguments...
6506   // These operations are automatically eliminated by the prolog/epilog pass
6507   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6508   SDValue CallSeqStart = Chain;
6509 
6510   // Load the return address and frame pointer so it can be move somewhere else
6511   // later.
6512   SDValue LROp, FPOp;
6513   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6514 
6515   // Set up a copy of the stack pointer for use loading and storing any
6516   // arguments that may not fit in the registers available for argument
6517   // passing.
6518   SDValue StackPtr;
6519   if (isPPC64)
6520     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6521   else
6522     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6523 
6524   // Figure out which arguments are going to go in registers, and which in
6525   // memory.  Also, if this is a vararg function, floating point operations
6526   // must be stored to our stack, and loaded into integer regs as well, if
6527   // any integer regs are available for argument passing.
6528   unsigned ArgOffset = LinkageSize;
6529   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6530 
6531   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6532     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6533     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6534   };
6535   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6536     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6537     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6538   };
6539   static const MCPhysReg VR[] = {
6540     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6541     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6542   };
6543   const unsigned NumGPRs = array_lengthof(GPR_32);
6544   const unsigned NumFPRs = 13;
6545   const unsigned NumVRs  = array_lengthof(VR);
6546 
6547   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6548 
6549   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6550   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6551 
6552   SmallVector<SDValue, 8> MemOpChains;
6553   for (unsigned i = 0; i != NumOps; ++i) {
6554     SDValue Arg = OutVals[i];
6555     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6556 
6557     // PtrOff will be used to store the current argument to the stack if a
6558     // register cannot be found for it.
6559     SDValue PtrOff;
6560 
6561     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6562 
6563     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6564 
6565     // On PPC64, promote integers to 64-bit values.
6566     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6567       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6568       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6569       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6570     }
6571 
6572     // FIXME memcpy is used way more than necessary.  Correctness first.
6573     // Note: "by value" is code for passing a structure by value, not
6574     // basic types.
6575     if (Flags.isByVal()) {
6576       unsigned Size = Flags.getByValSize();
6577       // Very small objects are passed right-justified.  Everything else is
6578       // passed left-justified.
6579       if (Size==1 || Size==2) {
6580         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6581         if (GPR_idx != NumGPRs) {
6582           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6583                                         MachinePointerInfo(), VT);
6584           MemOpChains.push_back(Load.getValue(1));
6585           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6586 
6587           ArgOffset += PtrByteSize;
6588         } else {
6589           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6590                                           PtrOff.getValueType());
6591           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6592           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6593                                                             CallSeqStart,
6594                                                             Flags, DAG, dl);
6595           ArgOffset += PtrByteSize;
6596         }
6597         continue;
6598       }
6599       // Copy entire object into memory.  There are cases where gcc-generated
6600       // code assumes it is there, even if it could be put entirely into
6601       // registers.  (This is not what the doc says.)
6602       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6603                                                         CallSeqStart,
6604                                                         Flags, DAG, dl);
6605 
6606       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6607       // copy the pieces of the object that fit into registers from the
6608       // parameter save area.
6609       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6610         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6611         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6612         if (GPR_idx != NumGPRs) {
6613           SDValue Load =
6614               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6615           MemOpChains.push_back(Load.getValue(1));
6616           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6617           ArgOffset += PtrByteSize;
6618         } else {
6619           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6620           break;
6621         }
6622       }
6623       continue;
6624     }
6625 
6626     switch (Arg.getSimpleValueType().SimpleTy) {
6627     default: llvm_unreachable("Unexpected ValueType for argument!");
6628     case MVT::i1:
6629     case MVT::i32:
6630     case MVT::i64:
6631       if (GPR_idx != NumGPRs) {
6632         if (Arg.getValueType() == MVT::i1)
6633           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6634 
6635         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6636       } else {
6637         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6638                          isPPC64, isTailCall, false, MemOpChains,
6639                          TailCallArguments, dl);
6640       }
6641       ArgOffset += PtrByteSize;
6642       break;
6643     case MVT::f32:
6644     case MVT::f64:
6645       if (FPR_idx != NumFPRs) {
6646         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6647 
6648         if (isVarArg) {
6649           SDValue Store =
6650               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6651           MemOpChains.push_back(Store);
6652 
6653           // Float varargs are always shadowed in available integer registers
6654           if (GPR_idx != NumGPRs) {
6655             SDValue Load =
6656                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6657             MemOpChains.push_back(Load.getValue(1));
6658             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6659           }
6660           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6661             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6662             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6663             SDValue Load =
6664                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6665             MemOpChains.push_back(Load.getValue(1));
6666             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6667           }
6668         } else {
6669           // If we have any FPRs remaining, we may also have GPRs remaining.
6670           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6671           // GPRs.
6672           if (GPR_idx != NumGPRs)
6673             ++GPR_idx;
6674           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6675               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6676             ++GPR_idx;
6677         }
6678       } else
6679         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6680                          isPPC64, isTailCall, false, MemOpChains,
6681                          TailCallArguments, dl);
6682       if (isPPC64)
6683         ArgOffset += 8;
6684       else
6685         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6686       break;
6687     case MVT::v4f32:
6688     case MVT::v4i32:
6689     case MVT::v8i16:
6690     case MVT::v16i8:
6691       if (isVarArg) {
6692         // These go aligned on the stack, or in the corresponding R registers
6693         // when within range.  The Darwin PPC ABI doc claims they also go in
6694         // V registers; in fact gcc does this only for arguments that are
6695         // prototyped, not for those that match the ...  We do it for all
6696         // arguments, seems to work.
6697         while (ArgOffset % 16 !=0) {
6698           ArgOffset += PtrByteSize;
6699           if (GPR_idx != NumGPRs)
6700             GPR_idx++;
6701         }
6702         // We could elide this store in the case where the object fits
6703         // entirely in R registers.  Maybe later.
6704         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6705                              DAG.getConstant(ArgOffset, dl, PtrVT));
6706         SDValue Store =
6707             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6708         MemOpChains.push_back(Store);
6709         if (VR_idx != NumVRs) {
6710           SDValue Load =
6711               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6712           MemOpChains.push_back(Load.getValue(1));
6713           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6714         }
6715         ArgOffset += 16;
6716         for (unsigned i=0; i<16; i+=PtrByteSize) {
6717           if (GPR_idx == NumGPRs)
6718             break;
6719           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6720                                    DAG.getConstant(i, dl, PtrVT));
6721           SDValue Load =
6722               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6723           MemOpChains.push_back(Load.getValue(1));
6724           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6725         }
6726         break;
6727       }
6728 
6729       // Non-varargs Altivec params generally go in registers, but have
6730       // stack space allocated at the end.
6731       if (VR_idx != NumVRs) {
6732         // Doesn't have GPR space allocated.
6733         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6734       } else if (nAltivecParamsAtEnd==0) {
6735         // We are emitting Altivec params in order.
6736         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6737                          isPPC64, isTailCall, true, MemOpChains,
6738                          TailCallArguments, dl);
6739         ArgOffset += 16;
6740       }
6741       break;
6742     }
6743   }
6744   // If all Altivec parameters fit in registers, as they usually do,
6745   // they get stack space following the non-Altivec parameters.  We
6746   // don't track this here because nobody below needs it.
6747   // If there are more Altivec parameters than fit in registers emit
6748   // the stores here.
6749   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6750     unsigned j = 0;
6751     // Offset is aligned; skip 1st 12 params which go in V registers.
6752     ArgOffset = ((ArgOffset+15)/16)*16;
6753     ArgOffset += 12*16;
6754     for (unsigned i = 0; i != NumOps; ++i) {
6755       SDValue Arg = OutVals[i];
6756       EVT ArgType = Outs[i].VT;
6757       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6758           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6759         if (++j > NumVRs) {
6760           SDValue PtrOff;
6761           // We are emitting Altivec params in order.
6762           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6763                            isPPC64, isTailCall, true, MemOpChains,
6764                            TailCallArguments, dl);
6765           ArgOffset += 16;
6766         }
6767       }
6768     }
6769   }
6770 
6771   if (!MemOpChains.empty())
6772     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6773 
6774   // On Darwin, R12 must contain the address of an indirect callee.  This does
6775   // not mean the MTCTR instruction must use R12; it's easier to model this as
6776   // an extra parameter, so do that.
6777   if (!isTailCall &&
6778       !isFunctionGlobalAddress(Callee) &&
6779       !isa<ExternalSymbolSDNode>(Callee) &&
6780       !isBLACompatibleAddress(Callee, DAG))
6781     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6782                                                    PPC::R12), Callee));
6783 
6784   // Build a sequence of copy-to-reg nodes chained together with token chain
6785   // and flag operands which copy the outgoing args into the appropriate regs.
6786   SDValue InFlag;
6787   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6788     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6789                              RegsToPass[i].second, InFlag);
6790     InFlag = Chain.getValue(1);
6791   }
6792 
6793   if (isTailCall)
6794     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6795                     TailCallArguments);
6796 
6797   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6798                     /* unused except on PPC64 ELFv1 */ false, DAG,
6799                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6800                     NumBytes, Ins, InVals, CS);
6801 }
6802 
6803 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6804                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6805                    CCState &State) {
6806 
6807   if (ValVT == MVT::f128)
6808     report_fatal_error("f128 is unimplemented on AIX.");
6809 
6810   if (ArgFlags.isByVal())
6811     report_fatal_error("Passing structure by value is unimplemented.");
6812 
6813   if (ArgFlags.isSRet())
6814     report_fatal_error("Struct return arguments are unimplemented.");
6815 
6816   if (ArgFlags.isNest())
6817     report_fatal_error("Nest arguments are unimplemented.");
6818 
6819   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6820       State.getMachineFunction().getSubtarget());
6821   const bool IsPPC64 = Subtarget.isPPC64();
6822   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6823 
6824   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6825                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6826                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6827   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6828                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6829                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6830 
6831   // Arguments always reserve parameter save area.
6832   switch (ValVT.SimpleTy) {
6833   default:
6834     report_fatal_error("Unhandled value type for argument.");
6835   case MVT::i64:
6836     // i64 arguments should have been split to i32 for PPC32.
6837     assert(IsPPC64 && "PPC32 should have split i64 values.");
6838     LLVM_FALLTHROUGH;
6839   case MVT::i1:
6840   case MVT::i32:
6841     State.AllocateStack(PtrByteSize, PtrByteSize);
6842     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6843       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6844       // Promote integers if needed.
6845       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6846         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6847                                     : CCValAssign::LocInfo::ZExt;
6848       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6849     }
6850     else
6851       report_fatal_error("Handling of placing parameters on the stack is "
6852                          "unimplemented!");
6853     return false;
6854 
6855   case MVT::f32:
6856   case MVT::f64: {
6857     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6858     const unsigned StoreSize = LocVT.getStoreSize();
6859     // Floats are always 4-byte aligned in the PSA on AIX.
6860     // This includes f64 in 64-bit mode for ABI compatibility.
6861     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6862     if (unsigned Reg = State.AllocateReg(FPR))
6863       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo));
6864     else
6865       report_fatal_error("Handling of placing parameters on the stack is "
6866                          "unimplemented!");
6867 
6868     // f32 reserves 1 GPR in both PPC32 and PPC64.
6869     // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64.
6870     for (unsigned i = 0; i < StoreSize; i += PtrByteSize)
6871       State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32);
6872     return false;
6873   }
6874   }
6875 }
6876 
6877 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6878                                                     bool IsPPC64) {
6879   assert((IsPPC64 || SVT != MVT::i64) &&
6880          "i64 should have been split for 32-bit codegen.");
6881 
6882   switch (SVT) {
6883   default:
6884     report_fatal_error("Unexpected value type for formal argument");
6885   case MVT::i1:
6886   case MVT::i32:
6887   case MVT::i64:
6888     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6889   case MVT::f32:
6890     return &PPC::F4RCRegClass;
6891   case MVT::f64:
6892     return &PPC::F8RCRegClass;
6893   }
6894 }
6895 
6896 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6897                                         SelectionDAG &DAG, SDValue ArgValue,
6898                                         MVT LocVT, const SDLoc &dl) {
6899   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6900   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6901 
6902   if (Flags.isSExt())
6903     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6904                            DAG.getValueType(ValVT));
6905   else if (Flags.isZExt())
6906     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6907                            DAG.getValueType(ValVT));
6908 
6909   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6910 }
6911 
6912 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6913     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6914     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6915     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6916 
6917   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6918           CallConv == CallingConv::Fast) &&
6919          "Unexpected calling convention!");
6920 
6921   if (isVarArg)
6922     report_fatal_error("This call type is unimplemented on AIX.");
6923 
6924   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6925     report_fatal_error("Tail call support is unimplemented on AIX.");
6926 
6927   if (useSoftFloat())
6928     report_fatal_error("Soft float support is unimplemented on AIX.");
6929 
6930   const PPCSubtarget &Subtarget =
6931       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6932   if (Subtarget.hasQPX())
6933     report_fatal_error("QPX support is not supported on AIX.");
6934 
6935   const bool IsPPC64 = Subtarget.isPPC64();
6936   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6937 
6938   // Assign locations to all of the incoming arguments.
6939   SmallVector<CCValAssign, 16> ArgLocs;
6940   MachineFunction &MF = DAG.getMachineFunction();
6941   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6942 
6943   // Reserve space for the linkage area on the stack.
6944   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6945   // On AIX a minimum of 8 words is saved to the parameter save area.
6946   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6947   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6948   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6949 
6950   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6951     CCValAssign &VA = ArgLocs[i];
6952     SDValue ArgValue;
6953     ISD::ArgFlagsTy Flags = Ins[i].Flags;
6954     if (VA.isRegLoc()) {
6955       EVT ValVT = VA.getValVT();
6956       MVT LocVT = VA.getLocVT();
6957       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6958       unsigned VReg =
6959           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6960       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6961       if (ValVT.isScalarInteger() &&
6962           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
6963         ArgValue =
6964             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6965       }
6966       InVals.push_back(ArgValue);
6967     } else {
6968       report_fatal_error("Handling of formal arguments on the stack is "
6969                          "unimplemented!");
6970     }
6971   }
6972 
6973   // Area that is at least reserved in the caller of this function.
6974   unsigned MinReservedArea = CCInfo.getNextStackOffset();
6975 
6976   // Set the size that is at least reserved in caller of this function. Tail
6977   // call optimized function's reserved stack space needs to be aligned so
6978   // that taking the difference between two stack areas will result in an
6979   // aligned stack.
6980   MinReservedArea =
6981       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
6982   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6983   FuncInfo->setMinReservedArea(MinReservedArea);
6984 
6985   return Chain;
6986 }
6987 
6988 SDValue PPCTargetLowering::LowerCall_AIX(
6989     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6990     bool isTailCall, bool isPatchPoint,
6991     const SmallVectorImpl<ISD::OutputArg> &Outs,
6992     const SmallVectorImpl<SDValue> &OutVals,
6993     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6994     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6995     ImmutableCallSite CS) const {
6996 
6997   assert((CallConv == CallingConv::C ||
6998           CallConv == CallingConv::Cold ||
6999           CallConv == CallingConv::Fast) && "Unexpected calling convention!");
7000 
7001   if (isVarArg || isPatchPoint)
7002     report_fatal_error("This call type is unimplemented on AIX.");
7003 
7004   const PPCSubtarget& Subtarget =
7005       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
7006   if (Subtarget.hasQPX())
7007     report_fatal_error("QPX is not supported on AIX.");
7008   if (Subtarget.hasAltivec())
7009     report_fatal_error("Altivec support is unimplemented on AIX.");
7010 
7011   MachineFunction &MF = DAG.getMachineFunction();
7012   SmallVector<CCValAssign, 16> ArgLocs;
7013   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
7014 
7015   // Reserve space for the linkage save area (LSA) on the stack.
7016   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
7017   //   [SP][CR][LR][2 x reserved][TOC].
7018   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
7019   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
7020   const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4;
7021   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
7022   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
7023 
7024   // The prolog code of the callee may store up to 8 GPR argument registers to
7025   // the stack, allowing va_start to index over them in memory if the callee
7026   // is variadic.
7027   // Because we cannot tell if this is needed on the caller side, we have to
7028   // conservatively assume that it is needed.  As such, make sure we have at
7029   // least enough stack space for the caller to store the 8 GPRs.
7030   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
7031   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
7032 
7033   // Adjust the stack pointer for the new arguments...
7034   // These operations are automatically eliminated by the prolog/epilog pass.
7035   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
7036   SDValue CallSeqStart = Chain;
7037 
7038   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7039 
7040   for (CCValAssign &VA : ArgLocs) {
7041     SDValue Arg = OutVals[VA.getValNo()];
7042 
7043     switch (VA.getLocInfo()) {
7044     default: report_fatal_error("Unexpected argument extension type.");
7045     case CCValAssign::Full: break;
7046     case CCValAssign::ZExt:
7047       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7048       break;
7049     case CCValAssign::SExt:
7050       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7051       break;
7052     }
7053 
7054     if (VA.isRegLoc())
7055       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7056 
7057     if (VA.isMemLoc())
7058       report_fatal_error("Handling of placing parameters on the stack is "
7059                          "unimplemented!");
7060   }
7061 
7062   // For indirect calls, we need to save the TOC base to the stack for
7063   // restoration after the call.
7064   if (!isTailCall && !isPatchPoint &&
7065       !isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee)) {
7066     const MCRegister TOCBaseReg = Subtarget.getTOCPointerRegister();
7067     const MCRegister StackPtrReg = Subtarget.getStackPointerRegister();
7068     const MVT PtrVT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
7069     const unsigned TOCSaveOffset =
7070         Subtarget.getFrameLowering()->getTOCSaveOffset();
7071 
7072     setUsesTOCBasePtr(DAG);
7073     SDValue Val = DAG.getCopyFromReg(Chain, dl, TOCBaseReg, PtrVT);
7074     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
7075     SDValue StackPtr = DAG.getRegister(StackPtrReg, PtrVT);
7076     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
7077     Chain = DAG.getStore(
7078         Val.getValue(1), dl, Val, AddPtr,
7079         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
7080   }
7081 
7082   // Build a sequence of copy-to-reg nodes chained together with token chain
7083   // and flag operands which copy the outgoing args into the appropriate regs.
7084   SDValue InFlag;
7085   for (auto Reg : RegsToPass) {
7086     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7087     InFlag = Chain.getValue(1);
7088   }
7089 
7090   const int SPDiff = 0;
7091   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
7092                     /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass,
7093                     InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins,
7094                     InVals, CS);
7095 }
7096 
7097 bool
7098 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7099                                   MachineFunction &MF, bool isVarArg,
7100                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7101                                   LLVMContext &Context) const {
7102   SmallVector<CCValAssign, 16> RVLocs;
7103   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7104   return CCInfo.CheckReturn(
7105       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7106                 ? RetCC_PPC_Cold
7107                 : RetCC_PPC);
7108 }
7109 
7110 SDValue
7111 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7112                                bool isVarArg,
7113                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7114                                const SmallVectorImpl<SDValue> &OutVals,
7115                                const SDLoc &dl, SelectionDAG &DAG) const {
7116   SmallVector<CCValAssign, 16> RVLocs;
7117   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7118                  *DAG.getContext());
7119   CCInfo.AnalyzeReturn(Outs,
7120                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7121                            ? RetCC_PPC_Cold
7122                            : RetCC_PPC);
7123 
7124   SDValue Flag;
7125   SmallVector<SDValue, 4> RetOps(1, Chain);
7126 
7127   // Copy the result values into the output registers.
7128   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7129     CCValAssign &VA = RVLocs[i];
7130     assert(VA.isRegLoc() && "Can only return in registers!");
7131 
7132     SDValue Arg = OutVals[RealResIdx];
7133 
7134     switch (VA.getLocInfo()) {
7135     default: llvm_unreachable("Unknown loc info!");
7136     case CCValAssign::Full: break;
7137     case CCValAssign::AExt:
7138       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7139       break;
7140     case CCValAssign::ZExt:
7141       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7142       break;
7143     case CCValAssign::SExt:
7144       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7145       break;
7146     }
7147     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7148       bool isLittleEndian = Subtarget.isLittleEndian();
7149       // Legalize ret f64 -> ret 2 x i32.
7150       SDValue SVal =
7151           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7152                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7153       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7154       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7155       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7156                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7157       Flag = Chain.getValue(1);
7158       VA = RVLocs[++i]; // skip ahead to next loc
7159       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7160     } else
7161       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7162     Flag = Chain.getValue(1);
7163     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7164   }
7165 
7166   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7167   const MCPhysReg *I =
7168     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7169   if (I) {
7170     for (; *I; ++I) {
7171 
7172       if (PPC::G8RCRegClass.contains(*I))
7173         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7174       else if (PPC::F8RCRegClass.contains(*I))
7175         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7176       else if (PPC::CRRCRegClass.contains(*I))
7177         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7178       else if (PPC::VRRCRegClass.contains(*I))
7179         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7180       else
7181         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7182     }
7183   }
7184 
7185   RetOps[0] = Chain;  // Update chain.
7186 
7187   // Add the flag if we have it.
7188   if (Flag.getNode())
7189     RetOps.push_back(Flag);
7190 
7191   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7192 }
7193 
7194 SDValue
7195 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7196                                                 SelectionDAG &DAG) const {
7197   SDLoc dl(Op);
7198 
7199   // Get the correct type for integers.
7200   EVT IntVT = Op.getValueType();
7201 
7202   // Get the inputs.
7203   SDValue Chain = Op.getOperand(0);
7204   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7205   // Build a DYNAREAOFFSET node.
7206   SDValue Ops[2] = {Chain, FPSIdx};
7207   SDVTList VTs = DAG.getVTList(IntVT);
7208   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7209 }
7210 
7211 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7212                                              SelectionDAG &DAG) const {
7213   // When we pop the dynamic allocation we need to restore the SP link.
7214   SDLoc dl(Op);
7215 
7216   // Get the correct type for pointers.
7217   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7218 
7219   // Construct the stack pointer operand.
7220   bool isPPC64 = Subtarget.isPPC64();
7221   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7222   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7223 
7224   // Get the operands for the STACKRESTORE.
7225   SDValue Chain = Op.getOperand(0);
7226   SDValue SaveSP = Op.getOperand(1);
7227 
7228   // Load the old link SP.
7229   SDValue LoadLinkSP =
7230       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7231 
7232   // Restore the stack pointer.
7233   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7234 
7235   // Store the old link SP.
7236   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7237 }
7238 
7239 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7240   MachineFunction &MF = DAG.getMachineFunction();
7241   bool isPPC64 = Subtarget.isPPC64();
7242   EVT PtrVT = getPointerTy(MF.getDataLayout());
7243 
7244   // Get current frame pointer save index.  The users of this index will be
7245   // primarily DYNALLOC instructions.
7246   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7247   int RASI = FI->getReturnAddrSaveIndex();
7248 
7249   // If the frame pointer save index hasn't been defined yet.
7250   if (!RASI) {
7251     // Find out what the fix offset of the frame pointer save area.
7252     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7253     // Allocate the frame index for frame pointer save area.
7254     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7255     // Save the result.
7256     FI->setReturnAddrSaveIndex(RASI);
7257   }
7258   return DAG.getFrameIndex(RASI, PtrVT);
7259 }
7260 
7261 SDValue
7262 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7263   MachineFunction &MF = DAG.getMachineFunction();
7264   bool isPPC64 = Subtarget.isPPC64();
7265   EVT PtrVT = getPointerTy(MF.getDataLayout());
7266 
7267   // Get current frame pointer save index.  The users of this index will be
7268   // primarily DYNALLOC instructions.
7269   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7270   int FPSI = FI->getFramePointerSaveIndex();
7271 
7272   // If the frame pointer save index hasn't been defined yet.
7273   if (!FPSI) {
7274     // Find out what the fix offset of the frame pointer save area.
7275     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7276     // Allocate the frame index for frame pointer save area.
7277     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7278     // Save the result.
7279     FI->setFramePointerSaveIndex(FPSI);
7280   }
7281   return DAG.getFrameIndex(FPSI, PtrVT);
7282 }
7283 
7284 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7285                                                    SelectionDAG &DAG) const {
7286   // Get the inputs.
7287   SDValue Chain = Op.getOperand(0);
7288   SDValue Size  = Op.getOperand(1);
7289   SDLoc dl(Op);
7290 
7291   // Get the correct type for pointers.
7292   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7293   // Negate the size.
7294   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7295                                 DAG.getConstant(0, dl, PtrVT), Size);
7296   // Construct a node for the frame pointer save index.
7297   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7298   // Build a DYNALLOC node.
7299   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7300   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7301   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7302 }
7303 
7304 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7305                                                      SelectionDAG &DAG) const {
7306   MachineFunction &MF = DAG.getMachineFunction();
7307 
7308   bool isPPC64 = Subtarget.isPPC64();
7309   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7310 
7311   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7312   return DAG.getFrameIndex(FI, PtrVT);
7313 }
7314 
7315 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7316                                                SelectionDAG &DAG) const {
7317   SDLoc DL(Op);
7318   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7319                      DAG.getVTList(MVT::i32, MVT::Other),
7320                      Op.getOperand(0), Op.getOperand(1));
7321 }
7322 
7323 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7324                                                 SelectionDAG &DAG) const {
7325   SDLoc DL(Op);
7326   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7327                      Op.getOperand(0), Op.getOperand(1));
7328 }
7329 
7330 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7331   if (Op.getValueType().isVector())
7332     return LowerVectorLoad(Op, DAG);
7333 
7334   assert(Op.getValueType() == MVT::i1 &&
7335          "Custom lowering only for i1 loads");
7336 
7337   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7338 
7339   SDLoc dl(Op);
7340   LoadSDNode *LD = cast<LoadSDNode>(Op);
7341 
7342   SDValue Chain = LD->getChain();
7343   SDValue BasePtr = LD->getBasePtr();
7344   MachineMemOperand *MMO = LD->getMemOperand();
7345 
7346   SDValue NewLD =
7347       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7348                      BasePtr, MVT::i8, MMO);
7349   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7350 
7351   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7352   return DAG.getMergeValues(Ops, dl);
7353 }
7354 
7355 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7356   if (Op.getOperand(1).getValueType().isVector())
7357     return LowerVectorStore(Op, DAG);
7358 
7359   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7360          "Custom lowering only for i1 stores");
7361 
7362   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7363 
7364   SDLoc dl(Op);
7365   StoreSDNode *ST = cast<StoreSDNode>(Op);
7366 
7367   SDValue Chain = ST->getChain();
7368   SDValue BasePtr = ST->getBasePtr();
7369   SDValue Value = ST->getValue();
7370   MachineMemOperand *MMO = ST->getMemOperand();
7371 
7372   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7373                       Value);
7374   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7375 }
7376 
7377 // FIXME: Remove this once the ANDI glue bug is fixed:
7378 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7379   assert(Op.getValueType() == MVT::i1 &&
7380          "Custom lowering only for i1 results");
7381 
7382   SDLoc DL(Op);
7383   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7384                      Op.getOperand(0));
7385 }
7386 
7387 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7388                                                SelectionDAG &DAG) const {
7389 
7390   // Implements a vector truncate that fits in a vector register as a shuffle.
7391   // We want to legalize vector truncates down to where the source fits in
7392   // a vector register (and target is therefore smaller than vector register
7393   // size).  At that point legalization will try to custom lower the sub-legal
7394   // result and get here - where we can contain the truncate as a single target
7395   // operation.
7396 
7397   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7398   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7399   //
7400   // We will implement it for big-endian ordering as this (where x denotes
7401   // undefined):
7402   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7403   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7404   //
7405   // The same operation in little-endian ordering will be:
7406   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7407   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7408 
7409   assert(Op.getValueType().isVector() && "Vector type expected.");
7410 
7411   SDLoc DL(Op);
7412   SDValue N1 = Op.getOperand(0);
7413   unsigned SrcSize = N1.getValueType().getSizeInBits();
7414   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7415   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7416 
7417   EVT TrgVT = Op.getValueType();
7418   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7419   EVT EltVT = TrgVT.getVectorElementType();
7420   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7421   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7422 
7423   // First list the elements we want to keep.
7424   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7425   SmallVector<int, 16> ShuffV;
7426   if (Subtarget.isLittleEndian())
7427     for (unsigned i = 0; i < TrgNumElts; ++i)
7428       ShuffV.push_back(i * SizeMult);
7429   else
7430     for (unsigned i = 1; i <= TrgNumElts; ++i)
7431       ShuffV.push_back(i * SizeMult - 1);
7432 
7433   // Populate the remaining elements with undefs.
7434   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7435     // ShuffV.push_back(i + WideNumElts);
7436     ShuffV.push_back(WideNumElts + 1);
7437 
7438   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7439   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7440 }
7441 
7442 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7443 /// possible.
7444 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7445   // Not FP? Not a fsel.
7446   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7447       !Op.getOperand(2).getValueType().isFloatingPoint())
7448     return Op;
7449 
7450   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7451   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7452   // We might be able to do better than this under some circumstances, but in
7453   // general, fsel-based lowering of select is a finite-math-only optimization.
7454   // For more information, see section F.3 of the 2.06 ISA specification.
7455   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7456   // presence of infinities.
7457   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7458     return Op;
7459   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7460 
7461   EVT ResVT = Op.getValueType();
7462   EVT CmpVT = Op.getOperand(0).getValueType();
7463   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7464   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7465   SDLoc dl(Op);
7466 
7467   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7468     switch (CC) {
7469     default:
7470       // Not a min/max but with finite math, we may still be able to use fsel.
7471       if (HasNoInfs && HasNoNaNs)
7472         break;
7473       return Op;
7474     case ISD::SETOGT:
7475     case ISD::SETGT:
7476       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7477     case ISD::SETOLT:
7478     case ISD::SETLT:
7479       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7480     }
7481   }
7482 
7483   // TODO: Propagate flags from the select rather than global settings.
7484   SDNodeFlags Flags;
7485   Flags.setNoInfs(true);
7486   Flags.setNoNaNs(true);
7487 
7488   // If the RHS of the comparison is a 0.0, we don't need to do the
7489   // subtraction at all.
7490   SDValue Sel1;
7491   if (isFloatingPointZero(RHS))
7492     switch (CC) {
7493     default: break;       // SETUO etc aren't handled by fsel.
7494     case ISD::SETNE:
7495       std::swap(TV, FV);
7496       LLVM_FALLTHROUGH;
7497     case ISD::SETEQ:
7498       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7499         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7500       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7501       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7502         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7503       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7504                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7505     case ISD::SETULT:
7506     case ISD::SETLT:
7507       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7508       LLVM_FALLTHROUGH;
7509     case ISD::SETOGE:
7510     case ISD::SETGE:
7511       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7512         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7513       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7514     case ISD::SETUGT:
7515     case ISD::SETGT:
7516       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7517       LLVM_FALLTHROUGH;
7518     case ISD::SETOLE:
7519     case ISD::SETLE:
7520       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7521         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7522       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7523                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7524     }
7525 
7526   SDValue Cmp;
7527   switch (CC) {
7528   default: break;       // SETUO etc aren't handled by fsel.
7529   case ISD::SETNE:
7530     std::swap(TV, FV);
7531     LLVM_FALLTHROUGH;
7532   case ISD::SETEQ:
7533     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7534     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7535       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7536     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7537     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7538       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7539     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7540                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7541   case ISD::SETULT:
7542   case ISD::SETLT:
7543     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7544     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7545       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7546     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7547   case ISD::SETOGE:
7548   case ISD::SETGE:
7549     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7550     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7551       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7552     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7553   case ISD::SETUGT:
7554   case ISD::SETGT:
7555     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7556     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7557       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7558     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7559   case ISD::SETOLE:
7560   case ISD::SETLE:
7561     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7562     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7563       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7564     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7565   }
7566   return Op;
7567 }
7568 
7569 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7570                                                SelectionDAG &DAG,
7571                                                const SDLoc &dl) const {
7572   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7573   SDValue Src = Op.getOperand(0);
7574   if (Src.getValueType() == MVT::f32)
7575     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7576 
7577   SDValue Tmp;
7578   switch (Op.getSimpleValueType().SimpleTy) {
7579   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7580   case MVT::i32:
7581     Tmp = DAG.getNode(
7582         Op.getOpcode() == ISD::FP_TO_SINT
7583             ? PPCISD::FCTIWZ
7584             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7585         dl, MVT::f64, Src);
7586     break;
7587   case MVT::i64:
7588     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7589            "i64 FP_TO_UINT is supported only with FPCVT");
7590     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7591                                                         PPCISD::FCTIDUZ,
7592                       dl, MVT::f64, Src);
7593     break;
7594   }
7595 
7596   // Convert the FP value to an int value through memory.
7597   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7598     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7599   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7600   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7601   MachinePointerInfo MPI =
7602       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7603 
7604   // Emit a store to the stack slot.
7605   SDValue Chain;
7606   if (i32Stack) {
7607     MachineFunction &MF = DAG.getMachineFunction();
7608     MachineMemOperand *MMO =
7609       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7610     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7611     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7612               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7613   } else
7614     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7615 
7616   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7617   // add in a bias on big endian.
7618   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7619     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7620                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7621     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7622   }
7623 
7624   RLI.Chain = Chain;
7625   RLI.Ptr = FIPtr;
7626   RLI.MPI = MPI;
7627 }
7628 
7629 /// Custom lowers floating point to integer conversions to use
7630 /// the direct move instructions available in ISA 2.07 to avoid the
7631 /// need for load/store combinations.
7632 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7633                                                     SelectionDAG &DAG,
7634                                                     const SDLoc &dl) const {
7635   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7636   SDValue Src = Op.getOperand(0);
7637 
7638   if (Src.getValueType() == MVT::f32)
7639     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7640 
7641   SDValue Tmp;
7642   switch (Op.getSimpleValueType().SimpleTy) {
7643   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7644   case MVT::i32:
7645     Tmp = DAG.getNode(
7646         Op.getOpcode() == ISD::FP_TO_SINT
7647             ? PPCISD::FCTIWZ
7648             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7649         dl, MVT::f64, Src);
7650     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7651     break;
7652   case MVT::i64:
7653     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7654            "i64 FP_TO_UINT is supported only with FPCVT");
7655     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7656                                                         PPCISD::FCTIDUZ,
7657                       dl, MVT::f64, Src);
7658     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7659     break;
7660   }
7661   return Tmp;
7662 }
7663 
7664 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7665                                           const SDLoc &dl) const {
7666 
7667   // FP to INT conversions are legal for f128.
7668   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7669     return Op;
7670 
7671   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7672   // PPC (the libcall is not available).
7673   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7674     if (Op.getValueType() == MVT::i32) {
7675       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7676         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7677                                  MVT::f64, Op.getOperand(0),
7678                                  DAG.getIntPtrConstant(0, dl));
7679         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7680                                  MVT::f64, Op.getOperand(0),
7681                                  DAG.getIntPtrConstant(1, dl));
7682 
7683         // Add the two halves of the long double in round-to-zero mode.
7684         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7685 
7686         // Now use a smaller FP_TO_SINT.
7687         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7688       }
7689       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7690         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7691         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7692         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7693         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7694         // FIXME: generated code sucks.
7695         // TODO: Are there fast-math-flags to propagate to this FSUB?
7696         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7697                                    Op.getOperand(0), Tmp);
7698         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7699         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7700                            DAG.getConstant(0x80000000, dl, MVT::i32));
7701         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7702                                     Op.getOperand(0));
7703         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7704                                ISD::SETGE);
7705       }
7706     }
7707 
7708     return SDValue();
7709   }
7710 
7711   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7712     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7713 
7714   ReuseLoadInfo RLI;
7715   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7716 
7717   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7718                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7719 }
7720 
7721 // We're trying to insert a regular store, S, and then a load, L. If the
7722 // incoming value, O, is a load, we might just be able to have our load use the
7723 // address used by O. However, we don't know if anything else will store to
7724 // that address before we can load from it. To prevent this situation, we need
7725 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7726 // the same chain operand as O, we create a token factor from the chain results
7727 // of O and L, and we replace all uses of O's chain result with that token
7728 // factor (see spliceIntoChain below for this last part).
7729 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7730                                             ReuseLoadInfo &RLI,
7731                                             SelectionDAG &DAG,
7732                                             ISD::LoadExtType ET) const {
7733   SDLoc dl(Op);
7734   if (ET == ISD::NON_EXTLOAD &&
7735       (Op.getOpcode() == ISD::FP_TO_UINT ||
7736        Op.getOpcode() == ISD::FP_TO_SINT) &&
7737       isOperationLegalOrCustom(Op.getOpcode(),
7738                                Op.getOperand(0).getValueType())) {
7739 
7740     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7741     return true;
7742   }
7743 
7744   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7745   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7746       LD->isNonTemporal())
7747     return false;
7748   if (LD->getMemoryVT() != MemVT)
7749     return false;
7750 
7751   RLI.Ptr = LD->getBasePtr();
7752   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7753     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7754            "Non-pre-inc AM on PPC?");
7755     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7756                           LD->getOffset());
7757   }
7758 
7759   RLI.Chain = LD->getChain();
7760   RLI.MPI = LD->getPointerInfo();
7761   RLI.IsDereferenceable = LD->isDereferenceable();
7762   RLI.IsInvariant = LD->isInvariant();
7763   RLI.Alignment = LD->getAlignment();
7764   RLI.AAInfo = LD->getAAInfo();
7765   RLI.Ranges = LD->getRanges();
7766 
7767   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7768   return true;
7769 }
7770 
7771 // Given the head of the old chain, ResChain, insert a token factor containing
7772 // it and NewResChain, and make users of ResChain now be users of that token
7773 // factor.
7774 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7775 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7776                                         SDValue NewResChain,
7777                                         SelectionDAG &DAG) const {
7778   if (!ResChain)
7779     return;
7780 
7781   SDLoc dl(NewResChain);
7782 
7783   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7784                            NewResChain, DAG.getUNDEF(MVT::Other));
7785   assert(TF.getNode() != NewResChain.getNode() &&
7786          "A new TF really is required here");
7787 
7788   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7789   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7790 }
7791 
7792 /// Analyze profitability of direct move
7793 /// prefer float load to int load plus direct move
7794 /// when there is no integer use of int load
7795 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7796   SDNode *Origin = Op.getOperand(0).getNode();
7797   if (Origin->getOpcode() != ISD::LOAD)
7798     return true;
7799 
7800   // If there is no LXSIBZX/LXSIHZX, like Power8,
7801   // prefer direct move if the memory size is 1 or 2 bytes.
7802   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7803   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7804     return true;
7805 
7806   for (SDNode::use_iterator UI = Origin->use_begin(),
7807                             UE = Origin->use_end();
7808        UI != UE; ++UI) {
7809 
7810     // Only look at the users of the loaded value.
7811     if (UI.getUse().get().getResNo() != 0)
7812       continue;
7813 
7814     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7815         UI->getOpcode() != ISD::UINT_TO_FP)
7816       return true;
7817   }
7818 
7819   return false;
7820 }
7821 
7822 /// Custom lowers integer to floating point conversions to use
7823 /// the direct move instructions available in ISA 2.07 to avoid the
7824 /// need for load/store combinations.
7825 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7826                                                     SelectionDAG &DAG,
7827                                                     const SDLoc &dl) const {
7828   assert((Op.getValueType() == MVT::f32 ||
7829           Op.getValueType() == MVT::f64) &&
7830          "Invalid floating point type as target of conversion");
7831   assert(Subtarget.hasFPCVT() &&
7832          "Int to FP conversions with direct moves require FPCVT");
7833   SDValue FP;
7834   SDValue Src = Op.getOperand(0);
7835   bool SinglePrec = Op.getValueType() == MVT::f32;
7836   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7837   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7838   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7839                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7840 
7841   if (WordInt) {
7842     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7843                      dl, MVT::f64, Src);
7844     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7845   }
7846   else {
7847     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7848     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7849   }
7850 
7851   return FP;
7852 }
7853 
7854 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7855 
7856   EVT VecVT = Vec.getValueType();
7857   assert(VecVT.isVector() && "Expected a vector type.");
7858   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7859 
7860   EVT EltVT = VecVT.getVectorElementType();
7861   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7862   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7863 
7864   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7865   SmallVector<SDValue, 16> Ops(NumConcat);
7866   Ops[0] = Vec;
7867   SDValue UndefVec = DAG.getUNDEF(VecVT);
7868   for (unsigned i = 1; i < NumConcat; ++i)
7869     Ops[i] = UndefVec;
7870 
7871   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7872 }
7873 
7874 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7875                                                 const SDLoc &dl) const {
7876 
7877   unsigned Opc = Op.getOpcode();
7878   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7879          "Unexpected conversion type");
7880   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7881          "Supports conversions to v2f64/v4f32 only.");
7882 
7883   bool SignedConv = Opc == ISD::SINT_TO_FP;
7884   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7885 
7886   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7887   EVT WideVT = Wide.getValueType();
7888   unsigned WideNumElts = WideVT.getVectorNumElements();
7889   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7890 
7891   SmallVector<int, 16> ShuffV;
7892   for (unsigned i = 0; i < WideNumElts; ++i)
7893     ShuffV.push_back(i + WideNumElts);
7894 
7895   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7896   int SaveElts = FourEltRes ? 4 : 2;
7897   if (Subtarget.isLittleEndian())
7898     for (int i = 0; i < SaveElts; i++)
7899       ShuffV[i * Stride] = i;
7900   else
7901     for (int i = 1; i <= SaveElts; i++)
7902       ShuffV[i * Stride - 1] = i - 1;
7903 
7904   SDValue ShuffleSrc2 =
7905       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7906   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7907   unsigned ExtendOp =
7908       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7909 
7910   SDValue Extend;
7911   if (!Subtarget.hasP9Altivec() && SignedConv) {
7912     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7913     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7914                          DAG.getValueType(Op.getOperand(0).getValueType()));
7915   } else
7916     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7917 
7918   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7919 }
7920 
7921 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7922                                           SelectionDAG &DAG) const {
7923   SDLoc dl(Op);
7924 
7925   EVT InVT = Op.getOperand(0).getValueType();
7926   EVT OutVT = Op.getValueType();
7927   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7928       isOperationCustom(Op.getOpcode(), InVT))
7929     return LowerINT_TO_FPVector(Op, DAG, dl);
7930 
7931   // Conversions to f128 are legal.
7932   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7933     return Op;
7934 
7935   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7936     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7937       return SDValue();
7938 
7939     SDValue Value = Op.getOperand(0);
7940     // The values are now known to be -1 (false) or 1 (true). To convert this
7941     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7942     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7943     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7944 
7945     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7946 
7947     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7948 
7949     if (Op.getValueType() != MVT::v4f64)
7950       Value = DAG.getNode(ISD::FP_ROUND, dl,
7951                           Op.getValueType(), Value,
7952                           DAG.getIntPtrConstant(1, dl));
7953     return Value;
7954   }
7955 
7956   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7957   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7958     return SDValue();
7959 
7960   if (Op.getOperand(0).getValueType() == MVT::i1)
7961     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7962                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7963                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7964 
7965   // If we have direct moves, we can do all the conversion, skip the store/load
7966   // however, without FPCVT we can't do most conversions.
7967   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7968       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7969     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7970 
7971   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7972          "UINT_TO_FP is supported only with FPCVT");
7973 
7974   // If we have FCFIDS, then use it when converting to single-precision.
7975   // Otherwise, convert to double-precision and then round.
7976   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7977                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7978                                                             : PPCISD::FCFIDS)
7979                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7980                                                             : PPCISD::FCFID);
7981   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7982                   ? MVT::f32
7983                   : MVT::f64;
7984 
7985   if (Op.getOperand(0).getValueType() == MVT::i64) {
7986     SDValue SINT = Op.getOperand(0);
7987     // When converting to single-precision, we actually need to convert
7988     // to double-precision first and then round to single-precision.
7989     // To avoid double-rounding effects during that operation, we have
7990     // to prepare the input operand.  Bits that might be truncated when
7991     // converting to double-precision are replaced by a bit that won't
7992     // be lost at this stage, but is below the single-precision rounding
7993     // position.
7994     //
7995     // However, if -enable-unsafe-fp-math is in effect, accept double
7996     // rounding to avoid the extra overhead.
7997     if (Op.getValueType() == MVT::f32 &&
7998         !Subtarget.hasFPCVT() &&
7999         !DAG.getTarget().Options.UnsafeFPMath) {
8000 
8001       // Twiddle input to make sure the low 11 bits are zero.  (If this
8002       // is the case, we are guaranteed the value will fit into the 53 bit
8003       // mantissa of an IEEE double-precision value without rounding.)
8004       // If any of those low 11 bits were not zero originally, make sure
8005       // bit 12 (value 2048) is set instead, so that the final rounding
8006       // to single-precision gets the correct result.
8007       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8008                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
8009       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
8010                           Round, DAG.getConstant(2047, dl, MVT::i64));
8011       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
8012       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
8013                           Round, DAG.getConstant(-2048, dl, MVT::i64));
8014 
8015       // However, we cannot use that value unconditionally: if the magnitude
8016       // of the input value is small, the bit-twiddling we did above might
8017       // end up visibly changing the output.  Fortunately, in that case, we
8018       // don't need to twiddle bits since the original input will convert
8019       // exactly to double-precision floating-point already.  Therefore,
8020       // construct a conditional to use the original value if the top 11
8021       // bits are all sign-bit copies, and use the rounded value computed
8022       // above otherwise.
8023       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
8024                                  SINT, DAG.getConstant(53, dl, MVT::i32));
8025       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
8026                          Cond, DAG.getConstant(1, dl, MVT::i64));
8027       Cond = DAG.getSetCC(dl, MVT::i32,
8028                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
8029 
8030       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
8031     }
8032 
8033     ReuseLoadInfo RLI;
8034     SDValue Bits;
8035 
8036     MachineFunction &MF = DAG.getMachineFunction();
8037     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
8038       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
8039                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
8040       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8041     } else if (Subtarget.hasLFIWAX() &&
8042                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
8043       MachineMemOperand *MMO =
8044         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8045                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8046       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8047       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
8048                                      DAG.getVTList(MVT::f64, MVT::Other),
8049                                      Ops, MVT::i32, MMO);
8050       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8051     } else if (Subtarget.hasFPCVT() &&
8052                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
8053       MachineMemOperand *MMO =
8054         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8055                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8056       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8057       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8058                                      DAG.getVTList(MVT::f64, MVT::Other),
8059                                      Ops, MVT::i32, MMO);
8060       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8061     } else if (((Subtarget.hasLFIWAX() &&
8062                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8063                 (Subtarget.hasFPCVT() &&
8064                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8065                SINT.getOperand(0).getValueType() == MVT::i32) {
8066       MachineFrameInfo &MFI = MF.getFrameInfo();
8067       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8068 
8069       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8070       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8071 
8072       SDValue Store =
8073           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8074                        MachinePointerInfo::getFixedStack(
8075                            DAG.getMachineFunction(), FrameIdx));
8076 
8077       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8078              "Expected an i32 store");
8079 
8080       RLI.Ptr = FIdx;
8081       RLI.Chain = Store;
8082       RLI.MPI =
8083           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8084       RLI.Alignment = 4;
8085 
8086       MachineMemOperand *MMO =
8087         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8088                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8089       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8090       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8091                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8092                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8093                                      Ops, MVT::i32, MMO);
8094     } else
8095       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8096 
8097     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8098 
8099     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8100       FP = DAG.getNode(ISD::FP_ROUND, dl,
8101                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8102     return FP;
8103   }
8104 
8105   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8106          "Unhandled INT_TO_FP type in custom expander!");
8107   // Since we only generate this in 64-bit mode, we can take advantage of
8108   // 64-bit registers.  In particular, sign extend the input value into the
8109   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8110   // then lfd it and fcfid it.
8111   MachineFunction &MF = DAG.getMachineFunction();
8112   MachineFrameInfo &MFI = MF.getFrameInfo();
8113   EVT PtrVT = getPointerTy(MF.getDataLayout());
8114 
8115   SDValue Ld;
8116   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8117     ReuseLoadInfo RLI;
8118     bool ReusingLoad;
8119     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8120                                             DAG))) {
8121       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8122       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8123 
8124       SDValue Store =
8125           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8126                        MachinePointerInfo::getFixedStack(
8127                            DAG.getMachineFunction(), FrameIdx));
8128 
8129       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8130              "Expected an i32 store");
8131 
8132       RLI.Ptr = FIdx;
8133       RLI.Chain = Store;
8134       RLI.MPI =
8135           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8136       RLI.Alignment = 4;
8137     }
8138 
8139     MachineMemOperand *MMO =
8140       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8141                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8142     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8143     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8144                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8145                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8146                                  Ops, MVT::i32, MMO);
8147     if (ReusingLoad)
8148       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8149   } else {
8150     assert(Subtarget.isPPC64() &&
8151            "i32->FP without LFIWAX supported only on PPC64");
8152 
8153     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8154     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8155 
8156     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8157                                 Op.getOperand(0));
8158 
8159     // STD the extended value into the stack slot.
8160     SDValue Store = DAG.getStore(
8161         DAG.getEntryNode(), dl, Ext64, FIdx,
8162         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8163 
8164     // Load the value as a double.
8165     Ld = DAG.getLoad(
8166         MVT::f64, dl, Store, FIdx,
8167         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8168   }
8169 
8170   // FCFID it and return it.
8171   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8172   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8173     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8174                      DAG.getIntPtrConstant(0, dl));
8175   return FP;
8176 }
8177 
8178 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8179                                             SelectionDAG &DAG) const {
8180   SDLoc dl(Op);
8181   /*
8182    The rounding mode is in bits 30:31 of FPSR, and has the following
8183    settings:
8184      00 Round to nearest
8185      01 Round to 0
8186      10 Round to +inf
8187      11 Round to -inf
8188 
8189   FLT_ROUNDS, on the other hand, expects the following:
8190     -1 Undefined
8191      0 Round to 0
8192      1 Round to nearest
8193      2 Round to +inf
8194      3 Round to -inf
8195 
8196   To perform the conversion, we do:
8197     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8198   */
8199 
8200   MachineFunction &MF = DAG.getMachineFunction();
8201   EVT VT = Op.getValueType();
8202   EVT PtrVT = getPointerTy(MF.getDataLayout());
8203 
8204   // Save FP Control Word to register
8205   EVT NodeTys[] = {
8206     MVT::f64,    // return register
8207     MVT::Glue    // unused in this context
8208   };
8209   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8210 
8211   // Save FP register to stack slot
8212   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8213   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8214   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8215                                MachinePointerInfo());
8216 
8217   // Load FP Control Word from low 32 bits of stack slot.
8218   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8219   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8220   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8221 
8222   // Transform as necessary
8223   SDValue CWD1 =
8224     DAG.getNode(ISD::AND, dl, MVT::i32,
8225                 CWD, DAG.getConstant(3, dl, MVT::i32));
8226   SDValue CWD2 =
8227     DAG.getNode(ISD::SRL, dl, MVT::i32,
8228                 DAG.getNode(ISD::AND, dl, MVT::i32,
8229                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8230                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8231                             DAG.getConstant(3, dl, MVT::i32)),
8232                 DAG.getConstant(1, dl, MVT::i32));
8233 
8234   SDValue RetVal =
8235     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8236 
8237   return DAG.getNode((VT.getSizeInBits() < 16 ?
8238                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8239 }
8240 
8241 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8242   EVT VT = Op.getValueType();
8243   unsigned BitWidth = VT.getSizeInBits();
8244   SDLoc dl(Op);
8245   assert(Op.getNumOperands() == 3 &&
8246          VT == Op.getOperand(1).getValueType() &&
8247          "Unexpected SHL!");
8248 
8249   // Expand into a bunch of logical ops.  Note that these ops
8250   // depend on the PPC behavior for oversized shift amounts.
8251   SDValue Lo = Op.getOperand(0);
8252   SDValue Hi = Op.getOperand(1);
8253   SDValue Amt = Op.getOperand(2);
8254   EVT AmtVT = Amt.getValueType();
8255 
8256   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8257                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8258   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8259   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8260   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8261   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8262                              DAG.getConstant(-BitWidth, dl, AmtVT));
8263   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8264   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8265   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8266   SDValue OutOps[] = { OutLo, OutHi };
8267   return DAG.getMergeValues(OutOps, dl);
8268 }
8269 
8270 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8271   EVT VT = Op.getValueType();
8272   SDLoc dl(Op);
8273   unsigned BitWidth = VT.getSizeInBits();
8274   assert(Op.getNumOperands() == 3 &&
8275          VT == Op.getOperand(1).getValueType() &&
8276          "Unexpected SRL!");
8277 
8278   // Expand into a bunch of logical ops.  Note that these ops
8279   // depend on the PPC behavior for oversized shift amounts.
8280   SDValue Lo = Op.getOperand(0);
8281   SDValue Hi = Op.getOperand(1);
8282   SDValue Amt = Op.getOperand(2);
8283   EVT AmtVT = Amt.getValueType();
8284 
8285   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8286                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8287   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8288   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8289   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8290   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8291                              DAG.getConstant(-BitWidth, dl, AmtVT));
8292   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8293   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8294   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8295   SDValue OutOps[] = { OutLo, OutHi };
8296   return DAG.getMergeValues(OutOps, dl);
8297 }
8298 
8299 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8300   SDLoc dl(Op);
8301   EVT VT = Op.getValueType();
8302   unsigned BitWidth = VT.getSizeInBits();
8303   assert(Op.getNumOperands() == 3 &&
8304          VT == Op.getOperand(1).getValueType() &&
8305          "Unexpected SRA!");
8306 
8307   // Expand into a bunch of logical ops, followed by a select_cc.
8308   SDValue Lo = Op.getOperand(0);
8309   SDValue Hi = Op.getOperand(1);
8310   SDValue Amt = Op.getOperand(2);
8311   EVT AmtVT = Amt.getValueType();
8312 
8313   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8314                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8315   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8316   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8317   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8318   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8319                              DAG.getConstant(-BitWidth, dl, AmtVT));
8320   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
8321   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8322   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8323                                   Tmp4, Tmp6, ISD::SETLE);
8324   SDValue OutOps[] = { OutLo, OutHi };
8325   return DAG.getMergeValues(OutOps, dl);
8326 }
8327 
8328 //===----------------------------------------------------------------------===//
8329 // Vector related lowering.
8330 //
8331 
8332 /// BuildSplatI - Build a canonical splati of Val with an element size of
8333 /// SplatSize.  Cast the result to VT.
8334 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8335                            SelectionDAG &DAG, const SDLoc &dl) {
8336   static const MVT VTys[] = { // canonical VT to use for each size.
8337     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8338   };
8339 
8340   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8341 
8342   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8343   if (Val == -1)
8344     SplatSize = 1;
8345 
8346   EVT CanonicalVT = VTys[SplatSize-1];
8347 
8348   // Build a canonical splat for this value.
8349   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8350 }
8351 
8352 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8353 /// specified intrinsic ID.
8354 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8355                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8356   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8357   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8358                      DAG.getConstant(IID, dl, MVT::i32), Op);
8359 }
8360 
8361 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8362 /// specified intrinsic ID.
8363 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8364                                 SelectionDAG &DAG, const SDLoc &dl,
8365                                 EVT DestVT = MVT::Other) {
8366   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8367   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8368                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8369 }
8370 
8371 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8372 /// specified intrinsic ID.
8373 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8374                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8375                                 EVT DestVT = MVT::Other) {
8376   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8377   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8378                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8379 }
8380 
8381 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8382 /// amount.  The result has the specified value type.
8383 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8384                            SelectionDAG &DAG, const SDLoc &dl) {
8385   // Force LHS/RHS to be the right type.
8386   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8387   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8388 
8389   int Ops[16];
8390   for (unsigned i = 0; i != 16; ++i)
8391     Ops[i] = i + Amt;
8392   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8393   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8394 }
8395 
8396 /// Do we have an efficient pattern in a .td file for this node?
8397 ///
8398 /// \param V - pointer to the BuildVectorSDNode being matched
8399 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8400 ///
8401 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8402 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8403 /// the opposite is true (expansion is beneficial) are:
8404 /// - The node builds a vector out of integers that are not 32 or 64-bits
8405 /// - The node builds a vector out of constants
8406 /// - The node is a "load-and-splat"
8407 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8408 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8409                                             bool HasDirectMove,
8410                                             bool HasP8Vector) {
8411   EVT VecVT = V->getValueType(0);
8412   bool RightType = VecVT == MVT::v2f64 ||
8413     (HasP8Vector && VecVT == MVT::v4f32) ||
8414     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8415   if (!RightType)
8416     return false;
8417 
8418   bool IsSplat = true;
8419   bool IsLoad = false;
8420   SDValue Op0 = V->getOperand(0);
8421 
8422   // This function is called in a block that confirms the node is not a constant
8423   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8424   // different constants.
8425   if (V->isConstant())
8426     return false;
8427   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8428     if (V->getOperand(i).isUndef())
8429       return false;
8430     // We want to expand nodes that represent load-and-splat even if the
8431     // loaded value is a floating point truncation or conversion to int.
8432     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8433         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8434          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8435         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8436          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8437         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8438          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8439       IsLoad = true;
8440     // If the operands are different or the input is not a load and has more
8441     // uses than just this BV node, then it isn't a splat.
8442     if (V->getOperand(i) != Op0 ||
8443         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8444       IsSplat = false;
8445   }
8446   return !(IsSplat && IsLoad);
8447 }
8448 
8449 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8450 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8451 
8452   SDLoc dl(Op);
8453   SDValue Op0 = Op->getOperand(0);
8454 
8455   if (!EnableQuadPrecision ||
8456       (Op.getValueType() != MVT::f128 ) ||
8457       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8458       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8459       (Op0.getOperand(1).getValueType() != MVT::i64))
8460     return SDValue();
8461 
8462   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8463                      Op0.getOperand(1));
8464 }
8465 
8466 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8467   const SDValue *InputLoad = &Op;
8468   if (InputLoad->getOpcode() == ISD::BITCAST)
8469     InputLoad = &InputLoad->getOperand(0);
8470   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8471     InputLoad = &InputLoad->getOperand(0);
8472   if (InputLoad->getOpcode() != ISD::LOAD)
8473     return nullptr;
8474   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8475   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8476 }
8477 
8478 // If this is a case we can't handle, return null and let the default
8479 // expansion code take care of it.  If we CAN select this case, and if it
8480 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8481 // this case more efficiently than a constant pool load, lower it to the
8482 // sequence of ops that should be used.
8483 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8484                                              SelectionDAG &DAG) const {
8485   SDLoc dl(Op);
8486   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8487   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8488 
8489   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8490     // We first build an i32 vector, load it into a QPX register,
8491     // then convert it to a floating-point vector and compare it
8492     // to a zero vector to get the boolean result.
8493     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8494     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8495     MachinePointerInfo PtrInfo =
8496         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8497     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8498     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8499 
8500     assert(BVN->getNumOperands() == 4 &&
8501       "BUILD_VECTOR for v4i1 does not have 4 operands");
8502 
8503     bool IsConst = true;
8504     for (unsigned i = 0; i < 4; ++i) {
8505       if (BVN->getOperand(i).isUndef()) continue;
8506       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8507         IsConst = false;
8508         break;
8509       }
8510     }
8511 
8512     if (IsConst) {
8513       Constant *One =
8514         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8515       Constant *NegOne =
8516         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8517 
8518       Constant *CV[4];
8519       for (unsigned i = 0; i < 4; ++i) {
8520         if (BVN->getOperand(i).isUndef())
8521           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8522         else if (isNullConstant(BVN->getOperand(i)))
8523           CV[i] = NegOne;
8524         else
8525           CV[i] = One;
8526       }
8527 
8528       Constant *CP = ConstantVector::get(CV);
8529       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8530                                           16 /* alignment */);
8531 
8532       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8533       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8534       return DAG.getMemIntrinsicNode(
8535           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8536           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8537     }
8538 
8539     SmallVector<SDValue, 4> Stores;
8540     for (unsigned i = 0; i < 4; ++i) {
8541       if (BVN->getOperand(i).isUndef()) continue;
8542 
8543       unsigned Offset = 4*i;
8544       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8545       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8546 
8547       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8548       if (StoreSize > 4) {
8549         Stores.push_back(
8550             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8551                               PtrInfo.getWithOffset(Offset), MVT::i32));
8552       } else {
8553         SDValue StoreValue = BVN->getOperand(i);
8554         if (StoreSize < 4)
8555           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8556 
8557         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8558                                       PtrInfo.getWithOffset(Offset)));
8559       }
8560     }
8561 
8562     SDValue StoreChain;
8563     if (!Stores.empty())
8564       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8565     else
8566       StoreChain = DAG.getEntryNode();
8567 
8568     // Now load from v4i32 into the QPX register; this will extend it to
8569     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8570     // is typed as v4f64 because the QPX register integer states are not
8571     // explicitly represented.
8572 
8573     SDValue Ops[] = {StoreChain,
8574                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8575                      FIdx};
8576     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8577 
8578     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8579       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8580     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8581       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8582       LoadedVect);
8583 
8584     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8585 
8586     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8587   }
8588 
8589   // All other QPX vectors are handled by generic code.
8590   if (Subtarget.hasQPX())
8591     return SDValue();
8592 
8593   // Check if this is a splat of a constant value.
8594   APInt APSplatBits, APSplatUndef;
8595   unsigned SplatBitSize;
8596   bool HasAnyUndefs;
8597   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8598                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8599       SplatBitSize > 32) {
8600 
8601     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8602     // Handle load-and-splat patterns as we have instructions that will do this
8603     // in one go.
8604     if (InputLoad && DAG.isSplatValue(Op, true)) {
8605       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8606 
8607       // We have handling for 4 and 8 byte elements.
8608       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8609 
8610       // Checking for a single use of this load, we have to check for vector
8611       // width (128 bits) / ElementSize uses (since each operand of the
8612       // BUILD_VECTOR is a separate use of the value.
8613       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8614           ((Subtarget.hasVSX() && ElementSize == 64) ||
8615            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8616         SDValue Ops[] = {
8617           LD->getChain(),    // Chain
8618           LD->getBasePtr(),  // Ptr
8619           DAG.getValueType(Op.getValueType()) // VT
8620         };
8621         return
8622           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8623                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8624                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8625       }
8626     }
8627 
8628     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8629     // lowered to VSX instructions under certain conditions.
8630     // Without VSX, there is no pattern more efficient than expanding the node.
8631     if (Subtarget.hasVSX() &&
8632         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8633                                         Subtarget.hasP8Vector()))
8634       return Op;
8635     return SDValue();
8636   }
8637 
8638   unsigned SplatBits = APSplatBits.getZExtValue();
8639   unsigned SplatUndef = APSplatUndef.getZExtValue();
8640   unsigned SplatSize = SplatBitSize / 8;
8641 
8642   // First, handle single instruction cases.
8643 
8644   // All zeros?
8645   if (SplatBits == 0) {
8646     // Canonicalize all zero vectors to be v4i32.
8647     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8648       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8649       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8650     }
8651     return Op;
8652   }
8653 
8654   // We have XXSPLTIB for constant splats one byte wide
8655   // FIXME: SplatBits is an unsigned int being cast to an int while passing it
8656   // as an argument to BuildSplatiI. Given SplatSize == 1 it is okay here.
8657   if (Subtarget.hasP9Vector() && SplatSize == 1)
8658     return BuildSplatI(SplatBits, SplatSize, Op.getValueType(), DAG, dl);
8659 
8660   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8661   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8662                     (32-SplatBitSize));
8663   if (SextVal >= -16 && SextVal <= 15)
8664     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8665 
8666   // Two instruction sequences.
8667 
8668   // If this value is in the range [-32,30] and is even, use:
8669   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8670   // If this value is in the range [17,31] and is odd, use:
8671   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8672   // If this value is in the range [-31,-17] and is odd, use:
8673   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8674   // Note the last two are three-instruction sequences.
8675   if (SextVal >= -32 && SextVal <= 31) {
8676     // To avoid having these optimizations undone by constant folding,
8677     // we convert to a pseudo that will be expanded later into one of
8678     // the above forms.
8679     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8680     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8681               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8682     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8683     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8684     if (VT == Op.getValueType())
8685       return RetVal;
8686     else
8687       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8688   }
8689 
8690   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8691   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8692   // for fneg/fabs.
8693   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8694     // Make -1 and vspltisw -1:
8695     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8696 
8697     // Make the VSLW intrinsic, computing 0x8000_0000.
8698     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8699                                    OnesV, DAG, dl);
8700 
8701     // xor by OnesV to invert it.
8702     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8703     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8704   }
8705 
8706   // Check to see if this is a wide variety of vsplti*, binop self cases.
8707   static const signed char SplatCsts[] = {
8708     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8709     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8710   };
8711 
8712   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8713     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8714     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8715     int i = SplatCsts[idx];
8716 
8717     // Figure out what shift amount will be used by altivec if shifted by i in
8718     // this splat size.
8719     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8720 
8721     // vsplti + shl self.
8722     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8723       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8724       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8725         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8726         Intrinsic::ppc_altivec_vslw
8727       };
8728       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8729       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8730     }
8731 
8732     // vsplti + srl self.
8733     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8734       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8735       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8736         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8737         Intrinsic::ppc_altivec_vsrw
8738       };
8739       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8740       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8741     }
8742 
8743     // vsplti + sra self.
8744     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8745       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8746       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8747         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8748         Intrinsic::ppc_altivec_vsraw
8749       };
8750       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8751       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8752     }
8753 
8754     // vsplti + rol self.
8755     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8756                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8757       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8758       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8759         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8760         Intrinsic::ppc_altivec_vrlw
8761       };
8762       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8763       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8764     }
8765 
8766     // t = vsplti c, result = vsldoi t, t, 1
8767     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8768       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8769       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8770       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8771     }
8772     // t = vsplti c, result = vsldoi t, t, 2
8773     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8774       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8775       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8776       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8777     }
8778     // t = vsplti c, result = vsldoi t, t, 3
8779     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8780       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8781       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8782       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8783     }
8784   }
8785 
8786   return SDValue();
8787 }
8788 
8789 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8790 /// the specified operations to build the shuffle.
8791 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8792                                       SDValue RHS, SelectionDAG &DAG,
8793                                       const SDLoc &dl) {
8794   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8795   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8796   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8797 
8798   enum {
8799     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8800     OP_VMRGHW,
8801     OP_VMRGLW,
8802     OP_VSPLTISW0,
8803     OP_VSPLTISW1,
8804     OP_VSPLTISW2,
8805     OP_VSPLTISW3,
8806     OP_VSLDOI4,
8807     OP_VSLDOI8,
8808     OP_VSLDOI12
8809   };
8810 
8811   if (OpNum == OP_COPY) {
8812     if (LHSID == (1*9+2)*9+3) return LHS;
8813     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8814     return RHS;
8815   }
8816 
8817   SDValue OpLHS, OpRHS;
8818   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8819   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8820 
8821   int ShufIdxs[16];
8822   switch (OpNum) {
8823   default: llvm_unreachable("Unknown i32 permute!");
8824   case OP_VMRGHW:
8825     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8826     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8827     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8828     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8829     break;
8830   case OP_VMRGLW:
8831     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8832     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8833     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8834     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8835     break;
8836   case OP_VSPLTISW0:
8837     for (unsigned i = 0; i != 16; ++i)
8838       ShufIdxs[i] = (i&3)+0;
8839     break;
8840   case OP_VSPLTISW1:
8841     for (unsigned i = 0; i != 16; ++i)
8842       ShufIdxs[i] = (i&3)+4;
8843     break;
8844   case OP_VSPLTISW2:
8845     for (unsigned i = 0; i != 16; ++i)
8846       ShufIdxs[i] = (i&3)+8;
8847     break;
8848   case OP_VSPLTISW3:
8849     for (unsigned i = 0; i != 16; ++i)
8850       ShufIdxs[i] = (i&3)+12;
8851     break;
8852   case OP_VSLDOI4:
8853     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8854   case OP_VSLDOI8:
8855     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8856   case OP_VSLDOI12:
8857     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8858   }
8859   EVT VT = OpLHS.getValueType();
8860   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8861   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8862   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8863   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8864 }
8865 
8866 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8867 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8868 /// SDValue.
8869 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8870                                            SelectionDAG &DAG) const {
8871   const unsigned BytesInVector = 16;
8872   bool IsLE = Subtarget.isLittleEndian();
8873   SDLoc dl(N);
8874   SDValue V1 = N->getOperand(0);
8875   SDValue V2 = N->getOperand(1);
8876   unsigned ShiftElts = 0, InsertAtByte = 0;
8877   bool Swap = false;
8878 
8879   // Shifts required to get the byte we want at element 7.
8880   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8881                                    0, 15, 14, 13, 12, 11, 10, 9};
8882   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8883                                 1, 2,  3,  4,  5,  6,  7,  8};
8884 
8885   ArrayRef<int> Mask = N->getMask();
8886   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8887 
8888   // For each mask element, find out if we're just inserting something
8889   // from V2 into V1 or vice versa.
8890   // Possible permutations inserting an element from V2 into V1:
8891   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8892   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8893   //   ...
8894   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8895   // Inserting from V1 into V2 will be similar, except mask range will be
8896   // [16,31].
8897 
8898   bool FoundCandidate = false;
8899   // If both vector operands for the shuffle are the same vector, the mask
8900   // will contain only elements from the first one and the second one will be
8901   // undef.
8902   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8903   // Go through the mask of half-words to find an element that's being moved
8904   // from one vector to the other.
8905   for (unsigned i = 0; i < BytesInVector; ++i) {
8906     unsigned CurrentElement = Mask[i];
8907     // If 2nd operand is undefined, we should only look for element 7 in the
8908     // Mask.
8909     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8910       continue;
8911 
8912     bool OtherElementsInOrder = true;
8913     // Examine the other elements in the Mask to see if they're in original
8914     // order.
8915     for (unsigned j = 0; j < BytesInVector; ++j) {
8916       if (j == i)
8917         continue;
8918       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8919       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8920       // in which we always assume we're always picking from the 1st operand.
8921       int MaskOffset =
8922           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8923       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8924         OtherElementsInOrder = false;
8925         break;
8926       }
8927     }
8928     // If other elements are in original order, we record the number of shifts
8929     // we need to get the element we want into element 7. Also record which byte
8930     // in the vector we should insert into.
8931     if (OtherElementsInOrder) {
8932       // If 2nd operand is undefined, we assume no shifts and no swapping.
8933       if (V2.isUndef()) {
8934         ShiftElts = 0;
8935         Swap = false;
8936       } else {
8937         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8938         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8939                          : BigEndianShifts[CurrentElement & 0xF];
8940         Swap = CurrentElement < BytesInVector;
8941       }
8942       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8943       FoundCandidate = true;
8944       break;
8945     }
8946   }
8947 
8948   if (!FoundCandidate)
8949     return SDValue();
8950 
8951   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8952   // optionally with VECSHL if shift is required.
8953   if (Swap)
8954     std::swap(V1, V2);
8955   if (V2.isUndef())
8956     V2 = V1;
8957   if (ShiftElts) {
8958     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8959                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8960     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8961                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8962   }
8963   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8964                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8965 }
8966 
8967 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8968 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8969 /// SDValue.
8970 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8971                                            SelectionDAG &DAG) const {
8972   const unsigned NumHalfWords = 8;
8973   const unsigned BytesInVector = NumHalfWords * 2;
8974   // Check that the shuffle is on half-words.
8975   if (!isNByteElemShuffleMask(N, 2, 1))
8976     return SDValue();
8977 
8978   bool IsLE = Subtarget.isLittleEndian();
8979   SDLoc dl(N);
8980   SDValue V1 = N->getOperand(0);
8981   SDValue V2 = N->getOperand(1);
8982   unsigned ShiftElts = 0, InsertAtByte = 0;
8983   bool Swap = false;
8984 
8985   // Shifts required to get the half-word we want at element 3.
8986   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8987   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8988 
8989   uint32_t Mask = 0;
8990   uint32_t OriginalOrderLow = 0x1234567;
8991   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8992   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8993   // 32-bit space, only need 4-bit nibbles per element.
8994   for (unsigned i = 0; i < NumHalfWords; ++i) {
8995     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8996     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8997   }
8998 
8999   // For each mask element, find out if we're just inserting something
9000   // from V2 into V1 or vice versa.  Possible permutations inserting an element
9001   // from V2 into V1:
9002   //   X, 1, 2, 3, 4, 5, 6, 7
9003   //   0, X, 2, 3, 4, 5, 6, 7
9004   //   0, 1, X, 3, 4, 5, 6, 7
9005   //   0, 1, 2, X, 4, 5, 6, 7
9006   //   0, 1, 2, 3, X, 5, 6, 7
9007   //   0, 1, 2, 3, 4, X, 6, 7
9008   //   0, 1, 2, 3, 4, 5, X, 7
9009   //   0, 1, 2, 3, 4, 5, 6, X
9010   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
9011 
9012   bool FoundCandidate = false;
9013   // Go through the mask of half-words to find an element that's being moved
9014   // from one vector to the other.
9015   for (unsigned i = 0; i < NumHalfWords; ++i) {
9016     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
9017     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
9018     uint32_t MaskOtherElts = ~(0xF << MaskShift);
9019     uint32_t TargetOrder = 0x0;
9020 
9021     // If both vector operands for the shuffle are the same vector, the mask
9022     // will contain only elements from the first one and the second one will be
9023     // undef.
9024     if (V2.isUndef()) {
9025       ShiftElts = 0;
9026       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
9027       TargetOrder = OriginalOrderLow;
9028       Swap = false;
9029       // Skip if not the correct element or mask of other elements don't equal
9030       // to our expected order.
9031       if (MaskOneElt == VINSERTHSrcElem &&
9032           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9033         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9034         FoundCandidate = true;
9035         break;
9036       }
9037     } else { // If both operands are defined.
9038       // Target order is [8,15] if the current mask is between [0,7].
9039       TargetOrder =
9040           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9041       // Skip if mask of other elements don't equal our expected order.
9042       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9043         // We only need the last 3 bits for the number of shifts.
9044         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9045                          : BigEndianShifts[MaskOneElt & 0x7];
9046         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9047         Swap = MaskOneElt < NumHalfWords;
9048         FoundCandidate = true;
9049         break;
9050       }
9051     }
9052   }
9053 
9054   if (!FoundCandidate)
9055     return SDValue();
9056 
9057   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9058   // optionally with VECSHL if shift is required.
9059   if (Swap)
9060     std::swap(V1, V2);
9061   if (V2.isUndef())
9062     V2 = V1;
9063   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9064   if (ShiftElts) {
9065     // Double ShiftElts because we're left shifting on v16i8 type.
9066     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9067                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9068     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9069     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9070                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9071     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9072   }
9073   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9074   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9075                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9076   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9077 }
9078 
9079 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9080 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9081 /// return the code it can be lowered into.  Worst case, it can always be
9082 /// lowered into a vperm.
9083 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9084                                                SelectionDAG &DAG) const {
9085   SDLoc dl(Op);
9086   SDValue V1 = Op.getOperand(0);
9087   SDValue V2 = Op.getOperand(1);
9088   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9089   EVT VT = Op.getValueType();
9090   bool isLittleEndian = Subtarget.isLittleEndian();
9091 
9092   unsigned ShiftElts, InsertAtByte;
9093   bool Swap = false;
9094 
9095   // If this is a load-and-splat, we can do that with a single instruction
9096   // in some cases. However if the load has multiple uses, we don't want to
9097   // combine it because that will just produce multiple loads.
9098   const SDValue *InputLoad = getNormalLoadInput(V1);
9099   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9100       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9101       InputLoad->hasOneUse()) {
9102     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9103     int SplatIdx =
9104       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9105 
9106     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9107     // For 4-byte load-and-splat, we need Power9.
9108     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9109       uint64_t Offset = 0;
9110       if (IsFourByte)
9111         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9112       else
9113         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9114       SDValue BasePtr = LD->getBasePtr();
9115       if (Offset != 0)
9116         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9117                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9118       SDValue Ops[] = {
9119         LD->getChain(),    // Chain
9120         BasePtr,           // BasePtr
9121         DAG.getValueType(Op.getValueType()) // VT
9122       };
9123       SDVTList VTL =
9124         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9125       SDValue LdSplt =
9126         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9127                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9128       if (LdSplt.getValueType() != SVOp->getValueType(0))
9129         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9130       return LdSplt;
9131     }
9132   }
9133   if (Subtarget.hasP9Vector() &&
9134       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9135                            isLittleEndian)) {
9136     if (Swap)
9137       std::swap(V1, V2);
9138     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9139     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9140     if (ShiftElts) {
9141       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9142                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9143       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9144                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9145       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9146     }
9147     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9148                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9149     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9150   }
9151 
9152   if (Subtarget.hasP9Altivec()) {
9153     SDValue NewISDNode;
9154     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9155       return NewISDNode;
9156 
9157     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9158       return NewISDNode;
9159   }
9160 
9161   if (Subtarget.hasVSX() &&
9162       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9163     if (Swap)
9164       std::swap(V1, V2);
9165     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9166     SDValue Conv2 =
9167         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9168 
9169     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9170                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9171     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9172   }
9173 
9174   if (Subtarget.hasVSX() &&
9175     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9176     if (Swap)
9177       std::swap(V1, V2);
9178     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9179     SDValue Conv2 =
9180         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9181 
9182     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9183                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9184     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9185   }
9186 
9187   if (Subtarget.hasP9Vector()) {
9188      if (PPC::isXXBRHShuffleMask(SVOp)) {
9189       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9190       SDValue ReveHWord = DAG.getNode(ISD::BSWAP, dl, MVT::v8i16, Conv);
9191       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9192     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9193       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9194       SDValue ReveWord = DAG.getNode(ISD::BSWAP, dl, MVT::v4i32, Conv);
9195       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9196     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9197       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9198       SDValue ReveDWord = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Conv);
9199       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9200     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9201       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9202       SDValue ReveQWord = DAG.getNode(ISD::BSWAP, dl, MVT::v1i128, Conv);
9203       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9204     }
9205   }
9206 
9207   if (Subtarget.hasVSX()) {
9208     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9209       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9210 
9211       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9212       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9213                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9214       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9215     }
9216 
9217     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9218     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9219       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9220       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9221       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9222     }
9223   }
9224 
9225   if (Subtarget.hasQPX()) {
9226     if (VT.getVectorNumElements() != 4)
9227       return SDValue();
9228 
9229     if (V2.isUndef()) V2 = V1;
9230 
9231     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9232     if (AlignIdx != -1) {
9233       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9234                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9235     } else if (SVOp->isSplat()) {
9236       int SplatIdx = SVOp->getSplatIndex();
9237       if (SplatIdx >= 4) {
9238         std::swap(V1, V2);
9239         SplatIdx -= 4;
9240       }
9241 
9242       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9243                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9244     }
9245 
9246     // Lower this into a qvgpci/qvfperm pair.
9247 
9248     // Compute the qvgpci literal
9249     unsigned idx = 0;
9250     for (unsigned i = 0; i < 4; ++i) {
9251       int m = SVOp->getMaskElt(i);
9252       unsigned mm = m >= 0 ? (unsigned) m : i;
9253       idx |= mm << (3-i)*3;
9254     }
9255 
9256     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9257                              DAG.getConstant(idx, dl, MVT::i32));
9258     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9259   }
9260 
9261   // Cases that are handled by instructions that take permute immediates
9262   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9263   // selected by the instruction selector.
9264   if (V2.isUndef()) {
9265     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9266         PPC::isSplatShuffleMask(SVOp, 2) ||
9267         PPC::isSplatShuffleMask(SVOp, 4) ||
9268         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9269         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9270         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9271         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9272         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9273         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9274         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9275         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9276         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9277         (Subtarget.hasP8Altivec() && (
9278          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9279          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9280          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9281       return Op;
9282     }
9283   }
9284 
9285   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9286   // and produce a fixed permutation.  If any of these match, do not lower to
9287   // VPERM.
9288   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9289   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9290       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9291       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9292       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9293       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9294       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9295       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9296       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9297       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9298       (Subtarget.hasP8Altivec() && (
9299        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9300        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9301        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9302     return Op;
9303 
9304   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9305   // perfect shuffle table to emit an optimal matching sequence.
9306   ArrayRef<int> PermMask = SVOp->getMask();
9307 
9308   unsigned PFIndexes[4];
9309   bool isFourElementShuffle = true;
9310   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9311     unsigned EltNo = 8;   // Start out undef.
9312     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9313       if (PermMask[i*4+j] < 0)
9314         continue;   // Undef, ignore it.
9315 
9316       unsigned ByteSource = PermMask[i*4+j];
9317       if ((ByteSource & 3) != j) {
9318         isFourElementShuffle = false;
9319         break;
9320       }
9321 
9322       if (EltNo == 8) {
9323         EltNo = ByteSource/4;
9324       } else if (EltNo != ByteSource/4) {
9325         isFourElementShuffle = false;
9326         break;
9327       }
9328     }
9329     PFIndexes[i] = EltNo;
9330   }
9331 
9332   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9333   // perfect shuffle vector to determine if it is cost effective to do this as
9334   // discrete instructions, or whether we should use a vperm.
9335   // For now, we skip this for little endian until such time as we have a
9336   // little-endian perfect shuffle table.
9337   if (isFourElementShuffle && !isLittleEndian) {
9338     // Compute the index in the perfect shuffle table.
9339     unsigned PFTableIndex =
9340       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9341 
9342     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9343     unsigned Cost  = (PFEntry >> 30);
9344 
9345     // Determining when to avoid vperm is tricky.  Many things affect the cost
9346     // of vperm, particularly how many times the perm mask needs to be computed.
9347     // For example, if the perm mask can be hoisted out of a loop or is already
9348     // used (perhaps because there are multiple permutes with the same shuffle
9349     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9350     // the loop requires an extra register.
9351     //
9352     // As a compromise, we only emit discrete instructions if the shuffle can be
9353     // generated in 3 or fewer operations.  When we have loop information
9354     // available, if this block is within a loop, we should avoid using vperm
9355     // for 3-operation perms and use a constant pool load instead.
9356     if (Cost < 3)
9357       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9358   }
9359 
9360   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9361   // vector that will get spilled to the constant pool.
9362   if (V2.isUndef()) V2 = V1;
9363 
9364   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9365   // that it is in input element units, not in bytes.  Convert now.
9366 
9367   // For little endian, the order of the input vectors is reversed, and
9368   // the permutation mask is complemented with respect to 31.  This is
9369   // necessary to produce proper semantics with the big-endian-biased vperm
9370   // instruction.
9371   EVT EltVT = V1.getValueType().getVectorElementType();
9372   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9373 
9374   SmallVector<SDValue, 16> ResultMask;
9375   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9376     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9377 
9378     for (unsigned j = 0; j != BytesPerElement; ++j)
9379       if (isLittleEndian)
9380         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9381                                              dl, MVT::i32));
9382       else
9383         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9384                                              MVT::i32));
9385   }
9386 
9387   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9388   if (isLittleEndian)
9389     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9390                        V2, V1, VPermMask);
9391   else
9392     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9393                        V1, V2, VPermMask);
9394 }
9395 
9396 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9397 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9398 /// information about the intrinsic.
9399 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9400                                  bool &isDot, const PPCSubtarget &Subtarget) {
9401   unsigned IntrinsicID =
9402       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9403   CompareOpc = -1;
9404   isDot = false;
9405   switch (IntrinsicID) {
9406   default:
9407     return false;
9408   // Comparison predicates.
9409   case Intrinsic::ppc_altivec_vcmpbfp_p:
9410     CompareOpc = 966;
9411     isDot = true;
9412     break;
9413   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9414     CompareOpc = 198;
9415     isDot = true;
9416     break;
9417   case Intrinsic::ppc_altivec_vcmpequb_p:
9418     CompareOpc = 6;
9419     isDot = true;
9420     break;
9421   case Intrinsic::ppc_altivec_vcmpequh_p:
9422     CompareOpc = 70;
9423     isDot = true;
9424     break;
9425   case Intrinsic::ppc_altivec_vcmpequw_p:
9426     CompareOpc = 134;
9427     isDot = true;
9428     break;
9429   case Intrinsic::ppc_altivec_vcmpequd_p:
9430     if (Subtarget.hasP8Altivec()) {
9431       CompareOpc = 199;
9432       isDot = true;
9433     } else
9434       return false;
9435     break;
9436   case Intrinsic::ppc_altivec_vcmpneb_p:
9437   case Intrinsic::ppc_altivec_vcmpneh_p:
9438   case Intrinsic::ppc_altivec_vcmpnew_p:
9439   case Intrinsic::ppc_altivec_vcmpnezb_p:
9440   case Intrinsic::ppc_altivec_vcmpnezh_p:
9441   case Intrinsic::ppc_altivec_vcmpnezw_p:
9442     if (Subtarget.hasP9Altivec()) {
9443       switch (IntrinsicID) {
9444       default:
9445         llvm_unreachable("Unknown comparison intrinsic.");
9446       case Intrinsic::ppc_altivec_vcmpneb_p:
9447         CompareOpc = 7;
9448         break;
9449       case Intrinsic::ppc_altivec_vcmpneh_p:
9450         CompareOpc = 71;
9451         break;
9452       case Intrinsic::ppc_altivec_vcmpnew_p:
9453         CompareOpc = 135;
9454         break;
9455       case Intrinsic::ppc_altivec_vcmpnezb_p:
9456         CompareOpc = 263;
9457         break;
9458       case Intrinsic::ppc_altivec_vcmpnezh_p:
9459         CompareOpc = 327;
9460         break;
9461       case Intrinsic::ppc_altivec_vcmpnezw_p:
9462         CompareOpc = 391;
9463         break;
9464       }
9465       isDot = true;
9466     } else
9467       return false;
9468     break;
9469   case Intrinsic::ppc_altivec_vcmpgefp_p:
9470     CompareOpc = 454;
9471     isDot = true;
9472     break;
9473   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9474     CompareOpc = 710;
9475     isDot = true;
9476     break;
9477   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9478     CompareOpc = 774;
9479     isDot = true;
9480     break;
9481   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9482     CompareOpc = 838;
9483     isDot = true;
9484     break;
9485   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9486     CompareOpc = 902;
9487     isDot = true;
9488     break;
9489   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9490     if (Subtarget.hasP8Altivec()) {
9491       CompareOpc = 967;
9492       isDot = true;
9493     } else
9494       return false;
9495     break;
9496   case Intrinsic::ppc_altivec_vcmpgtub_p:
9497     CompareOpc = 518;
9498     isDot = true;
9499     break;
9500   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9501     CompareOpc = 582;
9502     isDot = true;
9503     break;
9504   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9505     CompareOpc = 646;
9506     isDot = true;
9507     break;
9508   case Intrinsic::ppc_altivec_vcmpgtud_p:
9509     if (Subtarget.hasP8Altivec()) {
9510       CompareOpc = 711;
9511       isDot = true;
9512     } else
9513       return false;
9514     break;
9515 
9516   // VSX predicate comparisons use the same infrastructure
9517   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9518   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9519   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9520   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9521   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9522   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9523     if (Subtarget.hasVSX()) {
9524       switch (IntrinsicID) {
9525       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9526         CompareOpc = 99;
9527         break;
9528       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9529         CompareOpc = 115;
9530         break;
9531       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9532         CompareOpc = 107;
9533         break;
9534       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9535         CompareOpc = 67;
9536         break;
9537       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9538         CompareOpc = 83;
9539         break;
9540       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9541         CompareOpc = 75;
9542         break;
9543       }
9544       isDot = true;
9545     } else
9546       return false;
9547     break;
9548 
9549   // Normal Comparisons.
9550   case Intrinsic::ppc_altivec_vcmpbfp:
9551     CompareOpc = 966;
9552     break;
9553   case Intrinsic::ppc_altivec_vcmpeqfp:
9554     CompareOpc = 198;
9555     break;
9556   case Intrinsic::ppc_altivec_vcmpequb:
9557     CompareOpc = 6;
9558     break;
9559   case Intrinsic::ppc_altivec_vcmpequh:
9560     CompareOpc = 70;
9561     break;
9562   case Intrinsic::ppc_altivec_vcmpequw:
9563     CompareOpc = 134;
9564     break;
9565   case Intrinsic::ppc_altivec_vcmpequd:
9566     if (Subtarget.hasP8Altivec())
9567       CompareOpc = 199;
9568     else
9569       return false;
9570     break;
9571   case Intrinsic::ppc_altivec_vcmpneb:
9572   case Intrinsic::ppc_altivec_vcmpneh:
9573   case Intrinsic::ppc_altivec_vcmpnew:
9574   case Intrinsic::ppc_altivec_vcmpnezb:
9575   case Intrinsic::ppc_altivec_vcmpnezh:
9576   case Intrinsic::ppc_altivec_vcmpnezw:
9577     if (Subtarget.hasP9Altivec())
9578       switch (IntrinsicID) {
9579       default:
9580         llvm_unreachable("Unknown comparison intrinsic.");
9581       case Intrinsic::ppc_altivec_vcmpneb:
9582         CompareOpc = 7;
9583         break;
9584       case Intrinsic::ppc_altivec_vcmpneh:
9585         CompareOpc = 71;
9586         break;
9587       case Intrinsic::ppc_altivec_vcmpnew:
9588         CompareOpc = 135;
9589         break;
9590       case Intrinsic::ppc_altivec_vcmpnezb:
9591         CompareOpc = 263;
9592         break;
9593       case Intrinsic::ppc_altivec_vcmpnezh:
9594         CompareOpc = 327;
9595         break;
9596       case Intrinsic::ppc_altivec_vcmpnezw:
9597         CompareOpc = 391;
9598         break;
9599       }
9600     else
9601       return false;
9602     break;
9603   case Intrinsic::ppc_altivec_vcmpgefp:
9604     CompareOpc = 454;
9605     break;
9606   case Intrinsic::ppc_altivec_vcmpgtfp:
9607     CompareOpc = 710;
9608     break;
9609   case Intrinsic::ppc_altivec_vcmpgtsb:
9610     CompareOpc = 774;
9611     break;
9612   case Intrinsic::ppc_altivec_vcmpgtsh:
9613     CompareOpc = 838;
9614     break;
9615   case Intrinsic::ppc_altivec_vcmpgtsw:
9616     CompareOpc = 902;
9617     break;
9618   case Intrinsic::ppc_altivec_vcmpgtsd:
9619     if (Subtarget.hasP8Altivec())
9620       CompareOpc = 967;
9621     else
9622       return false;
9623     break;
9624   case Intrinsic::ppc_altivec_vcmpgtub:
9625     CompareOpc = 518;
9626     break;
9627   case Intrinsic::ppc_altivec_vcmpgtuh:
9628     CompareOpc = 582;
9629     break;
9630   case Intrinsic::ppc_altivec_vcmpgtuw:
9631     CompareOpc = 646;
9632     break;
9633   case Intrinsic::ppc_altivec_vcmpgtud:
9634     if (Subtarget.hasP8Altivec())
9635       CompareOpc = 711;
9636     else
9637       return false;
9638     break;
9639   }
9640   return true;
9641 }
9642 
9643 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9644 /// lower, do it, otherwise return null.
9645 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9646                                                    SelectionDAG &DAG) const {
9647   unsigned IntrinsicID =
9648     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9649 
9650   SDLoc dl(Op);
9651 
9652   if (IntrinsicID == Intrinsic::thread_pointer) {
9653     // Reads the thread pointer register, used for __builtin_thread_pointer.
9654     if (Subtarget.isPPC64())
9655       return DAG.getRegister(PPC::X13, MVT::i64);
9656     return DAG.getRegister(PPC::R2, MVT::i32);
9657   }
9658 
9659   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9660   // opcode number of the comparison.
9661   int CompareOpc;
9662   bool isDot;
9663   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9664     return SDValue();    // Don't custom lower most intrinsics.
9665 
9666   // If this is a non-dot comparison, make the VCMP node and we are done.
9667   if (!isDot) {
9668     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9669                               Op.getOperand(1), Op.getOperand(2),
9670                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9671     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9672   }
9673 
9674   // Create the PPCISD altivec 'dot' comparison node.
9675   SDValue Ops[] = {
9676     Op.getOperand(2),  // LHS
9677     Op.getOperand(3),  // RHS
9678     DAG.getConstant(CompareOpc, dl, MVT::i32)
9679   };
9680   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9681   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9682 
9683   // Now that we have the comparison, emit a copy from the CR to a GPR.
9684   // This is flagged to the above dot comparison.
9685   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9686                                 DAG.getRegister(PPC::CR6, MVT::i32),
9687                                 CompNode.getValue(1));
9688 
9689   // Unpack the result based on how the target uses it.
9690   unsigned BitNo;   // Bit # of CR6.
9691   bool InvertBit;   // Invert result?
9692   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9693   default:  // Can't happen, don't crash on invalid number though.
9694   case 0:   // Return the value of the EQ bit of CR6.
9695     BitNo = 0; InvertBit = false;
9696     break;
9697   case 1:   // Return the inverted value of the EQ bit of CR6.
9698     BitNo = 0; InvertBit = true;
9699     break;
9700   case 2:   // Return the value of the LT bit of CR6.
9701     BitNo = 2; InvertBit = false;
9702     break;
9703   case 3:   // Return the inverted value of the LT bit of CR6.
9704     BitNo = 2; InvertBit = true;
9705     break;
9706   }
9707 
9708   // Shift the bit into the low position.
9709   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9710                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9711   // Isolate the bit.
9712   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9713                       DAG.getConstant(1, dl, MVT::i32));
9714 
9715   // If we are supposed to, toggle the bit.
9716   if (InvertBit)
9717     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9718                         DAG.getConstant(1, dl, MVT::i32));
9719   return Flags;
9720 }
9721 
9722 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9723                                                SelectionDAG &DAG) const {
9724   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9725   // the beginning of the argument list.
9726   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9727   SDLoc DL(Op);
9728   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9729   case Intrinsic::ppc_cfence: {
9730     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9731     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9732     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9733                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9734                                                   Op.getOperand(ArgStart + 1)),
9735                                       Op.getOperand(0)),
9736                    0);
9737   }
9738   default:
9739     break;
9740   }
9741   return SDValue();
9742 }
9743 
9744 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9745   // Check for a DIV with the same operands as this REM.
9746   for (auto UI : Op.getOperand(1)->uses()) {
9747     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9748         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9749       if (UI->getOperand(0) == Op.getOperand(0) &&
9750           UI->getOperand(1) == Op.getOperand(1))
9751         return SDValue();
9752   }
9753   return Op;
9754 }
9755 
9756 // Lower scalar BSWAP64 to xxbrd.
9757 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9758   SDLoc dl(Op);
9759   // MTVSRDD
9760   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9761                    Op.getOperand(0));
9762   // XXBRD
9763   Op = DAG.getNode(ISD::BSWAP, dl, MVT::v2i64, Op);
9764   // MFVSRD
9765   int VectorIndex = 0;
9766   if (Subtarget.isLittleEndian())
9767     VectorIndex = 1;
9768   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9769                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9770   return Op;
9771 }
9772 
9773 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9774 // compared to a value that is atomically loaded (atomic loads zero-extend).
9775 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9776                                                 SelectionDAG &DAG) const {
9777   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9778          "Expecting an atomic compare-and-swap here.");
9779   SDLoc dl(Op);
9780   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9781   EVT MemVT = AtomicNode->getMemoryVT();
9782   if (MemVT.getSizeInBits() >= 32)
9783     return Op;
9784 
9785   SDValue CmpOp = Op.getOperand(2);
9786   // If this is already correctly zero-extended, leave it alone.
9787   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9788   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9789     return Op;
9790 
9791   // Clear the high bits of the compare operand.
9792   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9793   SDValue NewCmpOp =
9794     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9795                 DAG.getConstant(MaskVal, dl, MVT::i32));
9796 
9797   // Replace the existing compare operand with the properly zero-extended one.
9798   SmallVector<SDValue, 4> Ops;
9799   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9800     Ops.push_back(AtomicNode->getOperand(i));
9801   Ops[2] = NewCmpOp;
9802   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9803   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9804   auto NodeTy =
9805     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9806   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9807 }
9808 
9809 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9810                                                  SelectionDAG &DAG) const {
9811   SDLoc dl(Op);
9812   // Create a stack slot that is 16-byte aligned.
9813   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9814   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9815   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9816   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9817 
9818   // Store the input value into Value#0 of the stack slot.
9819   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9820                                MachinePointerInfo());
9821   // Load it out.
9822   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9823 }
9824 
9825 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9826                                                   SelectionDAG &DAG) const {
9827   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9828          "Should only be called for ISD::INSERT_VECTOR_ELT");
9829 
9830   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9831   // We have legal lowering for constant indices but not for variable ones.
9832   if (!C)
9833     return SDValue();
9834 
9835   EVT VT = Op.getValueType();
9836   SDLoc dl(Op);
9837   SDValue V1 = Op.getOperand(0);
9838   SDValue V2 = Op.getOperand(1);
9839   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9840   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9841     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9842     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9843     unsigned InsertAtElement = C->getZExtValue();
9844     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9845     if (Subtarget.isLittleEndian()) {
9846       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9847     }
9848     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9849                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9850   }
9851   return Op;
9852 }
9853 
9854 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9855                                                    SelectionDAG &DAG) const {
9856   SDLoc dl(Op);
9857   SDNode *N = Op.getNode();
9858 
9859   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9860          "Unknown extract_vector_elt type");
9861 
9862   SDValue Value = N->getOperand(0);
9863 
9864   // The first part of this is like the store lowering except that we don't
9865   // need to track the chain.
9866 
9867   // The values are now known to be -1 (false) or 1 (true). To convert this
9868   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9869   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9870   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9871 
9872   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9873   // understand how to form the extending load.
9874   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9875 
9876   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9877 
9878   // Now convert to an integer and store.
9879   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9880     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9881     Value);
9882 
9883   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9884   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9885   MachinePointerInfo PtrInfo =
9886       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9887   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9888   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9889 
9890   SDValue StoreChain = DAG.getEntryNode();
9891   SDValue Ops[] = {StoreChain,
9892                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9893                    Value, FIdx};
9894   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9895 
9896   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9897     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9898 
9899   // Extract the value requested.
9900   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9901   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9902   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9903 
9904   SDValue IntVal =
9905       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9906 
9907   if (!Subtarget.useCRBits())
9908     return IntVal;
9909 
9910   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9911 }
9912 
9913 /// Lowering for QPX v4i1 loads
9914 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9915                                            SelectionDAG &DAG) const {
9916   SDLoc dl(Op);
9917   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9918   SDValue LoadChain = LN->getChain();
9919   SDValue BasePtr = LN->getBasePtr();
9920 
9921   if (Op.getValueType() == MVT::v4f64 ||
9922       Op.getValueType() == MVT::v4f32) {
9923     EVT MemVT = LN->getMemoryVT();
9924     unsigned Alignment = LN->getAlignment();
9925 
9926     // If this load is properly aligned, then it is legal.
9927     if (Alignment >= MemVT.getStoreSize())
9928       return Op;
9929 
9930     EVT ScalarVT = Op.getValueType().getScalarType(),
9931         ScalarMemVT = MemVT.getScalarType();
9932     unsigned Stride = ScalarMemVT.getStoreSize();
9933 
9934     SDValue Vals[4], LoadChains[4];
9935     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9936       SDValue Load;
9937       if (ScalarVT != ScalarMemVT)
9938         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9939                               BasePtr,
9940                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9941                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9942                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9943       else
9944         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9945                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9946                            MinAlign(Alignment, Idx * Stride),
9947                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9948 
9949       if (Idx == 0 && LN->isIndexed()) {
9950         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9951                "Unknown addressing mode on vector load");
9952         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9953                                   LN->getAddressingMode());
9954       }
9955 
9956       Vals[Idx] = Load;
9957       LoadChains[Idx] = Load.getValue(1);
9958 
9959       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9960                             DAG.getConstant(Stride, dl,
9961                                             BasePtr.getValueType()));
9962     }
9963 
9964     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9965     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9966 
9967     if (LN->isIndexed()) {
9968       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9969       return DAG.getMergeValues(RetOps, dl);
9970     }
9971 
9972     SDValue RetOps[] = { Value, TF };
9973     return DAG.getMergeValues(RetOps, dl);
9974   }
9975 
9976   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9977   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9978 
9979   // To lower v4i1 from a byte array, we load the byte elements of the
9980   // vector and then reuse the BUILD_VECTOR logic.
9981 
9982   SDValue VectElmts[4], VectElmtChains[4];
9983   for (unsigned i = 0; i < 4; ++i) {
9984     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9985     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9986 
9987     VectElmts[i] = DAG.getExtLoad(
9988         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9989         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9990         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9991     VectElmtChains[i] = VectElmts[i].getValue(1);
9992   }
9993 
9994   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9995   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9996 
9997   SDValue RVals[] = { Value, LoadChain };
9998   return DAG.getMergeValues(RVals, dl);
9999 }
10000 
10001 /// Lowering for QPX v4i1 stores
10002 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
10003                                             SelectionDAG &DAG) const {
10004   SDLoc dl(Op);
10005   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
10006   SDValue StoreChain = SN->getChain();
10007   SDValue BasePtr = SN->getBasePtr();
10008   SDValue Value = SN->getValue();
10009 
10010   if (Value.getValueType() == MVT::v4f64 ||
10011       Value.getValueType() == MVT::v4f32) {
10012     EVT MemVT = SN->getMemoryVT();
10013     unsigned Alignment = SN->getAlignment();
10014 
10015     // If this store is properly aligned, then it is legal.
10016     if (Alignment >= MemVT.getStoreSize())
10017       return Op;
10018 
10019     EVT ScalarVT = Value.getValueType().getScalarType(),
10020         ScalarMemVT = MemVT.getScalarType();
10021     unsigned Stride = ScalarMemVT.getStoreSize();
10022 
10023     SDValue Stores[4];
10024     for (unsigned Idx = 0; Idx < 4; ++Idx) {
10025       SDValue Ex = DAG.getNode(
10026           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
10027           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
10028       SDValue Store;
10029       if (ScalarVT != ScalarMemVT)
10030         Store =
10031             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
10032                               SN->getPointerInfo().getWithOffset(Idx * Stride),
10033                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
10034                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
10035       else
10036         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10037                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10038                              MinAlign(Alignment, Idx * Stride),
10039                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10040 
10041       if (Idx == 0 && SN->isIndexed()) {
10042         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10043                "Unknown addressing mode on vector store");
10044         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10045                                     SN->getAddressingMode());
10046       }
10047 
10048       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10049                             DAG.getConstant(Stride, dl,
10050                                             BasePtr.getValueType()));
10051       Stores[Idx] = Store;
10052     }
10053 
10054     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10055 
10056     if (SN->isIndexed()) {
10057       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10058       return DAG.getMergeValues(RetOps, dl);
10059     }
10060 
10061     return TF;
10062   }
10063 
10064   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10065   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10066 
10067   // The values are now known to be -1 (false) or 1 (true). To convert this
10068   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10069   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10070   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10071 
10072   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10073   // understand how to form the extending load.
10074   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10075 
10076   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10077 
10078   // Now convert to an integer and store.
10079   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10080     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10081     Value);
10082 
10083   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10084   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10085   MachinePointerInfo PtrInfo =
10086       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10087   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10088   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10089 
10090   SDValue Ops[] = {StoreChain,
10091                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10092                    Value, FIdx};
10093   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10094 
10095   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10096     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10097 
10098   // Move data into the byte array.
10099   SDValue Loads[4], LoadChains[4];
10100   for (unsigned i = 0; i < 4; ++i) {
10101     unsigned Offset = 4*i;
10102     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10103     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10104 
10105     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10106                            PtrInfo.getWithOffset(Offset));
10107     LoadChains[i] = Loads[i].getValue(1);
10108   }
10109 
10110   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10111 
10112   SDValue Stores[4];
10113   for (unsigned i = 0; i < 4; ++i) {
10114     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10115     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10116 
10117     Stores[i] = DAG.getTruncStore(
10118         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10119         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10120         SN->getAAInfo());
10121   }
10122 
10123   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10124 
10125   return StoreChain;
10126 }
10127 
10128 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10129   SDLoc dl(Op);
10130   if (Op.getValueType() == MVT::v4i32) {
10131     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10132 
10133     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10134     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10135 
10136     SDValue RHSSwap =   // = vrlw RHS, 16
10137       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10138 
10139     // Shrinkify inputs to v8i16.
10140     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10141     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10142     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10143 
10144     // Low parts multiplied together, generating 32-bit results (we ignore the
10145     // top parts).
10146     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10147                                         LHS, RHS, DAG, dl, MVT::v4i32);
10148 
10149     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10150                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10151     // Shift the high parts up 16 bits.
10152     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10153                               Neg16, DAG, dl);
10154     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10155   } else if (Op.getValueType() == MVT::v8i16) {
10156     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10157 
10158     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10159 
10160     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10161                             LHS, RHS, Zero, DAG, dl);
10162   } else if (Op.getValueType() == MVT::v16i8) {
10163     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10164     bool isLittleEndian = Subtarget.isLittleEndian();
10165 
10166     // Multiply the even 8-bit parts, producing 16-bit sums.
10167     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10168                                            LHS, RHS, DAG, dl, MVT::v8i16);
10169     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10170 
10171     // Multiply the odd 8-bit parts, producing 16-bit sums.
10172     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10173                                           LHS, RHS, DAG, dl, MVT::v8i16);
10174     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10175 
10176     // Merge the results together.  Because vmuleub and vmuloub are
10177     // instructions with a big-endian bias, we must reverse the
10178     // element numbering and reverse the meaning of "odd" and "even"
10179     // when generating little endian code.
10180     int Ops[16];
10181     for (unsigned i = 0; i != 8; ++i) {
10182       if (isLittleEndian) {
10183         Ops[i*2  ] = 2*i;
10184         Ops[i*2+1] = 2*i+16;
10185       } else {
10186         Ops[i*2  ] = 2*i+1;
10187         Ops[i*2+1] = 2*i+1+16;
10188       }
10189     }
10190     if (isLittleEndian)
10191       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10192     else
10193       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10194   } else {
10195     llvm_unreachable("Unknown mul to lower!");
10196   }
10197 }
10198 
10199 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10200 
10201   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10202 
10203   EVT VT = Op.getValueType();
10204   assert(VT.isVector() &&
10205          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10206   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10207           VT == MVT::v16i8) &&
10208          "Unexpected vector element type!");
10209   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10210          "Current subtarget doesn't support smax v2i64!");
10211 
10212   // For vector abs, it can be lowered to:
10213   // abs x
10214   // ==>
10215   // y = -x
10216   // smax(x, y)
10217 
10218   SDLoc dl(Op);
10219   SDValue X = Op.getOperand(0);
10220   SDValue Zero = DAG.getConstant(0, dl, VT);
10221   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10222 
10223   // SMAX patch https://reviews.llvm.org/D47332
10224   // hasn't landed yet, so use intrinsic first here.
10225   // TODO: Should use SMAX directly once SMAX patch landed
10226   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10227   if (VT == MVT::v2i64)
10228     BifID = Intrinsic::ppc_altivec_vmaxsd;
10229   else if (VT == MVT::v8i16)
10230     BifID = Intrinsic::ppc_altivec_vmaxsh;
10231   else if (VT == MVT::v16i8)
10232     BifID = Intrinsic::ppc_altivec_vmaxsb;
10233 
10234   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10235 }
10236 
10237 // Custom lowering for fpext vf32 to v2f64
10238 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10239 
10240   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10241          "Should only be called for ISD::FP_EXTEND");
10242 
10243   // We only want to custom lower an extend from v2f32 to v2f64.
10244   if (Op.getValueType() != MVT::v2f64 ||
10245       Op.getOperand(0).getValueType() != MVT::v2f32)
10246     return SDValue();
10247 
10248   SDLoc dl(Op);
10249   SDValue Op0 = Op.getOperand(0);
10250 
10251   switch (Op0.getOpcode()) {
10252   default:
10253     return SDValue();
10254   case ISD::EXTRACT_SUBVECTOR: {
10255     assert(Op0.getNumOperands() == 2 &&
10256            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10257            "Node should have 2 operands with second one being a constant!");
10258 
10259     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10260       return SDValue();
10261 
10262     // Custom lower is only done for high or low doubleword.
10263     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10264     if (Idx % 2 != 0)
10265       return SDValue();
10266 
10267     // Since input is v4f32, at this point Idx is either 0 or 2.
10268     // Shift to get the doubleword position we want.
10269     int DWord = Idx >> 1;
10270 
10271     // High and low word positions are different on little endian.
10272     if (Subtarget.isLittleEndian())
10273       DWord ^= 0x1;
10274 
10275     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10276                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10277   }
10278   case ISD::FADD:
10279   case ISD::FMUL:
10280   case ISD::FSUB: {
10281     SDValue NewLoad[2];
10282     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10283       // Ensure both input are loads.
10284       SDValue LdOp = Op0.getOperand(i);
10285       if (LdOp.getOpcode() != ISD::LOAD)
10286         return SDValue();
10287       // Generate new load node.
10288       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10289       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10290       NewLoad[i] = DAG.getMemIntrinsicNode(
10291           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10292           LD->getMemoryVT(), LD->getMemOperand());
10293     }
10294     SDValue NewOp =
10295         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10296                     NewLoad[1], Op0.getNode()->getFlags());
10297     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10298                        DAG.getConstant(0, dl, MVT::i32));
10299   }
10300   case ISD::LOAD: {
10301     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10302     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10303     SDValue NewLd = DAG.getMemIntrinsicNode(
10304         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10305         LD->getMemoryVT(), LD->getMemOperand());
10306     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10307                        DAG.getConstant(0, dl, MVT::i32));
10308   }
10309   }
10310   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10311 }
10312 
10313 /// LowerOperation - Provide custom lowering hooks for some operations.
10314 ///
10315 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10316   switch (Op.getOpcode()) {
10317   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10318   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10319   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10320   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10321   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10322   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10323   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10324   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10325   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10326 
10327   // Variable argument lowering.
10328   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10329   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10330   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10331 
10332   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10333   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10334   case ISD::GET_DYNAMIC_AREA_OFFSET:
10335     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10336 
10337   // Exception handling lowering.
10338   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10339   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10340   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10341 
10342   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10343   case ISD::STORE:              return LowerSTORE(Op, DAG);
10344   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10345   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10346   case ISD::FP_TO_UINT:
10347   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10348   case ISD::UINT_TO_FP:
10349   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10350   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10351 
10352   // Lower 64-bit shifts.
10353   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10354   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10355   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10356 
10357   // Vector-related lowering.
10358   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10359   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10360   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10361   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10362   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10363   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10364   case ISD::MUL:                return LowerMUL(Op, DAG);
10365   case ISD::ABS:                return LowerABS(Op, DAG);
10366   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10367 
10368   // For counter-based loop handling.
10369   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10370 
10371   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10372 
10373   // Frame & Return address.
10374   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10375   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10376 
10377   case ISD::INTRINSIC_VOID:
10378     return LowerINTRINSIC_VOID(Op, DAG);
10379   case ISD::SREM:
10380   case ISD::UREM:
10381     return LowerREM(Op, DAG);
10382   case ISD::BSWAP:
10383     return LowerBSWAP(Op, DAG);
10384   case ISD::ATOMIC_CMP_SWAP:
10385     return LowerATOMIC_CMP_SWAP(Op, DAG);
10386   }
10387 }
10388 
10389 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10390                                            SmallVectorImpl<SDValue>&Results,
10391                                            SelectionDAG &DAG) const {
10392   SDLoc dl(N);
10393   switch (N->getOpcode()) {
10394   default:
10395     llvm_unreachable("Do not know how to custom type legalize this operation!");
10396   case ISD::READCYCLECOUNTER: {
10397     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10398     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10399 
10400     Results.push_back(RTB);
10401     Results.push_back(RTB.getValue(1));
10402     Results.push_back(RTB.getValue(2));
10403     break;
10404   }
10405   case ISD::INTRINSIC_W_CHAIN: {
10406     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10407         Intrinsic::loop_decrement)
10408       break;
10409 
10410     assert(N->getValueType(0) == MVT::i1 &&
10411            "Unexpected result type for CTR decrement intrinsic");
10412     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10413                                  N->getValueType(0));
10414     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10415     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10416                                  N->getOperand(1));
10417 
10418     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10419     Results.push_back(NewInt.getValue(1));
10420     break;
10421   }
10422   case ISD::VAARG: {
10423     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10424       return;
10425 
10426     EVT VT = N->getValueType(0);
10427 
10428     if (VT == MVT::i64) {
10429       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10430 
10431       Results.push_back(NewNode);
10432       Results.push_back(NewNode.getValue(1));
10433     }
10434     return;
10435   }
10436   case ISD::FP_TO_SINT:
10437   case ISD::FP_TO_UINT:
10438     // LowerFP_TO_INT() can only handle f32 and f64.
10439     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10440       return;
10441     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10442     return;
10443   case ISD::TRUNCATE: {
10444     EVT TrgVT = N->getValueType(0);
10445     EVT OpVT = N->getOperand(0).getValueType();
10446     if (TrgVT.isVector() &&
10447         isOperationCustom(N->getOpcode(), TrgVT) &&
10448         OpVT.getSizeInBits() <= 128 &&
10449         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10450       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10451     return;
10452   }
10453   case ISD::BITCAST:
10454     // Don't handle bitcast here.
10455     return;
10456   }
10457 }
10458 
10459 //===----------------------------------------------------------------------===//
10460 //  Other Lowering Code
10461 //===----------------------------------------------------------------------===//
10462 
10463 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10464   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10465   Function *Func = Intrinsic::getDeclaration(M, Id);
10466   return Builder.CreateCall(Func, {});
10467 }
10468 
10469 // The mappings for emitLeading/TrailingFence is taken from
10470 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10471 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10472                                                  Instruction *Inst,
10473                                                  AtomicOrdering Ord) const {
10474   if (Ord == AtomicOrdering::SequentiallyConsistent)
10475     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10476   if (isReleaseOrStronger(Ord))
10477     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10478   return nullptr;
10479 }
10480 
10481 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10482                                                   Instruction *Inst,
10483                                                   AtomicOrdering Ord) const {
10484   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10485     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10486     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10487     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10488     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10489       return Builder.CreateCall(
10490           Intrinsic::getDeclaration(
10491               Builder.GetInsertBlock()->getParent()->getParent(),
10492               Intrinsic::ppc_cfence, {Inst->getType()}),
10493           {Inst});
10494     // FIXME: Can use isync for rmw operation.
10495     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10496   }
10497   return nullptr;
10498 }
10499 
10500 MachineBasicBlock *
10501 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10502                                     unsigned AtomicSize,
10503                                     unsigned BinOpcode,
10504                                     unsigned CmpOpcode,
10505                                     unsigned CmpPred) const {
10506   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10507   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10508 
10509   auto LoadMnemonic = PPC::LDARX;
10510   auto StoreMnemonic = PPC::STDCX;
10511   switch (AtomicSize) {
10512   default:
10513     llvm_unreachable("Unexpected size of atomic entity");
10514   case 1:
10515     LoadMnemonic = PPC::LBARX;
10516     StoreMnemonic = PPC::STBCX;
10517     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10518     break;
10519   case 2:
10520     LoadMnemonic = PPC::LHARX;
10521     StoreMnemonic = PPC::STHCX;
10522     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10523     break;
10524   case 4:
10525     LoadMnemonic = PPC::LWARX;
10526     StoreMnemonic = PPC::STWCX;
10527     break;
10528   case 8:
10529     LoadMnemonic = PPC::LDARX;
10530     StoreMnemonic = PPC::STDCX;
10531     break;
10532   }
10533 
10534   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10535   MachineFunction *F = BB->getParent();
10536   MachineFunction::iterator It = ++BB->getIterator();
10537 
10538   Register dest = MI.getOperand(0).getReg();
10539   Register ptrA = MI.getOperand(1).getReg();
10540   Register ptrB = MI.getOperand(2).getReg();
10541   Register incr = MI.getOperand(3).getReg();
10542   DebugLoc dl = MI.getDebugLoc();
10543 
10544   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10545   MachineBasicBlock *loop2MBB =
10546     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10547   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10548   F->insert(It, loopMBB);
10549   if (CmpOpcode)
10550     F->insert(It, loop2MBB);
10551   F->insert(It, exitMBB);
10552   exitMBB->splice(exitMBB->begin(), BB,
10553                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10554   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10555 
10556   MachineRegisterInfo &RegInfo = F->getRegInfo();
10557   Register TmpReg = (!BinOpcode) ? incr :
10558     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10559                                            : &PPC::GPRCRegClass);
10560 
10561   //  thisMBB:
10562   //   ...
10563   //   fallthrough --> loopMBB
10564   BB->addSuccessor(loopMBB);
10565 
10566   //  loopMBB:
10567   //   l[wd]arx dest, ptr
10568   //   add r0, dest, incr
10569   //   st[wd]cx. r0, ptr
10570   //   bne- loopMBB
10571   //   fallthrough --> exitMBB
10572 
10573   // For max/min...
10574   //  loopMBB:
10575   //   l[wd]arx dest, ptr
10576   //   cmpl?[wd] incr, dest
10577   //   bgt exitMBB
10578   //  loop2MBB:
10579   //   st[wd]cx. dest, ptr
10580   //   bne- loopMBB
10581   //   fallthrough --> exitMBB
10582 
10583   BB = loopMBB;
10584   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10585     .addReg(ptrA).addReg(ptrB);
10586   if (BinOpcode)
10587     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10588   if (CmpOpcode) {
10589     // Signed comparisons of byte or halfword values must be sign-extended.
10590     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10591       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10592       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10593               ExtReg).addReg(dest);
10594       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10595         .addReg(incr).addReg(ExtReg);
10596     } else
10597       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10598         .addReg(incr).addReg(dest);
10599 
10600     BuildMI(BB, dl, TII->get(PPC::BCC))
10601       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10602     BB->addSuccessor(loop2MBB);
10603     BB->addSuccessor(exitMBB);
10604     BB = loop2MBB;
10605   }
10606   BuildMI(BB, dl, TII->get(StoreMnemonic))
10607     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10608   BuildMI(BB, dl, TII->get(PPC::BCC))
10609     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10610   BB->addSuccessor(loopMBB);
10611   BB->addSuccessor(exitMBB);
10612 
10613   //  exitMBB:
10614   //   ...
10615   BB = exitMBB;
10616   return BB;
10617 }
10618 
10619 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10620     MachineInstr &MI, MachineBasicBlock *BB,
10621     bool is8bit, // operation
10622     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10623   // If we support part-word atomic mnemonics, just use them
10624   if (Subtarget.hasPartwordAtomics())
10625     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10626                             CmpPred);
10627 
10628   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10629   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10630   // In 64 bit mode we have to use 64 bits for addresses, even though the
10631   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10632   // registers without caring whether they're 32 or 64, but here we're
10633   // doing actual arithmetic on the addresses.
10634   bool is64bit = Subtarget.isPPC64();
10635   bool isLittleEndian = Subtarget.isLittleEndian();
10636   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10637 
10638   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10639   MachineFunction *F = BB->getParent();
10640   MachineFunction::iterator It = ++BB->getIterator();
10641 
10642   Register dest = MI.getOperand(0).getReg();
10643   Register ptrA = MI.getOperand(1).getReg();
10644   Register ptrB = MI.getOperand(2).getReg();
10645   Register incr = MI.getOperand(3).getReg();
10646   DebugLoc dl = MI.getDebugLoc();
10647 
10648   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10649   MachineBasicBlock *loop2MBB =
10650       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10651   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10652   F->insert(It, loopMBB);
10653   if (CmpOpcode)
10654     F->insert(It, loop2MBB);
10655   F->insert(It, exitMBB);
10656   exitMBB->splice(exitMBB->begin(), BB,
10657                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10658   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10659 
10660   MachineRegisterInfo &RegInfo = F->getRegInfo();
10661   const TargetRegisterClass *RC =
10662       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10663   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10664 
10665   Register PtrReg = RegInfo.createVirtualRegister(RC);
10666   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10667   Register ShiftReg =
10668       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10669   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10670   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10671   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10672   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10673   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10674   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10675   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10676   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10677   Register Ptr1Reg;
10678   Register TmpReg =
10679       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10680 
10681   //  thisMBB:
10682   //   ...
10683   //   fallthrough --> loopMBB
10684   BB->addSuccessor(loopMBB);
10685 
10686   // The 4-byte load must be aligned, while a char or short may be
10687   // anywhere in the word.  Hence all this nasty bookkeeping code.
10688   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10689   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10690   //   xori shift, shift1, 24 [16]
10691   //   rlwinm ptr, ptr1, 0, 0, 29
10692   //   slw incr2, incr, shift
10693   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10694   //   slw mask, mask2, shift
10695   //  loopMBB:
10696   //   lwarx tmpDest, ptr
10697   //   add tmp, tmpDest, incr2
10698   //   andc tmp2, tmpDest, mask
10699   //   and tmp3, tmp, mask
10700   //   or tmp4, tmp3, tmp2
10701   //   stwcx. tmp4, ptr
10702   //   bne- loopMBB
10703   //   fallthrough --> exitMBB
10704   //   srw dest, tmpDest, shift
10705   if (ptrA != ZeroReg) {
10706     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10707     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10708         .addReg(ptrA)
10709         .addReg(ptrB);
10710   } else {
10711     Ptr1Reg = ptrB;
10712   }
10713   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10714   // mode.
10715   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10716       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10717       .addImm(3)
10718       .addImm(27)
10719       .addImm(is8bit ? 28 : 27);
10720   if (!isLittleEndian)
10721     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10722         .addReg(Shift1Reg)
10723         .addImm(is8bit ? 24 : 16);
10724   if (is64bit)
10725     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10726         .addReg(Ptr1Reg)
10727         .addImm(0)
10728         .addImm(61);
10729   else
10730     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10731         .addReg(Ptr1Reg)
10732         .addImm(0)
10733         .addImm(0)
10734         .addImm(29);
10735   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10736   if (is8bit)
10737     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10738   else {
10739     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10740     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10741         .addReg(Mask3Reg)
10742         .addImm(65535);
10743   }
10744   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10745       .addReg(Mask2Reg)
10746       .addReg(ShiftReg);
10747 
10748   BB = loopMBB;
10749   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10750       .addReg(ZeroReg)
10751       .addReg(PtrReg);
10752   if (BinOpcode)
10753     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10754         .addReg(Incr2Reg)
10755         .addReg(TmpDestReg);
10756   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10757       .addReg(TmpDestReg)
10758       .addReg(MaskReg);
10759   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10760   if (CmpOpcode) {
10761     // For unsigned comparisons, we can directly compare the shifted values.
10762     // For signed comparisons we shift and sign extend.
10763     Register SReg = RegInfo.createVirtualRegister(GPRC);
10764     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10765         .addReg(TmpDestReg)
10766         .addReg(MaskReg);
10767     unsigned ValueReg = SReg;
10768     unsigned CmpReg = Incr2Reg;
10769     if (CmpOpcode == PPC::CMPW) {
10770       ValueReg = RegInfo.createVirtualRegister(GPRC);
10771       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10772           .addReg(SReg)
10773           .addReg(ShiftReg);
10774       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10775       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10776           .addReg(ValueReg);
10777       ValueReg = ValueSReg;
10778       CmpReg = incr;
10779     }
10780     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10781         .addReg(CmpReg)
10782         .addReg(ValueReg);
10783     BuildMI(BB, dl, TII->get(PPC::BCC))
10784         .addImm(CmpPred)
10785         .addReg(PPC::CR0)
10786         .addMBB(exitMBB);
10787     BB->addSuccessor(loop2MBB);
10788     BB->addSuccessor(exitMBB);
10789     BB = loop2MBB;
10790   }
10791   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10792   BuildMI(BB, dl, TII->get(PPC::STWCX))
10793       .addReg(Tmp4Reg)
10794       .addReg(ZeroReg)
10795       .addReg(PtrReg);
10796   BuildMI(BB, dl, TII->get(PPC::BCC))
10797       .addImm(PPC::PRED_NE)
10798       .addReg(PPC::CR0)
10799       .addMBB(loopMBB);
10800   BB->addSuccessor(loopMBB);
10801   BB->addSuccessor(exitMBB);
10802 
10803   //  exitMBB:
10804   //   ...
10805   BB = exitMBB;
10806   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10807       .addReg(TmpDestReg)
10808       .addReg(ShiftReg);
10809   return BB;
10810 }
10811 
10812 llvm::MachineBasicBlock *
10813 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10814                                     MachineBasicBlock *MBB) const {
10815   DebugLoc DL = MI.getDebugLoc();
10816   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10817   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10818 
10819   MachineFunction *MF = MBB->getParent();
10820   MachineRegisterInfo &MRI = MF->getRegInfo();
10821 
10822   const BasicBlock *BB = MBB->getBasicBlock();
10823   MachineFunction::iterator I = ++MBB->getIterator();
10824 
10825   Register DstReg = MI.getOperand(0).getReg();
10826   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10827   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10828   Register mainDstReg = MRI.createVirtualRegister(RC);
10829   Register restoreDstReg = MRI.createVirtualRegister(RC);
10830 
10831   MVT PVT = getPointerTy(MF->getDataLayout());
10832   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10833          "Invalid Pointer Size!");
10834   // For v = setjmp(buf), we generate
10835   //
10836   // thisMBB:
10837   //  SjLjSetup mainMBB
10838   //  bl mainMBB
10839   //  v_restore = 1
10840   //  b sinkMBB
10841   //
10842   // mainMBB:
10843   //  buf[LabelOffset] = LR
10844   //  v_main = 0
10845   //
10846   // sinkMBB:
10847   //  v = phi(main, restore)
10848   //
10849 
10850   MachineBasicBlock *thisMBB = MBB;
10851   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10852   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10853   MF->insert(I, mainMBB);
10854   MF->insert(I, sinkMBB);
10855 
10856   MachineInstrBuilder MIB;
10857 
10858   // Transfer the remainder of BB and its successor edges to sinkMBB.
10859   sinkMBB->splice(sinkMBB->begin(), MBB,
10860                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10861   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10862 
10863   // Note that the structure of the jmp_buf used here is not compatible
10864   // with that used by libc, and is not designed to be. Specifically, it
10865   // stores only those 'reserved' registers that LLVM does not otherwise
10866   // understand how to spill. Also, by convention, by the time this
10867   // intrinsic is called, Clang has already stored the frame address in the
10868   // first slot of the buffer and stack address in the third. Following the
10869   // X86 target code, we'll store the jump address in the second slot. We also
10870   // need to save the TOC pointer (R2) to handle jumps between shared
10871   // libraries, and that will be stored in the fourth slot. The thread
10872   // identifier (R13) is not affected.
10873 
10874   // thisMBB:
10875   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10876   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10877   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10878 
10879   // Prepare IP either in reg.
10880   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10881   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10882   Register BufReg = MI.getOperand(1).getReg();
10883 
10884   if (Subtarget.is64BitELFABI()) {
10885     setUsesTOCBasePtr(*MBB->getParent());
10886     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10887               .addReg(PPC::X2)
10888               .addImm(TOCOffset)
10889               .addReg(BufReg)
10890               .cloneMemRefs(MI);
10891   }
10892 
10893   // Naked functions never have a base pointer, and so we use r1. For all
10894   // other functions, this decision must be delayed until during PEI.
10895   unsigned BaseReg;
10896   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10897     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10898   else
10899     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10900 
10901   MIB = BuildMI(*thisMBB, MI, DL,
10902                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10903             .addReg(BaseReg)
10904             .addImm(BPOffset)
10905             .addReg(BufReg)
10906             .cloneMemRefs(MI);
10907 
10908   // Setup
10909   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10910   MIB.addRegMask(TRI->getNoPreservedMask());
10911 
10912   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10913 
10914   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10915           .addMBB(mainMBB);
10916   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10917 
10918   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10919   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10920 
10921   // mainMBB:
10922   //  mainDstReg = 0
10923   MIB =
10924       BuildMI(mainMBB, DL,
10925               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10926 
10927   // Store IP
10928   if (Subtarget.isPPC64()) {
10929     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10930             .addReg(LabelReg)
10931             .addImm(LabelOffset)
10932             .addReg(BufReg);
10933   } else {
10934     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10935             .addReg(LabelReg)
10936             .addImm(LabelOffset)
10937             .addReg(BufReg);
10938   }
10939   MIB.cloneMemRefs(MI);
10940 
10941   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10942   mainMBB->addSuccessor(sinkMBB);
10943 
10944   // sinkMBB:
10945   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10946           TII->get(PPC::PHI), DstReg)
10947     .addReg(mainDstReg).addMBB(mainMBB)
10948     .addReg(restoreDstReg).addMBB(thisMBB);
10949 
10950   MI.eraseFromParent();
10951   return sinkMBB;
10952 }
10953 
10954 MachineBasicBlock *
10955 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10956                                      MachineBasicBlock *MBB) const {
10957   DebugLoc DL = MI.getDebugLoc();
10958   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10959 
10960   MachineFunction *MF = MBB->getParent();
10961   MachineRegisterInfo &MRI = MF->getRegInfo();
10962 
10963   MVT PVT = getPointerTy(MF->getDataLayout());
10964   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10965          "Invalid Pointer Size!");
10966 
10967   const TargetRegisterClass *RC =
10968     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10969   Register Tmp = MRI.createVirtualRegister(RC);
10970   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10971   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10972   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10973   unsigned BP =
10974       (PVT == MVT::i64)
10975           ? PPC::X30
10976           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10977                                                               : PPC::R30);
10978 
10979   MachineInstrBuilder MIB;
10980 
10981   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10982   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10983   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10984   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10985 
10986   Register BufReg = MI.getOperand(0).getReg();
10987 
10988   // Reload FP (the jumped-to function may not have had a
10989   // frame pointer, and if so, then its r31 will be restored
10990   // as necessary).
10991   if (PVT == MVT::i64) {
10992     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10993             .addImm(0)
10994             .addReg(BufReg);
10995   } else {
10996     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10997             .addImm(0)
10998             .addReg(BufReg);
10999   }
11000   MIB.cloneMemRefs(MI);
11001 
11002   // Reload IP
11003   if (PVT == MVT::i64) {
11004     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
11005             .addImm(LabelOffset)
11006             .addReg(BufReg);
11007   } else {
11008     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
11009             .addImm(LabelOffset)
11010             .addReg(BufReg);
11011   }
11012   MIB.cloneMemRefs(MI);
11013 
11014   // Reload SP
11015   if (PVT == MVT::i64) {
11016     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
11017             .addImm(SPOffset)
11018             .addReg(BufReg);
11019   } else {
11020     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
11021             .addImm(SPOffset)
11022             .addReg(BufReg);
11023   }
11024   MIB.cloneMemRefs(MI);
11025 
11026   // Reload BP
11027   if (PVT == MVT::i64) {
11028     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
11029             .addImm(BPOffset)
11030             .addReg(BufReg);
11031   } else {
11032     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
11033             .addImm(BPOffset)
11034             .addReg(BufReg);
11035   }
11036   MIB.cloneMemRefs(MI);
11037 
11038   // Reload TOC
11039   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11040     setUsesTOCBasePtr(*MBB->getParent());
11041     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11042               .addImm(TOCOffset)
11043               .addReg(BufReg)
11044               .cloneMemRefs(MI);
11045   }
11046 
11047   // Jump
11048   BuildMI(*MBB, MI, DL,
11049           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11050   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11051 
11052   MI.eraseFromParent();
11053   return MBB;
11054 }
11055 
11056 MachineBasicBlock *
11057 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11058                                                MachineBasicBlock *BB) const {
11059   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11060       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11061     if (Subtarget.is64BitELFABI() &&
11062         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11063       // Call lowering should have added an r2 operand to indicate a dependence
11064       // on the TOC base pointer value. It can't however, because there is no
11065       // way to mark the dependence as implicit there, and so the stackmap code
11066       // will confuse it with a regular operand. Instead, add the dependence
11067       // here.
11068       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11069     }
11070 
11071     return emitPatchPoint(MI, BB);
11072   }
11073 
11074   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11075       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11076     return emitEHSjLjSetJmp(MI, BB);
11077   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11078              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11079     return emitEHSjLjLongJmp(MI, BB);
11080   }
11081 
11082   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11083 
11084   // To "insert" these instructions we actually have to insert their
11085   // control-flow patterns.
11086   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11087   MachineFunction::iterator It = ++BB->getIterator();
11088 
11089   MachineFunction *F = BB->getParent();
11090 
11091   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11092       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11093       MI.getOpcode() == PPC::SELECT_I8) {
11094     SmallVector<MachineOperand, 2> Cond;
11095     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11096         MI.getOpcode() == PPC::SELECT_CC_I8)
11097       Cond.push_back(MI.getOperand(4));
11098     else
11099       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11100     Cond.push_back(MI.getOperand(1));
11101 
11102     DebugLoc dl = MI.getDebugLoc();
11103     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11104                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11105   } else if (MI.getOpcode() == PPC::SELECT_CC_F4 ||
11106              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11107              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11108              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11109              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11110              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11111              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11112              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11113              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11114              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11115              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11116              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11117              MI.getOpcode() == PPC::SELECT_F4 ||
11118              MI.getOpcode() == PPC::SELECT_F8 ||
11119              MI.getOpcode() == PPC::SELECT_F16 ||
11120              MI.getOpcode() == PPC::SELECT_QFRC ||
11121              MI.getOpcode() == PPC::SELECT_QSRC ||
11122              MI.getOpcode() == PPC::SELECT_QBRC ||
11123              MI.getOpcode() == PPC::SELECT_SPE ||
11124              MI.getOpcode() == PPC::SELECT_SPE4 ||
11125              MI.getOpcode() == PPC::SELECT_VRRC ||
11126              MI.getOpcode() == PPC::SELECT_VSFRC ||
11127              MI.getOpcode() == PPC::SELECT_VSSRC ||
11128              MI.getOpcode() == PPC::SELECT_VSRC) {
11129     // The incoming instruction knows the destination vreg to set, the
11130     // condition code register to branch on, the true/false values to
11131     // select between, and a branch opcode to use.
11132 
11133     //  thisMBB:
11134     //  ...
11135     //   TrueVal = ...
11136     //   cmpTY ccX, r1, r2
11137     //   bCC copy1MBB
11138     //   fallthrough --> copy0MBB
11139     MachineBasicBlock *thisMBB = BB;
11140     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11141     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11142     DebugLoc dl = MI.getDebugLoc();
11143     F->insert(It, copy0MBB);
11144     F->insert(It, sinkMBB);
11145 
11146     // Transfer the remainder of BB and its successor edges to sinkMBB.
11147     sinkMBB->splice(sinkMBB->begin(), BB,
11148                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11149     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11150 
11151     // Next, add the true and fallthrough blocks as its successors.
11152     BB->addSuccessor(copy0MBB);
11153     BB->addSuccessor(sinkMBB);
11154 
11155     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11156         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11157         MI.getOpcode() == PPC::SELECT_F16 ||
11158         MI.getOpcode() == PPC::SELECT_SPE4 ||
11159         MI.getOpcode() == PPC::SELECT_SPE ||
11160         MI.getOpcode() == PPC::SELECT_QFRC ||
11161         MI.getOpcode() == PPC::SELECT_QSRC ||
11162         MI.getOpcode() == PPC::SELECT_QBRC ||
11163         MI.getOpcode() == PPC::SELECT_VRRC ||
11164         MI.getOpcode() == PPC::SELECT_VSFRC ||
11165         MI.getOpcode() == PPC::SELECT_VSSRC ||
11166         MI.getOpcode() == PPC::SELECT_VSRC) {
11167       BuildMI(BB, dl, TII->get(PPC::BC))
11168           .addReg(MI.getOperand(1).getReg())
11169           .addMBB(sinkMBB);
11170     } else {
11171       unsigned SelectPred = MI.getOperand(4).getImm();
11172       BuildMI(BB, dl, TII->get(PPC::BCC))
11173           .addImm(SelectPred)
11174           .addReg(MI.getOperand(1).getReg())
11175           .addMBB(sinkMBB);
11176     }
11177 
11178     //  copy0MBB:
11179     //   %FalseValue = ...
11180     //   # fallthrough to sinkMBB
11181     BB = copy0MBB;
11182 
11183     // Update machine-CFG edges
11184     BB->addSuccessor(sinkMBB);
11185 
11186     //  sinkMBB:
11187     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11188     //  ...
11189     BB = sinkMBB;
11190     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11191         .addReg(MI.getOperand(3).getReg())
11192         .addMBB(copy0MBB)
11193         .addReg(MI.getOperand(2).getReg())
11194         .addMBB(thisMBB);
11195   } else if (MI.getOpcode() == PPC::ReadTB) {
11196     // To read the 64-bit time-base register on a 32-bit target, we read the
11197     // two halves. Should the counter have wrapped while it was being read, we
11198     // need to try again.
11199     // ...
11200     // readLoop:
11201     // mfspr Rx,TBU # load from TBU
11202     // mfspr Ry,TB  # load from TB
11203     // mfspr Rz,TBU # load from TBU
11204     // cmpw crX,Rx,Rz # check if 'old'='new'
11205     // bne readLoop   # branch if they're not equal
11206     // ...
11207 
11208     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11209     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11210     DebugLoc dl = MI.getDebugLoc();
11211     F->insert(It, readMBB);
11212     F->insert(It, sinkMBB);
11213 
11214     // Transfer the remainder of BB and its successor edges to sinkMBB.
11215     sinkMBB->splice(sinkMBB->begin(), BB,
11216                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11217     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11218 
11219     BB->addSuccessor(readMBB);
11220     BB = readMBB;
11221 
11222     MachineRegisterInfo &RegInfo = F->getRegInfo();
11223     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11224     Register LoReg = MI.getOperand(0).getReg();
11225     Register HiReg = MI.getOperand(1).getReg();
11226 
11227     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11228     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11229     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11230 
11231     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11232 
11233     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11234         .addReg(HiReg)
11235         .addReg(ReadAgainReg);
11236     BuildMI(BB, dl, TII->get(PPC::BCC))
11237         .addImm(PPC::PRED_NE)
11238         .addReg(CmpReg)
11239         .addMBB(readMBB);
11240 
11241     BB->addSuccessor(readMBB);
11242     BB->addSuccessor(sinkMBB);
11243   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11244     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11245   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11246     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11247   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11248     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11249   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11250     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11251 
11252   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11253     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11254   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11255     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11256   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11257     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11258   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11259     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11260 
11261   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11262     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11263   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11264     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11265   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11266     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11267   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11268     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11269 
11270   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11271     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11272   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11273     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11274   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11275     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11277     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11278 
11279   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11280     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11281   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11282     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11284     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11286     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11287 
11288   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11289     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11290   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11291     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11293     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11295     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11296 
11297   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11298     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11299   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11300     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11302     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11304     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11305 
11306   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11307     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11308   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11309     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11311     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11313     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11314 
11315   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11316     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11317   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11318     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11320     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11322     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11323 
11324   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11325     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11326   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11327     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11329     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11331     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11332 
11333   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11334     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11335   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11336     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11337   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11338     BB = EmitAtomicBinary(MI, BB, 4, 0);
11339   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11340     BB = EmitAtomicBinary(MI, BB, 8, 0);
11341   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11342            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11343            (Subtarget.hasPartwordAtomics() &&
11344             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11345            (Subtarget.hasPartwordAtomics() &&
11346             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11347     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11348 
11349     auto LoadMnemonic = PPC::LDARX;
11350     auto StoreMnemonic = PPC::STDCX;
11351     switch (MI.getOpcode()) {
11352     default:
11353       llvm_unreachable("Compare and swap of unknown size");
11354     case PPC::ATOMIC_CMP_SWAP_I8:
11355       LoadMnemonic = PPC::LBARX;
11356       StoreMnemonic = PPC::STBCX;
11357       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11358       break;
11359     case PPC::ATOMIC_CMP_SWAP_I16:
11360       LoadMnemonic = PPC::LHARX;
11361       StoreMnemonic = PPC::STHCX;
11362       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11363       break;
11364     case PPC::ATOMIC_CMP_SWAP_I32:
11365       LoadMnemonic = PPC::LWARX;
11366       StoreMnemonic = PPC::STWCX;
11367       break;
11368     case PPC::ATOMIC_CMP_SWAP_I64:
11369       LoadMnemonic = PPC::LDARX;
11370       StoreMnemonic = PPC::STDCX;
11371       break;
11372     }
11373     Register dest = MI.getOperand(0).getReg();
11374     Register ptrA = MI.getOperand(1).getReg();
11375     Register ptrB = MI.getOperand(2).getReg();
11376     Register oldval = MI.getOperand(3).getReg();
11377     Register newval = MI.getOperand(4).getReg();
11378     DebugLoc dl = MI.getDebugLoc();
11379 
11380     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11381     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11382     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11383     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11384     F->insert(It, loop1MBB);
11385     F->insert(It, loop2MBB);
11386     F->insert(It, midMBB);
11387     F->insert(It, exitMBB);
11388     exitMBB->splice(exitMBB->begin(), BB,
11389                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11390     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11391 
11392     //  thisMBB:
11393     //   ...
11394     //   fallthrough --> loopMBB
11395     BB->addSuccessor(loop1MBB);
11396 
11397     // loop1MBB:
11398     //   l[bhwd]arx dest, ptr
11399     //   cmp[wd] dest, oldval
11400     //   bne- midMBB
11401     // loop2MBB:
11402     //   st[bhwd]cx. newval, ptr
11403     //   bne- loopMBB
11404     //   b exitBB
11405     // midMBB:
11406     //   st[bhwd]cx. dest, ptr
11407     // exitBB:
11408     BB = loop1MBB;
11409     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11410     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11411         .addReg(oldval)
11412         .addReg(dest);
11413     BuildMI(BB, dl, TII->get(PPC::BCC))
11414         .addImm(PPC::PRED_NE)
11415         .addReg(PPC::CR0)
11416         .addMBB(midMBB);
11417     BB->addSuccessor(loop2MBB);
11418     BB->addSuccessor(midMBB);
11419 
11420     BB = loop2MBB;
11421     BuildMI(BB, dl, TII->get(StoreMnemonic))
11422         .addReg(newval)
11423         .addReg(ptrA)
11424         .addReg(ptrB);
11425     BuildMI(BB, dl, TII->get(PPC::BCC))
11426         .addImm(PPC::PRED_NE)
11427         .addReg(PPC::CR0)
11428         .addMBB(loop1MBB);
11429     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11430     BB->addSuccessor(loop1MBB);
11431     BB->addSuccessor(exitMBB);
11432 
11433     BB = midMBB;
11434     BuildMI(BB, dl, TII->get(StoreMnemonic))
11435         .addReg(dest)
11436         .addReg(ptrA)
11437         .addReg(ptrB);
11438     BB->addSuccessor(exitMBB);
11439 
11440     //  exitMBB:
11441     //   ...
11442     BB = exitMBB;
11443   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11444              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11445     // We must use 64-bit registers for addresses when targeting 64-bit,
11446     // since we're actually doing arithmetic on them.  Other registers
11447     // can be 32-bit.
11448     bool is64bit = Subtarget.isPPC64();
11449     bool isLittleEndian = Subtarget.isLittleEndian();
11450     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11451 
11452     Register dest = MI.getOperand(0).getReg();
11453     Register ptrA = MI.getOperand(1).getReg();
11454     Register ptrB = MI.getOperand(2).getReg();
11455     Register oldval = MI.getOperand(3).getReg();
11456     Register newval = MI.getOperand(4).getReg();
11457     DebugLoc dl = MI.getDebugLoc();
11458 
11459     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11460     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11461     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11462     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11463     F->insert(It, loop1MBB);
11464     F->insert(It, loop2MBB);
11465     F->insert(It, midMBB);
11466     F->insert(It, exitMBB);
11467     exitMBB->splice(exitMBB->begin(), BB,
11468                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11469     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11470 
11471     MachineRegisterInfo &RegInfo = F->getRegInfo();
11472     const TargetRegisterClass *RC =
11473         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11474     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11475 
11476     Register PtrReg = RegInfo.createVirtualRegister(RC);
11477     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11478     Register ShiftReg =
11479         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11480     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11481     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11482     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11483     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11484     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11485     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11486     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11487     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11488     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11489     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11490     Register Ptr1Reg;
11491     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11492     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11493     //  thisMBB:
11494     //   ...
11495     //   fallthrough --> loopMBB
11496     BB->addSuccessor(loop1MBB);
11497 
11498     // The 4-byte load must be aligned, while a char or short may be
11499     // anywhere in the word.  Hence all this nasty bookkeeping code.
11500     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11501     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11502     //   xori shift, shift1, 24 [16]
11503     //   rlwinm ptr, ptr1, 0, 0, 29
11504     //   slw newval2, newval, shift
11505     //   slw oldval2, oldval,shift
11506     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11507     //   slw mask, mask2, shift
11508     //   and newval3, newval2, mask
11509     //   and oldval3, oldval2, mask
11510     // loop1MBB:
11511     //   lwarx tmpDest, ptr
11512     //   and tmp, tmpDest, mask
11513     //   cmpw tmp, oldval3
11514     //   bne- midMBB
11515     // loop2MBB:
11516     //   andc tmp2, tmpDest, mask
11517     //   or tmp4, tmp2, newval3
11518     //   stwcx. tmp4, ptr
11519     //   bne- loop1MBB
11520     //   b exitBB
11521     // midMBB:
11522     //   stwcx. tmpDest, ptr
11523     // exitBB:
11524     //   srw dest, tmpDest, shift
11525     if (ptrA != ZeroReg) {
11526       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11527       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11528           .addReg(ptrA)
11529           .addReg(ptrB);
11530     } else {
11531       Ptr1Reg = ptrB;
11532     }
11533 
11534     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11535     // mode.
11536     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11537         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11538         .addImm(3)
11539         .addImm(27)
11540         .addImm(is8bit ? 28 : 27);
11541     if (!isLittleEndian)
11542       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11543           .addReg(Shift1Reg)
11544           .addImm(is8bit ? 24 : 16);
11545     if (is64bit)
11546       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11547           .addReg(Ptr1Reg)
11548           .addImm(0)
11549           .addImm(61);
11550     else
11551       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11552           .addReg(Ptr1Reg)
11553           .addImm(0)
11554           .addImm(0)
11555           .addImm(29);
11556     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11557         .addReg(newval)
11558         .addReg(ShiftReg);
11559     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11560         .addReg(oldval)
11561         .addReg(ShiftReg);
11562     if (is8bit)
11563       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11564     else {
11565       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11566       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11567           .addReg(Mask3Reg)
11568           .addImm(65535);
11569     }
11570     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11571         .addReg(Mask2Reg)
11572         .addReg(ShiftReg);
11573     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11574         .addReg(NewVal2Reg)
11575         .addReg(MaskReg);
11576     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11577         .addReg(OldVal2Reg)
11578         .addReg(MaskReg);
11579 
11580     BB = loop1MBB;
11581     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11582         .addReg(ZeroReg)
11583         .addReg(PtrReg);
11584     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11585         .addReg(TmpDestReg)
11586         .addReg(MaskReg);
11587     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11588         .addReg(TmpReg)
11589         .addReg(OldVal3Reg);
11590     BuildMI(BB, dl, TII->get(PPC::BCC))
11591         .addImm(PPC::PRED_NE)
11592         .addReg(PPC::CR0)
11593         .addMBB(midMBB);
11594     BB->addSuccessor(loop2MBB);
11595     BB->addSuccessor(midMBB);
11596 
11597     BB = loop2MBB;
11598     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11599         .addReg(TmpDestReg)
11600         .addReg(MaskReg);
11601     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11602         .addReg(Tmp2Reg)
11603         .addReg(NewVal3Reg);
11604     BuildMI(BB, dl, TII->get(PPC::STWCX))
11605         .addReg(Tmp4Reg)
11606         .addReg(ZeroReg)
11607         .addReg(PtrReg);
11608     BuildMI(BB, dl, TII->get(PPC::BCC))
11609         .addImm(PPC::PRED_NE)
11610         .addReg(PPC::CR0)
11611         .addMBB(loop1MBB);
11612     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11613     BB->addSuccessor(loop1MBB);
11614     BB->addSuccessor(exitMBB);
11615 
11616     BB = midMBB;
11617     BuildMI(BB, dl, TII->get(PPC::STWCX))
11618         .addReg(TmpDestReg)
11619         .addReg(ZeroReg)
11620         .addReg(PtrReg);
11621     BB->addSuccessor(exitMBB);
11622 
11623     //  exitMBB:
11624     //   ...
11625     BB = exitMBB;
11626     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11627         .addReg(TmpReg)
11628         .addReg(ShiftReg);
11629   } else if (MI.getOpcode() == PPC::FADDrtz) {
11630     // This pseudo performs an FADD with rounding mode temporarily forced
11631     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11632     // is not modeled at the SelectionDAG level.
11633     Register Dest = MI.getOperand(0).getReg();
11634     Register Src1 = MI.getOperand(1).getReg();
11635     Register Src2 = MI.getOperand(2).getReg();
11636     DebugLoc dl = MI.getDebugLoc();
11637 
11638     MachineRegisterInfo &RegInfo = F->getRegInfo();
11639     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11640 
11641     // Save FPSCR value.
11642     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11643 
11644     // Set rounding mode to round-to-zero.
11645     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11646     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11647 
11648     // Perform addition.
11649     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11650 
11651     // Restore FPSCR value.
11652     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11653   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11654              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11655              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11656              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11657     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11658                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11659                           ? PPC::ANDI8o
11660                           : PPC::ANDIo;
11661     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11662                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11663 
11664     MachineRegisterInfo &RegInfo = F->getRegInfo();
11665     Register Dest = RegInfo.createVirtualRegister(
11666         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11667 
11668     DebugLoc dl = MI.getDebugLoc();
11669     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11670         .addReg(MI.getOperand(1).getReg())
11671         .addImm(1);
11672     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11673             MI.getOperand(0).getReg())
11674         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11675   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11676     DebugLoc Dl = MI.getDebugLoc();
11677     MachineRegisterInfo &RegInfo = F->getRegInfo();
11678     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11679     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11680     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11681             MI.getOperand(0).getReg())
11682         .addReg(CRReg);
11683   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11684     DebugLoc Dl = MI.getDebugLoc();
11685     unsigned Imm = MI.getOperand(1).getImm();
11686     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11687     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11688             MI.getOperand(0).getReg())
11689         .addReg(PPC::CR0EQ);
11690   } else if (MI.getOpcode() == PPC::SETRNDi) {
11691     DebugLoc dl = MI.getDebugLoc();
11692     Register OldFPSCRReg = MI.getOperand(0).getReg();
11693 
11694     // Save FPSCR value.
11695     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11696 
11697     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11698     // the following settings:
11699     //   00 Round to nearest
11700     //   01 Round to 0
11701     //   10 Round to +inf
11702     //   11 Round to -inf
11703 
11704     // When the operand is immediate, using the two least significant bits of
11705     // the immediate to set the bits 62:63 of FPSCR.
11706     unsigned Mode = MI.getOperand(1).getImm();
11707     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11708       .addImm(31);
11709 
11710     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11711       .addImm(30);
11712   } else if (MI.getOpcode() == PPC::SETRND) {
11713     DebugLoc dl = MI.getDebugLoc();
11714 
11715     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11716     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11717     // If the target doesn't have DirectMove, we should use stack to do the
11718     // conversion, because the target doesn't have the instructions like mtvsrd
11719     // or mfvsrd to do this conversion directly.
11720     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11721       if (Subtarget.hasDirectMove()) {
11722         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11723           .addReg(SrcReg);
11724       } else {
11725         // Use stack to do the register copy.
11726         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11727         MachineRegisterInfo &RegInfo = F->getRegInfo();
11728         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11729         if (RC == &PPC::F8RCRegClass) {
11730           // Copy register from F8RCRegClass to G8RCRegclass.
11731           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11732                  "Unsupported RegClass.");
11733 
11734           StoreOp = PPC::STFD;
11735           LoadOp = PPC::LD;
11736         } else {
11737           // Copy register from G8RCRegClass to F8RCRegclass.
11738           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11739                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11740                  "Unsupported RegClass.");
11741         }
11742 
11743         MachineFrameInfo &MFI = F->getFrameInfo();
11744         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11745 
11746         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11747           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11748           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11749           MFI.getObjectAlignment(FrameIdx));
11750 
11751         // Store the SrcReg into the stack.
11752         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11753           .addReg(SrcReg)
11754           .addImm(0)
11755           .addFrameIndex(FrameIdx)
11756           .addMemOperand(MMOStore);
11757 
11758         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11759           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11760           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11761           MFI.getObjectAlignment(FrameIdx));
11762 
11763         // Load from the stack where SrcReg is stored, and save to DestReg,
11764         // so we have done the RegClass conversion from RegClass::SrcReg to
11765         // RegClass::DestReg.
11766         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11767           .addImm(0)
11768           .addFrameIndex(FrameIdx)
11769           .addMemOperand(MMOLoad);
11770       }
11771     };
11772 
11773     Register OldFPSCRReg = MI.getOperand(0).getReg();
11774 
11775     // Save FPSCR value.
11776     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11777 
11778     // When the operand is gprc register, use two least significant bits of the
11779     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11780     //
11781     // copy OldFPSCRTmpReg, OldFPSCRReg
11782     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11783     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11784     // copy NewFPSCRReg, NewFPSCRTmpReg
11785     // mtfsf 255, NewFPSCRReg
11786     MachineOperand SrcOp = MI.getOperand(1);
11787     MachineRegisterInfo &RegInfo = F->getRegInfo();
11788     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11789 
11790     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11791 
11792     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11793     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11794 
11795     // The first operand of INSERT_SUBREG should be a register which has
11796     // subregisters, we only care about its RegClass, so we should use an
11797     // IMPLICIT_DEF register.
11798     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11799     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11800       .addReg(ImDefReg)
11801       .add(SrcOp)
11802       .addImm(1);
11803 
11804     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11805     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11806       .addReg(OldFPSCRTmpReg)
11807       .addReg(ExtSrcReg)
11808       .addImm(0)
11809       .addImm(62);
11810 
11811     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11812     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11813 
11814     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11815     // bits of FPSCR.
11816     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11817       .addImm(255)
11818       .addReg(NewFPSCRReg)
11819       .addImm(0)
11820       .addImm(0);
11821   } else {
11822     llvm_unreachable("Unexpected instr type to insert");
11823   }
11824 
11825   MI.eraseFromParent(); // The pseudo instruction is gone now.
11826   return BB;
11827 }
11828 
11829 //===----------------------------------------------------------------------===//
11830 // Target Optimization Hooks
11831 //===----------------------------------------------------------------------===//
11832 
11833 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11834   // For the estimates, convergence is quadratic, so we essentially double the
11835   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11836   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11837   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11838   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11839   if (VT.getScalarType() == MVT::f64)
11840     RefinementSteps++;
11841   return RefinementSteps;
11842 }
11843 
11844 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11845                                            int Enabled, int &RefinementSteps,
11846                                            bool &UseOneConstNR,
11847                                            bool Reciprocal) const {
11848   EVT VT = Operand.getValueType();
11849   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11850       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11851       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11852       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11853       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11854       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11855     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11856       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11857 
11858     // The Newton-Raphson computation with a single constant does not provide
11859     // enough accuracy on some CPUs.
11860     UseOneConstNR = !Subtarget.needsTwoConstNR();
11861     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11862   }
11863   return SDValue();
11864 }
11865 
11866 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11867                                             int Enabled,
11868                                             int &RefinementSteps) const {
11869   EVT VT = Operand.getValueType();
11870   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11871       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11872       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11873       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11874       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11875       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11876     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11877       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11878     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11879   }
11880   return SDValue();
11881 }
11882 
11883 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11884   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11885   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11886   // enabled for division), this functionality is redundant with the default
11887   // combiner logic (once the division -> reciprocal/multiply transformation
11888   // has taken place). As a result, this matters more for older cores than for
11889   // newer ones.
11890 
11891   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11892   // reciprocal if there are two or more FDIVs (for embedded cores with only
11893   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11894   switch (Subtarget.getCPUDirective()) {
11895   default:
11896     return 3;
11897   case PPC::DIR_440:
11898   case PPC::DIR_A2:
11899   case PPC::DIR_E500:
11900   case PPC::DIR_E500mc:
11901   case PPC::DIR_E5500:
11902     return 2;
11903   }
11904 }
11905 
11906 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11907 // collapsed, and so we need to look through chains of them.
11908 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11909                                      int64_t& Offset, SelectionDAG &DAG) {
11910   if (DAG.isBaseWithConstantOffset(Loc)) {
11911     Base = Loc.getOperand(0);
11912     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11913 
11914     // The base might itself be a base plus an offset, and if so, accumulate
11915     // that as well.
11916     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11917   }
11918 }
11919 
11920 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11921                             unsigned Bytes, int Dist,
11922                             SelectionDAG &DAG) {
11923   if (VT.getSizeInBits() / 8 != Bytes)
11924     return false;
11925 
11926   SDValue BaseLoc = Base->getBasePtr();
11927   if (Loc.getOpcode() == ISD::FrameIndex) {
11928     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11929       return false;
11930     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11931     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11932     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11933     int FS  = MFI.getObjectSize(FI);
11934     int BFS = MFI.getObjectSize(BFI);
11935     if (FS != BFS || FS != (int)Bytes) return false;
11936     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11937   }
11938 
11939   SDValue Base1 = Loc, Base2 = BaseLoc;
11940   int64_t Offset1 = 0, Offset2 = 0;
11941   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11942   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11943   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11944     return true;
11945 
11946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11947   const GlobalValue *GV1 = nullptr;
11948   const GlobalValue *GV2 = nullptr;
11949   Offset1 = 0;
11950   Offset2 = 0;
11951   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11952   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11953   if (isGA1 && isGA2 && GV1 == GV2)
11954     return Offset1 == (Offset2 + Dist*Bytes);
11955   return false;
11956 }
11957 
11958 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11959 // not enforce equality of the chain operands.
11960 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11961                             unsigned Bytes, int Dist,
11962                             SelectionDAG &DAG) {
11963   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11964     EVT VT = LS->getMemoryVT();
11965     SDValue Loc = LS->getBasePtr();
11966     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11967   }
11968 
11969   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11970     EVT VT;
11971     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11972     default: return false;
11973     case Intrinsic::ppc_qpx_qvlfd:
11974     case Intrinsic::ppc_qpx_qvlfda:
11975       VT = MVT::v4f64;
11976       break;
11977     case Intrinsic::ppc_qpx_qvlfs:
11978     case Intrinsic::ppc_qpx_qvlfsa:
11979       VT = MVT::v4f32;
11980       break;
11981     case Intrinsic::ppc_qpx_qvlfcd:
11982     case Intrinsic::ppc_qpx_qvlfcda:
11983       VT = MVT::v2f64;
11984       break;
11985     case Intrinsic::ppc_qpx_qvlfcs:
11986     case Intrinsic::ppc_qpx_qvlfcsa:
11987       VT = MVT::v2f32;
11988       break;
11989     case Intrinsic::ppc_qpx_qvlfiwa:
11990     case Intrinsic::ppc_qpx_qvlfiwz:
11991     case Intrinsic::ppc_altivec_lvx:
11992     case Intrinsic::ppc_altivec_lvxl:
11993     case Intrinsic::ppc_vsx_lxvw4x:
11994     case Intrinsic::ppc_vsx_lxvw4x_be:
11995       VT = MVT::v4i32;
11996       break;
11997     case Intrinsic::ppc_vsx_lxvd2x:
11998     case Intrinsic::ppc_vsx_lxvd2x_be:
11999       VT = MVT::v2f64;
12000       break;
12001     case Intrinsic::ppc_altivec_lvebx:
12002       VT = MVT::i8;
12003       break;
12004     case Intrinsic::ppc_altivec_lvehx:
12005       VT = MVT::i16;
12006       break;
12007     case Intrinsic::ppc_altivec_lvewx:
12008       VT = MVT::i32;
12009       break;
12010     }
12011 
12012     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
12013   }
12014 
12015   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
12016     EVT VT;
12017     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12018     default: return false;
12019     case Intrinsic::ppc_qpx_qvstfd:
12020     case Intrinsic::ppc_qpx_qvstfda:
12021       VT = MVT::v4f64;
12022       break;
12023     case Intrinsic::ppc_qpx_qvstfs:
12024     case Intrinsic::ppc_qpx_qvstfsa:
12025       VT = MVT::v4f32;
12026       break;
12027     case Intrinsic::ppc_qpx_qvstfcd:
12028     case Intrinsic::ppc_qpx_qvstfcda:
12029       VT = MVT::v2f64;
12030       break;
12031     case Intrinsic::ppc_qpx_qvstfcs:
12032     case Intrinsic::ppc_qpx_qvstfcsa:
12033       VT = MVT::v2f32;
12034       break;
12035     case Intrinsic::ppc_qpx_qvstfiw:
12036     case Intrinsic::ppc_qpx_qvstfiwa:
12037     case Intrinsic::ppc_altivec_stvx:
12038     case Intrinsic::ppc_altivec_stvxl:
12039     case Intrinsic::ppc_vsx_stxvw4x:
12040       VT = MVT::v4i32;
12041       break;
12042     case Intrinsic::ppc_vsx_stxvd2x:
12043       VT = MVT::v2f64;
12044       break;
12045     case Intrinsic::ppc_vsx_stxvw4x_be:
12046       VT = MVT::v4i32;
12047       break;
12048     case Intrinsic::ppc_vsx_stxvd2x_be:
12049       VT = MVT::v2f64;
12050       break;
12051     case Intrinsic::ppc_altivec_stvebx:
12052       VT = MVT::i8;
12053       break;
12054     case Intrinsic::ppc_altivec_stvehx:
12055       VT = MVT::i16;
12056       break;
12057     case Intrinsic::ppc_altivec_stvewx:
12058       VT = MVT::i32;
12059       break;
12060     }
12061 
12062     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12063   }
12064 
12065   return false;
12066 }
12067 
12068 // Return true is there is a nearyby consecutive load to the one provided
12069 // (regardless of alignment). We search up and down the chain, looking though
12070 // token factors and other loads (but nothing else). As a result, a true result
12071 // indicates that it is safe to create a new consecutive load adjacent to the
12072 // load provided.
12073 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12074   SDValue Chain = LD->getChain();
12075   EVT VT = LD->getMemoryVT();
12076 
12077   SmallSet<SDNode *, 16> LoadRoots;
12078   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12079   SmallSet<SDNode *, 16> Visited;
12080 
12081   // First, search up the chain, branching to follow all token-factor operands.
12082   // If we find a consecutive load, then we're done, otherwise, record all
12083   // nodes just above the top-level loads and token factors.
12084   while (!Queue.empty()) {
12085     SDNode *ChainNext = Queue.pop_back_val();
12086     if (!Visited.insert(ChainNext).second)
12087       continue;
12088 
12089     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12090       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12091         return true;
12092 
12093       if (!Visited.count(ChainLD->getChain().getNode()))
12094         Queue.push_back(ChainLD->getChain().getNode());
12095     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12096       for (const SDUse &O : ChainNext->ops())
12097         if (!Visited.count(O.getNode()))
12098           Queue.push_back(O.getNode());
12099     } else
12100       LoadRoots.insert(ChainNext);
12101   }
12102 
12103   // Second, search down the chain, starting from the top-level nodes recorded
12104   // in the first phase. These top-level nodes are the nodes just above all
12105   // loads and token factors. Starting with their uses, recursively look though
12106   // all loads (just the chain uses) and token factors to find a consecutive
12107   // load.
12108   Visited.clear();
12109   Queue.clear();
12110 
12111   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12112        IE = LoadRoots.end(); I != IE; ++I) {
12113     Queue.push_back(*I);
12114 
12115     while (!Queue.empty()) {
12116       SDNode *LoadRoot = Queue.pop_back_val();
12117       if (!Visited.insert(LoadRoot).second)
12118         continue;
12119 
12120       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12121         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12122           return true;
12123 
12124       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12125            UE = LoadRoot->use_end(); UI != UE; ++UI)
12126         if (((isa<MemSDNode>(*UI) &&
12127             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12128             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12129           Queue.push_back(*UI);
12130     }
12131   }
12132 
12133   return false;
12134 }
12135 
12136 /// This function is called when we have proved that a SETCC node can be replaced
12137 /// by subtraction (and other supporting instructions) so that the result of
12138 /// comparison is kept in a GPR instead of CR. This function is purely for
12139 /// codegen purposes and has some flags to guide the codegen process.
12140 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12141                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12142   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12143 
12144   // Zero extend the operands to the largest legal integer. Originally, they
12145   // must be of a strictly smaller size.
12146   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12147                          DAG.getConstant(Size, DL, MVT::i32));
12148   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12149                          DAG.getConstant(Size, DL, MVT::i32));
12150 
12151   // Swap if needed. Depends on the condition code.
12152   if (Swap)
12153     std::swap(Op0, Op1);
12154 
12155   // Subtract extended integers.
12156   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12157 
12158   // Move the sign bit to the least significant position and zero out the rest.
12159   // Now the least significant bit carries the result of original comparison.
12160   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12161                              DAG.getConstant(Size - 1, DL, MVT::i32));
12162   auto Final = Shifted;
12163 
12164   // Complement the result if needed. Based on the condition code.
12165   if (Complement)
12166     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12167                         DAG.getConstant(1, DL, MVT::i64));
12168 
12169   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12170 }
12171 
12172 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12173                                                   DAGCombinerInfo &DCI) const {
12174   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12175 
12176   SelectionDAG &DAG = DCI.DAG;
12177   SDLoc DL(N);
12178 
12179   // Size of integers being compared has a critical role in the following
12180   // analysis, so we prefer to do this when all types are legal.
12181   if (!DCI.isAfterLegalizeDAG())
12182     return SDValue();
12183 
12184   // If all users of SETCC extend its value to a legal integer type
12185   // then we replace SETCC with a subtraction
12186   for (SDNode::use_iterator UI = N->use_begin(),
12187        UE = N->use_end(); UI != UE; ++UI) {
12188     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12189       return SDValue();
12190   }
12191 
12192   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12193   auto OpSize = N->getOperand(0).getValueSizeInBits();
12194 
12195   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12196 
12197   if (OpSize < Size) {
12198     switch (CC) {
12199     default: break;
12200     case ISD::SETULT:
12201       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12202     case ISD::SETULE:
12203       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12204     case ISD::SETUGT:
12205       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12206     case ISD::SETUGE:
12207       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12208     }
12209   }
12210 
12211   return SDValue();
12212 }
12213 
12214 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12215                                                   DAGCombinerInfo &DCI) const {
12216   SelectionDAG &DAG = DCI.DAG;
12217   SDLoc dl(N);
12218 
12219   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12220   // If we're tracking CR bits, we need to be careful that we don't have:
12221   //   trunc(binary-ops(zext(x), zext(y)))
12222   // or
12223   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12224   // such that we're unnecessarily moving things into GPRs when it would be
12225   // better to keep them in CR bits.
12226 
12227   // Note that trunc here can be an actual i1 trunc, or can be the effective
12228   // truncation that comes from a setcc or select_cc.
12229   if (N->getOpcode() == ISD::TRUNCATE &&
12230       N->getValueType(0) != MVT::i1)
12231     return SDValue();
12232 
12233   if (N->getOperand(0).getValueType() != MVT::i32 &&
12234       N->getOperand(0).getValueType() != MVT::i64)
12235     return SDValue();
12236 
12237   if (N->getOpcode() == ISD::SETCC ||
12238       N->getOpcode() == ISD::SELECT_CC) {
12239     // If we're looking at a comparison, then we need to make sure that the
12240     // high bits (all except for the first) don't matter the result.
12241     ISD::CondCode CC =
12242       cast<CondCodeSDNode>(N->getOperand(
12243         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12244     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12245 
12246     if (ISD::isSignedIntSetCC(CC)) {
12247       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12248           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12249         return SDValue();
12250     } else if (ISD::isUnsignedIntSetCC(CC)) {
12251       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12252                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12253           !DAG.MaskedValueIsZero(N->getOperand(1),
12254                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12255         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12256                                              : SDValue());
12257     } else {
12258       // This is neither a signed nor an unsigned comparison, just make sure
12259       // that the high bits are equal.
12260       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12261       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12262 
12263       // We don't really care about what is known about the first bit (if
12264       // anything), so clear it in all masks prior to comparing them.
12265       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12266       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12267 
12268       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12269         return SDValue();
12270     }
12271   }
12272 
12273   // We now know that the higher-order bits are irrelevant, we just need to
12274   // make sure that all of the intermediate operations are bit operations, and
12275   // all inputs are extensions.
12276   if (N->getOperand(0).getOpcode() != ISD::AND &&
12277       N->getOperand(0).getOpcode() != ISD::OR  &&
12278       N->getOperand(0).getOpcode() != ISD::XOR &&
12279       N->getOperand(0).getOpcode() != ISD::SELECT &&
12280       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12281       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12282       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12283       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12284       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12285     return SDValue();
12286 
12287   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12288       N->getOperand(1).getOpcode() != ISD::AND &&
12289       N->getOperand(1).getOpcode() != ISD::OR  &&
12290       N->getOperand(1).getOpcode() != ISD::XOR &&
12291       N->getOperand(1).getOpcode() != ISD::SELECT &&
12292       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12293       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12294       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12295       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12296       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12297     return SDValue();
12298 
12299   SmallVector<SDValue, 4> Inputs;
12300   SmallVector<SDValue, 8> BinOps, PromOps;
12301   SmallPtrSet<SDNode *, 16> Visited;
12302 
12303   for (unsigned i = 0; i < 2; ++i) {
12304     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12305           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12306           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12307           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12308         isa<ConstantSDNode>(N->getOperand(i)))
12309       Inputs.push_back(N->getOperand(i));
12310     else
12311       BinOps.push_back(N->getOperand(i));
12312 
12313     if (N->getOpcode() == ISD::TRUNCATE)
12314       break;
12315   }
12316 
12317   // Visit all inputs, collect all binary operations (and, or, xor and
12318   // select) that are all fed by extensions.
12319   while (!BinOps.empty()) {
12320     SDValue BinOp = BinOps.back();
12321     BinOps.pop_back();
12322 
12323     if (!Visited.insert(BinOp.getNode()).second)
12324       continue;
12325 
12326     PromOps.push_back(BinOp);
12327 
12328     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12329       // The condition of the select is not promoted.
12330       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12331         continue;
12332       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12333         continue;
12334 
12335       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12336             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12337             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12338            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12339           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12340         Inputs.push_back(BinOp.getOperand(i));
12341       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12342                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12343                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12344                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12345                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12346                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12347                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12348                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12349                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12350         BinOps.push_back(BinOp.getOperand(i));
12351       } else {
12352         // We have an input that is not an extension or another binary
12353         // operation; we'll abort this transformation.
12354         return SDValue();
12355       }
12356     }
12357   }
12358 
12359   // Make sure that this is a self-contained cluster of operations (which
12360   // is not quite the same thing as saying that everything has only one
12361   // use).
12362   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12363     if (isa<ConstantSDNode>(Inputs[i]))
12364       continue;
12365 
12366     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12367                               UE = Inputs[i].getNode()->use_end();
12368          UI != UE; ++UI) {
12369       SDNode *User = *UI;
12370       if (User != N && !Visited.count(User))
12371         return SDValue();
12372 
12373       // Make sure that we're not going to promote the non-output-value
12374       // operand(s) or SELECT or SELECT_CC.
12375       // FIXME: Although we could sometimes handle this, and it does occur in
12376       // practice that one of the condition inputs to the select is also one of
12377       // the outputs, we currently can't deal with this.
12378       if (User->getOpcode() == ISD::SELECT) {
12379         if (User->getOperand(0) == Inputs[i])
12380           return SDValue();
12381       } else if (User->getOpcode() == ISD::SELECT_CC) {
12382         if (User->getOperand(0) == Inputs[i] ||
12383             User->getOperand(1) == Inputs[i])
12384           return SDValue();
12385       }
12386     }
12387   }
12388 
12389   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12390     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12391                               UE = PromOps[i].getNode()->use_end();
12392          UI != UE; ++UI) {
12393       SDNode *User = *UI;
12394       if (User != N && !Visited.count(User))
12395         return SDValue();
12396 
12397       // Make sure that we're not going to promote the non-output-value
12398       // operand(s) or SELECT or SELECT_CC.
12399       // FIXME: Although we could sometimes handle this, and it does occur in
12400       // practice that one of the condition inputs to the select is also one of
12401       // the outputs, we currently can't deal with this.
12402       if (User->getOpcode() == ISD::SELECT) {
12403         if (User->getOperand(0) == PromOps[i])
12404           return SDValue();
12405       } else if (User->getOpcode() == ISD::SELECT_CC) {
12406         if (User->getOperand(0) == PromOps[i] ||
12407             User->getOperand(1) == PromOps[i])
12408           return SDValue();
12409       }
12410     }
12411   }
12412 
12413   // Replace all inputs with the extension operand.
12414   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12415     // Constants may have users outside the cluster of to-be-promoted nodes,
12416     // and so we need to replace those as we do the promotions.
12417     if (isa<ConstantSDNode>(Inputs[i]))
12418       continue;
12419     else
12420       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12421   }
12422 
12423   std::list<HandleSDNode> PromOpHandles;
12424   for (auto &PromOp : PromOps)
12425     PromOpHandles.emplace_back(PromOp);
12426 
12427   // Replace all operations (these are all the same, but have a different
12428   // (i1) return type). DAG.getNode will validate that the types of
12429   // a binary operator match, so go through the list in reverse so that
12430   // we've likely promoted both operands first. Any intermediate truncations or
12431   // extensions disappear.
12432   while (!PromOpHandles.empty()) {
12433     SDValue PromOp = PromOpHandles.back().getValue();
12434     PromOpHandles.pop_back();
12435 
12436     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12437         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12438         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12439         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12440       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12441           PromOp.getOperand(0).getValueType() != MVT::i1) {
12442         // The operand is not yet ready (see comment below).
12443         PromOpHandles.emplace_front(PromOp);
12444         continue;
12445       }
12446 
12447       SDValue RepValue = PromOp.getOperand(0);
12448       if (isa<ConstantSDNode>(RepValue))
12449         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12450 
12451       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12452       continue;
12453     }
12454 
12455     unsigned C;
12456     switch (PromOp.getOpcode()) {
12457     default:             C = 0; break;
12458     case ISD::SELECT:    C = 1; break;
12459     case ISD::SELECT_CC: C = 2; break;
12460     }
12461 
12462     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12463          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12464         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12465          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12466       // The to-be-promoted operands of this node have not yet been
12467       // promoted (this should be rare because we're going through the
12468       // list backward, but if one of the operands has several users in
12469       // this cluster of to-be-promoted nodes, it is possible).
12470       PromOpHandles.emplace_front(PromOp);
12471       continue;
12472     }
12473 
12474     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12475                                 PromOp.getNode()->op_end());
12476 
12477     // If there are any constant inputs, make sure they're replaced now.
12478     for (unsigned i = 0; i < 2; ++i)
12479       if (isa<ConstantSDNode>(Ops[C+i]))
12480         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12481 
12482     DAG.ReplaceAllUsesOfValueWith(PromOp,
12483       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12484   }
12485 
12486   // Now we're left with the initial truncation itself.
12487   if (N->getOpcode() == ISD::TRUNCATE)
12488     return N->getOperand(0);
12489 
12490   // Otherwise, this is a comparison. The operands to be compared have just
12491   // changed type (to i1), but everything else is the same.
12492   return SDValue(N, 0);
12493 }
12494 
12495 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12496                                                   DAGCombinerInfo &DCI) const {
12497   SelectionDAG &DAG = DCI.DAG;
12498   SDLoc dl(N);
12499 
12500   // If we're tracking CR bits, we need to be careful that we don't have:
12501   //   zext(binary-ops(trunc(x), trunc(y)))
12502   // or
12503   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12504   // such that we're unnecessarily moving things into CR bits that can more
12505   // efficiently stay in GPRs. Note that if we're not certain that the high
12506   // bits are set as required by the final extension, we still may need to do
12507   // some masking to get the proper behavior.
12508 
12509   // This same functionality is important on PPC64 when dealing with
12510   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12511   // the return values of functions. Because it is so similar, it is handled
12512   // here as well.
12513 
12514   if (N->getValueType(0) != MVT::i32 &&
12515       N->getValueType(0) != MVT::i64)
12516     return SDValue();
12517 
12518   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12519         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12520     return SDValue();
12521 
12522   if (N->getOperand(0).getOpcode() != ISD::AND &&
12523       N->getOperand(0).getOpcode() != ISD::OR  &&
12524       N->getOperand(0).getOpcode() != ISD::XOR &&
12525       N->getOperand(0).getOpcode() != ISD::SELECT &&
12526       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12527     return SDValue();
12528 
12529   SmallVector<SDValue, 4> Inputs;
12530   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12531   SmallPtrSet<SDNode *, 16> Visited;
12532 
12533   // Visit all inputs, collect all binary operations (and, or, xor and
12534   // select) that are all fed by truncations.
12535   while (!BinOps.empty()) {
12536     SDValue BinOp = BinOps.back();
12537     BinOps.pop_back();
12538 
12539     if (!Visited.insert(BinOp.getNode()).second)
12540       continue;
12541 
12542     PromOps.push_back(BinOp);
12543 
12544     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12545       // The condition of the select is not promoted.
12546       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12547         continue;
12548       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12549         continue;
12550 
12551       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12552           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12553         Inputs.push_back(BinOp.getOperand(i));
12554       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12555                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12556                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12557                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12558                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12559         BinOps.push_back(BinOp.getOperand(i));
12560       } else {
12561         // We have an input that is not a truncation or another binary
12562         // operation; we'll abort this transformation.
12563         return SDValue();
12564       }
12565     }
12566   }
12567 
12568   // The operands of a select that must be truncated when the select is
12569   // promoted because the operand is actually part of the to-be-promoted set.
12570   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12571 
12572   // Make sure that this is a self-contained cluster of operations (which
12573   // is not quite the same thing as saying that everything has only one
12574   // use).
12575   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12576     if (isa<ConstantSDNode>(Inputs[i]))
12577       continue;
12578 
12579     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12580                               UE = Inputs[i].getNode()->use_end();
12581          UI != UE; ++UI) {
12582       SDNode *User = *UI;
12583       if (User != N && !Visited.count(User))
12584         return SDValue();
12585 
12586       // If we're going to promote the non-output-value operand(s) or SELECT or
12587       // SELECT_CC, record them for truncation.
12588       if (User->getOpcode() == ISD::SELECT) {
12589         if (User->getOperand(0) == Inputs[i])
12590           SelectTruncOp[0].insert(std::make_pair(User,
12591                                     User->getOperand(0).getValueType()));
12592       } else if (User->getOpcode() == ISD::SELECT_CC) {
12593         if (User->getOperand(0) == Inputs[i])
12594           SelectTruncOp[0].insert(std::make_pair(User,
12595                                     User->getOperand(0).getValueType()));
12596         if (User->getOperand(1) == Inputs[i])
12597           SelectTruncOp[1].insert(std::make_pair(User,
12598                                     User->getOperand(1).getValueType()));
12599       }
12600     }
12601   }
12602 
12603   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12604     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12605                               UE = PromOps[i].getNode()->use_end();
12606          UI != UE; ++UI) {
12607       SDNode *User = *UI;
12608       if (User != N && !Visited.count(User))
12609         return SDValue();
12610 
12611       // If we're going to promote the non-output-value operand(s) or SELECT or
12612       // SELECT_CC, record them for truncation.
12613       if (User->getOpcode() == ISD::SELECT) {
12614         if (User->getOperand(0) == PromOps[i])
12615           SelectTruncOp[0].insert(std::make_pair(User,
12616                                     User->getOperand(0).getValueType()));
12617       } else if (User->getOpcode() == ISD::SELECT_CC) {
12618         if (User->getOperand(0) == PromOps[i])
12619           SelectTruncOp[0].insert(std::make_pair(User,
12620                                     User->getOperand(0).getValueType()));
12621         if (User->getOperand(1) == PromOps[i])
12622           SelectTruncOp[1].insert(std::make_pair(User,
12623                                     User->getOperand(1).getValueType()));
12624       }
12625     }
12626   }
12627 
12628   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12629   bool ReallyNeedsExt = false;
12630   if (N->getOpcode() != ISD::ANY_EXTEND) {
12631     // If all of the inputs are not already sign/zero extended, then
12632     // we'll still need to do that at the end.
12633     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12634       if (isa<ConstantSDNode>(Inputs[i]))
12635         continue;
12636 
12637       unsigned OpBits =
12638         Inputs[i].getOperand(0).getValueSizeInBits();
12639       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12640 
12641       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12642            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12643                                   APInt::getHighBitsSet(OpBits,
12644                                                         OpBits-PromBits))) ||
12645           (N->getOpcode() == ISD::SIGN_EXTEND &&
12646            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12647              (OpBits-(PromBits-1)))) {
12648         ReallyNeedsExt = true;
12649         break;
12650       }
12651     }
12652   }
12653 
12654   // Replace all inputs, either with the truncation operand, or a
12655   // truncation or extension to the final output type.
12656   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12657     // Constant inputs need to be replaced with the to-be-promoted nodes that
12658     // use them because they might have users outside of the cluster of
12659     // promoted nodes.
12660     if (isa<ConstantSDNode>(Inputs[i]))
12661       continue;
12662 
12663     SDValue InSrc = Inputs[i].getOperand(0);
12664     if (Inputs[i].getValueType() == N->getValueType(0))
12665       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12666     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12667       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12668         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12669     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12670       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12671         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12672     else
12673       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12674         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12675   }
12676 
12677   std::list<HandleSDNode> PromOpHandles;
12678   for (auto &PromOp : PromOps)
12679     PromOpHandles.emplace_back(PromOp);
12680 
12681   // Replace all operations (these are all the same, but have a different
12682   // (promoted) return type). DAG.getNode will validate that the types of
12683   // a binary operator match, so go through the list in reverse so that
12684   // we've likely promoted both operands first.
12685   while (!PromOpHandles.empty()) {
12686     SDValue PromOp = PromOpHandles.back().getValue();
12687     PromOpHandles.pop_back();
12688 
12689     unsigned C;
12690     switch (PromOp.getOpcode()) {
12691     default:             C = 0; break;
12692     case ISD::SELECT:    C = 1; break;
12693     case ISD::SELECT_CC: C = 2; break;
12694     }
12695 
12696     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12697          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12698         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12699          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12700       // The to-be-promoted operands of this node have not yet been
12701       // promoted (this should be rare because we're going through the
12702       // list backward, but if one of the operands has several users in
12703       // this cluster of to-be-promoted nodes, it is possible).
12704       PromOpHandles.emplace_front(PromOp);
12705       continue;
12706     }
12707 
12708     // For SELECT and SELECT_CC nodes, we do a similar check for any
12709     // to-be-promoted comparison inputs.
12710     if (PromOp.getOpcode() == ISD::SELECT ||
12711         PromOp.getOpcode() == ISD::SELECT_CC) {
12712       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12713            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12714           (SelectTruncOp[1].count(PromOp.getNode()) &&
12715            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12716         PromOpHandles.emplace_front(PromOp);
12717         continue;
12718       }
12719     }
12720 
12721     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12722                                 PromOp.getNode()->op_end());
12723 
12724     // If this node has constant inputs, then they'll need to be promoted here.
12725     for (unsigned i = 0; i < 2; ++i) {
12726       if (!isa<ConstantSDNode>(Ops[C+i]))
12727         continue;
12728       if (Ops[C+i].getValueType() == N->getValueType(0))
12729         continue;
12730 
12731       if (N->getOpcode() == ISD::SIGN_EXTEND)
12732         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12733       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12734         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12735       else
12736         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12737     }
12738 
12739     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12740     // truncate them again to the original value type.
12741     if (PromOp.getOpcode() == ISD::SELECT ||
12742         PromOp.getOpcode() == ISD::SELECT_CC) {
12743       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12744       if (SI0 != SelectTruncOp[0].end())
12745         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12746       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12747       if (SI1 != SelectTruncOp[1].end())
12748         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12749     }
12750 
12751     DAG.ReplaceAllUsesOfValueWith(PromOp,
12752       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12753   }
12754 
12755   // Now we're left with the initial extension itself.
12756   if (!ReallyNeedsExt)
12757     return N->getOperand(0);
12758 
12759   // To zero extend, just mask off everything except for the first bit (in the
12760   // i1 case).
12761   if (N->getOpcode() == ISD::ZERO_EXTEND)
12762     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12763                        DAG.getConstant(APInt::getLowBitsSet(
12764                                          N->getValueSizeInBits(0), PromBits),
12765                                        dl, N->getValueType(0)));
12766 
12767   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12768          "Invalid extension type");
12769   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12770   SDValue ShiftCst =
12771       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12772   return DAG.getNode(
12773       ISD::SRA, dl, N->getValueType(0),
12774       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12775       ShiftCst);
12776 }
12777 
12778 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12779                                         DAGCombinerInfo &DCI) const {
12780   assert(N->getOpcode() == ISD::SETCC &&
12781          "Should be called with a SETCC node");
12782 
12783   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12784   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12785     SDValue LHS = N->getOperand(0);
12786     SDValue RHS = N->getOperand(1);
12787 
12788     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12789     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12790         LHS.hasOneUse())
12791       std::swap(LHS, RHS);
12792 
12793     // x == 0-y --> x+y == 0
12794     // x != 0-y --> x+y != 0
12795     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12796         RHS.hasOneUse()) {
12797       SDLoc DL(N);
12798       SelectionDAG &DAG = DCI.DAG;
12799       EVT VT = N->getValueType(0);
12800       EVT OpVT = LHS.getValueType();
12801       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12802       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12803     }
12804   }
12805 
12806   return DAGCombineTruncBoolExt(N, DCI);
12807 }
12808 
12809 // Is this an extending load from an f32 to an f64?
12810 static bool isFPExtLoad(SDValue Op) {
12811   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12812     return LD->getExtensionType() == ISD::EXTLOAD &&
12813       Op.getValueType() == MVT::f64;
12814   return false;
12815 }
12816 
12817 /// Reduces the number of fp-to-int conversion when building a vector.
12818 ///
12819 /// If this vector is built out of floating to integer conversions,
12820 /// transform it to a vector built out of floating point values followed by a
12821 /// single floating to integer conversion of the vector.
12822 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12823 /// becomes (fptosi (build_vector ($A, $B, ...)))
12824 SDValue PPCTargetLowering::
12825 combineElementTruncationToVectorTruncation(SDNode *N,
12826                                            DAGCombinerInfo &DCI) const {
12827   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12828          "Should be called with a BUILD_VECTOR node");
12829 
12830   SelectionDAG &DAG = DCI.DAG;
12831   SDLoc dl(N);
12832 
12833   SDValue FirstInput = N->getOperand(0);
12834   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12835          "The input operand must be an fp-to-int conversion.");
12836 
12837   // This combine happens after legalization so the fp_to_[su]i nodes are
12838   // already converted to PPCSISD nodes.
12839   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12840   if (FirstConversion == PPCISD::FCTIDZ ||
12841       FirstConversion == PPCISD::FCTIDUZ ||
12842       FirstConversion == PPCISD::FCTIWZ ||
12843       FirstConversion == PPCISD::FCTIWUZ) {
12844     bool IsSplat = true;
12845     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12846       FirstConversion == PPCISD::FCTIWUZ;
12847     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12848     SmallVector<SDValue, 4> Ops;
12849     EVT TargetVT = N->getValueType(0);
12850     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12851       SDValue NextOp = N->getOperand(i);
12852       if (NextOp.getOpcode() != PPCISD::MFVSR)
12853         return SDValue();
12854       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12855       if (NextConversion != FirstConversion)
12856         return SDValue();
12857       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12858       // This is not valid if the input was originally double precision. It is
12859       // also not profitable to do unless this is an extending load in which
12860       // case doing this combine will allow us to combine consecutive loads.
12861       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12862         return SDValue();
12863       if (N->getOperand(i) != FirstInput)
12864         IsSplat = false;
12865     }
12866 
12867     // If this is a splat, we leave it as-is since there will be only a single
12868     // fp-to-int conversion followed by a splat of the integer. This is better
12869     // for 32-bit and smaller ints and neutral for 64-bit ints.
12870     if (IsSplat)
12871       return SDValue();
12872 
12873     // Now that we know we have the right type of node, get its operands
12874     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12875       SDValue In = N->getOperand(i).getOperand(0);
12876       if (Is32Bit) {
12877         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12878         // here, we know that all inputs are extending loads so this is safe).
12879         if (In.isUndef())
12880           Ops.push_back(DAG.getUNDEF(SrcVT));
12881         else {
12882           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12883                                       MVT::f32, In.getOperand(0),
12884                                       DAG.getIntPtrConstant(1, dl));
12885           Ops.push_back(Trunc);
12886         }
12887       } else
12888         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12889     }
12890 
12891     unsigned Opcode;
12892     if (FirstConversion == PPCISD::FCTIDZ ||
12893         FirstConversion == PPCISD::FCTIWZ)
12894       Opcode = ISD::FP_TO_SINT;
12895     else
12896       Opcode = ISD::FP_TO_UINT;
12897 
12898     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12899     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12900     return DAG.getNode(Opcode, dl, TargetVT, BV);
12901   }
12902   return SDValue();
12903 }
12904 
12905 /// Reduce the number of loads when building a vector.
12906 ///
12907 /// Building a vector out of multiple loads can be converted to a load
12908 /// of the vector type if the loads are consecutive. If the loads are
12909 /// consecutive but in descending order, a shuffle is added at the end
12910 /// to reorder the vector.
12911 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12912   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12913          "Should be called with a BUILD_VECTOR node");
12914 
12915   SDLoc dl(N);
12916 
12917   // Return early for non byte-sized type, as they can't be consecutive.
12918   if (!N->getValueType(0).getVectorElementType().isByteSized())
12919     return SDValue();
12920 
12921   bool InputsAreConsecutiveLoads = true;
12922   bool InputsAreReverseConsecutive = true;
12923   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12924   SDValue FirstInput = N->getOperand(0);
12925   bool IsRoundOfExtLoad = false;
12926 
12927   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12928       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12929     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12930     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12931   }
12932   // Not a build vector of (possibly fp_rounded) loads.
12933   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12934       N->getNumOperands() == 1)
12935     return SDValue();
12936 
12937   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12938     // If any inputs are fp_round(extload), they all must be.
12939     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12940       return SDValue();
12941 
12942     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12943       N->getOperand(i);
12944     if (NextInput.getOpcode() != ISD::LOAD)
12945       return SDValue();
12946 
12947     SDValue PreviousInput =
12948       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12949     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12950     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12951 
12952     // If any inputs are fp_round(extload), they all must be.
12953     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12954       return SDValue();
12955 
12956     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12957       InputsAreConsecutiveLoads = false;
12958     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12959       InputsAreReverseConsecutive = false;
12960 
12961     // Exit early if the loads are neither consecutive nor reverse consecutive.
12962     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12963       return SDValue();
12964   }
12965 
12966   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12967          "The loads cannot be both consecutive and reverse consecutive.");
12968 
12969   SDValue FirstLoadOp =
12970     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12971   SDValue LastLoadOp =
12972     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12973                        N->getOperand(N->getNumOperands()-1);
12974 
12975   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12976   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12977   if (InputsAreConsecutiveLoads) {
12978     assert(LD1 && "Input needs to be a LoadSDNode.");
12979     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12980                        LD1->getBasePtr(), LD1->getPointerInfo(),
12981                        LD1->getAlignment());
12982   }
12983   if (InputsAreReverseConsecutive) {
12984     assert(LDL && "Input needs to be a LoadSDNode.");
12985     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12986                                LDL->getBasePtr(), LDL->getPointerInfo(),
12987                                LDL->getAlignment());
12988     SmallVector<int, 16> Ops;
12989     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12990       Ops.push_back(i);
12991 
12992     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12993                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12994   }
12995   return SDValue();
12996 }
12997 
12998 // This function adds the required vector_shuffle needed to get
12999 // the elements of the vector extract in the correct position
13000 // as specified by the CorrectElems encoding.
13001 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
13002                                       SDValue Input, uint64_t Elems,
13003                                       uint64_t CorrectElems) {
13004   SDLoc dl(N);
13005 
13006   unsigned NumElems = Input.getValueType().getVectorNumElements();
13007   SmallVector<int, 16> ShuffleMask(NumElems, -1);
13008 
13009   // Knowing the element indices being extracted from the original
13010   // vector and the order in which they're being inserted, just put
13011   // them at element indices required for the instruction.
13012   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13013     if (DAG.getDataLayout().isLittleEndian())
13014       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
13015     else
13016       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
13017     CorrectElems = CorrectElems >> 8;
13018     Elems = Elems >> 8;
13019   }
13020 
13021   SDValue Shuffle =
13022       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
13023                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
13024 
13025   EVT Ty = N->getValueType(0);
13026   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
13027   return BV;
13028 }
13029 
13030 // Look for build vector patterns where input operands come from sign
13031 // extended vector_extract elements of specific indices. If the correct indices
13032 // aren't used, add a vector shuffle to fix up the indices and create a new
13033 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13034 // during instruction selection.
13035 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13036   // This array encodes the indices that the vector sign extend instructions
13037   // extract from when extending from one type to another for both BE and LE.
13038   // The right nibble of each byte corresponds to the LE incides.
13039   // and the left nibble of each byte corresponds to the BE incides.
13040   // For example: 0x3074B8FC  byte->word
13041   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13042   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13043   // For example: 0x000070F8  byte->double word
13044   // For LE: the allowed indices are: 0x0,0x8
13045   // For BE: the allowed indices are: 0x7,0xF
13046   uint64_t TargetElems[] = {
13047       0x3074B8FC, // b->w
13048       0x000070F8, // b->d
13049       0x10325476, // h->w
13050       0x00003074, // h->d
13051       0x00001032, // w->d
13052   };
13053 
13054   uint64_t Elems = 0;
13055   int Index;
13056   SDValue Input;
13057 
13058   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13059     if (!Op)
13060       return false;
13061     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13062         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13063       return false;
13064 
13065     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13066     // of the right width.
13067     SDValue Extract = Op.getOperand(0);
13068     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13069       Extract = Extract.getOperand(0);
13070     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13071       return false;
13072 
13073     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13074     if (!ExtOp)
13075       return false;
13076 
13077     Index = ExtOp->getZExtValue();
13078     if (Input && Input != Extract.getOperand(0))
13079       return false;
13080 
13081     if (!Input)
13082       Input = Extract.getOperand(0);
13083 
13084     Elems = Elems << 8;
13085     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13086     Elems |= Index;
13087 
13088     return true;
13089   };
13090 
13091   // If the build vector operands aren't sign extended vector extracts,
13092   // of the same input vector, then return.
13093   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13094     if (!isSExtOfVecExtract(N->getOperand(i))) {
13095       return SDValue();
13096     }
13097   }
13098 
13099   // If the vector extract indicies are not correct, add the appropriate
13100   // vector_shuffle.
13101   int TgtElemArrayIdx;
13102   int InputSize = Input.getValueType().getScalarSizeInBits();
13103   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13104   if (InputSize + OutputSize == 40)
13105     TgtElemArrayIdx = 0;
13106   else if (InputSize + OutputSize == 72)
13107     TgtElemArrayIdx = 1;
13108   else if (InputSize + OutputSize == 48)
13109     TgtElemArrayIdx = 2;
13110   else if (InputSize + OutputSize == 80)
13111     TgtElemArrayIdx = 3;
13112   else if (InputSize + OutputSize == 96)
13113     TgtElemArrayIdx = 4;
13114   else
13115     return SDValue();
13116 
13117   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13118   CorrectElems = DAG.getDataLayout().isLittleEndian()
13119                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13120                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13121   if (Elems != CorrectElems) {
13122     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13123   }
13124 
13125   // Regular lowering will catch cases where a shuffle is not needed.
13126   return SDValue();
13127 }
13128 
13129 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13130                                                  DAGCombinerInfo &DCI) const {
13131   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13132          "Should be called with a BUILD_VECTOR node");
13133 
13134   SelectionDAG &DAG = DCI.DAG;
13135   SDLoc dl(N);
13136 
13137   if (!Subtarget.hasVSX())
13138     return SDValue();
13139 
13140   // The target independent DAG combiner will leave a build_vector of
13141   // float-to-int conversions intact. We can generate MUCH better code for
13142   // a float-to-int conversion of a vector of floats.
13143   SDValue FirstInput = N->getOperand(0);
13144   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13145     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13146     if (Reduced)
13147       return Reduced;
13148   }
13149 
13150   // If we're building a vector out of consecutive loads, just load that
13151   // vector type.
13152   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13153   if (Reduced)
13154     return Reduced;
13155 
13156   // If we're building a vector out of extended elements from another vector
13157   // we have P9 vector integer extend instructions. The code assumes legal
13158   // input types (i.e. it can't handle things like v4i16) so do not run before
13159   // legalization.
13160   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13161     Reduced = combineBVOfVecSExt(N, DAG);
13162     if (Reduced)
13163       return Reduced;
13164   }
13165 
13166 
13167   if (N->getValueType(0) != MVT::v2f64)
13168     return SDValue();
13169 
13170   // Looking for:
13171   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13172   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13173       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13174     return SDValue();
13175   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13176       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13177     return SDValue();
13178   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13179     return SDValue();
13180 
13181   SDValue Ext1 = FirstInput.getOperand(0);
13182   SDValue Ext2 = N->getOperand(1).getOperand(0);
13183   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13184      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13185     return SDValue();
13186 
13187   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13188   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13189   if (!Ext1Op || !Ext2Op)
13190     return SDValue();
13191   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13192       Ext1.getOperand(0) != Ext2.getOperand(0))
13193     return SDValue();
13194 
13195   int FirstElem = Ext1Op->getZExtValue();
13196   int SecondElem = Ext2Op->getZExtValue();
13197   int SubvecIdx;
13198   if (FirstElem == 0 && SecondElem == 1)
13199     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13200   else if (FirstElem == 2 && SecondElem == 3)
13201     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13202   else
13203     return SDValue();
13204 
13205   SDValue SrcVec = Ext1.getOperand(0);
13206   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13207     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13208   return DAG.getNode(NodeType, dl, MVT::v2f64,
13209                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13210 }
13211 
13212 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13213                                               DAGCombinerInfo &DCI) const {
13214   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13215           N->getOpcode() == ISD::UINT_TO_FP) &&
13216          "Need an int -> FP conversion node here");
13217 
13218   if (useSoftFloat() || !Subtarget.has64BitSupport())
13219     return SDValue();
13220 
13221   SelectionDAG &DAG = DCI.DAG;
13222   SDLoc dl(N);
13223   SDValue Op(N, 0);
13224 
13225   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13226   // from the hardware.
13227   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13228     return SDValue();
13229   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13230       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13231     return SDValue();
13232 
13233   SDValue FirstOperand(Op.getOperand(0));
13234   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13235     (FirstOperand.getValueType() == MVT::i8 ||
13236      FirstOperand.getValueType() == MVT::i16);
13237   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13238     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13239     bool DstDouble = Op.getValueType() == MVT::f64;
13240     unsigned ConvOp = Signed ?
13241       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13242       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13243     SDValue WidthConst =
13244       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13245                             dl, false);
13246     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13247     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13248     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13249                                          DAG.getVTList(MVT::f64, MVT::Other),
13250                                          Ops, MVT::i8, LDN->getMemOperand());
13251 
13252     // For signed conversion, we need to sign-extend the value in the VSR
13253     if (Signed) {
13254       SDValue ExtOps[] = { Ld, WidthConst };
13255       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13256       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13257     } else
13258       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13259   }
13260 
13261 
13262   // For i32 intermediate values, unfortunately, the conversion functions
13263   // leave the upper 32 bits of the value are undefined. Within the set of
13264   // scalar instructions, we have no method for zero- or sign-extending the
13265   // value. Thus, we cannot handle i32 intermediate values here.
13266   if (Op.getOperand(0).getValueType() == MVT::i32)
13267     return SDValue();
13268 
13269   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13270          "UINT_TO_FP is supported only with FPCVT");
13271 
13272   // If we have FCFIDS, then use it when converting to single-precision.
13273   // Otherwise, convert to double-precision and then round.
13274   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13275                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13276                                                             : PPCISD::FCFIDS)
13277                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13278                                                             : PPCISD::FCFID);
13279   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13280                   ? MVT::f32
13281                   : MVT::f64;
13282 
13283   // If we're converting from a float, to an int, and back to a float again,
13284   // then we don't need the store/load pair at all.
13285   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13286        Subtarget.hasFPCVT()) ||
13287       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13288     SDValue Src = Op.getOperand(0).getOperand(0);
13289     if (Src.getValueType() == MVT::f32) {
13290       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13291       DCI.AddToWorklist(Src.getNode());
13292     } else if (Src.getValueType() != MVT::f64) {
13293       // Make sure that we don't pick up a ppc_fp128 source value.
13294       return SDValue();
13295     }
13296 
13297     unsigned FCTOp =
13298       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13299                                                         PPCISD::FCTIDUZ;
13300 
13301     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13302     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13303 
13304     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13305       FP = DAG.getNode(ISD::FP_ROUND, dl,
13306                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13307       DCI.AddToWorklist(FP.getNode());
13308     }
13309 
13310     return FP;
13311   }
13312 
13313   return SDValue();
13314 }
13315 
13316 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13317 // builtins) into loads with swaps.
13318 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13319                                               DAGCombinerInfo &DCI) const {
13320   SelectionDAG &DAG = DCI.DAG;
13321   SDLoc dl(N);
13322   SDValue Chain;
13323   SDValue Base;
13324   MachineMemOperand *MMO;
13325 
13326   switch (N->getOpcode()) {
13327   default:
13328     llvm_unreachable("Unexpected opcode for little endian VSX load");
13329   case ISD::LOAD: {
13330     LoadSDNode *LD = cast<LoadSDNode>(N);
13331     Chain = LD->getChain();
13332     Base = LD->getBasePtr();
13333     MMO = LD->getMemOperand();
13334     // If the MMO suggests this isn't a load of a full vector, leave
13335     // things alone.  For a built-in, we have to make the change for
13336     // correctness, so if there is a size problem that will be a bug.
13337     if (MMO->getSize() < 16)
13338       return SDValue();
13339     break;
13340   }
13341   case ISD::INTRINSIC_W_CHAIN: {
13342     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13343     Chain = Intrin->getChain();
13344     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13345     // us what we want. Get operand 2 instead.
13346     Base = Intrin->getOperand(2);
13347     MMO = Intrin->getMemOperand();
13348     break;
13349   }
13350   }
13351 
13352   MVT VecTy = N->getValueType(0).getSimpleVT();
13353 
13354   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13355   // aligned and the type is a vector with elements up to 4 bytes
13356   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13357       && VecTy.getScalarSizeInBits() <= 32 ) {
13358     return SDValue();
13359   }
13360 
13361   SDValue LoadOps[] = { Chain, Base };
13362   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13363                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13364                                          LoadOps, MVT::v2f64, MMO);
13365 
13366   DCI.AddToWorklist(Load.getNode());
13367   Chain = Load.getValue(1);
13368   SDValue Swap = DAG.getNode(
13369       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13370   DCI.AddToWorklist(Swap.getNode());
13371 
13372   // Add a bitcast if the resulting load type doesn't match v2f64.
13373   if (VecTy != MVT::v2f64) {
13374     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13375     DCI.AddToWorklist(N.getNode());
13376     // Package {bitcast value, swap's chain} to match Load's shape.
13377     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13378                        N, Swap.getValue(1));
13379   }
13380 
13381   return Swap;
13382 }
13383 
13384 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13385 // builtins) into stores with swaps.
13386 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13387                                                DAGCombinerInfo &DCI) const {
13388   SelectionDAG &DAG = DCI.DAG;
13389   SDLoc dl(N);
13390   SDValue Chain;
13391   SDValue Base;
13392   unsigned SrcOpnd;
13393   MachineMemOperand *MMO;
13394 
13395   switch (N->getOpcode()) {
13396   default:
13397     llvm_unreachable("Unexpected opcode for little endian VSX store");
13398   case ISD::STORE: {
13399     StoreSDNode *ST = cast<StoreSDNode>(N);
13400     Chain = ST->getChain();
13401     Base = ST->getBasePtr();
13402     MMO = ST->getMemOperand();
13403     SrcOpnd = 1;
13404     // If the MMO suggests this isn't a store of a full vector, leave
13405     // things alone.  For a built-in, we have to make the change for
13406     // correctness, so if there is a size problem that will be a bug.
13407     if (MMO->getSize() < 16)
13408       return SDValue();
13409     break;
13410   }
13411   case ISD::INTRINSIC_VOID: {
13412     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13413     Chain = Intrin->getChain();
13414     // Intrin->getBasePtr() oddly does not get what we want.
13415     Base = Intrin->getOperand(3);
13416     MMO = Intrin->getMemOperand();
13417     SrcOpnd = 2;
13418     break;
13419   }
13420   }
13421 
13422   SDValue Src = N->getOperand(SrcOpnd);
13423   MVT VecTy = Src.getValueType().getSimpleVT();
13424 
13425   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13426   // aligned and the type is a vector with elements up to 4 bytes
13427   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13428       && VecTy.getScalarSizeInBits() <= 32 ) {
13429     return SDValue();
13430   }
13431 
13432   // All stores are done as v2f64 and possible bit cast.
13433   if (VecTy != MVT::v2f64) {
13434     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13435     DCI.AddToWorklist(Src.getNode());
13436   }
13437 
13438   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13439                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13440   DCI.AddToWorklist(Swap.getNode());
13441   Chain = Swap.getValue(1);
13442   SDValue StoreOps[] = { Chain, Swap, Base };
13443   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13444                                           DAG.getVTList(MVT::Other),
13445                                           StoreOps, VecTy, MMO);
13446   DCI.AddToWorklist(Store.getNode());
13447   return Store;
13448 }
13449 
13450 // Handle DAG combine for STORE (FP_TO_INT F).
13451 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13452                                                DAGCombinerInfo &DCI) const {
13453 
13454   SelectionDAG &DAG = DCI.DAG;
13455   SDLoc dl(N);
13456   unsigned Opcode = N->getOperand(1).getOpcode();
13457 
13458   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13459          && "Not a FP_TO_INT Instruction!");
13460 
13461   SDValue Val = N->getOperand(1).getOperand(0);
13462   EVT Op1VT = N->getOperand(1).getValueType();
13463   EVT ResVT = Val.getValueType();
13464 
13465   // Floating point types smaller than 32 bits are not legal on Power.
13466   if (ResVT.getScalarSizeInBits() < 32)
13467     return SDValue();
13468 
13469   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13470   bool ValidTypeForStoreFltAsInt =
13471         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13472          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13473 
13474   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13475       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13476     return SDValue();
13477 
13478   // Extend f32 values to f64
13479   if (ResVT.getScalarSizeInBits() == 32) {
13480     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13481     DCI.AddToWorklist(Val.getNode());
13482   }
13483 
13484   // Set signed or unsigned conversion opcode.
13485   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13486                           PPCISD::FP_TO_SINT_IN_VSR :
13487                           PPCISD::FP_TO_UINT_IN_VSR;
13488 
13489   Val = DAG.getNode(ConvOpcode,
13490                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13491   DCI.AddToWorklist(Val.getNode());
13492 
13493   // Set number of bytes being converted.
13494   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13495   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13496                     DAG.getIntPtrConstant(ByteSize, dl, false),
13497                     DAG.getValueType(Op1VT) };
13498 
13499   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13500           DAG.getVTList(MVT::Other), Ops,
13501           cast<StoreSDNode>(N)->getMemoryVT(),
13502           cast<StoreSDNode>(N)->getMemOperand());
13503 
13504   DCI.AddToWorklist(Val.getNode());
13505   return Val;
13506 }
13507 
13508 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13509                                                 LSBaseSDNode *LSBase,
13510                                                 DAGCombinerInfo &DCI) const {
13511   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13512         "Not a reverse memop pattern!");
13513 
13514   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13515     auto Mask = SVN->getMask();
13516     int i = 0;
13517     auto I = Mask.rbegin();
13518     auto E = Mask.rend();
13519 
13520     for (; I != E; ++I) {
13521       if (*I != i)
13522         return false;
13523       i++;
13524     }
13525     return true;
13526   };
13527 
13528   SelectionDAG &DAG = DCI.DAG;
13529   EVT VT = SVN->getValueType(0);
13530 
13531   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13532     return SDValue();
13533 
13534   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13535   // See comment in PPCVSXSwapRemoval.cpp.
13536   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13537   if (!Subtarget.hasP9Vector())
13538     return SDValue();
13539 
13540   if(!IsElementReverse(SVN))
13541     return SDValue();
13542 
13543   if (LSBase->getOpcode() == ISD::LOAD) {
13544     SDLoc dl(SVN);
13545     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13546     return DAG.getMemIntrinsicNode(
13547         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13548         LSBase->getMemoryVT(), LSBase->getMemOperand());
13549   }
13550 
13551   if (LSBase->getOpcode() == ISD::STORE) {
13552     SDLoc dl(LSBase);
13553     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13554                           LSBase->getBasePtr()};
13555     return DAG.getMemIntrinsicNode(
13556         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13557         LSBase->getMemoryVT(), LSBase->getMemOperand());
13558   }
13559 
13560   llvm_unreachable("Expected a load or store node here");
13561 }
13562 
13563 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13564                                              DAGCombinerInfo &DCI) const {
13565   SelectionDAG &DAG = DCI.DAG;
13566   SDLoc dl(N);
13567   switch (N->getOpcode()) {
13568   default: break;
13569   case ISD::ADD:
13570     return combineADD(N, DCI);
13571   case ISD::SHL:
13572     return combineSHL(N, DCI);
13573   case ISD::SRA:
13574     return combineSRA(N, DCI);
13575   case ISD::SRL:
13576     return combineSRL(N, DCI);
13577   case ISD::MUL:
13578     return combineMUL(N, DCI);
13579   case PPCISD::SHL:
13580     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13581         return N->getOperand(0);
13582     break;
13583   case PPCISD::SRL:
13584     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13585         return N->getOperand(0);
13586     break;
13587   case PPCISD::SRA:
13588     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13589       if (C->isNullValue() ||   //  0 >>s V -> 0.
13590           C->isAllOnesValue())    // -1 >>s V -> -1.
13591         return N->getOperand(0);
13592     }
13593     break;
13594   case ISD::SIGN_EXTEND:
13595   case ISD::ZERO_EXTEND:
13596   case ISD::ANY_EXTEND:
13597     return DAGCombineExtBoolTrunc(N, DCI);
13598   case ISD::TRUNCATE:
13599     return combineTRUNCATE(N, DCI);
13600   case ISD::SETCC:
13601     if (SDValue CSCC = combineSetCC(N, DCI))
13602       return CSCC;
13603     LLVM_FALLTHROUGH;
13604   case ISD::SELECT_CC:
13605     return DAGCombineTruncBoolExt(N, DCI);
13606   case ISD::SINT_TO_FP:
13607   case ISD::UINT_TO_FP:
13608     return combineFPToIntToFP(N, DCI);
13609   case ISD::VECTOR_SHUFFLE:
13610     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13611       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13612       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13613     }
13614     break;
13615   case ISD::STORE: {
13616 
13617     EVT Op1VT = N->getOperand(1).getValueType();
13618     unsigned Opcode = N->getOperand(1).getOpcode();
13619 
13620     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13621       SDValue Val= combineStoreFPToInt(N, DCI);
13622       if (Val)
13623         return Val;
13624     }
13625 
13626     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13627       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13628       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13629       if (Val)
13630         return Val;
13631     }
13632 
13633     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13634     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13635         N->getOperand(1).getNode()->hasOneUse() &&
13636         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13637          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13638 
13639       // STBRX can only handle simple types and it makes no sense to store less
13640       // two bytes in byte-reversed order.
13641       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13642       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13643         break;
13644 
13645       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13646       // Do an any-extend to 32-bits if this is a half-word input.
13647       if (BSwapOp.getValueType() == MVT::i16)
13648         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13649 
13650       // If the type of BSWAP operand is wider than stored memory width
13651       // it need to be shifted to the right side before STBRX.
13652       if (Op1VT.bitsGT(mVT)) {
13653         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13654         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13655                               DAG.getConstant(Shift, dl, MVT::i32));
13656         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13657         if (Op1VT == MVT::i64)
13658           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13659       }
13660 
13661       SDValue Ops[] = {
13662         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13663       };
13664       return
13665         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13666                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13667                                 cast<StoreSDNode>(N)->getMemOperand());
13668     }
13669 
13670     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13671     // So it can increase the chance of CSE constant construction.
13672     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13673         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13674       // Need to sign-extended to 64-bits to handle negative values.
13675       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13676       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13677                                     MemVT.getSizeInBits());
13678       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13679 
13680       // DAG.getTruncStore() can't be used here because it doesn't accept
13681       // the general (base + offset) addressing mode.
13682       // So we use UpdateNodeOperands and setTruncatingStore instead.
13683       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13684                              N->getOperand(3));
13685       cast<StoreSDNode>(N)->setTruncatingStore(true);
13686       return SDValue(N, 0);
13687     }
13688 
13689     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13690     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13691     if (Op1VT.isSimple()) {
13692       MVT StoreVT = Op1VT.getSimpleVT();
13693       if (Subtarget.needsSwapsForVSXMemOps() &&
13694           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13695            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13696         return expandVSXStoreForLE(N, DCI);
13697     }
13698     break;
13699   }
13700   case ISD::LOAD: {
13701     LoadSDNode *LD = cast<LoadSDNode>(N);
13702     EVT VT = LD->getValueType(0);
13703 
13704     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13705     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13706     if (VT.isSimple()) {
13707       MVT LoadVT = VT.getSimpleVT();
13708       if (Subtarget.needsSwapsForVSXMemOps() &&
13709           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13710            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13711         return expandVSXLoadForLE(N, DCI);
13712     }
13713 
13714     // We sometimes end up with a 64-bit integer load, from which we extract
13715     // two single-precision floating-point numbers. This happens with
13716     // std::complex<float>, and other similar structures, because of the way we
13717     // canonicalize structure copies. However, if we lack direct moves,
13718     // then the final bitcasts from the extracted integer values to the
13719     // floating-point numbers turn into store/load pairs. Even with direct moves,
13720     // just loading the two floating-point numbers is likely better.
13721     auto ReplaceTwoFloatLoad = [&]() {
13722       if (VT != MVT::i64)
13723         return false;
13724 
13725       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13726           LD->isVolatile())
13727         return false;
13728 
13729       //  We're looking for a sequence like this:
13730       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13731       //      t16: i64 = srl t13, Constant:i32<32>
13732       //    t17: i32 = truncate t16
13733       //  t18: f32 = bitcast t17
13734       //    t19: i32 = truncate t13
13735       //  t20: f32 = bitcast t19
13736 
13737       if (!LD->hasNUsesOfValue(2, 0))
13738         return false;
13739 
13740       auto UI = LD->use_begin();
13741       while (UI.getUse().getResNo() != 0) ++UI;
13742       SDNode *Trunc = *UI++;
13743       while (UI.getUse().getResNo() != 0) ++UI;
13744       SDNode *RightShift = *UI;
13745       if (Trunc->getOpcode() != ISD::TRUNCATE)
13746         std::swap(Trunc, RightShift);
13747 
13748       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13749           Trunc->getValueType(0) != MVT::i32 ||
13750           !Trunc->hasOneUse())
13751         return false;
13752       if (RightShift->getOpcode() != ISD::SRL ||
13753           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13754           RightShift->getConstantOperandVal(1) != 32 ||
13755           !RightShift->hasOneUse())
13756         return false;
13757 
13758       SDNode *Trunc2 = *RightShift->use_begin();
13759       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13760           Trunc2->getValueType(0) != MVT::i32 ||
13761           !Trunc2->hasOneUse())
13762         return false;
13763 
13764       SDNode *Bitcast = *Trunc->use_begin();
13765       SDNode *Bitcast2 = *Trunc2->use_begin();
13766 
13767       if (Bitcast->getOpcode() != ISD::BITCAST ||
13768           Bitcast->getValueType(0) != MVT::f32)
13769         return false;
13770       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13771           Bitcast2->getValueType(0) != MVT::f32)
13772         return false;
13773 
13774       if (Subtarget.isLittleEndian())
13775         std::swap(Bitcast, Bitcast2);
13776 
13777       // Bitcast has the second float (in memory-layout order) and Bitcast2
13778       // has the first one.
13779 
13780       SDValue BasePtr = LD->getBasePtr();
13781       if (LD->isIndexed()) {
13782         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13783                "Non-pre-inc AM on PPC?");
13784         BasePtr =
13785           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13786                       LD->getOffset());
13787       }
13788 
13789       auto MMOFlags =
13790           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13791       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13792                                       LD->getPointerInfo(), LD->getAlignment(),
13793                                       MMOFlags, LD->getAAInfo());
13794       SDValue AddPtr =
13795         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13796                     BasePtr, DAG.getIntPtrConstant(4, dl));
13797       SDValue FloatLoad2 = DAG.getLoad(
13798           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13799           LD->getPointerInfo().getWithOffset(4),
13800           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13801 
13802       if (LD->isIndexed()) {
13803         // Note that DAGCombine should re-form any pre-increment load(s) from
13804         // what is produced here if that makes sense.
13805         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13806       }
13807 
13808       DCI.CombineTo(Bitcast2, FloatLoad);
13809       DCI.CombineTo(Bitcast, FloatLoad2);
13810 
13811       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13812                                     SDValue(FloatLoad2.getNode(), 1));
13813       return true;
13814     };
13815 
13816     if (ReplaceTwoFloatLoad())
13817       return SDValue(N, 0);
13818 
13819     EVT MemVT = LD->getMemoryVT();
13820     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13821     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13822     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13823     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13824     if (LD->isUnindexed() && VT.isVector() &&
13825         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13826           // P8 and later hardware should just use LOAD.
13827           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13828                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13829          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13830           LD->getAlignment() >= ScalarABIAlignment)) &&
13831         LD->getAlignment() < ABIAlignment) {
13832       // This is a type-legal unaligned Altivec or QPX load.
13833       SDValue Chain = LD->getChain();
13834       SDValue Ptr = LD->getBasePtr();
13835       bool isLittleEndian = Subtarget.isLittleEndian();
13836 
13837       // This implements the loading of unaligned vectors as described in
13838       // the venerable Apple Velocity Engine overview. Specifically:
13839       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13840       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13841       //
13842       // The general idea is to expand a sequence of one or more unaligned
13843       // loads into an alignment-based permutation-control instruction (lvsl
13844       // or lvsr), a series of regular vector loads (which always truncate
13845       // their input address to an aligned address), and a series of
13846       // permutations.  The results of these permutations are the requested
13847       // loaded values.  The trick is that the last "extra" load is not taken
13848       // from the address you might suspect (sizeof(vector) bytes after the
13849       // last requested load), but rather sizeof(vector) - 1 bytes after the
13850       // last requested vector. The point of this is to avoid a page fault if
13851       // the base address happened to be aligned. This works because if the
13852       // base address is aligned, then adding less than a full vector length
13853       // will cause the last vector in the sequence to be (re)loaded.
13854       // Otherwise, the next vector will be fetched as you might suspect was
13855       // necessary.
13856 
13857       // We might be able to reuse the permutation generation from
13858       // a different base address offset from this one by an aligned amount.
13859       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13860       // optimization later.
13861       Intrinsic::ID Intr, IntrLD, IntrPerm;
13862       MVT PermCntlTy, PermTy, LDTy;
13863       if (Subtarget.hasAltivec()) {
13864         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13865                                  Intrinsic::ppc_altivec_lvsl;
13866         IntrLD = Intrinsic::ppc_altivec_lvx;
13867         IntrPerm = Intrinsic::ppc_altivec_vperm;
13868         PermCntlTy = MVT::v16i8;
13869         PermTy = MVT::v4i32;
13870         LDTy = MVT::v4i32;
13871       } else {
13872         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13873                                        Intrinsic::ppc_qpx_qvlpcls;
13874         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13875                                        Intrinsic::ppc_qpx_qvlfs;
13876         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13877         PermCntlTy = MVT::v4f64;
13878         PermTy = MVT::v4f64;
13879         LDTy = MemVT.getSimpleVT();
13880       }
13881 
13882       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13883 
13884       // Create the new MMO for the new base load. It is like the original MMO,
13885       // but represents an area in memory almost twice the vector size centered
13886       // on the original address. If the address is unaligned, we might start
13887       // reading up to (sizeof(vector)-1) bytes below the address of the
13888       // original unaligned load.
13889       MachineFunction &MF = DAG.getMachineFunction();
13890       MachineMemOperand *BaseMMO =
13891         MF.getMachineMemOperand(LD->getMemOperand(),
13892                                 -(long)MemVT.getStoreSize()+1,
13893                                 2*MemVT.getStoreSize()-1);
13894 
13895       // Create the new base load.
13896       SDValue LDXIntID =
13897           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13898       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13899       SDValue BaseLoad =
13900         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13901                                 DAG.getVTList(PermTy, MVT::Other),
13902                                 BaseLoadOps, LDTy, BaseMMO);
13903 
13904       // Note that the value of IncOffset (which is provided to the next
13905       // load's pointer info offset value, and thus used to calculate the
13906       // alignment), and the value of IncValue (which is actually used to
13907       // increment the pointer value) are different! This is because we
13908       // require the next load to appear to be aligned, even though it
13909       // is actually offset from the base pointer by a lesser amount.
13910       int IncOffset = VT.getSizeInBits() / 8;
13911       int IncValue = IncOffset;
13912 
13913       // Walk (both up and down) the chain looking for another load at the real
13914       // (aligned) offset (the alignment of the other load does not matter in
13915       // this case). If found, then do not use the offset reduction trick, as
13916       // that will prevent the loads from being later combined (as they would
13917       // otherwise be duplicates).
13918       if (!findConsecutiveLoad(LD, DAG))
13919         --IncValue;
13920 
13921       SDValue Increment =
13922           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13923       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13924 
13925       MachineMemOperand *ExtraMMO =
13926         MF.getMachineMemOperand(LD->getMemOperand(),
13927                                 1, 2*MemVT.getStoreSize()-1);
13928       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13929       SDValue ExtraLoad =
13930         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13931                                 DAG.getVTList(PermTy, MVT::Other),
13932                                 ExtraLoadOps, LDTy, ExtraMMO);
13933 
13934       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13935         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13936 
13937       // Because vperm has a big-endian bias, we must reverse the order
13938       // of the input vectors and complement the permute control vector
13939       // when generating little endian code.  We have already handled the
13940       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13941       // and ExtraLoad here.
13942       SDValue Perm;
13943       if (isLittleEndian)
13944         Perm = BuildIntrinsicOp(IntrPerm,
13945                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13946       else
13947         Perm = BuildIntrinsicOp(IntrPerm,
13948                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13949 
13950       if (VT != PermTy)
13951         Perm = Subtarget.hasAltivec() ?
13952                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13953                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13954                                DAG.getTargetConstant(1, dl, MVT::i64));
13955                                // second argument is 1 because this rounding
13956                                // is always exact.
13957 
13958       // The output of the permutation is our loaded result, the TokenFactor is
13959       // our new chain.
13960       DCI.CombineTo(N, Perm, TF);
13961       return SDValue(N, 0);
13962     }
13963     }
13964     break;
13965     case ISD::INTRINSIC_WO_CHAIN: {
13966       bool isLittleEndian = Subtarget.isLittleEndian();
13967       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13968       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13969                                            : Intrinsic::ppc_altivec_lvsl);
13970       if ((IID == Intr ||
13971            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13972            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13973         N->getOperand(1)->getOpcode() == ISD::ADD) {
13974         SDValue Add = N->getOperand(1);
13975 
13976         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13977                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13978 
13979         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13980                                   APInt::getAllOnesValue(Bits /* alignment */)
13981                                       .zext(Add.getScalarValueSizeInBits()))) {
13982           SDNode *BasePtr = Add->getOperand(0).getNode();
13983           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13984                                     UE = BasePtr->use_end();
13985                UI != UE; ++UI) {
13986             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13987                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13988               // We've found another LVSL/LVSR, and this address is an aligned
13989               // multiple of that one. The results will be the same, so use the
13990               // one we've just found instead.
13991 
13992               return SDValue(*UI, 0);
13993             }
13994           }
13995         }
13996 
13997         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13998           SDNode *BasePtr = Add->getOperand(0).getNode();
13999           for (SDNode::use_iterator UI = BasePtr->use_begin(),
14000                UE = BasePtr->use_end(); UI != UE; ++UI) {
14001             if (UI->getOpcode() == ISD::ADD &&
14002                 isa<ConstantSDNode>(UI->getOperand(1)) &&
14003                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
14004                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
14005                 (1ULL << Bits) == 0) {
14006               SDNode *OtherAdd = *UI;
14007               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
14008                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
14009                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14010                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
14011                   return SDValue(*VI, 0);
14012                 }
14013               }
14014             }
14015           }
14016         }
14017       }
14018 
14019       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
14020       // Expose the vabsduw/h/b opportunity for down stream
14021       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
14022           (IID == Intrinsic::ppc_altivec_vmaxsw ||
14023            IID == Intrinsic::ppc_altivec_vmaxsh ||
14024            IID == Intrinsic::ppc_altivec_vmaxsb)) {
14025         SDValue V1 = N->getOperand(1);
14026         SDValue V2 = N->getOperand(2);
14027         if ((V1.getSimpleValueType() == MVT::v4i32 ||
14028              V1.getSimpleValueType() == MVT::v8i16 ||
14029              V1.getSimpleValueType() == MVT::v16i8) &&
14030             V1.getSimpleValueType() == V2.getSimpleValueType()) {
14031           // (0-a, a)
14032           if (V1.getOpcode() == ISD::SUB &&
14033               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14034               V1.getOperand(1) == V2) {
14035             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14036           }
14037           // (a, 0-a)
14038           if (V2.getOpcode() == ISD::SUB &&
14039               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14040               V2.getOperand(1) == V1) {
14041             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14042           }
14043           // (x-y, y-x)
14044           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14045               V1.getOperand(0) == V2.getOperand(1) &&
14046               V1.getOperand(1) == V2.getOperand(0)) {
14047             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14048           }
14049         }
14050       }
14051     }
14052 
14053     break;
14054   case ISD::INTRINSIC_W_CHAIN:
14055     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14056     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14057     if (Subtarget.needsSwapsForVSXMemOps()) {
14058       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14059       default:
14060         break;
14061       case Intrinsic::ppc_vsx_lxvw4x:
14062       case Intrinsic::ppc_vsx_lxvd2x:
14063         return expandVSXLoadForLE(N, DCI);
14064       }
14065     }
14066     break;
14067   case ISD::INTRINSIC_VOID:
14068     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14069     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14070     if (Subtarget.needsSwapsForVSXMemOps()) {
14071       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14072       default:
14073         break;
14074       case Intrinsic::ppc_vsx_stxvw4x:
14075       case Intrinsic::ppc_vsx_stxvd2x:
14076         return expandVSXStoreForLE(N, DCI);
14077       }
14078     }
14079     break;
14080   case ISD::BSWAP:
14081     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14082     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14083         N->getOperand(0).hasOneUse() &&
14084         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14085          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14086           N->getValueType(0) == MVT::i64))) {
14087       SDValue Load = N->getOperand(0);
14088       LoadSDNode *LD = cast<LoadSDNode>(Load);
14089       // Create the byte-swapping load.
14090       SDValue Ops[] = {
14091         LD->getChain(),    // Chain
14092         LD->getBasePtr(),  // Ptr
14093         DAG.getValueType(N->getValueType(0)) // VT
14094       };
14095       SDValue BSLoad =
14096         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14097                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14098                                               MVT::i64 : MVT::i32, MVT::Other),
14099                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14100 
14101       // If this is an i16 load, insert the truncate.
14102       SDValue ResVal = BSLoad;
14103       if (N->getValueType(0) == MVT::i16)
14104         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14105 
14106       // First, combine the bswap away.  This makes the value produced by the
14107       // load dead.
14108       DCI.CombineTo(N, ResVal);
14109 
14110       // Next, combine the load away, we give it a bogus result value but a real
14111       // chain result.  The result value is dead because the bswap is dead.
14112       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14113 
14114       // Return N so it doesn't get rechecked!
14115       return SDValue(N, 0);
14116     }
14117     break;
14118   case PPCISD::VCMP:
14119     // If a VCMPo node already exists with exactly the same operands as this
14120     // node, use its result instead of this node (VCMPo computes both a CR6 and
14121     // a normal output).
14122     //
14123     if (!N->getOperand(0).hasOneUse() &&
14124         !N->getOperand(1).hasOneUse() &&
14125         !N->getOperand(2).hasOneUse()) {
14126 
14127       // Scan all of the users of the LHS, looking for VCMPo's that match.
14128       SDNode *VCMPoNode = nullptr;
14129 
14130       SDNode *LHSN = N->getOperand(0).getNode();
14131       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14132            UI != E; ++UI)
14133         if (UI->getOpcode() == PPCISD::VCMPo &&
14134             UI->getOperand(1) == N->getOperand(1) &&
14135             UI->getOperand(2) == N->getOperand(2) &&
14136             UI->getOperand(0) == N->getOperand(0)) {
14137           VCMPoNode = *UI;
14138           break;
14139         }
14140 
14141       // If there is no VCMPo node, or if the flag value has a single use, don't
14142       // transform this.
14143       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14144         break;
14145 
14146       // Look at the (necessarily single) use of the flag value.  If it has a
14147       // chain, this transformation is more complex.  Note that multiple things
14148       // could use the value result, which we should ignore.
14149       SDNode *FlagUser = nullptr;
14150       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14151            FlagUser == nullptr; ++UI) {
14152         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14153         SDNode *User = *UI;
14154         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14155           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14156             FlagUser = User;
14157             break;
14158           }
14159         }
14160       }
14161 
14162       // If the user is a MFOCRF instruction, we know this is safe.
14163       // Otherwise we give up for right now.
14164       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14165         return SDValue(VCMPoNode, 0);
14166     }
14167     break;
14168   case ISD::BRCOND: {
14169     SDValue Cond = N->getOperand(1);
14170     SDValue Target = N->getOperand(2);
14171 
14172     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14173         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14174           Intrinsic::loop_decrement) {
14175 
14176       // We now need to make the intrinsic dead (it cannot be instruction
14177       // selected).
14178       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14179       assert(Cond.getNode()->hasOneUse() &&
14180              "Counter decrement has more than one use");
14181 
14182       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14183                          N->getOperand(0), Target);
14184     }
14185   }
14186   break;
14187   case ISD::BR_CC: {
14188     // If this is a branch on an altivec predicate comparison, lower this so
14189     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14190     // lowering is done pre-legalize, because the legalizer lowers the predicate
14191     // compare down to code that is difficult to reassemble.
14192     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14193     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14194 
14195     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14196     // value. If so, pass-through the AND to get to the intrinsic.
14197     if (LHS.getOpcode() == ISD::AND &&
14198         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14199         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14200           Intrinsic::loop_decrement &&
14201         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14202         !isNullConstant(LHS.getOperand(1)))
14203       LHS = LHS.getOperand(0);
14204 
14205     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14206         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14207           Intrinsic::loop_decrement &&
14208         isa<ConstantSDNode>(RHS)) {
14209       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14210              "Counter decrement comparison is not EQ or NE");
14211 
14212       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14213       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14214                     (CC == ISD::SETNE && !Val);
14215 
14216       // We now need to make the intrinsic dead (it cannot be instruction
14217       // selected).
14218       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14219       assert(LHS.getNode()->hasOneUse() &&
14220              "Counter decrement has more than one use");
14221 
14222       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14223                          N->getOperand(0), N->getOperand(4));
14224     }
14225 
14226     int CompareOpc;
14227     bool isDot;
14228 
14229     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14230         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14231         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14232       assert(isDot && "Can't compare against a vector result!");
14233 
14234       // If this is a comparison against something other than 0/1, then we know
14235       // that the condition is never/always true.
14236       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14237       if (Val != 0 && Val != 1) {
14238         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14239           return N->getOperand(0);
14240         // Always !=, turn it into an unconditional branch.
14241         return DAG.getNode(ISD::BR, dl, MVT::Other,
14242                            N->getOperand(0), N->getOperand(4));
14243       }
14244 
14245       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14246 
14247       // Create the PPCISD altivec 'dot' comparison node.
14248       SDValue Ops[] = {
14249         LHS.getOperand(2),  // LHS of compare
14250         LHS.getOperand(3),  // RHS of compare
14251         DAG.getConstant(CompareOpc, dl, MVT::i32)
14252       };
14253       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14254       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14255 
14256       // Unpack the result based on how the target uses it.
14257       PPC::Predicate CompOpc;
14258       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14259       default:  // Can't happen, don't crash on invalid number though.
14260       case 0:   // Branch on the value of the EQ bit of CR6.
14261         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14262         break;
14263       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14264         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14265         break;
14266       case 2:   // Branch on the value of the LT bit of CR6.
14267         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14268         break;
14269       case 3:   // Branch on the inverted value of the LT bit of CR6.
14270         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14271         break;
14272       }
14273 
14274       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14275                          DAG.getConstant(CompOpc, dl, MVT::i32),
14276                          DAG.getRegister(PPC::CR6, MVT::i32),
14277                          N->getOperand(4), CompNode.getValue(1));
14278     }
14279     break;
14280   }
14281   case ISD::BUILD_VECTOR:
14282     return DAGCombineBuildVector(N, DCI);
14283   case ISD::ABS:
14284     return combineABS(N, DCI);
14285   case ISD::VSELECT:
14286     return combineVSelect(N, DCI);
14287   }
14288 
14289   return SDValue();
14290 }
14291 
14292 SDValue
14293 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14294                                  SelectionDAG &DAG,
14295                                  SmallVectorImpl<SDNode *> &Created) const {
14296   // fold (sdiv X, pow2)
14297   EVT VT = N->getValueType(0);
14298   if (VT == MVT::i64 && !Subtarget.isPPC64())
14299     return SDValue();
14300   if ((VT != MVT::i32 && VT != MVT::i64) ||
14301       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14302     return SDValue();
14303 
14304   SDLoc DL(N);
14305   SDValue N0 = N->getOperand(0);
14306 
14307   bool IsNegPow2 = (-Divisor).isPowerOf2();
14308   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14309   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14310 
14311   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14312   Created.push_back(Op.getNode());
14313 
14314   if (IsNegPow2) {
14315     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14316     Created.push_back(Op.getNode());
14317   }
14318 
14319   return Op;
14320 }
14321 
14322 //===----------------------------------------------------------------------===//
14323 // Inline Assembly Support
14324 //===----------------------------------------------------------------------===//
14325 
14326 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14327                                                       KnownBits &Known,
14328                                                       const APInt &DemandedElts,
14329                                                       const SelectionDAG &DAG,
14330                                                       unsigned Depth) const {
14331   Known.resetAll();
14332   switch (Op.getOpcode()) {
14333   default: break;
14334   case PPCISD::LBRX: {
14335     // lhbrx is known to have the top bits cleared out.
14336     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14337       Known.Zero = 0xFFFF0000;
14338     break;
14339   }
14340   case ISD::INTRINSIC_WO_CHAIN: {
14341     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14342     default: break;
14343     case Intrinsic::ppc_altivec_vcmpbfp_p:
14344     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14345     case Intrinsic::ppc_altivec_vcmpequb_p:
14346     case Intrinsic::ppc_altivec_vcmpequh_p:
14347     case Intrinsic::ppc_altivec_vcmpequw_p:
14348     case Intrinsic::ppc_altivec_vcmpequd_p:
14349     case Intrinsic::ppc_altivec_vcmpgefp_p:
14350     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14351     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14352     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14353     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14354     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14355     case Intrinsic::ppc_altivec_vcmpgtub_p:
14356     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14357     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14358     case Intrinsic::ppc_altivec_vcmpgtud_p:
14359       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14360       break;
14361     }
14362   }
14363   }
14364 }
14365 
14366 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14367   switch (Subtarget.getCPUDirective()) {
14368   default: break;
14369   case PPC::DIR_970:
14370   case PPC::DIR_PWR4:
14371   case PPC::DIR_PWR5:
14372   case PPC::DIR_PWR5X:
14373   case PPC::DIR_PWR6:
14374   case PPC::DIR_PWR6X:
14375   case PPC::DIR_PWR7:
14376   case PPC::DIR_PWR8:
14377   case PPC::DIR_PWR9:
14378   case PPC::DIR_PWR_FUTURE: {
14379     if (!ML)
14380       break;
14381 
14382     if (!DisableInnermostLoopAlign32) {
14383       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14384       // so that we can decrease cache misses and branch-prediction misses.
14385       // Actual alignment of the loop will depend on the hotness check and other
14386       // logic in alignBlocks.
14387       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14388         return Align(32);
14389     }
14390 
14391     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14392 
14393     // For small loops (between 5 and 8 instructions), align to a 32-byte
14394     // boundary so that the entire loop fits in one instruction-cache line.
14395     uint64_t LoopSize = 0;
14396     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14397       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14398         LoopSize += TII->getInstSizeInBytes(*J);
14399         if (LoopSize > 32)
14400           break;
14401       }
14402 
14403     if (LoopSize > 16 && LoopSize <= 32)
14404       return Align(32);
14405 
14406     break;
14407   }
14408   }
14409 
14410   return TargetLowering::getPrefLoopAlignment(ML);
14411 }
14412 
14413 /// getConstraintType - Given a constraint, return the type of
14414 /// constraint it is for this target.
14415 PPCTargetLowering::ConstraintType
14416 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14417   if (Constraint.size() == 1) {
14418     switch (Constraint[0]) {
14419     default: break;
14420     case 'b':
14421     case 'r':
14422     case 'f':
14423     case 'd':
14424     case 'v':
14425     case 'y':
14426       return C_RegisterClass;
14427     case 'Z':
14428       // FIXME: While Z does indicate a memory constraint, it specifically
14429       // indicates an r+r address (used in conjunction with the 'y' modifier
14430       // in the replacement string). Currently, we're forcing the base
14431       // register to be r0 in the asm printer (which is interpreted as zero)
14432       // and forming the complete address in the second register. This is
14433       // suboptimal.
14434       return C_Memory;
14435     }
14436   } else if (Constraint == "wc") { // individual CR bits.
14437     return C_RegisterClass;
14438   } else if (Constraint == "wa" || Constraint == "wd" ||
14439              Constraint == "wf" || Constraint == "ws" ||
14440              Constraint == "wi" || Constraint == "ww") {
14441     return C_RegisterClass; // VSX registers.
14442   }
14443   return TargetLowering::getConstraintType(Constraint);
14444 }
14445 
14446 /// Examine constraint type and operand type and determine a weight value.
14447 /// This object must already have been set up with the operand type
14448 /// and the current alternative constraint selected.
14449 TargetLowering::ConstraintWeight
14450 PPCTargetLowering::getSingleConstraintMatchWeight(
14451     AsmOperandInfo &info, const char *constraint) const {
14452   ConstraintWeight weight = CW_Invalid;
14453   Value *CallOperandVal = info.CallOperandVal;
14454     // If we don't have a value, we can't do a match,
14455     // but allow it at the lowest weight.
14456   if (!CallOperandVal)
14457     return CW_Default;
14458   Type *type = CallOperandVal->getType();
14459 
14460   // Look at the constraint type.
14461   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14462     return CW_Register; // an individual CR bit.
14463   else if ((StringRef(constraint) == "wa" ||
14464             StringRef(constraint) == "wd" ||
14465             StringRef(constraint) == "wf") &&
14466            type->isVectorTy())
14467     return CW_Register;
14468   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14469     return CW_Register; // just hold 64-bit integers data.
14470   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14471     return CW_Register;
14472   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14473     return CW_Register;
14474 
14475   switch (*constraint) {
14476   default:
14477     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14478     break;
14479   case 'b':
14480     if (type->isIntegerTy())
14481       weight = CW_Register;
14482     break;
14483   case 'f':
14484     if (type->isFloatTy())
14485       weight = CW_Register;
14486     break;
14487   case 'd':
14488     if (type->isDoubleTy())
14489       weight = CW_Register;
14490     break;
14491   case 'v':
14492     if (type->isVectorTy())
14493       weight = CW_Register;
14494     break;
14495   case 'y':
14496     weight = CW_Register;
14497     break;
14498   case 'Z':
14499     weight = CW_Memory;
14500     break;
14501   }
14502   return weight;
14503 }
14504 
14505 std::pair<unsigned, const TargetRegisterClass *>
14506 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14507                                                 StringRef Constraint,
14508                                                 MVT VT) const {
14509   if (Constraint.size() == 1) {
14510     // GCC RS6000 Constraint Letters
14511     switch (Constraint[0]) {
14512     case 'b':   // R1-R31
14513       if (VT == MVT::i64 && Subtarget.isPPC64())
14514         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14515       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14516     case 'r':   // R0-R31
14517       if (VT == MVT::i64 && Subtarget.isPPC64())
14518         return std::make_pair(0U, &PPC::G8RCRegClass);
14519       return std::make_pair(0U, &PPC::GPRCRegClass);
14520     // 'd' and 'f' constraints are both defined to be "the floating point
14521     // registers", where one is for 32-bit and the other for 64-bit. We don't
14522     // really care overly much here so just give them all the same reg classes.
14523     case 'd':
14524     case 'f':
14525       if (Subtarget.hasSPE()) {
14526         if (VT == MVT::f32 || VT == MVT::i32)
14527           return std::make_pair(0U, &PPC::GPRCRegClass);
14528         if (VT == MVT::f64 || VT == MVT::i64)
14529           return std::make_pair(0U, &PPC::SPERCRegClass);
14530       } else {
14531         if (VT == MVT::f32 || VT == MVT::i32)
14532           return std::make_pair(0U, &PPC::F4RCRegClass);
14533         if (VT == MVT::f64 || VT == MVT::i64)
14534           return std::make_pair(0U, &PPC::F8RCRegClass);
14535         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14536           return std::make_pair(0U, &PPC::QFRCRegClass);
14537         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14538           return std::make_pair(0U, &PPC::QSRCRegClass);
14539       }
14540       break;
14541     case 'v':
14542       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14543         return std::make_pair(0U, &PPC::QFRCRegClass);
14544       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14545         return std::make_pair(0U, &PPC::QSRCRegClass);
14546       if (Subtarget.hasAltivec())
14547         return std::make_pair(0U, &PPC::VRRCRegClass);
14548       break;
14549     case 'y':   // crrc
14550       return std::make_pair(0U, &PPC::CRRCRegClass);
14551     }
14552   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14553     // An individual CR bit.
14554     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14555   } else if ((Constraint == "wa" || Constraint == "wd" ||
14556              Constraint == "wf" || Constraint == "wi") &&
14557              Subtarget.hasVSX()) {
14558     return std::make_pair(0U, &PPC::VSRCRegClass);
14559   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14560     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14561       return std::make_pair(0U, &PPC::VSSRCRegClass);
14562     else
14563       return std::make_pair(0U, &PPC::VSFRCRegClass);
14564   }
14565 
14566   // If we name a VSX register, we can't defer to the base class because it
14567   // will not recognize the correct register (their names will be VSL{0-31}
14568   // and V{0-31} so they won't match). So we match them here.
14569   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14570     int VSNum = atoi(Constraint.data() + 3);
14571     assert(VSNum >= 0 && VSNum <= 63 &&
14572            "Attempted to access a vsr out of range");
14573     if (VSNum < 32)
14574       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14575     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14576   }
14577   std::pair<unsigned, const TargetRegisterClass *> R =
14578       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14579 
14580   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14581   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14582   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14583   // register.
14584   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14585   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14586   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14587       PPC::GPRCRegClass.contains(R.first))
14588     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14589                             PPC::sub_32, &PPC::G8RCRegClass),
14590                           &PPC::G8RCRegClass);
14591 
14592   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14593   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14594     R.first = PPC::CR0;
14595     R.second = &PPC::CRRCRegClass;
14596   }
14597 
14598   return R;
14599 }
14600 
14601 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14602 /// vector.  If it is invalid, don't add anything to Ops.
14603 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14604                                                      std::string &Constraint,
14605                                                      std::vector<SDValue>&Ops,
14606                                                      SelectionDAG &DAG) const {
14607   SDValue Result;
14608 
14609   // Only support length 1 constraints.
14610   if (Constraint.length() > 1) return;
14611 
14612   char Letter = Constraint[0];
14613   switch (Letter) {
14614   default: break;
14615   case 'I':
14616   case 'J':
14617   case 'K':
14618   case 'L':
14619   case 'M':
14620   case 'N':
14621   case 'O':
14622   case 'P': {
14623     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14624     if (!CST) return; // Must be an immediate to match.
14625     SDLoc dl(Op);
14626     int64_t Value = CST->getSExtValue();
14627     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14628                          // numbers are printed as such.
14629     switch (Letter) {
14630     default: llvm_unreachable("Unknown constraint letter!");
14631     case 'I':  // "I" is a signed 16-bit constant.
14632       if (isInt<16>(Value))
14633         Result = DAG.getTargetConstant(Value, dl, TCVT);
14634       break;
14635     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14636       if (isShiftedUInt<16, 16>(Value))
14637         Result = DAG.getTargetConstant(Value, dl, TCVT);
14638       break;
14639     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14640       if (isShiftedInt<16, 16>(Value))
14641         Result = DAG.getTargetConstant(Value, dl, TCVT);
14642       break;
14643     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14644       if (isUInt<16>(Value))
14645         Result = DAG.getTargetConstant(Value, dl, TCVT);
14646       break;
14647     case 'M':  // "M" is a constant that is greater than 31.
14648       if (Value > 31)
14649         Result = DAG.getTargetConstant(Value, dl, TCVT);
14650       break;
14651     case 'N':  // "N" is a positive constant that is an exact power of two.
14652       if (Value > 0 && isPowerOf2_64(Value))
14653         Result = DAG.getTargetConstant(Value, dl, TCVT);
14654       break;
14655     case 'O':  // "O" is the constant zero.
14656       if (Value == 0)
14657         Result = DAG.getTargetConstant(Value, dl, TCVT);
14658       break;
14659     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14660       if (isInt<16>(-Value))
14661         Result = DAG.getTargetConstant(Value, dl, TCVT);
14662       break;
14663     }
14664     break;
14665   }
14666   }
14667 
14668   if (Result.getNode()) {
14669     Ops.push_back(Result);
14670     return;
14671   }
14672 
14673   // Handle standard constraint letters.
14674   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14675 }
14676 
14677 // isLegalAddressingMode - Return true if the addressing mode represented
14678 // by AM is legal for this target, for a load/store of the specified type.
14679 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14680                                               const AddrMode &AM, Type *Ty,
14681                                               unsigned AS, Instruction *I) const {
14682   // PPC does not allow r+i addressing modes for vectors!
14683   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14684     return false;
14685 
14686   // PPC allows a sign-extended 16-bit immediate field.
14687   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14688     return false;
14689 
14690   // No global is ever allowed as a base.
14691   if (AM.BaseGV)
14692     return false;
14693 
14694   // PPC only support r+r,
14695   switch (AM.Scale) {
14696   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14697     break;
14698   case 1:
14699     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14700       return false;
14701     // Otherwise we have r+r or r+i.
14702     break;
14703   case 2:
14704     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14705       return false;
14706     // Allow 2*r as r+r.
14707     break;
14708   default:
14709     // No other scales are supported.
14710     return false;
14711   }
14712 
14713   return true;
14714 }
14715 
14716 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14717                                            SelectionDAG &DAG) const {
14718   MachineFunction &MF = DAG.getMachineFunction();
14719   MachineFrameInfo &MFI = MF.getFrameInfo();
14720   MFI.setReturnAddressIsTaken(true);
14721 
14722   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14723     return SDValue();
14724 
14725   SDLoc dl(Op);
14726   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14727 
14728   // Make sure the function does not optimize away the store of the RA to
14729   // the stack.
14730   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14731   FuncInfo->setLRStoreRequired();
14732   bool isPPC64 = Subtarget.isPPC64();
14733   auto PtrVT = getPointerTy(MF.getDataLayout());
14734 
14735   if (Depth > 0) {
14736     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14737     SDValue Offset =
14738         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14739                         isPPC64 ? MVT::i64 : MVT::i32);
14740     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14741                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14742                        MachinePointerInfo());
14743   }
14744 
14745   // Just load the return address off the stack.
14746   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14747   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14748                      MachinePointerInfo());
14749 }
14750 
14751 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14752                                           SelectionDAG &DAG) const {
14753   SDLoc dl(Op);
14754   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14755 
14756   MachineFunction &MF = DAG.getMachineFunction();
14757   MachineFrameInfo &MFI = MF.getFrameInfo();
14758   MFI.setFrameAddressIsTaken(true);
14759 
14760   EVT PtrVT = getPointerTy(MF.getDataLayout());
14761   bool isPPC64 = PtrVT == MVT::i64;
14762 
14763   // Naked functions never have a frame pointer, and so we use r1. For all
14764   // other functions, this decision must be delayed until during PEI.
14765   unsigned FrameReg;
14766   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14767     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14768   else
14769     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14770 
14771   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14772                                          PtrVT);
14773   while (Depth--)
14774     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14775                             FrameAddr, MachinePointerInfo());
14776   return FrameAddr;
14777 }
14778 
14779 // FIXME? Maybe this could be a TableGen attribute on some registers and
14780 // this table could be generated automatically from RegInfo.
14781 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14782                                               const MachineFunction &MF) const {
14783   bool isPPC64 = Subtarget.isPPC64();
14784   bool IsDarwinABI = Subtarget.isDarwinABI();
14785 
14786   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14787       (!isPPC64 && VT != MVT::i32))
14788     report_fatal_error("Invalid register global variable type");
14789 
14790   bool is64Bit = isPPC64 && VT == MVT::i64;
14791   Register Reg = StringSwitch<Register>(RegName)
14792                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14793                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14794                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14795                                   (is64Bit ? PPC::X13 : PPC::R13))
14796                    .Default(Register());
14797 
14798   if (Reg)
14799     return Reg;
14800   report_fatal_error("Invalid register name global variable");
14801 }
14802 
14803 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14804   // 32-bit SVR4 ABI access everything as got-indirect.
14805   if (Subtarget.is32BitELFABI())
14806     return true;
14807 
14808   // AIX accesses everything indirectly through the TOC, which is similar to
14809   // the GOT.
14810   if (Subtarget.isAIXABI())
14811     return true;
14812 
14813   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14814   // If it is small or large code model, module locals are accessed
14815   // indirectly by loading their address from .toc/.got.
14816   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14817     return true;
14818 
14819   // JumpTable and BlockAddress are accessed as got-indirect.
14820   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14821     return true;
14822 
14823   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14824     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14825 
14826   return false;
14827 }
14828 
14829 bool
14830 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14831   // The PowerPC target isn't yet aware of offsets.
14832   return false;
14833 }
14834 
14835 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14836                                            const CallInst &I,
14837                                            MachineFunction &MF,
14838                                            unsigned Intrinsic) const {
14839   switch (Intrinsic) {
14840   case Intrinsic::ppc_qpx_qvlfd:
14841   case Intrinsic::ppc_qpx_qvlfs:
14842   case Intrinsic::ppc_qpx_qvlfcd:
14843   case Intrinsic::ppc_qpx_qvlfcs:
14844   case Intrinsic::ppc_qpx_qvlfiwa:
14845   case Intrinsic::ppc_qpx_qvlfiwz:
14846   case Intrinsic::ppc_altivec_lvx:
14847   case Intrinsic::ppc_altivec_lvxl:
14848   case Intrinsic::ppc_altivec_lvebx:
14849   case Intrinsic::ppc_altivec_lvehx:
14850   case Intrinsic::ppc_altivec_lvewx:
14851   case Intrinsic::ppc_vsx_lxvd2x:
14852   case Intrinsic::ppc_vsx_lxvw4x: {
14853     EVT VT;
14854     switch (Intrinsic) {
14855     case Intrinsic::ppc_altivec_lvebx:
14856       VT = MVT::i8;
14857       break;
14858     case Intrinsic::ppc_altivec_lvehx:
14859       VT = MVT::i16;
14860       break;
14861     case Intrinsic::ppc_altivec_lvewx:
14862       VT = MVT::i32;
14863       break;
14864     case Intrinsic::ppc_vsx_lxvd2x:
14865       VT = MVT::v2f64;
14866       break;
14867     case Intrinsic::ppc_qpx_qvlfd:
14868       VT = MVT::v4f64;
14869       break;
14870     case Intrinsic::ppc_qpx_qvlfs:
14871       VT = MVT::v4f32;
14872       break;
14873     case Intrinsic::ppc_qpx_qvlfcd:
14874       VT = MVT::v2f64;
14875       break;
14876     case Intrinsic::ppc_qpx_qvlfcs:
14877       VT = MVT::v2f32;
14878       break;
14879     default:
14880       VT = MVT::v4i32;
14881       break;
14882     }
14883 
14884     Info.opc = ISD::INTRINSIC_W_CHAIN;
14885     Info.memVT = VT;
14886     Info.ptrVal = I.getArgOperand(0);
14887     Info.offset = -VT.getStoreSize()+1;
14888     Info.size = 2*VT.getStoreSize()-1;
14889     Info.align = Align::None();
14890     Info.flags = MachineMemOperand::MOLoad;
14891     return true;
14892   }
14893   case Intrinsic::ppc_qpx_qvlfda:
14894   case Intrinsic::ppc_qpx_qvlfsa:
14895   case Intrinsic::ppc_qpx_qvlfcda:
14896   case Intrinsic::ppc_qpx_qvlfcsa:
14897   case Intrinsic::ppc_qpx_qvlfiwaa:
14898   case Intrinsic::ppc_qpx_qvlfiwza: {
14899     EVT VT;
14900     switch (Intrinsic) {
14901     case Intrinsic::ppc_qpx_qvlfda:
14902       VT = MVT::v4f64;
14903       break;
14904     case Intrinsic::ppc_qpx_qvlfsa:
14905       VT = MVT::v4f32;
14906       break;
14907     case Intrinsic::ppc_qpx_qvlfcda:
14908       VT = MVT::v2f64;
14909       break;
14910     case Intrinsic::ppc_qpx_qvlfcsa:
14911       VT = MVT::v2f32;
14912       break;
14913     default:
14914       VT = MVT::v4i32;
14915       break;
14916     }
14917 
14918     Info.opc = ISD::INTRINSIC_W_CHAIN;
14919     Info.memVT = VT;
14920     Info.ptrVal = I.getArgOperand(0);
14921     Info.offset = 0;
14922     Info.size = VT.getStoreSize();
14923     Info.align = Align::None();
14924     Info.flags = MachineMemOperand::MOLoad;
14925     return true;
14926   }
14927   case Intrinsic::ppc_qpx_qvstfd:
14928   case Intrinsic::ppc_qpx_qvstfs:
14929   case Intrinsic::ppc_qpx_qvstfcd:
14930   case Intrinsic::ppc_qpx_qvstfcs:
14931   case Intrinsic::ppc_qpx_qvstfiw:
14932   case Intrinsic::ppc_altivec_stvx:
14933   case Intrinsic::ppc_altivec_stvxl:
14934   case Intrinsic::ppc_altivec_stvebx:
14935   case Intrinsic::ppc_altivec_stvehx:
14936   case Intrinsic::ppc_altivec_stvewx:
14937   case Intrinsic::ppc_vsx_stxvd2x:
14938   case Intrinsic::ppc_vsx_stxvw4x: {
14939     EVT VT;
14940     switch (Intrinsic) {
14941     case Intrinsic::ppc_altivec_stvebx:
14942       VT = MVT::i8;
14943       break;
14944     case Intrinsic::ppc_altivec_stvehx:
14945       VT = MVT::i16;
14946       break;
14947     case Intrinsic::ppc_altivec_stvewx:
14948       VT = MVT::i32;
14949       break;
14950     case Intrinsic::ppc_vsx_stxvd2x:
14951       VT = MVT::v2f64;
14952       break;
14953     case Intrinsic::ppc_qpx_qvstfd:
14954       VT = MVT::v4f64;
14955       break;
14956     case Intrinsic::ppc_qpx_qvstfs:
14957       VT = MVT::v4f32;
14958       break;
14959     case Intrinsic::ppc_qpx_qvstfcd:
14960       VT = MVT::v2f64;
14961       break;
14962     case Intrinsic::ppc_qpx_qvstfcs:
14963       VT = MVT::v2f32;
14964       break;
14965     default:
14966       VT = MVT::v4i32;
14967       break;
14968     }
14969 
14970     Info.opc = ISD::INTRINSIC_VOID;
14971     Info.memVT = VT;
14972     Info.ptrVal = I.getArgOperand(1);
14973     Info.offset = -VT.getStoreSize()+1;
14974     Info.size = 2*VT.getStoreSize()-1;
14975     Info.align = Align::None();
14976     Info.flags = MachineMemOperand::MOStore;
14977     return true;
14978   }
14979   case Intrinsic::ppc_qpx_qvstfda:
14980   case Intrinsic::ppc_qpx_qvstfsa:
14981   case Intrinsic::ppc_qpx_qvstfcda:
14982   case Intrinsic::ppc_qpx_qvstfcsa:
14983   case Intrinsic::ppc_qpx_qvstfiwa: {
14984     EVT VT;
14985     switch (Intrinsic) {
14986     case Intrinsic::ppc_qpx_qvstfda:
14987       VT = MVT::v4f64;
14988       break;
14989     case Intrinsic::ppc_qpx_qvstfsa:
14990       VT = MVT::v4f32;
14991       break;
14992     case Intrinsic::ppc_qpx_qvstfcda:
14993       VT = MVT::v2f64;
14994       break;
14995     case Intrinsic::ppc_qpx_qvstfcsa:
14996       VT = MVT::v2f32;
14997       break;
14998     default:
14999       VT = MVT::v4i32;
15000       break;
15001     }
15002 
15003     Info.opc = ISD::INTRINSIC_VOID;
15004     Info.memVT = VT;
15005     Info.ptrVal = I.getArgOperand(1);
15006     Info.offset = 0;
15007     Info.size = VT.getStoreSize();
15008     Info.align = Align::None();
15009     Info.flags = MachineMemOperand::MOStore;
15010     return true;
15011   }
15012   default:
15013     break;
15014   }
15015 
15016   return false;
15017 }
15018 
15019 /// getOptimalMemOpType - Returns the target specific optimal type for load
15020 /// and store operations as a result of memset, memcpy, and memmove
15021 /// lowering. If DstAlign is zero that means it's safe to destination
15022 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
15023 /// means there isn't a need to check it against alignment requirement,
15024 /// probably because the source does not need to be loaded. If 'IsMemset' is
15025 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
15026 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
15027 /// source is constant so it does not need to be loaded.
15028 /// It returns EVT::Other if the type should be determined using generic
15029 /// target-independent logic.
15030 EVT PPCTargetLowering::getOptimalMemOpType(
15031     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
15032     bool ZeroMemset, bool MemcpyStrSrc,
15033     const AttributeList &FuncAttributes) const {
15034   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15035     // When expanding a memset, require at least two QPX instructions to cover
15036     // the cost of loading the value to be stored from the constant pool.
15037     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
15038        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
15039         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15040       return MVT::v4f64;
15041     }
15042 
15043     // We should use Altivec/VSX loads and stores when available. For unaligned
15044     // addresses, unaligned VSX loads are only fast starting with the P8.
15045     if (Subtarget.hasAltivec() && Size >= 16 &&
15046         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
15047          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15048       return MVT::v4i32;
15049   }
15050 
15051   if (Subtarget.isPPC64()) {
15052     return MVT::i64;
15053   }
15054 
15055   return MVT::i32;
15056 }
15057 
15058 /// Returns true if it is beneficial to convert a load of a constant
15059 /// to just the constant itself.
15060 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15061                                                           Type *Ty) const {
15062   assert(Ty->isIntegerTy());
15063 
15064   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15065   return !(BitSize == 0 || BitSize > 64);
15066 }
15067 
15068 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15069   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15070     return false;
15071   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15072   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15073   return NumBits1 == 64 && NumBits2 == 32;
15074 }
15075 
15076 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15077   if (!VT1.isInteger() || !VT2.isInteger())
15078     return false;
15079   unsigned NumBits1 = VT1.getSizeInBits();
15080   unsigned NumBits2 = VT2.getSizeInBits();
15081   return NumBits1 == 64 && NumBits2 == 32;
15082 }
15083 
15084 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15085   // Generally speaking, zexts are not free, but they are free when they can be
15086   // folded with other operations.
15087   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15088     EVT MemVT = LD->getMemoryVT();
15089     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15090          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15091         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15092          LD->getExtensionType() == ISD::ZEXTLOAD))
15093       return true;
15094   }
15095 
15096   // FIXME: Add other cases...
15097   //  - 32-bit shifts with a zext to i64
15098   //  - zext after ctlz, bswap, etc.
15099   //  - zext after and by a constant mask
15100 
15101   return TargetLowering::isZExtFree(Val, VT2);
15102 }
15103 
15104 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15105   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15106          "invalid fpext types");
15107   // Extending to float128 is not free.
15108   if (DestVT == MVT::f128)
15109     return false;
15110   return true;
15111 }
15112 
15113 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15114   return isInt<16>(Imm) || isUInt<16>(Imm);
15115 }
15116 
15117 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15118   return isInt<16>(Imm) || isUInt<16>(Imm);
15119 }
15120 
15121 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15122                                                        unsigned,
15123                                                        unsigned,
15124                                                        MachineMemOperand::Flags,
15125                                                        bool *Fast) const {
15126   if (DisablePPCUnaligned)
15127     return false;
15128 
15129   // PowerPC supports unaligned memory access for simple non-vector types.
15130   // Although accessing unaligned addresses is not as efficient as accessing
15131   // aligned addresses, it is generally more efficient than manual expansion,
15132   // and generally only traps for software emulation when crossing page
15133   // boundaries.
15134 
15135   if (!VT.isSimple())
15136     return false;
15137 
15138   if (VT.getSimpleVT().isVector()) {
15139     if (Subtarget.hasVSX()) {
15140       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15141           VT != MVT::v4f32 && VT != MVT::v4i32)
15142         return false;
15143     } else {
15144       return false;
15145     }
15146   }
15147 
15148   if (VT == MVT::ppcf128)
15149     return false;
15150 
15151   if (Fast)
15152     *Fast = true;
15153 
15154   return true;
15155 }
15156 
15157 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15158                                                    EVT VT) const {
15159   VT = VT.getScalarType();
15160 
15161   if (!VT.isSimple())
15162     return false;
15163 
15164   switch (VT.getSimpleVT().SimpleTy) {
15165   case MVT::f32:
15166   case MVT::f64:
15167     return true;
15168   case MVT::f128:
15169     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15170   default:
15171     break;
15172   }
15173 
15174   return false;
15175 }
15176 
15177 const MCPhysReg *
15178 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15179   // LR is a callee-save register, but we must treat it as clobbered by any call
15180   // site. Hence we include LR in the scratch registers, which are in turn added
15181   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15182   // to CTR, which is used by any indirect call.
15183   static const MCPhysReg ScratchRegs[] = {
15184     PPC::X12, PPC::LR8, PPC::CTR8, 0
15185   };
15186 
15187   return ScratchRegs;
15188 }
15189 
15190 unsigned PPCTargetLowering::getExceptionPointerRegister(
15191     const Constant *PersonalityFn) const {
15192   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15193 }
15194 
15195 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15196     const Constant *PersonalityFn) const {
15197   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15198 }
15199 
15200 bool
15201 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15202                      EVT VT , unsigned DefinedValues) const {
15203   if (VT == MVT::v2i64)
15204     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15205 
15206   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15207     return true;
15208 
15209   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15210 }
15211 
15212 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15213   if (DisableILPPref || Subtarget.enableMachineScheduler())
15214     return TargetLowering::getSchedulingPreference(N);
15215 
15216   return Sched::ILP;
15217 }
15218 
15219 // Create a fast isel object.
15220 FastISel *
15221 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15222                                   const TargetLibraryInfo *LibInfo) const {
15223   return PPC::createFastISel(FuncInfo, LibInfo);
15224 }
15225 
15226 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15227   if (Subtarget.isDarwinABI()) return;
15228   if (!Subtarget.isPPC64()) return;
15229 
15230   // Update IsSplitCSR in PPCFunctionInfo
15231   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15232   PFI->setIsSplitCSR(true);
15233 }
15234 
15235 void PPCTargetLowering::insertCopiesSplitCSR(
15236   MachineBasicBlock *Entry,
15237   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15238   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15239   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15240   if (!IStart)
15241     return;
15242 
15243   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15244   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15245   MachineBasicBlock::iterator MBBI = Entry->begin();
15246   for (const MCPhysReg *I = IStart; *I; ++I) {
15247     const TargetRegisterClass *RC = nullptr;
15248     if (PPC::G8RCRegClass.contains(*I))
15249       RC = &PPC::G8RCRegClass;
15250     else if (PPC::F8RCRegClass.contains(*I))
15251       RC = &PPC::F8RCRegClass;
15252     else if (PPC::CRRCRegClass.contains(*I))
15253       RC = &PPC::CRRCRegClass;
15254     else if (PPC::VRRCRegClass.contains(*I))
15255       RC = &PPC::VRRCRegClass;
15256     else
15257       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15258 
15259     Register NewVR = MRI->createVirtualRegister(RC);
15260     // Create copy from CSR to a virtual register.
15261     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15262     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15263     // nounwind. If we want to generalize this later, we may need to emit
15264     // CFI pseudo-instructions.
15265     assert(Entry->getParent()->getFunction().hasFnAttribute(
15266              Attribute::NoUnwind) &&
15267            "Function should be nounwind in insertCopiesSplitCSR!");
15268     Entry->addLiveIn(*I);
15269     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15270       .addReg(*I);
15271 
15272     // Insert the copy-back instructions right before the terminator.
15273     for (auto *Exit : Exits)
15274       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15275               TII->get(TargetOpcode::COPY), *I)
15276         .addReg(NewVR);
15277   }
15278 }
15279 
15280 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15281 bool PPCTargetLowering::useLoadStackGuardNode() const {
15282   if (!Subtarget.isTargetLinux())
15283     return TargetLowering::useLoadStackGuardNode();
15284   return true;
15285 }
15286 
15287 // Override to disable global variable loading on Linux.
15288 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15289   if (!Subtarget.isTargetLinux())
15290     return TargetLowering::insertSSPDeclarations(M);
15291 }
15292 
15293 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15294                                      bool ForCodeSize) const {
15295   if (!VT.isSimple() || !Subtarget.hasVSX())
15296     return false;
15297 
15298   switch(VT.getSimpleVT().SimpleTy) {
15299   default:
15300     // For FP types that are currently not supported by PPC backend, return
15301     // false. Examples: f16, f80.
15302     return false;
15303   case MVT::f32:
15304   case MVT::f64:
15305   case MVT::ppcf128:
15306     return Imm.isPosZero();
15307   }
15308 }
15309 
15310 // For vector shift operation op, fold
15311 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15312 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15313                                   SelectionDAG &DAG) {
15314   SDValue N0 = N->getOperand(0);
15315   SDValue N1 = N->getOperand(1);
15316   EVT VT = N0.getValueType();
15317   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15318   unsigned Opcode = N->getOpcode();
15319   unsigned TargetOpcode;
15320 
15321   switch (Opcode) {
15322   default:
15323     llvm_unreachable("Unexpected shift operation");
15324   case ISD::SHL:
15325     TargetOpcode = PPCISD::SHL;
15326     break;
15327   case ISD::SRL:
15328     TargetOpcode = PPCISD::SRL;
15329     break;
15330   case ISD::SRA:
15331     TargetOpcode = PPCISD::SRA;
15332     break;
15333   }
15334 
15335   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15336       N1->getOpcode() == ISD::AND)
15337     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15338       if (Mask->getZExtValue() == OpSizeInBits - 1)
15339         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15340 
15341   return SDValue();
15342 }
15343 
15344 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15345   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15346     return Value;
15347 
15348   SDValue N0 = N->getOperand(0);
15349   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15350   if (!Subtarget.isISA3_0() ||
15351       N0.getOpcode() != ISD::SIGN_EXTEND ||
15352       N0.getOperand(0).getValueType() != MVT::i32 ||
15353       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15354     return SDValue();
15355 
15356   // We can't save an operation here if the value is already extended, and
15357   // the existing shift is easier to combine.
15358   SDValue ExtsSrc = N0.getOperand(0);
15359   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15360       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15361     return SDValue();
15362 
15363   SDLoc DL(N0);
15364   SDValue ShiftBy = SDValue(CN1, 0);
15365   // We want the shift amount to be i32 on the extswli, but the shift could
15366   // have an i64.
15367   if (ShiftBy.getValueType() == MVT::i64)
15368     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15369 
15370   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15371                          ShiftBy);
15372 }
15373 
15374 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15375   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15376     return Value;
15377 
15378   return SDValue();
15379 }
15380 
15381 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15382   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15383     return Value;
15384 
15385   return SDValue();
15386 }
15387 
15388 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15389 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15390 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15391 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15392 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15393                                  const PPCSubtarget &Subtarget) {
15394   if (!Subtarget.isPPC64())
15395     return SDValue();
15396 
15397   SDValue LHS = N->getOperand(0);
15398   SDValue RHS = N->getOperand(1);
15399 
15400   auto isZextOfCompareWithConstant = [](SDValue Op) {
15401     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15402         Op.getValueType() != MVT::i64)
15403       return false;
15404 
15405     SDValue Cmp = Op.getOperand(0);
15406     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15407         Cmp.getOperand(0).getValueType() != MVT::i64)
15408       return false;
15409 
15410     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15411       int64_t NegConstant = 0 - Constant->getSExtValue();
15412       // Due to the limitations of the addi instruction,
15413       // -C is required to be [-32768, 32767].
15414       return isInt<16>(NegConstant);
15415     }
15416 
15417     return false;
15418   };
15419 
15420   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15421   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15422 
15423   // If there is a pattern, canonicalize a zext operand to the RHS.
15424   if (LHSHasPattern && !RHSHasPattern)
15425     std::swap(LHS, RHS);
15426   else if (!LHSHasPattern && !RHSHasPattern)
15427     return SDValue();
15428 
15429   SDLoc DL(N);
15430   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15431   SDValue Cmp = RHS.getOperand(0);
15432   SDValue Z = Cmp.getOperand(0);
15433   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15434 
15435   assert(Constant && "Constant Should not be a null pointer.");
15436   int64_t NegConstant = 0 - Constant->getSExtValue();
15437 
15438   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15439   default: break;
15440   case ISD::SETNE: {
15441     //                                 when C == 0
15442     //                             --> addze X, (addic Z, -1).carry
15443     //                            /
15444     // add X, (zext(setne Z, C))--
15445     //                            \    when -32768 <= -C <= 32767 && C != 0
15446     //                             --> addze X, (addic (addi Z, -C), -1).carry
15447     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15448                               DAG.getConstant(NegConstant, DL, MVT::i64));
15449     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15450     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15451                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15452     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15453                        SDValue(Addc.getNode(), 1));
15454     }
15455   case ISD::SETEQ: {
15456     //                                 when C == 0
15457     //                             --> addze X, (subfic Z, 0).carry
15458     //                            /
15459     // add X, (zext(sete  Z, C))--
15460     //                            \    when -32768 <= -C <= 32767 && C != 0
15461     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15462     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15463                               DAG.getConstant(NegConstant, DL, MVT::i64));
15464     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15465     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15466                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15467     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15468                        SDValue(Subc.getNode(), 1));
15469     }
15470   }
15471 
15472   return SDValue();
15473 }
15474 
15475 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15476   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15477     return Value;
15478 
15479   return SDValue();
15480 }
15481 
15482 // Detect TRUNCATE operations on bitcasts of float128 values.
15483 // What we are looking for here is the situtation where we extract a subset
15484 // of bits from a 128 bit float.
15485 // This can be of two forms:
15486 // 1) BITCAST of f128 feeding TRUNCATE
15487 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15488 // The reason this is required is because we do not have a legal i128 type
15489 // and so we want to prevent having to store the f128 and then reload part
15490 // of it.
15491 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15492                                            DAGCombinerInfo &DCI) const {
15493   // If we are using CRBits then try that first.
15494   if (Subtarget.useCRBits()) {
15495     // Check if CRBits did anything and return that if it did.
15496     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15497       return CRTruncValue;
15498   }
15499 
15500   SDLoc dl(N);
15501   SDValue Op0 = N->getOperand(0);
15502 
15503   // Looking for a truncate of i128 to i64.
15504   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15505     return SDValue();
15506 
15507   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15508 
15509   // SRL feeding TRUNCATE.
15510   if (Op0.getOpcode() == ISD::SRL) {
15511     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15512     // The right shift has to be by 64 bits.
15513     if (!ConstNode || ConstNode->getZExtValue() != 64)
15514       return SDValue();
15515 
15516     // Switch the element number to extract.
15517     EltToExtract = EltToExtract ? 0 : 1;
15518     // Update Op0 past the SRL.
15519     Op0 = Op0.getOperand(0);
15520   }
15521 
15522   // BITCAST feeding a TRUNCATE possibly via SRL.
15523   if (Op0.getOpcode() == ISD::BITCAST &&
15524       Op0.getValueType() == MVT::i128 &&
15525       Op0.getOperand(0).getValueType() == MVT::f128) {
15526     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15527     return DCI.DAG.getNode(
15528         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15529         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15530   }
15531   return SDValue();
15532 }
15533 
15534 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15535   SelectionDAG &DAG = DCI.DAG;
15536 
15537   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15538   if (!ConstOpOrElement)
15539     return SDValue();
15540 
15541   // An imul is usually smaller than the alternative sequence for legal type.
15542   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15543       isOperationLegal(ISD::MUL, N->getValueType(0)))
15544     return SDValue();
15545 
15546   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15547     switch (this->Subtarget.getCPUDirective()) {
15548     default:
15549       // TODO: enhance the condition for subtarget before pwr8
15550       return false;
15551     case PPC::DIR_PWR8:
15552       //  type        mul     add    shl
15553       // scalar        4       1      1
15554       // vector        7       2      2
15555       return true;
15556     case PPC::DIR_PWR9:
15557     case PPC::DIR_PWR_FUTURE:
15558       //  type        mul     add    shl
15559       // scalar        5       2      2
15560       // vector        7       2      2
15561 
15562       // The cycle RATIO of related operations are showed as a table above.
15563       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15564       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15565       // are 4, it is always profitable; but for 3 instrs patterns
15566       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15567       // So we should only do it for vector type.
15568       return IsAddOne && IsNeg ? VT.isVector() : true;
15569     }
15570   };
15571 
15572   EVT VT = N->getValueType(0);
15573   SDLoc DL(N);
15574 
15575   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15576   bool IsNeg = MulAmt.isNegative();
15577   APInt MulAmtAbs = MulAmt.abs();
15578 
15579   if ((MulAmtAbs - 1).isPowerOf2()) {
15580     // (mul x, 2^N + 1) => (add (shl x, N), x)
15581     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15582 
15583     if (!IsProfitable(IsNeg, true, VT))
15584       return SDValue();
15585 
15586     SDValue Op0 = N->getOperand(0);
15587     SDValue Op1 =
15588         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15589                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15590     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15591 
15592     if (!IsNeg)
15593       return Res;
15594 
15595     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15596   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15597     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15598     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15599 
15600     if (!IsProfitable(IsNeg, false, VT))
15601       return SDValue();
15602 
15603     SDValue Op0 = N->getOperand(0);
15604     SDValue Op1 =
15605         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15606                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15607 
15608     if (!IsNeg)
15609       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15610     else
15611       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15612 
15613   } else {
15614     return SDValue();
15615   }
15616 }
15617 
15618 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15619   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15620   if (!Subtarget.is64BitELFABI())
15621     return false;
15622 
15623   // If not a tail call then no need to proceed.
15624   if (!CI->isTailCall())
15625     return false;
15626 
15627   // If tail calls are disabled for the caller then we are done.
15628   const Function *Caller = CI->getParent()->getParent();
15629   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15630   if (Attr.getValueAsString() == "true")
15631     return false;
15632 
15633   // If sibling calls have been disabled and tail-calls aren't guaranteed
15634   // there is no reason to duplicate.
15635   auto &TM = getTargetMachine();
15636   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15637     return false;
15638 
15639   // Can't tail call a function called indirectly, or if it has variadic args.
15640   const Function *Callee = CI->getCalledFunction();
15641   if (!Callee || Callee->isVarArg())
15642     return false;
15643 
15644   // Make sure the callee and caller calling conventions are eligible for tco.
15645   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15646                                            CI->getCallingConv()))
15647       return false;
15648 
15649   // If the function is local then we have a good chance at tail-calling it
15650   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15651 }
15652 
15653 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15654   if (!Subtarget.hasVSX())
15655     return false;
15656   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15657     return true;
15658   return VT == MVT::f32 || VT == MVT::f64 ||
15659     VT == MVT::v4f32 || VT == MVT::v2f64;
15660 }
15661 
15662 bool PPCTargetLowering::
15663 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15664   const Value *Mask = AndI.getOperand(1);
15665   // If the mask is suitable for andi. or andis. we should sink the and.
15666   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15667     // Can't handle constants wider than 64-bits.
15668     if (CI->getBitWidth() > 64)
15669       return false;
15670     int64_t ConstVal = CI->getZExtValue();
15671     return isUInt<16>(ConstVal) ||
15672       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15673   }
15674 
15675   // For non-constant masks, we can always use the record-form and.
15676   return true;
15677 }
15678 
15679 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15680 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15681 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15682 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15683 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15684 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15685   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15686   assert(Subtarget.hasP9Altivec() &&
15687          "Only combine this when P9 altivec supported!");
15688   EVT VT = N->getValueType(0);
15689   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15690     return SDValue();
15691 
15692   SelectionDAG &DAG = DCI.DAG;
15693   SDLoc dl(N);
15694   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15695     // Even for signed integers, if it's known to be positive (as signed
15696     // integer) due to zero-extended inputs.
15697     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15698     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15699     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15700          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15701         (SubOpcd1 == ISD::ZERO_EXTEND ||
15702          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15703       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15704                          N->getOperand(0)->getOperand(0),
15705                          N->getOperand(0)->getOperand(1),
15706                          DAG.getTargetConstant(0, dl, MVT::i32));
15707     }
15708 
15709     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15710     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15711         N->getOperand(0).hasOneUse()) {
15712       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15713                          N->getOperand(0)->getOperand(0),
15714                          N->getOperand(0)->getOperand(1),
15715                          DAG.getTargetConstant(1, dl, MVT::i32));
15716     }
15717   }
15718 
15719   return SDValue();
15720 }
15721 
15722 // For type v4i32/v8ii16/v16i8, transform
15723 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15724 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15725 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15726 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15727 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15728                                           DAGCombinerInfo &DCI) const {
15729   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15730   assert(Subtarget.hasP9Altivec() &&
15731          "Only combine this when P9 altivec supported!");
15732 
15733   SelectionDAG &DAG = DCI.DAG;
15734   SDLoc dl(N);
15735   SDValue Cond = N->getOperand(0);
15736   SDValue TrueOpnd = N->getOperand(1);
15737   SDValue FalseOpnd = N->getOperand(2);
15738   EVT VT = N->getOperand(1).getValueType();
15739 
15740   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15741       FalseOpnd.getOpcode() != ISD::SUB)
15742     return SDValue();
15743 
15744   // ABSD only available for type v4i32/v8i16/v16i8
15745   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15746     return SDValue();
15747 
15748   // At least to save one more dependent computation
15749   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15750     return SDValue();
15751 
15752   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15753 
15754   // Can only handle unsigned comparison here
15755   switch (CC) {
15756   default:
15757     return SDValue();
15758   case ISD::SETUGT:
15759   case ISD::SETUGE:
15760     break;
15761   case ISD::SETULT:
15762   case ISD::SETULE:
15763     std::swap(TrueOpnd, FalseOpnd);
15764     break;
15765   }
15766 
15767   SDValue CmpOpnd1 = Cond.getOperand(0);
15768   SDValue CmpOpnd2 = Cond.getOperand(1);
15769 
15770   // SETCC CmpOpnd1 CmpOpnd2 cond
15771   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15772   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15773   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15774       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15775       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15776       FalseOpnd.getOperand(1) == CmpOpnd1) {
15777     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15778                        CmpOpnd1, CmpOpnd2,
15779                        DAG.getTargetConstant(0, dl, MVT::i32));
15780   }
15781 
15782   return SDValue();
15783 }
15784