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/Module.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/MC/MCContext.h"
75 #include "llvm/MC/MCExpr.h"
76 #include "llvm/MC/MCRegisterInfo.h"
77 #include "llvm/MC/MCSymbolXCOFF.h"
78 #include "llvm/Support/AtomicOrdering.h"
79 #include "llvm/Support/BranchProbability.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/CodeGen.h"
82 #include "llvm/Support/CommandLine.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/Debug.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/KnownBits.h"
88 #include "llvm/Support/MachineValueType.h"
89 #include "llvm/Support/MathExtras.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include "llvm/Target/TargetMachine.h"
92 #include "llvm/Target/TargetOptions.h"
93 #include <algorithm>
94 #include <cassert>
95 #include <cstdint>
96 #include <iterator>
97 #include <list>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 
103 #define DEBUG_TYPE "ppc-lowering"
104 
105 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
106 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
109 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
112 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
113 
114 static cl::opt<bool> DisableSCO("disable-ppc-sco",
115 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
116 
117 static cl::opt<bool> DisableInnermostLoopAlign32("disable-ppc-innermost-loop-align32",
118 cl::desc("don't always align innermost loop to 32 bytes on ppc"), cl::Hidden);
119 
120 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
121 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
122 
123 static cl::opt<bool> UseAbsoluteJumpTables("ppc-use-absolute-jumptables",
124 cl::desc("use absolute jump tables on ppc"), cl::Hidden);
125 
126 STATISTIC(NumTailCalls, "Number of tail calls");
127 STATISTIC(NumSiblingCalls, "Number of sibling calls");
128 
129 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
130 
131 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl);
132 
133 // FIXME: Remove this once the bug has been fixed!
134 extern cl::opt<bool> ANDIGlueBug;
135 
136 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
137                                      const PPCSubtarget &STI)
138     : TargetLowering(TM), Subtarget(STI) {
139   // Use _setjmp/_longjmp instead of setjmp/longjmp.
140   setUseUnderscoreSetJmp(true);
141   setUseUnderscoreLongJmp(true);
142 
143   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
144   // arguments are at least 4/8 bytes aligned.
145   bool isPPC64 = Subtarget.isPPC64();
146   setMinStackArgumentAlignment(isPPC64 ? Align(8) : Align(4));
147 
148   // Set up the register classes.
149   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
150   if (!useSoftFloat()) {
151     if (hasSPE()) {
152       addRegisterClass(MVT::f32, &PPC::GPRCRegClass);
153       addRegisterClass(MVT::f64, &PPC::SPERCRegClass);
154     } else {
155       addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
156       addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
157     }
158   }
159 
160   // Match BITREVERSE to customized fast code sequence in the td file.
161   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
162   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
163 
164   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
165   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
166 
167   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
168   for (MVT VT : MVT::integer_valuetypes()) {
169     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
170     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
171   }
172 
173   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
174 
175   // PowerPC has pre-inc load and store's.
176   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
177   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
178   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
179   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
180   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
181   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
182   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
183   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
184   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
185   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
186   if (!Subtarget.hasSPE()) {
187     setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
188     setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
189     setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
190     setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
191   }
192 
193   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
194   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
195   for (MVT VT : ScalarIntVTs) {
196     setOperationAction(ISD::ADDC, VT, Legal);
197     setOperationAction(ISD::ADDE, VT, Legal);
198     setOperationAction(ISD::SUBC, VT, Legal);
199     setOperationAction(ISD::SUBE, VT, Legal);
200   }
201 
202   if (Subtarget.useCRBits()) {
203     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
204 
205     if (isPPC64 || Subtarget.hasFPCVT()) {
206       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
207       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
208                          isPPC64 ? MVT::i64 : MVT::i32);
209       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
210       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
211                         isPPC64 ? MVT::i64 : MVT::i32);
212     } else {
213       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
214       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
215     }
216 
217     // PowerPC does not support direct load/store of condition registers.
218     setOperationAction(ISD::LOAD, MVT::i1, Custom);
219     setOperationAction(ISD::STORE, MVT::i1, Custom);
220 
221     // FIXME: Remove this once the ANDI glue bug is fixed:
222     if (ANDIGlueBug)
223       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
224 
225     for (MVT VT : MVT::integer_valuetypes()) {
226       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
227       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
228       setTruncStoreAction(VT, MVT::i1, Expand);
229     }
230 
231     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
232   }
233 
234   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
235   // PPC (the libcall is not available).
236   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
237   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
238 
239   // We do not currently implement these libm ops for PowerPC.
240   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
241   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
242   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
243   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
244   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
245   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
246 
247   // PowerPC has no SREM/UREM instructions unless we are on P9
248   // On P9 we may use a hardware instruction to compute the remainder.
249   // The instructions are not legalized directly because in the cases where the
250   // result of both the remainder and the division is required it is more
251   // efficient to compute the remainder from the result of the division rather
252   // than use the remainder instruction.
253   if (Subtarget.isISA3_0()) {
254     setOperationAction(ISD::SREM, MVT::i32, Custom);
255     setOperationAction(ISD::UREM, MVT::i32, Custom);
256     setOperationAction(ISD::SREM, MVT::i64, Custom);
257     setOperationAction(ISD::UREM, MVT::i64, Custom);
258   } else {
259     setOperationAction(ISD::SREM, MVT::i32, Expand);
260     setOperationAction(ISD::UREM, MVT::i32, Expand);
261     setOperationAction(ISD::SREM, MVT::i64, Expand);
262     setOperationAction(ISD::UREM, MVT::i64, Expand);
263   }
264 
265   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
266   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
267   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
268   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
269   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
270   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
271   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
272   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
273   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
274 
275   // We don't support sin/cos/sqrt/fmod/pow
276   setOperationAction(ISD::FSIN , MVT::f64, Expand);
277   setOperationAction(ISD::FCOS , MVT::f64, Expand);
278   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
279   setOperationAction(ISD::FREM , MVT::f64, Expand);
280   setOperationAction(ISD::FPOW , MVT::f64, Expand);
281   setOperationAction(ISD::FSIN , MVT::f32, Expand);
282   setOperationAction(ISD::FCOS , MVT::f32, Expand);
283   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
284   setOperationAction(ISD::FREM , MVT::f32, Expand);
285   setOperationAction(ISD::FPOW , MVT::f32, Expand);
286   if (Subtarget.hasSPE()) {
287     setOperationAction(ISD::FMA  , MVT::f64, Expand);
288     setOperationAction(ISD::FMA  , MVT::f32, Expand);
289   } else {
290     setOperationAction(ISD::FMA  , MVT::f64, Legal);
291     setOperationAction(ISD::FMA  , MVT::f32, Legal);
292   }
293 
294   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
295 
296   // If we're enabling GP optimizations, use hardware square root
297   if (!Subtarget.hasFSQRT() &&
298       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
299         Subtarget.hasFRE()))
300     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
301 
302   if (!Subtarget.hasFSQRT() &&
303       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
304         Subtarget.hasFRES()))
305     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
306 
307   if (Subtarget.hasFCPSGN()) {
308     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
309     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
310   } else {
311     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
312     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
313   }
314 
315   if (Subtarget.hasFPRND()) {
316     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
317     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
318     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
319     setOperationAction(ISD::FROUND, MVT::f64, Legal);
320 
321     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
322     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
323     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
324     setOperationAction(ISD::FROUND, MVT::f32, Legal);
325   }
326 
327   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
328   // to speed up scalar BSWAP64.
329   // CTPOP or CTTZ were introduced in P8/P9 respectively
330   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
331   if (Subtarget.hasP9Vector())
332     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
333   else
334     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
335   if (Subtarget.isISA3_0()) {
336     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
337     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
338   } else {
339     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
340     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
341   }
342 
343   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
344     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
345     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
346   } else {
347     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
348     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
349   }
350 
351   // PowerPC does not have ROTR
352   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
353   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
354 
355   if (!Subtarget.useCRBits()) {
356     // PowerPC does not have Select
357     setOperationAction(ISD::SELECT, MVT::i32, Expand);
358     setOperationAction(ISD::SELECT, MVT::i64, Expand);
359     setOperationAction(ISD::SELECT, MVT::f32, Expand);
360     setOperationAction(ISD::SELECT, MVT::f64, Expand);
361   }
362 
363   // PowerPC wants to turn select_cc of FP into fsel when possible.
364   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
365   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
366 
367   // PowerPC wants to optimize integer setcc a bit
368   if (!Subtarget.useCRBits())
369     setOperationAction(ISD::SETCC, MVT::i32, Custom);
370 
371   // PowerPC does not have BRCOND which requires SetCC
372   if (!Subtarget.useCRBits())
373     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
374 
375   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
376 
377   if (Subtarget.hasSPE()) {
378     // SPE has built-in conversions
379     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Legal);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Legal);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Legal);
382   } else {
383     // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
384     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
385 
386     // PowerPC does not have [U|S]INT_TO_FP
387     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
388     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
389   }
390 
391   if (Subtarget.hasDirectMove() && isPPC64) {
392     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
393     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
394     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
395     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
396   } else {
397     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
398     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
399     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
400     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
401   }
402 
403   // We cannot sextinreg(i1).  Expand to shifts.
404   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
405 
406   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
407   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
408   // support continuation, user-level threading, and etc.. As a result, no
409   // other SjLj exception interfaces are implemented and please don't build
410   // your own exception handling based on them.
411   // LLVM/Clang supports zero-cost DWARF exception handling.
412   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
413   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
414 
415   // We want to legalize GlobalAddress and ConstantPool nodes into the
416   // appropriate instructions to materialize the address.
417   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
418   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
419   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
420   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
421   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
422   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
423   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
424   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
425   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
426   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
427 
428   // TRAP is legal.
429   setOperationAction(ISD::TRAP, MVT::Other, Legal);
430 
431   // TRAMPOLINE is custom lowered.
432   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
433   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
434 
435   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
436   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
437 
438   if (Subtarget.is64BitELFABI()) {
439     // VAARG always uses double-word chunks, so promote anything smaller.
440     setOperationAction(ISD::VAARG, MVT::i1, Promote);
441     AddPromotedToType(ISD::VAARG, MVT::i1, MVT::i64);
442     setOperationAction(ISD::VAARG, MVT::i8, Promote);
443     AddPromotedToType(ISD::VAARG, MVT::i8, MVT::i64);
444     setOperationAction(ISD::VAARG, MVT::i16, Promote);
445     AddPromotedToType(ISD::VAARG, MVT::i16, MVT::i64);
446     setOperationAction(ISD::VAARG, MVT::i32, Promote);
447     AddPromotedToType(ISD::VAARG, MVT::i32, MVT::i64);
448     setOperationAction(ISD::VAARG, MVT::Other, Expand);
449   } else if (Subtarget.is32BitELFABI()) {
450     // VAARG is custom lowered with the 32-bit SVR4 ABI.
451     setOperationAction(ISD::VAARG, MVT::Other, Custom);
452     setOperationAction(ISD::VAARG, MVT::i64, Custom);
453   } else
454     setOperationAction(ISD::VAARG, MVT::Other, Expand);
455 
456   // VACOPY is custom lowered with the 32-bit SVR4 ABI.
457   if (Subtarget.is32BitELFABI())
458     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
459   else
460     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
461 
462   // Use the default implementation.
463   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
464   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
465   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
466   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
467   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
468   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
469   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
470   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
471   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
472 
473   // We want to custom lower some of our intrinsics.
474   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
475 
476   // To handle counter-based loop conditions.
477   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
478 
479   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
480   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
481   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
482   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
483 
484   // Comparisons that require checking two conditions.
485   if (Subtarget.hasSPE()) {
486     setCondCodeAction(ISD::SETO, MVT::f32, Expand);
487     setCondCodeAction(ISD::SETO, MVT::f64, Expand);
488     setCondCodeAction(ISD::SETUO, MVT::f32, Expand);
489     setCondCodeAction(ISD::SETUO, MVT::f64, Expand);
490   }
491   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
492   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
493   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
494   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
495   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
496   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
497   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
498   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
499   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
500   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
501   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
502   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
503 
504   if (Subtarget.has64BitSupport()) {
505     // They also have instructions for converting between i64 and fp.
506     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
507     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
508     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
509     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
510     // This is just the low 32 bits of a (signed) fp->i64 conversion.
511     // We cannot do this with Promote because i64 is not a legal type.
512     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
513 
514     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
515       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
516   } else {
517     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
518     if (Subtarget.hasSPE())
519       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Legal);
520     else
521       setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
522   }
523 
524   // With the instructions enabled under FPCVT, we can do everything.
525   if (Subtarget.hasFPCVT()) {
526     if (Subtarget.has64BitSupport()) {
527       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
528       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
529       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
530       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
531     }
532 
533     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
534     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
535     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
536     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
537   }
538 
539   if (Subtarget.use64BitRegs()) {
540     // 64-bit PowerPC implementations can support i64 types directly
541     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
542     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
543     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
544     // 64-bit PowerPC wants to expand i128 shifts itself.
545     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
546     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
547     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
548   } else {
549     // 32-bit PowerPC wants to expand i64 shifts itself.
550     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
551     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
552     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
553   }
554 
555   if (Subtarget.hasVSX()) {
556     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
557     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
558     setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
559     setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
560   }
561 
562   if (Subtarget.hasAltivec()) {
563     // First set operation action for all vector types to expand. Then we
564     // will selectively turn on ones that can be effectively codegen'd.
565     for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
566       // add/sub are legal for all supported vector VT's.
567       setOperationAction(ISD::ADD, VT, Legal);
568       setOperationAction(ISD::SUB, VT, Legal);
569 
570       // For v2i64, these are only valid with P8Vector. This is corrected after
571       // the loop.
572       if (VT.getSizeInBits() <= 128 && VT.getScalarSizeInBits() <= 64) {
573         setOperationAction(ISD::SMAX, VT, Legal);
574         setOperationAction(ISD::SMIN, VT, Legal);
575         setOperationAction(ISD::UMAX, VT, Legal);
576         setOperationAction(ISD::UMIN, VT, Legal);
577       }
578       else {
579         setOperationAction(ISD::SMAX, VT, Expand);
580         setOperationAction(ISD::SMIN, VT, Expand);
581         setOperationAction(ISD::UMAX, VT, Expand);
582         setOperationAction(ISD::UMIN, VT, Expand);
583       }
584 
585       if (Subtarget.hasVSX()) {
586         setOperationAction(ISD::FMAXNUM, VT, Legal);
587         setOperationAction(ISD::FMINNUM, VT, Legal);
588       }
589 
590       // Vector instructions introduced in P8
591       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
592         setOperationAction(ISD::CTPOP, VT, Legal);
593         setOperationAction(ISD::CTLZ, VT, Legal);
594       }
595       else {
596         setOperationAction(ISD::CTPOP, VT, Expand);
597         setOperationAction(ISD::CTLZ, VT, Expand);
598       }
599 
600       // Vector instructions introduced in P9
601       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
602         setOperationAction(ISD::CTTZ, VT, Legal);
603       else
604         setOperationAction(ISD::CTTZ, VT, Expand);
605 
606       // We promote all shuffles to v16i8.
607       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
608       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
609 
610       // We promote all non-typed operations to v4i32.
611       setOperationAction(ISD::AND   , VT, Promote);
612       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
613       setOperationAction(ISD::OR    , VT, Promote);
614       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
615       setOperationAction(ISD::XOR   , VT, Promote);
616       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
617       setOperationAction(ISD::LOAD  , VT, Promote);
618       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
619       setOperationAction(ISD::SELECT, VT, Promote);
620       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
621       setOperationAction(ISD::VSELECT, VT, Legal);
622       setOperationAction(ISD::SELECT_CC, VT, Promote);
623       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
624       setOperationAction(ISD::STORE, VT, Promote);
625       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
626 
627       // No other operations are legal.
628       setOperationAction(ISD::MUL , VT, Expand);
629       setOperationAction(ISD::SDIV, VT, Expand);
630       setOperationAction(ISD::SREM, VT, Expand);
631       setOperationAction(ISD::UDIV, VT, Expand);
632       setOperationAction(ISD::UREM, VT, Expand);
633       setOperationAction(ISD::FDIV, VT, Expand);
634       setOperationAction(ISD::FREM, VT, Expand);
635       setOperationAction(ISD::FNEG, VT, Expand);
636       setOperationAction(ISD::FSQRT, VT, Expand);
637       setOperationAction(ISD::FLOG, VT, Expand);
638       setOperationAction(ISD::FLOG10, VT, Expand);
639       setOperationAction(ISD::FLOG2, VT, Expand);
640       setOperationAction(ISD::FEXP, VT, Expand);
641       setOperationAction(ISD::FEXP2, VT, Expand);
642       setOperationAction(ISD::FSIN, VT, Expand);
643       setOperationAction(ISD::FCOS, VT, Expand);
644       setOperationAction(ISD::FABS, VT, Expand);
645       setOperationAction(ISD::FFLOOR, VT, Expand);
646       setOperationAction(ISD::FCEIL,  VT, Expand);
647       setOperationAction(ISD::FTRUNC, VT, Expand);
648       setOperationAction(ISD::FRINT,  VT, Expand);
649       setOperationAction(ISD::FNEARBYINT, VT, Expand);
650       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
651       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
652       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
653       setOperationAction(ISD::MULHU, VT, Expand);
654       setOperationAction(ISD::MULHS, VT, Expand);
655       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
656       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
657       setOperationAction(ISD::UDIVREM, VT, Expand);
658       setOperationAction(ISD::SDIVREM, VT, Expand);
659       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
660       setOperationAction(ISD::FPOW, VT, Expand);
661       setOperationAction(ISD::BSWAP, VT, Expand);
662       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
663       setOperationAction(ISD::ROTL, VT, Expand);
664       setOperationAction(ISD::ROTR, VT, Expand);
665 
666       for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
667         setTruncStoreAction(VT, InnerVT, Expand);
668         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
669         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
670         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
671       }
672     }
673     if (!Subtarget.hasP8Vector()) {
674       setOperationAction(ISD::SMAX, MVT::v2i64, Expand);
675       setOperationAction(ISD::SMIN, MVT::v2i64, Expand);
676       setOperationAction(ISD::UMAX, MVT::v2i64, Expand);
677       setOperationAction(ISD::UMIN, MVT::v2i64, Expand);
678     }
679 
680     for (auto VT : {MVT::v2i64, MVT::v4i32, MVT::v8i16, MVT::v16i8})
681       setOperationAction(ISD::ABS, VT, Custom);
682 
683     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
684     // with merges, splats, etc.
685     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
686 
687     // Vector truncates to sub-word integer that fit in an Altivec/VSX register
688     // are cheap, so handle them before they get expanded to scalar.
689     setOperationAction(ISD::TRUNCATE, MVT::v8i8, Custom);
690     setOperationAction(ISD::TRUNCATE, MVT::v4i8, Custom);
691     setOperationAction(ISD::TRUNCATE, MVT::v2i8, Custom);
692     setOperationAction(ISD::TRUNCATE, MVT::v4i16, Custom);
693     setOperationAction(ISD::TRUNCATE, MVT::v2i16, Custom);
694 
695     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
696     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
697     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
698     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
699     setOperationAction(ISD::SELECT, MVT::v4i32,
700                        Subtarget.useCRBits() ? Legal : Expand);
701     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
702     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
703     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
704     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
705     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
706     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
707     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
708     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
709     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
710 
711     // Without hasP8Altivec set, v2i64 SMAX isn't available.
712     // But ABS custom lowering requires SMAX support.
713     if (!Subtarget.hasP8Altivec())
714       setOperationAction(ISD::ABS, MVT::v2i64, Expand);
715 
716     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
717     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
718     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
719     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
720 
721     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
722     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
723 
724     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
725       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
726       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
727     }
728 
729     if (Subtarget.hasP8Altivec())
730       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
731     else
732       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
733 
734     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
735     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
736 
737     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
738     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
739 
740     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
741     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
742     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
743     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
744 
745     // Altivec does not contain unordered floating-point compare instructions
746     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
747     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
748     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
749     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
750 
751     if (Subtarget.hasVSX()) {
752       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
753       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
754       if (Subtarget.hasP8Vector()) {
755         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
756         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
757       }
758       if (Subtarget.hasDirectMove() && isPPC64) {
759         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
760         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
761         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
762         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
763         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
764         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
765         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
766         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
767       }
768       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
769 
770       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
771       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
772       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
773       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
774       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
775 
776       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
777 
778       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
779       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
780 
781       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
782       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
783 
784       // Share the Altivec comparison restrictions.
785       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
786       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
787       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
788       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
789 
790       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
791       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
792 
793       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
794 
795       if (Subtarget.hasP8Vector())
796         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
797 
798       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
799 
800       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
801       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
802       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
803 
804       if (Subtarget.hasP8Altivec()) {
805         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
806         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
807         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
808 
809         // 128 bit shifts can be accomplished via 3 instructions for SHL and
810         // SRL, but not for SRA because of the instructions available:
811         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
812         // doing
813         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
814         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
815         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
816 
817         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
818       }
819       else {
820         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
821         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
822         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
823 
824         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
825 
826         // VSX v2i64 only supports non-arithmetic operations.
827         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
828         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
829       }
830 
831       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
832       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
833       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
834       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
835 
836       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
837 
838       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
839       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
840       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
841       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
842 
843       // Custom handling for partial vectors of integers converted to
844       // floating point. We already have optimal handling for v2i32 through
845       // the DAG combine, so those aren't necessary.
846       setOperationAction(ISD::UINT_TO_FP, MVT::v2i8, Custom);
847       setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Custom);
848       setOperationAction(ISD::UINT_TO_FP, MVT::v2i16, Custom);
849       setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
850       setOperationAction(ISD::SINT_TO_FP, MVT::v2i8, Custom);
851       setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Custom);
852       setOperationAction(ISD::SINT_TO_FP, MVT::v2i16, Custom);
853       setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
854 
855       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
856       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
857       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
858       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
859       setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
860       setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Legal);
861 
862       if (Subtarget.hasDirectMove())
863         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
864       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
865 
866       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
867     }
868 
869     if (Subtarget.hasP8Altivec()) {
870       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
871       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
872     }
873 
874     if (Subtarget.hasP9Vector()) {
875       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
876       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
877 
878       // 128 bit shifts can be accomplished via 3 instructions for SHL and
879       // SRL, but not for SRA because of the instructions available:
880       // VS{RL} and VS{RL}O.
881       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
882       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
883       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
884 
885       if (EnableQuadPrecision) {
886         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
887         setOperationAction(ISD::FADD, MVT::f128, Legal);
888         setOperationAction(ISD::FSUB, MVT::f128, Legal);
889         setOperationAction(ISD::FDIV, MVT::f128, Legal);
890         setOperationAction(ISD::FMUL, MVT::f128, Legal);
891         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
892         // No extending loads to f128 on PPC.
893         for (MVT FPT : MVT::fp_valuetypes())
894           setLoadExtAction(ISD::EXTLOAD, MVT::f128, FPT, Expand);
895         setOperationAction(ISD::FMA, MVT::f128, Legal);
896         setCondCodeAction(ISD::SETULT, MVT::f128, Expand);
897         setCondCodeAction(ISD::SETUGT, MVT::f128, Expand);
898         setCondCodeAction(ISD::SETUEQ, MVT::f128, Expand);
899         setCondCodeAction(ISD::SETOGE, MVT::f128, Expand);
900         setCondCodeAction(ISD::SETOLE, MVT::f128, Expand);
901         setCondCodeAction(ISD::SETONE, MVT::f128, Expand);
902 
903         setOperationAction(ISD::FTRUNC, MVT::f128, Legal);
904         setOperationAction(ISD::FRINT, MVT::f128, Legal);
905         setOperationAction(ISD::FFLOOR, MVT::f128, Legal);
906         setOperationAction(ISD::FCEIL, MVT::f128, Legal);
907         setOperationAction(ISD::FNEARBYINT, MVT::f128, Legal);
908         setOperationAction(ISD::FROUND, MVT::f128, Legal);
909 
910         setOperationAction(ISD::SELECT, MVT::f128, Expand);
911         setOperationAction(ISD::FP_ROUND, MVT::f64, Legal);
912         setOperationAction(ISD::FP_ROUND, MVT::f32, Legal);
913         setTruncStoreAction(MVT::f128, MVT::f64, Expand);
914         setTruncStoreAction(MVT::f128, MVT::f32, Expand);
915         setOperationAction(ISD::BITCAST, MVT::i128, Custom);
916         // No implementation for these ops for PowerPC.
917         setOperationAction(ISD::FSIN , MVT::f128, Expand);
918         setOperationAction(ISD::FCOS , MVT::f128, Expand);
919         setOperationAction(ISD::FPOW, MVT::f128, Expand);
920         setOperationAction(ISD::FPOWI, MVT::f128, Expand);
921         setOperationAction(ISD::FREM, MVT::f128, Expand);
922       }
923       setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Custom);
924 
925     }
926 
927     if (Subtarget.hasP9Altivec()) {
928       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
929       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
930 
931       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8,  Legal);
932       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Legal);
933       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i32, Legal);
934       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8,  Legal);
935       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Legal);
936       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
937       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
938     }
939   }
940 
941   if (Subtarget.hasQPX()) {
942     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
943     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
944     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
945     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
946 
947     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
948     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
949 
950     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
951     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
952 
953     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
954     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
955 
956     if (!Subtarget.useCRBits())
957       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
958     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
959 
960     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
961     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
962     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
963     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
964     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
966     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
967 
968     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
969     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
970 
971     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
972     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
973 
974     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
975     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
976     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
977     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
978     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
979     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
980     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
981     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
982     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
983     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
984 
985     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
986     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
987 
988     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
989     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
990 
991     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
992 
993     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
994     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
995     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
996     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
997 
998     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
999     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
1000 
1001     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
1002     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
1003 
1004     if (!Subtarget.useCRBits())
1005       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
1006     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
1007 
1008     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
1009     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
1010     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
1011     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
1012     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
1013     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
1014     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
1015 
1016     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
1017     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
1018 
1019     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
1020     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
1021     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
1022     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
1023     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
1024     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
1025     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
1026     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
1027     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
1028     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
1029 
1030     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1031     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1032 
1033     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
1034     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
1035 
1036     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
1037 
1038     setOperationAction(ISD::AND , MVT::v4i1, Legal);
1039     setOperationAction(ISD::OR , MVT::v4i1, Legal);
1040     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
1041 
1042     if (!Subtarget.useCRBits())
1043       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
1044     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
1045 
1046     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
1047     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
1048 
1049     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
1050     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
1051     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
1052     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
1053     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
1054     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
1055     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
1056 
1057     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
1058     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
1059 
1060     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
1061 
1062     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
1063     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
1064     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
1065     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
1066 
1067     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
1068     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
1069     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
1070     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
1071 
1072     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
1073     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
1074 
1075     // These need to set FE_INEXACT, and so cannot be vectorized here.
1076     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
1077     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
1078 
1079     if (TM.Options.UnsafeFPMath) {
1080       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
1081       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
1082 
1083       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
1084       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
1085     } else {
1086       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
1087       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
1088 
1089       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
1090       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
1091     }
1092   }
1093 
1094   if (Subtarget.has64BitSupport())
1095     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
1096 
1097   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
1098 
1099   if (!isPPC64) {
1100     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
1101     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
1102   }
1103 
1104   setBooleanContents(ZeroOrOneBooleanContent);
1105 
1106   if (Subtarget.hasAltivec()) {
1107     // Altivec instructions set fields to all zeros or all ones.
1108     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
1109   }
1110 
1111   if (!isPPC64) {
1112     // These libcalls are not available in 32-bit.
1113     setLibcallName(RTLIB::SHL_I128, nullptr);
1114     setLibcallName(RTLIB::SRL_I128, nullptr);
1115     setLibcallName(RTLIB::SRA_I128, nullptr);
1116   }
1117 
1118   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1119 
1120   // We have target-specific dag combine patterns for the following nodes:
1121   setTargetDAGCombine(ISD::ADD);
1122   setTargetDAGCombine(ISD::SHL);
1123   setTargetDAGCombine(ISD::SRA);
1124   setTargetDAGCombine(ISD::SRL);
1125   setTargetDAGCombine(ISD::MUL);
1126   setTargetDAGCombine(ISD::SINT_TO_FP);
1127   setTargetDAGCombine(ISD::BUILD_VECTOR);
1128   if (Subtarget.hasFPCVT())
1129     setTargetDAGCombine(ISD::UINT_TO_FP);
1130   setTargetDAGCombine(ISD::LOAD);
1131   setTargetDAGCombine(ISD::STORE);
1132   setTargetDAGCombine(ISD::BR_CC);
1133   if (Subtarget.useCRBits())
1134     setTargetDAGCombine(ISD::BRCOND);
1135   setTargetDAGCombine(ISD::BSWAP);
1136   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1137   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1138   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1139 
1140   setTargetDAGCombine(ISD::SIGN_EXTEND);
1141   setTargetDAGCombine(ISD::ZERO_EXTEND);
1142   setTargetDAGCombine(ISD::ANY_EXTEND);
1143 
1144   setTargetDAGCombine(ISD::TRUNCATE);
1145   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1146 
1147 
1148   if (Subtarget.useCRBits()) {
1149     setTargetDAGCombine(ISD::TRUNCATE);
1150     setTargetDAGCombine(ISD::SETCC);
1151     setTargetDAGCombine(ISD::SELECT_CC);
1152   }
1153 
1154   // Use reciprocal estimates.
1155   if (TM.Options.UnsafeFPMath) {
1156     setTargetDAGCombine(ISD::FDIV);
1157     setTargetDAGCombine(ISD::FSQRT);
1158   }
1159 
1160   if (Subtarget.hasP9Altivec()) {
1161     setTargetDAGCombine(ISD::ABS);
1162     setTargetDAGCombine(ISD::VSELECT);
1163   }
1164 
1165   // Darwin long double math library functions have $LDBL128 appended.
1166   if (Subtarget.isDarwin()) {
1167     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1168     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1169     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1170     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1171     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1172     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1173     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1174     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1175     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1176     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1177   }
1178 
1179   if (EnableQuadPrecision) {
1180     setLibcallName(RTLIB::LOG_F128, "logf128");
1181     setLibcallName(RTLIB::LOG2_F128, "log2f128");
1182     setLibcallName(RTLIB::LOG10_F128, "log10f128");
1183     setLibcallName(RTLIB::EXP_F128, "expf128");
1184     setLibcallName(RTLIB::EXP2_F128, "exp2f128");
1185     setLibcallName(RTLIB::SIN_F128, "sinf128");
1186     setLibcallName(RTLIB::COS_F128, "cosf128");
1187     setLibcallName(RTLIB::POW_F128, "powf128");
1188     setLibcallName(RTLIB::FMIN_F128, "fminf128");
1189     setLibcallName(RTLIB::FMAX_F128, "fmaxf128");
1190     setLibcallName(RTLIB::POWI_F128, "__powikf2");
1191     setLibcallName(RTLIB::REM_F128, "fmodf128");
1192   }
1193 
1194   // With 32 condition bits, we don't need to sink (and duplicate) compares
1195   // aggressively in CodeGenPrep.
1196   if (Subtarget.useCRBits()) {
1197     setHasMultipleConditionRegisters();
1198     setJumpIsExpensive();
1199   }
1200 
1201   setMinFunctionAlignment(Align(4));
1202   if (Subtarget.isDarwin())
1203     setPrefFunctionAlignment(Align(16));
1204 
1205   switch (Subtarget.getCPUDirective()) {
1206   default: break;
1207   case PPC::DIR_970:
1208   case PPC::DIR_A2:
1209   case PPC::DIR_E500:
1210   case PPC::DIR_E500mc:
1211   case PPC::DIR_E5500:
1212   case PPC::DIR_PWR4:
1213   case PPC::DIR_PWR5:
1214   case PPC::DIR_PWR5X:
1215   case PPC::DIR_PWR6:
1216   case PPC::DIR_PWR6X:
1217   case PPC::DIR_PWR7:
1218   case PPC::DIR_PWR8:
1219   case PPC::DIR_PWR9:
1220   case PPC::DIR_PWR_FUTURE:
1221     setPrefLoopAlignment(Align(16));
1222     setPrefFunctionAlignment(Align(16));
1223     break;
1224   }
1225 
1226   if (Subtarget.enableMachineScheduler())
1227     setSchedulingPreference(Sched::Source);
1228   else
1229     setSchedulingPreference(Sched::Hybrid);
1230 
1231   computeRegisterProperties(STI.getRegisterInfo());
1232 
1233   // The Freescale cores do better with aggressive inlining of memcpy and
1234   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1235   if (Subtarget.getCPUDirective() == PPC::DIR_E500mc ||
1236       Subtarget.getCPUDirective() == PPC::DIR_E5500) {
1237     MaxStoresPerMemset = 32;
1238     MaxStoresPerMemsetOptSize = 16;
1239     MaxStoresPerMemcpy = 32;
1240     MaxStoresPerMemcpyOptSize = 8;
1241     MaxStoresPerMemmove = 32;
1242     MaxStoresPerMemmoveOptSize = 8;
1243   } else if (Subtarget.getCPUDirective() == PPC::DIR_A2) {
1244     // The A2 also benefits from (very) aggressive inlining of memcpy and
1245     // friends. The overhead of a the function call, even when warm, can be
1246     // over one hundred cycles.
1247     MaxStoresPerMemset = 128;
1248     MaxStoresPerMemcpy = 128;
1249     MaxStoresPerMemmove = 128;
1250     MaxLoadsPerMemcmp = 128;
1251   } else {
1252     MaxLoadsPerMemcmp = 8;
1253     MaxLoadsPerMemcmpOptSize = 4;
1254   }
1255 }
1256 
1257 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1258 /// the desired ByVal argument alignment.
1259 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1260                              unsigned MaxMaxAlign) {
1261   if (MaxAlign == MaxMaxAlign)
1262     return;
1263   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1264     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1265       MaxAlign = 32;
1266     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1267       MaxAlign = 16;
1268   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1269     unsigned EltAlign = 0;
1270     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1271     if (EltAlign > MaxAlign)
1272       MaxAlign = EltAlign;
1273   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1274     for (auto *EltTy : STy->elements()) {
1275       unsigned EltAlign = 0;
1276       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1277       if (EltAlign > MaxAlign)
1278         MaxAlign = EltAlign;
1279       if (MaxAlign == MaxMaxAlign)
1280         break;
1281     }
1282   }
1283 }
1284 
1285 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1286 /// function arguments in the caller parameter area.
1287 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1288                                                   const DataLayout &DL) const {
1289   // Darwin passes everything on 4 byte boundary.
1290   if (Subtarget.isDarwin())
1291     return 4;
1292 
1293   // 16byte and wider vectors are passed on 16byte boundary.
1294   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1295   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1296   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1297     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1298   return Align;
1299 }
1300 
1301 bool PPCTargetLowering::useSoftFloat() const {
1302   return Subtarget.useSoftFloat();
1303 }
1304 
1305 bool PPCTargetLowering::hasSPE() const {
1306   return Subtarget.hasSPE();
1307 }
1308 
1309 bool PPCTargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
1310   return VT.isScalarInteger();
1311 }
1312 
1313 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1314   switch ((PPCISD::NodeType)Opcode) {
1315   case PPCISD::FIRST_NUMBER:    break;
1316   case PPCISD::FSEL:            return "PPCISD::FSEL";
1317   case PPCISD::XSMAXCDP:        return "PPCISD::XSMAXCDP";
1318   case PPCISD::XSMINCDP:        return "PPCISD::XSMINCDP";
1319   case PPCISD::FCFID:           return "PPCISD::FCFID";
1320   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1321   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1322   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1323   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1324   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1325   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1326   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1327   case PPCISD::FP_TO_UINT_IN_VSR:
1328                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1329   case PPCISD::FP_TO_SINT_IN_VSR:
1330                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1331   case PPCISD::FRE:             return "PPCISD::FRE";
1332   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1333   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1334   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1335   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1336   case PPCISD::VPERM:           return "PPCISD::VPERM";
1337   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1338   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1339   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1340   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1341   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1342   case PPCISD::CMPB:            return "PPCISD::CMPB";
1343   case PPCISD::Hi:              return "PPCISD::Hi";
1344   case PPCISD::Lo:              return "PPCISD::Lo";
1345   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1346   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1347   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1348   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1349   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1350   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1351   case PPCISD::SRL:             return "PPCISD::SRL";
1352   case PPCISD::SRA:             return "PPCISD::SRA";
1353   case PPCISD::SHL:             return "PPCISD::SHL";
1354   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1355   case PPCISD::CALL:            return "PPCISD::CALL";
1356   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1357   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1358   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1359   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1360   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1361   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1362   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1363   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1364   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1365   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1366   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1367   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1368   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1369   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1370   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1371   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1372   case PPCISD::VCMP:            return "PPCISD::VCMP";
1373   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1374   case PPCISD::LBRX:            return "PPCISD::LBRX";
1375   case PPCISD::STBRX:           return "PPCISD::STBRX";
1376   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1377   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1378   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1379   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1380   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1381   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1382   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1383   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1384   case PPCISD::LOAD_VEC_BE:     return "PPCISD::LOAD_VEC_BE";
1385   case PPCISD::STORE_VEC_BE:    return "PPCISD::STORE_VEC_BE";
1386   case PPCISD::ST_VSR_SCAL_INT:
1387                                 return "PPCISD::ST_VSR_SCAL_INT";
1388   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1389   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1390   case PPCISD::BDZ:             return "PPCISD::BDZ";
1391   case PPCISD::MFFS:            return "PPCISD::MFFS";
1392   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1393   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1394   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1395   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1396   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1397   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1398   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1399   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1400   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1401   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1402   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1403   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1404   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1405   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1406   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1407   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1408   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1409   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1410   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1411   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1412   case PPCISD::SC:              return "PPCISD::SC";
1413   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1414   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1415   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1416   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1417   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1418   case PPCISD::VABSD:           return "PPCISD::VABSD";
1419   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1420   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1421   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1422   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1423   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1424   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1425   case PPCISD::BUILD_FP128:     return "PPCISD::BUILD_FP128";
1426   case PPCISD::BUILD_SPE64:     return "PPCISD::BUILD_SPE64";
1427   case PPCISD::EXTRACT_SPE:     return "PPCISD::EXTRACT_SPE";
1428   case PPCISD::EXTSWSLI:        return "PPCISD::EXTSWSLI";
1429   case PPCISD::LD_VSX_LH:       return "PPCISD::LD_VSX_LH";
1430   case PPCISD::FP_EXTEND_HALF:  return "PPCISD::FP_EXTEND_HALF";
1431   case PPCISD::LD_SPLAT:        return "PPCISD::LD_SPLAT";
1432   }
1433   return nullptr;
1434 }
1435 
1436 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1437                                           EVT VT) const {
1438   if (!VT.isVector())
1439     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1440 
1441   if (Subtarget.hasQPX())
1442     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1443 
1444   return VT.changeVectorElementTypeToInteger();
1445 }
1446 
1447 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1448   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1449   return true;
1450 }
1451 
1452 //===----------------------------------------------------------------------===//
1453 // Node matching predicates, for use by the tblgen matching code.
1454 //===----------------------------------------------------------------------===//
1455 
1456 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1457 static bool isFloatingPointZero(SDValue Op) {
1458   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1459     return CFP->getValueAPF().isZero();
1460   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1461     // Maybe this has already been legalized into the constant pool?
1462     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1463       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1464         return CFP->getValueAPF().isZero();
1465   }
1466   return false;
1467 }
1468 
1469 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1470 /// true if Op is undef or if it matches the specified value.
1471 static bool isConstantOrUndef(int Op, int Val) {
1472   return Op < 0 || Op == Val;
1473 }
1474 
1475 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1476 /// VPKUHUM instruction.
1477 /// The ShuffleKind distinguishes between big-endian operations with
1478 /// two different inputs (0), either-endian operations with two identical
1479 /// inputs (1), and little-endian operations with two different inputs (2).
1480 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1481 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1482                                SelectionDAG &DAG) {
1483   bool IsLE = DAG.getDataLayout().isLittleEndian();
1484   if (ShuffleKind == 0) {
1485     if (IsLE)
1486       return false;
1487     for (unsigned i = 0; i != 16; ++i)
1488       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1489         return false;
1490   } else if (ShuffleKind == 2) {
1491     if (!IsLE)
1492       return false;
1493     for (unsigned i = 0; i != 16; ++i)
1494       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1495         return false;
1496   } else if (ShuffleKind == 1) {
1497     unsigned j = IsLE ? 0 : 1;
1498     for (unsigned i = 0; i != 8; ++i)
1499       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1500           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1501         return false;
1502   }
1503   return true;
1504 }
1505 
1506 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1507 /// VPKUWUM instruction.
1508 /// The ShuffleKind distinguishes between big-endian operations with
1509 /// two different inputs (0), either-endian operations with two identical
1510 /// inputs (1), and little-endian operations with two different inputs (2).
1511 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1512 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1513                                SelectionDAG &DAG) {
1514   bool IsLE = DAG.getDataLayout().isLittleEndian();
1515   if (ShuffleKind == 0) {
1516     if (IsLE)
1517       return false;
1518     for (unsigned i = 0; i != 16; i += 2)
1519       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1520           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1521         return false;
1522   } else if (ShuffleKind == 2) {
1523     if (!IsLE)
1524       return false;
1525     for (unsigned i = 0; i != 16; i += 2)
1526       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1527           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1528         return false;
1529   } else if (ShuffleKind == 1) {
1530     unsigned j = IsLE ? 0 : 2;
1531     for (unsigned i = 0; i != 8; i += 2)
1532       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1533           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1534           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1535           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1536         return false;
1537   }
1538   return true;
1539 }
1540 
1541 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1542 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1543 /// current subtarget.
1544 ///
1545 /// The ShuffleKind distinguishes between big-endian operations with
1546 /// two different inputs (0), either-endian operations with two identical
1547 /// inputs (1), and little-endian operations with two different inputs (2).
1548 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1549 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1550                                SelectionDAG &DAG) {
1551   const PPCSubtarget& Subtarget =
1552       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1553   if (!Subtarget.hasP8Vector())
1554     return false;
1555 
1556   bool IsLE = DAG.getDataLayout().isLittleEndian();
1557   if (ShuffleKind == 0) {
1558     if (IsLE)
1559       return false;
1560     for (unsigned i = 0; i != 16; i += 4)
1561       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1562           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1563           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1564           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1565         return false;
1566   } else if (ShuffleKind == 2) {
1567     if (!IsLE)
1568       return false;
1569     for (unsigned i = 0; i != 16; i += 4)
1570       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1571           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1572           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1573           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1574         return false;
1575   } else if (ShuffleKind == 1) {
1576     unsigned j = IsLE ? 0 : 4;
1577     for (unsigned i = 0; i != 8; i += 4)
1578       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1579           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1580           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1581           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1582           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1583           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1584           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1585           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1586         return false;
1587   }
1588   return true;
1589 }
1590 
1591 /// isVMerge - Common function, used to match vmrg* shuffles.
1592 ///
1593 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1594                      unsigned LHSStart, unsigned RHSStart) {
1595   if (N->getValueType(0) != MVT::v16i8)
1596     return false;
1597   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1598          "Unsupported merge size!");
1599 
1600   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1601     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1602       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1603                              LHSStart+j+i*UnitSize) ||
1604           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1605                              RHSStart+j+i*UnitSize))
1606         return false;
1607     }
1608   return true;
1609 }
1610 
1611 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1612 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1613 /// The ShuffleKind distinguishes between big-endian merges with two
1614 /// different inputs (0), either-endian merges with two identical inputs (1),
1615 /// and little-endian merges with two different inputs (2).  For the latter,
1616 /// the input operands are swapped (see PPCInstrAltivec.td).
1617 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1618                              unsigned ShuffleKind, SelectionDAG &DAG) {
1619   if (DAG.getDataLayout().isLittleEndian()) {
1620     if (ShuffleKind == 1) // unary
1621       return isVMerge(N, UnitSize, 0, 0);
1622     else if (ShuffleKind == 2) // swapped
1623       return isVMerge(N, UnitSize, 0, 16);
1624     else
1625       return false;
1626   } else {
1627     if (ShuffleKind == 1) // unary
1628       return isVMerge(N, UnitSize, 8, 8);
1629     else if (ShuffleKind == 0) // normal
1630       return isVMerge(N, UnitSize, 8, 24);
1631     else
1632       return false;
1633   }
1634 }
1635 
1636 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1637 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1638 /// The ShuffleKind distinguishes between big-endian merges with two
1639 /// different inputs (0), either-endian merges with two identical inputs (1),
1640 /// and little-endian merges with two different inputs (2).  For the latter,
1641 /// the input operands are swapped (see PPCInstrAltivec.td).
1642 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1643                              unsigned ShuffleKind, SelectionDAG &DAG) {
1644   if (DAG.getDataLayout().isLittleEndian()) {
1645     if (ShuffleKind == 1) // unary
1646       return isVMerge(N, UnitSize, 8, 8);
1647     else if (ShuffleKind == 2) // swapped
1648       return isVMerge(N, UnitSize, 8, 24);
1649     else
1650       return false;
1651   } else {
1652     if (ShuffleKind == 1) // unary
1653       return isVMerge(N, UnitSize, 0, 0);
1654     else if (ShuffleKind == 0) // normal
1655       return isVMerge(N, UnitSize, 0, 16);
1656     else
1657       return false;
1658   }
1659 }
1660 
1661 /**
1662  * Common function used to match vmrgew and vmrgow shuffles
1663  *
1664  * The indexOffset determines whether to look for even or odd words in
1665  * the shuffle mask. This is based on the of the endianness of the target
1666  * machine.
1667  *   - Little Endian:
1668  *     - Use offset of 0 to check for odd elements
1669  *     - Use offset of 4 to check for even elements
1670  *   - Big Endian:
1671  *     - Use offset of 0 to check for even elements
1672  *     - Use offset of 4 to check for odd elements
1673  * A detailed description of the vector element ordering for little endian and
1674  * big endian can be found at
1675  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1676  * Targeting your applications - what little endian and big endian IBM XL C/C++
1677  * compiler differences mean to you
1678  *
1679  * The mask to the shuffle vector instruction specifies the indices of the
1680  * elements from the two input vectors to place in the result. The elements are
1681  * numbered in array-access order, starting with the first vector. These vectors
1682  * are always of type v16i8, thus each vector will contain 16 elements of size
1683  * 8. More info on the shuffle vector can be found in the
1684  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1685  * Language Reference.
1686  *
1687  * The RHSStartValue indicates whether the same input vectors are used (unary)
1688  * or two different input vectors are used, based on the following:
1689  *   - If the instruction uses the same vector for both inputs, the range of the
1690  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1691  *     be 0.
1692  *   - If the instruction has two different vectors then the range of the
1693  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1694  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1695  *     to 31 specify elements in the second vector).
1696  *
1697  * \param[in] N The shuffle vector SD Node to analyze
1698  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1699  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1700  * vector to the shuffle_vector instruction
1701  * \return true iff this shuffle vector represents an even or odd word merge
1702  */
1703 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1704                      unsigned RHSStartValue) {
1705   if (N->getValueType(0) != MVT::v16i8)
1706     return false;
1707 
1708   for (unsigned i = 0; i < 2; ++i)
1709     for (unsigned j = 0; j < 4; ++j)
1710       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1711                              i*RHSStartValue+j+IndexOffset) ||
1712           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1713                              i*RHSStartValue+j+IndexOffset+8))
1714         return false;
1715   return true;
1716 }
1717 
1718 /**
1719  * Determine if the specified shuffle mask is suitable for the vmrgew or
1720  * vmrgow instructions.
1721  *
1722  * \param[in] N The shuffle vector SD Node to analyze
1723  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1724  * \param[in] ShuffleKind Identify the type of merge:
1725  *   - 0 = big-endian merge with two different inputs;
1726  *   - 1 = either-endian merge with two identical inputs;
1727  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1728  *     little-endian merges).
1729  * \param[in] DAG The current SelectionDAG
1730  * \return true iff this shuffle mask
1731  */
1732 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1733                               unsigned ShuffleKind, SelectionDAG &DAG) {
1734   if (DAG.getDataLayout().isLittleEndian()) {
1735     unsigned indexOffset = CheckEven ? 4 : 0;
1736     if (ShuffleKind == 1) // Unary
1737       return isVMerge(N, indexOffset, 0);
1738     else if (ShuffleKind == 2) // swapped
1739       return isVMerge(N, indexOffset, 16);
1740     else
1741       return false;
1742   }
1743   else {
1744     unsigned indexOffset = CheckEven ? 0 : 4;
1745     if (ShuffleKind == 1) // Unary
1746       return isVMerge(N, indexOffset, 0);
1747     else if (ShuffleKind == 0) // Normal
1748       return isVMerge(N, indexOffset, 16);
1749     else
1750       return false;
1751   }
1752   return false;
1753 }
1754 
1755 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1756 /// amount, otherwise return -1.
1757 /// The ShuffleKind distinguishes between big-endian operations with two
1758 /// different inputs (0), either-endian operations with two identical inputs
1759 /// (1), and little-endian operations with two different inputs (2).  For the
1760 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1761 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1762                              SelectionDAG &DAG) {
1763   if (N->getValueType(0) != MVT::v16i8)
1764     return -1;
1765 
1766   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1767 
1768   // Find the first non-undef value in the shuffle mask.
1769   unsigned i;
1770   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1771     /*search*/;
1772 
1773   if (i == 16) return -1;  // all undef.
1774 
1775   // Otherwise, check to see if the rest of the elements are consecutively
1776   // numbered from this value.
1777   unsigned ShiftAmt = SVOp->getMaskElt(i);
1778   if (ShiftAmt < i) return -1;
1779 
1780   ShiftAmt -= i;
1781   bool isLE = DAG.getDataLayout().isLittleEndian();
1782 
1783   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1784     // Check the rest of the elements to see if they are consecutive.
1785     for (++i; i != 16; ++i)
1786       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1787         return -1;
1788   } else if (ShuffleKind == 1) {
1789     // Check the rest of the elements to see if they are consecutive.
1790     for (++i; i != 16; ++i)
1791       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1792         return -1;
1793   } else
1794     return -1;
1795 
1796   if (isLE)
1797     ShiftAmt = 16 - ShiftAmt;
1798 
1799   return ShiftAmt;
1800 }
1801 
1802 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1803 /// specifies a splat of a single element that is suitable for input to
1804 /// one of the splat operations (VSPLTB/VSPLTH/VSPLTW/XXSPLTW/LXVDSX/etc.).
1805 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1806   assert(N->getValueType(0) == MVT::v16i8 && isPowerOf2_32(EltSize) &&
1807          EltSize <= 8 && "Can only handle 1,2,4,8 byte element sizes");
1808 
1809   // The consecutive indices need to specify an element, not part of two
1810   // different elements.  So abandon ship early if this isn't the case.
1811   if (N->getMaskElt(0) % EltSize != 0)
1812     return false;
1813 
1814   // This is a splat operation if each element of the permute is the same, and
1815   // if the value doesn't reference the second vector.
1816   unsigned ElementBase = N->getMaskElt(0);
1817 
1818   // FIXME: Handle UNDEF elements too!
1819   if (ElementBase >= 16)
1820     return false;
1821 
1822   // Check that the indices are consecutive, in the case of a multi-byte element
1823   // splatted with a v16i8 mask.
1824   for (unsigned i = 1; i != EltSize; ++i)
1825     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1826       return false;
1827 
1828   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1829     if (N->getMaskElt(i) < 0) continue;
1830     for (unsigned j = 0; j != EltSize; ++j)
1831       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1832         return false;
1833   }
1834   return true;
1835 }
1836 
1837 /// Check that the mask is shuffling N byte elements. Within each N byte
1838 /// element of the mask, the indices could be either in increasing or
1839 /// decreasing order as long as they are consecutive.
1840 /// \param[in] N the shuffle vector SD Node to analyze
1841 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1842 /// Word/DoubleWord/QuadWord).
1843 /// \param[in] StepLen the delta indices number among the N byte element, if
1844 /// the mask is in increasing/decreasing order then it is 1/-1.
1845 /// \return true iff the mask is shuffling N byte elements.
1846 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1847                                    int StepLen) {
1848   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1849          "Unexpected element width.");
1850   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1851 
1852   unsigned NumOfElem = 16 / Width;
1853   unsigned MaskVal[16]; //  Width is never greater than 16
1854   for (unsigned i = 0; i < NumOfElem; ++i) {
1855     MaskVal[0] = N->getMaskElt(i * Width);
1856     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1857       return false;
1858     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1859       return false;
1860     }
1861 
1862     for (unsigned int j = 1; j < Width; ++j) {
1863       MaskVal[j] = N->getMaskElt(i * Width + j);
1864       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1865         return false;
1866       }
1867     }
1868   }
1869 
1870   return true;
1871 }
1872 
1873 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1874                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1875   if (!isNByteElemShuffleMask(N, 4, 1))
1876     return false;
1877 
1878   // Now we look at mask elements 0,4,8,12
1879   unsigned M0 = N->getMaskElt(0) / 4;
1880   unsigned M1 = N->getMaskElt(4) / 4;
1881   unsigned M2 = N->getMaskElt(8) / 4;
1882   unsigned M3 = N->getMaskElt(12) / 4;
1883   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1884   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1885 
1886   // Below, let H and L be arbitrary elements of the shuffle mask
1887   // where H is in the range [4,7] and L is in the range [0,3].
1888   // H, 1, 2, 3 or L, 5, 6, 7
1889   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1890       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1891     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1892     InsertAtByte = IsLE ? 12 : 0;
1893     Swap = M0 < 4;
1894     return true;
1895   }
1896   // 0, H, 2, 3 or 4, L, 6, 7
1897   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1898       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1899     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1900     InsertAtByte = IsLE ? 8 : 4;
1901     Swap = M1 < 4;
1902     return true;
1903   }
1904   // 0, 1, H, 3 or 4, 5, L, 7
1905   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1906       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1907     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1908     InsertAtByte = IsLE ? 4 : 8;
1909     Swap = M2 < 4;
1910     return true;
1911   }
1912   // 0, 1, 2, H or 4, 5, 6, L
1913   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1914       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1915     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1916     InsertAtByte = IsLE ? 0 : 12;
1917     Swap = M3 < 4;
1918     return true;
1919   }
1920 
1921   // If both vector operands for the shuffle are the same vector, the mask will
1922   // contain only elements from the first one and the second one will be undef.
1923   if (N->getOperand(1).isUndef()) {
1924     ShiftElts = 0;
1925     Swap = true;
1926     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1927     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1928       InsertAtByte = IsLE ? 12 : 0;
1929       return true;
1930     }
1931     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1932       InsertAtByte = IsLE ? 8 : 4;
1933       return true;
1934     }
1935     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1936       InsertAtByte = IsLE ? 4 : 8;
1937       return true;
1938     }
1939     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1940       InsertAtByte = IsLE ? 0 : 12;
1941       return true;
1942     }
1943   }
1944 
1945   return false;
1946 }
1947 
1948 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1949                                bool &Swap, bool IsLE) {
1950   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1951   // Ensure each byte index of the word is consecutive.
1952   if (!isNByteElemShuffleMask(N, 4, 1))
1953     return false;
1954 
1955   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1956   unsigned M0 = N->getMaskElt(0) / 4;
1957   unsigned M1 = N->getMaskElt(4) / 4;
1958   unsigned M2 = N->getMaskElt(8) / 4;
1959   unsigned M3 = N->getMaskElt(12) / 4;
1960 
1961   // If both vector operands for the shuffle are the same vector, the mask will
1962   // contain only elements from the first one and the second one will be undef.
1963   if (N->getOperand(1).isUndef()) {
1964     assert(M0 < 4 && "Indexing into an undef vector?");
1965     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1966       return false;
1967 
1968     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1969     Swap = false;
1970     return true;
1971   }
1972 
1973   // Ensure each word index of the ShuffleVector Mask is consecutive.
1974   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1975     return false;
1976 
1977   if (IsLE) {
1978     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1979       // Input vectors don't need to be swapped if the leading element
1980       // of the result is one of the 3 left elements of the second vector
1981       // (or if there is no shift to be done at all).
1982       Swap = false;
1983       ShiftElts = (8 - M0) % 8;
1984     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1985       // Input vectors need to be swapped if the leading element
1986       // of the result is one of the 3 left elements of the first vector
1987       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1988       Swap = true;
1989       ShiftElts = (4 - M0) % 4;
1990     }
1991 
1992     return true;
1993   } else {                                          // BE
1994     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1995       // Input vectors don't need to be swapped if the leading element
1996       // of the result is one of the 4 elements of the first vector.
1997       Swap = false;
1998       ShiftElts = M0;
1999     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
2000       // Input vectors need to be swapped if the leading element
2001       // of the result is one of the 4 elements of the right vector.
2002       Swap = true;
2003       ShiftElts = M0 - 4;
2004     }
2005 
2006     return true;
2007   }
2008 }
2009 
2010 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
2011   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2012 
2013   if (!isNByteElemShuffleMask(N, Width, -1))
2014     return false;
2015 
2016   for (int i = 0; i < 16; i += Width)
2017     if (N->getMaskElt(i) != i + Width - 1)
2018       return false;
2019 
2020   return true;
2021 }
2022 
2023 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
2024   return isXXBRShuffleMaskHelper(N, 2);
2025 }
2026 
2027 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
2028   return isXXBRShuffleMaskHelper(N, 4);
2029 }
2030 
2031 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
2032   return isXXBRShuffleMaskHelper(N, 8);
2033 }
2034 
2035 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
2036   return isXXBRShuffleMaskHelper(N, 16);
2037 }
2038 
2039 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
2040 /// if the inputs to the instruction should be swapped and set \p DM to the
2041 /// value for the immediate.
2042 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
2043 /// AND element 0 of the result comes from the first input (LE) or second input
2044 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
2045 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
2046 /// mask.
2047 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
2048                                bool &Swap, bool IsLE) {
2049   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
2050 
2051   // Ensure each byte index of the double word is consecutive.
2052   if (!isNByteElemShuffleMask(N, 8, 1))
2053     return false;
2054 
2055   unsigned M0 = N->getMaskElt(0) / 8;
2056   unsigned M1 = N->getMaskElt(8) / 8;
2057   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
2058 
2059   // If both vector operands for the shuffle are the same vector, the mask will
2060   // contain only elements from the first one and the second one will be undef.
2061   if (N->getOperand(1).isUndef()) {
2062     if ((M0 | M1) < 2) {
2063       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
2064       Swap = false;
2065       return true;
2066     } else
2067       return false;
2068   }
2069 
2070   if (IsLE) {
2071     if (M0 > 1 && M1 < 2) {
2072       Swap = false;
2073     } else if (M0 < 2 && M1 > 1) {
2074       M0 = (M0 + 2) % 4;
2075       M1 = (M1 + 2) % 4;
2076       Swap = true;
2077     } else
2078       return false;
2079 
2080     // Note: if control flow comes here that means Swap is already set above
2081     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
2082     return true;
2083   } else { // BE
2084     if (M0 < 2 && M1 > 1) {
2085       Swap = false;
2086     } else if (M0 > 1 && M1 < 2) {
2087       M0 = (M0 + 2) % 4;
2088       M1 = (M1 + 2) % 4;
2089       Swap = true;
2090     } else
2091       return false;
2092 
2093     // Note: if control flow comes here that means Swap is already set above
2094     DM = (M0 << 1) + (M1 & 1);
2095     return true;
2096   }
2097 }
2098 
2099 
2100 /// getSplatIdxForPPCMnemonics - Return the splat index as a value that is
2101 /// appropriate for PPC mnemonics (which have a big endian bias - namely
2102 /// elements are counted from the left of the vector register).
2103 unsigned PPC::getSplatIdxForPPCMnemonics(SDNode *N, unsigned EltSize,
2104                                          SelectionDAG &DAG) {
2105   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2106   assert(isSplatShuffleMask(SVOp, EltSize));
2107   if (DAG.getDataLayout().isLittleEndian())
2108     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
2109   else
2110     return SVOp->getMaskElt(0) / EltSize;
2111 }
2112 
2113 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
2114 /// by using a vspltis[bhw] instruction of the specified element size, return
2115 /// the constant being splatted.  The ByteSize field indicates the number of
2116 /// bytes of each element [124] -> [bhw].
2117 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
2118   SDValue OpVal(nullptr, 0);
2119 
2120   // If ByteSize of the splat is bigger than the element size of the
2121   // build_vector, then we have a case where we are checking for a splat where
2122   // multiple elements of the buildvector are folded together into a single
2123   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
2124   unsigned EltSize = 16/N->getNumOperands();
2125   if (EltSize < ByteSize) {
2126     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
2127     SDValue UniquedVals[4];
2128     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
2129 
2130     // See if all of the elements in the buildvector agree across.
2131     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2132       if (N->getOperand(i).isUndef()) continue;
2133       // If the element isn't a constant, bail fully out.
2134       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
2135 
2136       if (!UniquedVals[i&(Multiple-1)].getNode())
2137         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
2138       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
2139         return SDValue();  // no match.
2140     }
2141 
2142     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
2143     // either constant or undef values that are identical for each chunk.  See
2144     // if these chunks can form into a larger vspltis*.
2145 
2146     // Check to see if all of the leading entries are either 0 or -1.  If
2147     // neither, then this won't fit into the immediate field.
2148     bool LeadingZero = true;
2149     bool LeadingOnes = true;
2150     for (unsigned i = 0; i != Multiple-1; ++i) {
2151       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
2152 
2153       LeadingZero &= isNullConstant(UniquedVals[i]);
2154       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
2155     }
2156     // Finally, check the least significant entry.
2157     if (LeadingZero) {
2158       if (!UniquedVals[Multiple-1].getNode())
2159         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
2160       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
2161       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
2162         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2163     }
2164     if (LeadingOnes) {
2165       if (!UniquedVals[Multiple-1].getNode())
2166         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
2167       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2168       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2169         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2170     }
2171 
2172     return SDValue();
2173   }
2174 
2175   // Check to see if this buildvec has a single non-undef value in its elements.
2176   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2177     if (N->getOperand(i).isUndef()) continue;
2178     if (!OpVal.getNode())
2179       OpVal = N->getOperand(i);
2180     else if (OpVal != N->getOperand(i))
2181       return SDValue();
2182   }
2183 
2184   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2185 
2186   unsigned ValSizeInBytes = EltSize;
2187   uint64_t Value = 0;
2188   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2189     Value = CN->getZExtValue();
2190   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2191     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2192     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2193   }
2194 
2195   // If the splat value is larger than the element value, then we can never do
2196   // this splat.  The only case that we could fit the replicated bits into our
2197   // immediate field for would be zero, and we prefer to use vxor for it.
2198   if (ValSizeInBytes < ByteSize) return SDValue();
2199 
2200   // If the element value is larger than the splat value, check if it consists
2201   // of a repeated bit pattern of size ByteSize.
2202   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2203     return SDValue();
2204 
2205   // Properly sign extend the value.
2206   int MaskVal = SignExtend32(Value, ByteSize * 8);
2207 
2208   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2209   if (MaskVal == 0) return SDValue();
2210 
2211   // Finally, if this value fits in a 5 bit sext field, return it
2212   if (SignExtend32<5>(MaskVal) == MaskVal)
2213     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2214   return SDValue();
2215 }
2216 
2217 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2218 /// amount, otherwise return -1.
2219 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2220   EVT VT = N->getValueType(0);
2221   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2222     return -1;
2223 
2224   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2225 
2226   // Find the first non-undef value in the shuffle mask.
2227   unsigned i;
2228   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2229     /*search*/;
2230 
2231   if (i == 4) return -1;  // all undef.
2232 
2233   // Otherwise, check to see if the rest of the elements are consecutively
2234   // numbered from this value.
2235   unsigned ShiftAmt = SVOp->getMaskElt(i);
2236   if (ShiftAmt < i) return -1;
2237   ShiftAmt -= i;
2238 
2239   // Check the rest of the elements to see if they are consecutive.
2240   for (++i; i != 4; ++i)
2241     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2242       return -1;
2243 
2244   return ShiftAmt;
2245 }
2246 
2247 //===----------------------------------------------------------------------===//
2248 //  Addressing Mode Selection
2249 //===----------------------------------------------------------------------===//
2250 
2251 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2252 /// or 64-bit immediate, and if the value can be accurately represented as a
2253 /// sign extension from a 16-bit value.  If so, this returns true and the
2254 /// immediate.
2255 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2256   if (!isa<ConstantSDNode>(N))
2257     return false;
2258 
2259   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2260   if (N->getValueType(0) == MVT::i32)
2261     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2262   else
2263     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2264 }
2265 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2266   return isIntS16Immediate(Op.getNode(), Imm);
2267 }
2268 
2269 
2270 /// SelectAddressEVXRegReg - Given the specified address, check to see if it can
2271 /// be represented as an indexed [r+r] operation.
2272 bool PPCTargetLowering::SelectAddressEVXRegReg(SDValue N, SDValue &Base,
2273                                                SDValue &Index,
2274                                                SelectionDAG &DAG) const {
2275   for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
2276       UI != E; ++UI) {
2277     if (MemSDNode *Memop = dyn_cast<MemSDNode>(*UI)) {
2278       if (Memop->getMemoryVT() == MVT::f64) {
2279           Base = N.getOperand(0);
2280           Index = N.getOperand(1);
2281           return true;
2282       }
2283     }
2284   }
2285   return false;
2286 }
2287 
2288 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2289 /// can be represented as an indexed [r+r] operation.  Returns false if it
2290 /// can be more efficiently represented as [r+imm]. If \p EncodingAlignment is
2291 /// non-zero and N can be represented by a base register plus a signed 16-bit
2292 /// displacement, make a more precise judgement by checking (displacement % \p
2293 /// EncodingAlignment).
2294 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2295                                             SDValue &Index, SelectionDAG &DAG,
2296                                             unsigned EncodingAlignment) const {
2297   int16_t imm = 0;
2298   if (N.getOpcode() == ISD::ADD) {
2299     // Is there any SPE load/store (f64), which can't handle 16bit offset?
2300     // SPE load/store can only handle 8-bit offsets.
2301     if (hasSPE() && SelectAddressEVXRegReg(N, Base, Index, DAG))
2302         return true;
2303     if (isIntS16Immediate(N.getOperand(1), imm) &&
2304         (!EncodingAlignment || !(imm % EncodingAlignment)))
2305       return false; // r+i
2306     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2307       return false;    // r+i
2308 
2309     Base = N.getOperand(0);
2310     Index = N.getOperand(1);
2311     return true;
2312   } else if (N.getOpcode() == ISD::OR) {
2313     if (isIntS16Immediate(N.getOperand(1), imm) &&
2314         (!EncodingAlignment || !(imm % EncodingAlignment)))
2315       return false; // r+i can fold it if we can.
2316 
2317     // If this is an or of disjoint bitfields, we can codegen this as an add
2318     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2319     // disjoint.
2320     KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2321 
2322     if (LHSKnown.Zero.getBoolValue()) {
2323       KnownBits RHSKnown = DAG.computeKnownBits(N.getOperand(1));
2324       // If all of the bits are known zero on the LHS or RHS, the add won't
2325       // carry.
2326       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2327         Base = N.getOperand(0);
2328         Index = N.getOperand(1);
2329         return true;
2330       }
2331     }
2332   }
2333 
2334   return false;
2335 }
2336 
2337 // If we happen to be doing an i64 load or store into a stack slot that has
2338 // less than a 4-byte alignment, then the frame-index elimination may need to
2339 // use an indexed load or store instruction (because the offset may not be a
2340 // multiple of 4). The extra register needed to hold the offset comes from the
2341 // register scavenger, and it is possible that the scavenger will need to use
2342 // an emergency spill slot. As a result, we need to make sure that a spill slot
2343 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2344 // stack slot.
2345 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2346   // FIXME: This does not handle the LWA case.
2347   if (VT != MVT::i64)
2348     return;
2349 
2350   // NOTE: We'll exclude negative FIs here, which come from argument
2351   // lowering, because there are no known test cases triggering this problem
2352   // using packed structures (or similar). We can remove this exclusion if
2353   // we find such a test case. The reason why this is so test-case driven is
2354   // because this entire 'fixup' is only to prevent crashes (from the
2355   // register scavenger) on not-really-valid inputs. For example, if we have:
2356   //   %a = alloca i1
2357   //   %b = bitcast i1* %a to i64*
2358   //   store i64* a, i64 b
2359   // then the store should really be marked as 'align 1', but is not. If it
2360   // were marked as 'align 1' then the indexed form would have been
2361   // instruction-selected initially, and the problem this 'fixup' is preventing
2362   // won't happen regardless.
2363   if (FrameIdx < 0)
2364     return;
2365 
2366   MachineFunction &MF = DAG.getMachineFunction();
2367   MachineFrameInfo &MFI = MF.getFrameInfo();
2368 
2369   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2370   if (Align >= 4)
2371     return;
2372 
2373   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2374   FuncInfo->setHasNonRISpills();
2375 }
2376 
2377 /// Returns true if the address N can be represented by a base register plus
2378 /// a signed 16-bit displacement [r+imm], and if it is not better
2379 /// represented as reg+reg.  If \p EncodingAlignment is non-zero, only accept
2380 /// displacements that are multiples of that value.
2381 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2382                                             SDValue &Base,
2383                                             SelectionDAG &DAG,
2384                                             unsigned EncodingAlignment) const {
2385   // FIXME dl should come from parent load or store, not from address
2386   SDLoc dl(N);
2387   // If this can be more profitably realized as r+r, fail.
2388   if (SelectAddressRegReg(N, Disp, Base, DAG, EncodingAlignment))
2389     return false;
2390 
2391   if (N.getOpcode() == ISD::ADD) {
2392     int16_t imm = 0;
2393     if (isIntS16Immediate(N.getOperand(1), imm) &&
2394         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2395       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2396       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2397         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2398         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2399       } else {
2400         Base = N.getOperand(0);
2401       }
2402       return true; // [r+i]
2403     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2404       // Match LOAD (ADD (X, Lo(G))).
2405       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2406              && "Cannot handle constant offsets yet!");
2407       Disp = N.getOperand(1).getOperand(0);  // The global address.
2408       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2409              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2410              Disp.getOpcode() == ISD::TargetConstantPool ||
2411              Disp.getOpcode() == ISD::TargetJumpTable);
2412       Base = N.getOperand(0);
2413       return true;  // [&g+r]
2414     }
2415   } else if (N.getOpcode() == ISD::OR) {
2416     int16_t imm = 0;
2417     if (isIntS16Immediate(N.getOperand(1), imm) &&
2418         (!EncodingAlignment || (imm % EncodingAlignment) == 0)) {
2419       // If this is an or of disjoint bitfields, we can codegen this as an add
2420       // (for better address arithmetic) if the LHS and RHS of the OR are
2421       // provably disjoint.
2422       KnownBits LHSKnown = DAG.computeKnownBits(N.getOperand(0));
2423 
2424       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2425         // If all of the bits are known zero on the LHS or RHS, the add won't
2426         // carry.
2427         if (FrameIndexSDNode *FI =
2428               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2429           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2430           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2431         } else {
2432           Base = N.getOperand(0);
2433         }
2434         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2435         return true;
2436       }
2437     }
2438   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2439     // Loading from a constant address.
2440 
2441     // If this address fits entirely in a 16-bit sext immediate field, codegen
2442     // this as "d, 0"
2443     int16_t Imm;
2444     if (isIntS16Immediate(CN, Imm) &&
2445         (!EncodingAlignment || (Imm % EncodingAlignment) == 0)) {
2446       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2447       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2448                              CN->getValueType(0));
2449       return true;
2450     }
2451 
2452     // Handle 32-bit sext immediates with LIS + addr mode.
2453     if ((CN->getValueType(0) == MVT::i32 ||
2454          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2455         (!EncodingAlignment || (CN->getZExtValue() % EncodingAlignment) == 0)) {
2456       int Addr = (int)CN->getZExtValue();
2457 
2458       // Otherwise, break this down into an LIS + disp.
2459       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2460 
2461       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2462                                    MVT::i32);
2463       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2464       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2465       return true;
2466     }
2467   }
2468 
2469   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2470   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2471     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2472     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2473   } else
2474     Base = N;
2475   return true;      // [r+0]
2476 }
2477 
2478 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2479 /// represented as an indexed [r+r] operation.
2480 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2481                                                 SDValue &Index,
2482                                                 SelectionDAG &DAG) const {
2483   // Check to see if we can easily represent this as an [r+r] address.  This
2484   // will fail if it thinks that the address is more profitably represented as
2485   // reg+imm, e.g. where imm = 0.
2486   if (SelectAddressRegReg(N, Base, Index, DAG))
2487     return true;
2488 
2489   // If the address is the result of an add, we will utilize the fact that the
2490   // address calculation includes an implicit add.  However, we can reduce
2491   // register pressure if we do not materialize a constant just for use as the
2492   // index register.  We only get rid of the add if it is not an add of a
2493   // value and a 16-bit signed constant and both have a single use.
2494   int16_t imm = 0;
2495   if (N.getOpcode() == ISD::ADD &&
2496       (!isIntS16Immediate(N.getOperand(1), imm) ||
2497        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2498     Base = N.getOperand(0);
2499     Index = N.getOperand(1);
2500     return true;
2501   }
2502 
2503   // Otherwise, do it the hard way, using R0 as the base register.
2504   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2505                          N.getValueType());
2506   Index = N;
2507   return true;
2508 }
2509 
2510 /// Returns true if we should use a direct load into vector instruction
2511 /// (such as lxsd or lfd), instead of a load into gpr + direct move sequence.
2512 static bool usePartialVectorLoads(SDNode *N, const PPCSubtarget& ST) {
2513 
2514   // If there are any other uses other than scalar to vector, then we should
2515   // keep it as a scalar load -> direct move pattern to prevent multiple
2516   // loads.
2517   LoadSDNode *LD = dyn_cast<LoadSDNode>(N);
2518   if (!LD)
2519     return false;
2520 
2521   EVT MemVT = LD->getMemoryVT();
2522   if (!MemVT.isSimple())
2523     return false;
2524   switch(MemVT.getSimpleVT().SimpleTy) {
2525   case MVT::i64:
2526     break;
2527   case MVT::i32:
2528     if (!ST.hasP8Vector())
2529       return false;
2530     break;
2531   case MVT::i16:
2532   case MVT::i8:
2533     if (!ST.hasP9Vector())
2534       return false;
2535     break;
2536   default:
2537     return false;
2538   }
2539 
2540   SDValue LoadedVal(N, 0);
2541   if (!LoadedVal.hasOneUse())
2542     return false;
2543 
2544   for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end();
2545        UI != UE; ++UI)
2546     if (UI.getUse().get().getResNo() == 0 &&
2547         UI->getOpcode() != ISD::SCALAR_TO_VECTOR)
2548       return false;
2549 
2550   return true;
2551 }
2552 
2553 /// getPreIndexedAddressParts - returns true by value, base pointer and
2554 /// offset pointer and addressing mode by reference if the node's address
2555 /// can be legally represented as pre-indexed load / store address.
2556 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2557                                                   SDValue &Offset,
2558                                                   ISD::MemIndexedMode &AM,
2559                                                   SelectionDAG &DAG) const {
2560   if (DisablePPCPreinc) return false;
2561 
2562   bool isLoad = true;
2563   SDValue Ptr;
2564   EVT VT;
2565   unsigned Alignment;
2566   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2567     Ptr = LD->getBasePtr();
2568     VT = LD->getMemoryVT();
2569     Alignment = LD->getAlignment();
2570   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2571     Ptr = ST->getBasePtr();
2572     VT  = ST->getMemoryVT();
2573     Alignment = ST->getAlignment();
2574     isLoad = false;
2575   } else
2576     return false;
2577 
2578   // Do not generate pre-inc forms for specific loads that feed scalar_to_vector
2579   // instructions because we can fold these into a more efficient instruction
2580   // instead, (such as LXSD).
2581   if (isLoad && usePartialVectorLoads(N, Subtarget)) {
2582     return false;
2583   }
2584 
2585   // PowerPC doesn't have preinc load/store instructions for vectors (except
2586   // for QPX, which does have preinc r+r forms).
2587   if (VT.isVector()) {
2588     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2589       return false;
2590     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2591       AM = ISD::PRE_INC;
2592       return true;
2593     }
2594   }
2595 
2596   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2597     // Common code will reject creating a pre-inc form if the base pointer
2598     // is a frame index, or if N is a store and the base pointer is either
2599     // the same as or a predecessor of the value being stored.  Check for
2600     // those situations here, and try with swapped Base/Offset instead.
2601     bool Swap = false;
2602 
2603     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2604       Swap = true;
2605     else if (!isLoad) {
2606       SDValue Val = cast<StoreSDNode>(N)->getValue();
2607       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2608         Swap = true;
2609     }
2610 
2611     if (Swap)
2612       std::swap(Base, Offset);
2613 
2614     AM = ISD::PRE_INC;
2615     return true;
2616   }
2617 
2618   // LDU/STU can only handle immediates that are a multiple of 4.
2619   if (VT != MVT::i64) {
2620     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2621       return false;
2622   } else {
2623     // LDU/STU need an address with at least 4-byte alignment.
2624     if (Alignment < 4)
2625       return false;
2626 
2627     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2628       return false;
2629   }
2630 
2631   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2632     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2633     // sext i32 to i64 when addr mode is r+i.
2634     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2635         LD->getExtensionType() == ISD::SEXTLOAD &&
2636         isa<ConstantSDNode>(Offset))
2637       return false;
2638   }
2639 
2640   AM = ISD::PRE_INC;
2641   return true;
2642 }
2643 
2644 //===----------------------------------------------------------------------===//
2645 //  LowerOperation implementation
2646 //===----------------------------------------------------------------------===//
2647 
2648 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2649 /// and LoOpFlags to the target MO flags.
2650 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2651                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2652                                const GlobalValue *GV = nullptr) {
2653   HiOpFlags = PPCII::MO_HA;
2654   LoOpFlags = PPCII::MO_LO;
2655 
2656   // Don't use the pic base if not in PIC relocation model.
2657   if (IsPIC) {
2658     HiOpFlags |= PPCII::MO_PIC_FLAG;
2659     LoOpFlags |= PPCII::MO_PIC_FLAG;
2660   }
2661 
2662   // If this is a reference to a global value that requires a non-lazy-ptr, make
2663   // sure that instruction lowering adds it.
2664   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2665     HiOpFlags |= PPCII::MO_NLP_FLAG;
2666     LoOpFlags |= PPCII::MO_NLP_FLAG;
2667 
2668     if (GV->hasHiddenVisibility()) {
2669       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2670       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2671     }
2672   }
2673 }
2674 
2675 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2676                              SelectionDAG &DAG) {
2677   SDLoc DL(HiPart);
2678   EVT PtrVT = HiPart.getValueType();
2679   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2680 
2681   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2682   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2683 
2684   // With PIC, the first instruction is actually "GR+hi(&G)".
2685   if (isPIC)
2686     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2687                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2688 
2689   // Generate non-pic code that has direct accesses to the constant pool.
2690   // The address of the global is just (hi(&g)+lo(&g)).
2691   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2692 }
2693 
2694 static void setUsesTOCBasePtr(MachineFunction &MF) {
2695   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2696   FuncInfo->setUsesTOCBasePtr();
2697 }
2698 
2699 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2700   setUsesTOCBasePtr(DAG.getMachineFunction());
2701 }
2702 
2703 SDValue PPCTargetLowering::getTOCEntry(SelectionDAG &DAG, const SDLoc &dl,
2704                                        SDValue GA) const {
2705   const bool Is64Bit = Subtarget.isPPC64();
2706   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2707   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT)
2708                         : Subtarget.isAIXABI()
2709                               ? DAG.getRegister(PPC::R2, VT)
2710                               : DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2711   SDValue Ops[] = { GA, Reg };
2712   return DAG.getMemIntrinsicNode(
2713       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2714       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2715       MachineMemOperand::MOLoad);
2716 }
2717 
2718 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2719                                              SelectionDAG &DAG) const {
2720   EVT PtrVT = Op.getValueType();
2721   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2722   const Constant *C = CP->getConstVal();
2723 
2724   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2725   // The actual address of the GlobalValue is stored in the TOC.
2726   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2727     setUsesTOCBasePtr(DAG);
2728     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2729     return getTOCEntry(DAG, SDLoc(CP), GA);
2730   }
2731 
2732   unsigned MOHiFlag, MOLoFlag;
2733   bool IsPIC = isPositionIndependent();
2734   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2735 
2736   if (IsPIC && Subtarget.isSVR4ABI()) {
2737     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2738                                            PPCII::MO_PIC_FLAG);
2739     return getTOCEntry(DAG, SDLoc(CP), GA);
2740   }
2741 
2742   SDValue CPIHi =
2743     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2744   SDValue CPILo =
2745     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2746   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2747 }
2748 
2749 // For 64-bit PowerPC, prefer the more compact relative encodings.
2750 // This trades 32 bits per jump table entry for one or two instructions
2751 // on the jump site.
2752 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2753   if (isJumpTableRelative())
2754     return MachineJumpTableInfo::EK_LabelDifference32;
2755 
2756   return TargetLowering::getJumpTableEncoding();
2757 }
2758 
2759 bool PPCTargetLowering::isJumpTableRelative() const {
2760   if (UseAbsoluteJumpTables)
2761     return false;
2762   if (Subtarget.isPPC64() || Subtarget.isAIXABI())
2763     return true;
2764   return TargetLowering::isJumpTableRelative();
2765 }
2766 
2767 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2768                                                     SelectionDAG &DAG) const {
2769   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2770     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2771 
2772   switch (getTargetMachine().getCodeModel()) {
2773   case CodeModel::Small:
2774   case CodeModel::Medium:
2775     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2776   default:
2777     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2778                        getPointerTy(DAG.getDataLayout()));
2779   }
2780 }
2781 
2782 const MCExpr *
2783 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2784                                                 unsigned JTI,
2785                                                 MCContext &Ctx) const {
2786   if (!Subtarget.isPPC64() || Subtarget.isAIXABI())
2787     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2788 
2789   switch (getTargetMachine().getCodeModel()) {
2790   case CodeModel::Small:
2791   case CodeModel::Medium:
2792     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2793   default:
2794     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2795   }
2796 }
2797 
2798 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2799   EVT PtrVT = Op.getValueType();
2800   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2801 
2802   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2803   // The actual address of the GlobalValue is stored in the TOC.
2804   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2805     setUsesTOCBasePtr(DAG);
2806     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2807     return getTOCEntry(DAG, SDLoc(JT), GA);
2808   }
2809 
2810   unsigned MOHiFlag, MOLoFlag;
2811   bool IsPIC = isPositionIndependent();
2812   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2813 
2814   if (IsPIC && Subtarget.isSVR4ABI()) {
2815     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2816                                         PPCII::MO_PIC_FLAG);
2817     return getTOCEntry(DAG, SDLoc(GA), GA);
2818   }
2819 
2820   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2821   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2822   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2823 }
2824 
2825 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2826                                              SelectionDAG &DAG) const {
2827   EVT PtrVT = Op.getValueType();
2828   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2829   const BlockAddress *BA = BASDN->getBlockAddress();
2830 
2831   // 64-bit SVR4 ABI and AIX ABI code are always position-independent.
2832   // The actual BlockAddress is stored in the TOC.
2833   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2834     setUsesTOCBasePtr(DAG);
2835     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2836     return getTOCEntry(DAG, SDLoc(BASDN), GA);
2837   }
2838 
2839   // 32-bit position-independent ELF stores the BlockAddress in the .got.
2840   if (Subtarget.is32BitELFABI() && isPositionIndependent())
2841     return getTOCEntry(
2842         DAG, SDLoc(BASDN),
2843         DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset()));
2844 
2845   unsigned MOHiFlag, MOLoFlag;
2846   bool IsPIC = isPositionIndependent();
2847   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2848   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2849   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2850   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2851 }
2852 
2853 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2854                                               SelectionDAG &DAG) const {
2855   // FIXME: TLS addresses currently use medium model code sequences,
2856   // which is the most useful form.  Eventually support for small and
2857   // large models could be added if users need it, at the cost of
2858   // additional complexity.
2859   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2860   if (DAG.getTarget().useEmulatedTLS())
2861     return LowerToTLSEmulatedModel(GA, DAG);
2862 
2863   SDLoc dl(GA);
2864   const GlobalValue *GV = GA->getGlobal();
2865   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2866   bool is64bit = Subtarget.isPPC64();
2867   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2868   PICLevel::Level picLevel = M->getPICLevel();
2869 
2870   const TargetMachine &TM = getTargetMachine();
2871   TLSModel::Model Model = TM.getTLSModel(GV);
2872 
2873   if (Model == TLSModel::LocalExec) {
2874     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2875                                                PPCII::MO_TPREL_HA);
2876     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2877                                                PPCII::MO_TPREL_LO);
2878     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2879                              : DAG.getRegister(PPC::R2, MVT::i32);
2880 
2881     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2882     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2883   }
2884 
2885   if (Model == TLSModel::InitialExec) {
2886     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2887     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2888                                                 PPCII::MO_TLS);
2889     SDValue GOTPtr;
2890     if (is64bit) {
2891       setUsesTOCBasePtr(DAG);
2892       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2893       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2894                            PtrVT, GOTReg, TGA);
2895     } else {
2896       if (!TM.isPositionIndependent())
2897         GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2898       else if (picLevel == PICLevel::SmallPIC)
2899         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2900       else
2901         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2902     }
2903     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2904                                    PtrVT, TGA, GOTPtr);
2905     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2906   }
2907 
2908   if (Model == TLSModel::GeneralDynamic) {
2909     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2910     SDValue GOTPtr;
2911     if (is64bit) {
2912       setUsesTOCBasePtr(DAG);
2913       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2914       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2915                                    GOTReg, TGA);
2916     } else {
2917       if (picLevel == PICLevel::SmallPIC)
2918         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2919       else
2920         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2921     }
2922     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2923                        GOTPtr, TGA, TGA);
2924   }
2925 
2926   if (Model == TLSModel::LocalDynamic) {
2927     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2928     SDValue GOTPtr;
2929     if (is64bit) {
2930       setUsesTOCBasePtr(DAG);
2931       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2932       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2933                            GOTReg, TGA);
2934     } else {
2935       if (picLevel == PICLevel::SmallPIC)
2936         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2937       else
2938         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2939     }
2940     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2941                                   PtrVT, GOTPtr, TGA, TGA);
2942     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2943                                       PtrVT, TLSAddr, TGA);
2944     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2945   }
2946 
2947   llvm_unreachable("Unknown TLS model!");
2948 }
2949 
2950 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2951                                               SelectionDAG &DAG) const {
2952   EVT PtrVT = Op.getValueType();
2953   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2954   SDLoc DL(GSDN);
2955   const GlobalValue *GV = GSDN->getGlobal();
2956 
2957   // 64-bit SVR4 ABI & AIX ABI code is always position-independent.
2958   // The actual address of the GlobalValue is stored in the TOC.
2959   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) {
2960     setUsesTOCBasePtr(DAG);
2961     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2962     return getTOCEntry(DAG, DL, GA);
2963   }
2964 
2965   unsigned MOHiFlag, MOLoFlag;
2966   bool IsPIC = isPositionIndependent();
2967   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2968 
2969   if (IsPIC && Subtarget.isSVR4ABI()) {
2970     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2971                                             GSDN->getOffset(),
2972                                             PPCII::MO_PIC_FLAG);
2973     return getTOCEntry(DAG, DL, GA);
2974   }
2975 
2976   SDValue GAHi =
2977     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2978   SDValue GALo =
2979     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2980 
2981   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2982 
2983   // If the global reference is actually to a non-lazy-pointer, we have to do an
2984   // extra load to get the address of the global.
2985   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2986     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2987   return Ptr;
2988 }
2989 
2990 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2991   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2992   SDLoc dl(Op);
2993 
2994   if (Op.getValueType() == MVT::v2i64) {
2995     // When the operands themselves are v2i64 values, we need to do something
2996     // special because VSX has no underlying comparison operations for these.
2997     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2998       // Equality can be handled by casting to the legal type for Altivec
2999       // comparisons, everything else needs to be expanded.
3000       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
3001         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
3002                  DAG.getSetCC(dl, MVT::v4i32,
3003                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
3004                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
3005                    CC));
3006       }
3007 
3008       return SDValue();
3009     }
3010 
3011     // We handle most of these in the usual way.
3012     return Op;
3013   }
3014 
3015   // If we're comparing for equality to zero, expose the fact that this is
3016   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
3017   // fold the new nodes.
3018   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
3019     return V;
3020 
3021   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3022     // Leave comparisons against 0 and -1 alone for now, since they're usually
3023     // optimized.  FIXME: revisit this when we can custom lower all setcc
3024     // optimizations.
3025     if (C->isAllOnesValue() || C->isNullValue())
3026       return SDValue();
3027   }
3028 
3029   // If we have an integer seteq/setne, turn it into a compare against zero
3030   // by xor'ing the rhs with the lhs, which is faster than setting a
3031   // condition register, reading it back out, and masking the correct bit.  The
3032   // normal approach here uses sub to do this instead of xor.  Using xor exposes
3033   // the result to other bit-twiddling opportunities.
3034   EVT LHSVT = Op.getOperand(0).getValueType();
3035   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
3036     EVT VT = Op.getValueType();
3037     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
3038                                 Op.getOperand(1));
3039     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
3040   }
3041   return SDValue();
3042 }
3043 
3044 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3045   SDNode *Node = Op.getNode();
3046   EVT VT = Node->getValueType(0);
3047   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3048   SDValue InChain = Node->getOperand(0);
3049   SDValue VAListPtr = Node->getOperand(1);
3050   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3051   SDLoc dl(Node);
3052 
3053   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
3054 
3055   // gpr_index
3056   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3057                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
3058   InChain = GprIndex.getValue(1);
3059 
3060   if (VT == MVT::i64) {
3061     // Check if GprIndex is even
3062     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
3063                                  DAG.getConstant(1, dl, MVT::i32));
3064     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
3065                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
3066     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
3067                                           DAG.getConstant(1, dl, MVT::i32));
3068     // Align GprIndex to be even if it isn't
3069     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
3070                            GprIndex);
3071   }
3072 
3073   // fpr index is 1 byte after gpr
3074   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3075                                DAG.getConstant(1, dl, MVT::i32));
3076 
3077   // fpr
3078   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
3079                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
3080   InChain = FprIndex.getValue(1);
3081 
3082   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3083                                        DAG.getConstant(8, dl, MVT::i32));
3084 
3085   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
3086                                         DAG.getConstant(4, dl, MVT::i32));
3087 
3088   // areas
3089   SDValue OverflowArea =
3090       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
3091   InChain = OverflowArea.getValue(1);
3092 
3093   SDValue RegSaveArea =
3094       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
3095   InChain = RegSaveArea.getValue(1);
3096 
3097   // select overflow_area if index > 8
3098   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
3099                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
3100 
3101   // adjustment constant gpr_index * 4/8
3102   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
3103                                     VT.isInteger() ? GprIndex : FprIndex,
3104                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
3105                                                     MVT::i32));
3106 
3107   // OurReg = RegSaveArea + RegConstant
3108   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
3109                                RegConstant);
3110 
3111   // Floating types are 32 bytes into RegSaveArea
3112   if (VT.isFloatingPoint())
3113     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
3114                          DAG.getConstant(32, dl, MVT::i32));
3115 
3116   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
3117   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3118                                    VT.isInteger() ? GprIndex : FprIndex,
3119                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
3120                                                    MVT::i32));
3121 
3122   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
3123                               VT.isInteger() ? VAListPtr : FprPtr,
3124                               MachinePointerInfo(SV), MVT::i8);
3125 
3126   // determine if we should load from reg_save_area or overflow_area
3127   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
3128 
3129   // increase overflow_area by 4/8 if gpr/fpr > 8
3130   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
3131                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
3132                                           dl, MVT::i32));
3133 
3134   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
3135                              OverflowAreaPlusN);
3136 
3137   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
3138                               MachinePointerInfo(), MVT::i32);
3139 
3140   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
3141 }
3142 
3143 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3144   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
3145 
3146   // We have to copy the entire va_list struct:
3147   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
3148   return DAG.getMemcpy(Op.getOperand(0), Op,
3149                        Op.getOperand(1), Op.getOperand(2),
3150                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
3151                        false, MachinePointerInfo(), MachinePointerInfo());
3152 }
3153 
3154 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
3155                                                   SelectionDAG &DAG) const {
3156   return Op.getOperand(0);
3157 }
3158 
3159 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
3160                                                 SelectionDAG &DAG) const {
3161   SDValue Chain = Op.getOperand(0);
3162   SDValue Trmp = Op.getOperand(1); // trampoline
3163   SDValue FPtr = Op.getOperand(2); // nested function
3164   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
3165   SDLoc dl(Op);
3166 
3167   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3168   bool isPPC64 = (PtrVT == MVT::i64);
3169   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
3170 
3171   TargetLowering::ArgListTy Args;
3172   TargetLowering::ArgListEntry Entry;
3173 
3174   Entry.Ty = IntPtrTy;
3175   Entry.Node = Trmp; Args.push_back(Entry);
3176 
3177   // TrampSize == (isPPC64 ? 48 : 40);
3178   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
3179                                isPPC64 ? MVT::i64 : MVT::i32);
3180   Args.push_back(Entry);
3181 
3182   Entry.Node = FPtr; Args.push_back(Entry);
3183   Entry.Node = Nest; Args.push_back(Entry);
3184 
3185   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
3186   TargetLowering::CallLoweringInfo CLI(DAG);
3187   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
3188       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
3189       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
3190 
3191   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3192   return CallResult.second;
3193 }
3194 
3195 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3196   MachineFunction &MF = DAG.getMachineFunction();
3197   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3198   EVT PtrVT = getPointerTy(MF.getDataLayout());
3199 
3200   SDLoc dl(Op);
3201 
3202   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
3203     // vastart just stores the address of the VarArgsFrameIndex slot into the
3204     // memory location argument.
3205     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3206     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3207     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3208                         MachinePointerInfo(SV));
3209   }
3210 
3211   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
3212   // We suppose the given va_list is already allocated.
3213   //
3214   // typedef struct {
3215   //  char gpr;     /* index into the array of 8 GPRs
3216   //                 * stored in the register save area
3217   //                 * gpr=0 corresponds to r3,
3218   //                 * gpr=1 to r4, etc.
3219   //                 */
3220   //  char fpr;     /* index into the array of 8 FPRs
3221   //                 * stored in the register save area
3222   //                 * fpr=0 corresponds to f1,
3223   //                 * fpr=1 to f2, etc.
3224   //                 */
3225   //  char *overflow_arg_area;
3226   //                /* location on stack that holds
3227   //                 * the next overflow argument
3228   //                 */
3229   //  char *reg_save_area;
3230   //               /* where r3:r10 and f1:f8 (if saved)
3231   //                * are stored
3232   //                */
3233   // } va_list[1];
3234 
3235   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
3236   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
3237   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
3238                                             PtrVT);
3239   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
3240                                  PtrVT);
3241 
3242   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
3243   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
3244 
3245   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
3246   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
3247 
3248   uint64_t FPROffset = 1;
3249   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
3250 
3251   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3252 
3253   // Store first byte : number of int regs
3254   SDValue firstStore =
3255       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
3256                         MachinePointerInfo(SV), MVT::i8);
3257   uint64_t nextOffset = FPROffset;
3258   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
3259                                   ConstFPROffset);
3260 
3261   // Store second byte : number of float regs
3262   SDValue secondStore =
3263       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3264                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3265   nextOffset += StackOffset;
3266   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3267 
3268   // Store second word : arguments given on stack
3269   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3270                                     MachinePointerInfo(SV, nextOffset));
3271   nextOffset += FrameOffset;
3272   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3273 
3274   // Store third word : arguments given in registers
3275   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3276                       MachinePointerInfo(SV, nextOffset));
3277 }
3278 
3279 /// FPR - The set of FP registers that should be allocated for arguments
3280 /// on Darwin and AIX.
3281 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3282                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3283                                 PPC::F11, PPC::F12, PPC::F13};
3284 
3285 /// QFPR - The set of QPX registers that should be allocated for arguments.
3286 static const MCPhysReg QFPR[] = {
3287     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3288     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3289 
3290 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3291 /// the stack.
3292 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3293                                        unsigned PtrByteSize) {
3294   unsigned ArgSize = ArgVT.getStoreSize();
3295   if (Flags.isByVal())
3296     ArgSize = Flags.getByValSize();
3297 
3298   // Round up to multiples of the pointer size, except for array members,
3299   // which are always packed.
3300   if (!Flags.isInConsecutiveRegs())
3301     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3302 
3303   return ArgSize;
3304 }
3305 
3306 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3307 /// on the stack.
3308 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3309                                             ISD::ArgFlagsTy Flags,
3310                                             unsigned PtrByteSize) {
3311   unsigned Align = PtrByteSize;
3312 
3313   // Altivec parameters are padded to a 16 byte boundary.
3314   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3315       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3316       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3317       ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3318     Align = 16;
3319   // QPX vector types stored in double-precision are padded to a 32 byte
3320   // boundary.
3321   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3322     Align = 32;
3323 
3324   // ByVal parameters are aligned as requested.
3325   if (Flags.isByVal()) {
3326     unsigned BVAlign = Flags.getByValAlign();
3327     if (BVAlign > PtrByteSize) {
3328       if (BVAlign % PtrByteSize != 0)
3329           llvm_unreachable(
3330             "ByVal alignment is not a multiple of the pointer size");
3331 
3332       Align = BVAlign;
3333     }
3334   }
3335 
3336   // Array members are always packed to their original alignment.
3337   if (Flags.isInConsecutiveRegs()) {
3338     // If the array member was split into multiple registers, the first
3339     // needs to be aligned to the size of the full type.  (Except for
3340     // ppcf128, which is only aligned as its f64 components.)
3341     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3342       Align = OrigVT.getStoreSize();
3343     else
3344       Align = ArgVT.getStoreSize();
3345   }
3346 
3347   return Align;
3348 }
3349 
3350 /// CalculateStackSlotUsed - Return whether this argument will use its
3351 /// stack slot (instead of being passed in registers).  ArgOffset,
3352 /// AvailableFPRs, and AvailableVRs must hold the current argument
3353 /// position, and will be updated to account for this argument.
3354 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3355                                    ISD::ArgFlagsTy Flags,
3356                                    unsigned PtrByteSize,
3357                                    unsigned LinkageSize,
3358                                    unsigned ParamAreaSize,
3359                                    unsigned &ArgOffset,
3360                                    unsigned &AvailableFPRs,
3361                                    unsigned &AvailableVRs, bool HasQPX) {
3362   bool UseMemory = false;
3363 
3364   // Respect alignment of argument on the stack.
3365   unsigned Align =
3366     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3367   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3368   // If there's no space left in the argument save area, we must
3369   // use memory (this check also catches zero-sized arguments).
3370   if (ArgOffset >= LinkageSize + ParamAreaSize)
3371     UseMemory = true;
3372 
3373   // Allocate argument on the stack.
3374   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3375   if (Flags.isInConsecutiveRegsLast())
3376     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3377   // If we overran the argument save area, we must use memory
3378   // (this check catches arguments passed partially in memory)
3379   if (ArgOffset > LinkageSize + ParamAreaSize)
3380     UseMemory = true;
3381 
3382   // However, if the argument is actually passed in an FPR or a VR,
3383   // we don't use memory after all.
3384   if (!Flags.isByVal()) {
3385     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3386         // QPX registers overlap with the scalar FP registers.
3387         (HasQPX && (ArgVT == MVT::v4f32 ||
3388                     ArgVT == MVT::v4f64 ||
3389                     ArgVT == MVT::v4i1)))
3390       if (AvailableFPRs > 0) {
3391         --AvailableFPRs;
3392         return false;
3393       }
3394     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3395         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3396         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3397         ArgVT == MVT::v1i128 || ArgVT == MVT::f128)
3398       if (AvailableVRs > 0) {
3399         --AvailableVRs;
3400         return false;
3401       }
3402   }
3403 
3404   return UseMemory;
3405 }
3406 
3407 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3408 /// ensure minimum alignment required for target.
3409 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3410                                      unsigned NumBytes) {
3411   unsigned TargetAlign = Lowering->getStackAlignment();
3412   unsigned AlignMask = TargetAlign - 1;
3413   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3414   return NumBytes;
3415 }
3416 
3417 SDValue PPCTargetLowering::LowerFormalArguments(
3418     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3419     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3420     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3421   if (Subtarget.isAIXABI())
3422     return LowerFormalArguments_AIX(Chain, CallConv, isVarArg, Ins, dl, DAG,
3423                                     InVals);
3424   if (Subtarget.is64BitELFABI())
3425     return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3426                                        InVals);
3427   if (Subtarget.is32BitELFABI())
3428     return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins, dl, DAG,
3429                                        InVals);
3430 
3431   return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins, dl, DAG,
3432                                      InVals);
3433 }
3434 
3435 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3436     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3437     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3438     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3439 
3440   // 32-bit SVR4 ABI Stack Frame Layout:
3441   //              +-----------------------------------+
3442   //        +-->  |            Back chain             |
3443   //        |     +-----------------------------------+
3444   //        |     | Floating-point register save area |
3445   //        |     +-----------------------------------+
3446   //        |     |    General register save area     |
3447   //        |     +-----------------------------------+
3448   //        |     |          CR save word             |
3449   //        |     +-----------------------------------+
3450   //        |     |         VRSAVE save word          |
3451   //        |     +-----------------------------------+
3452   //        |     |         Alignment padding         |
3453   //        |     +-----------------------------------+
3454   //        |     |     Vector register save area     |
3455   //        |     +-----------------------------------+
3456   //        |     |       Local variable space        |
3457   //        |     +-----------------------------------+
3458   //        |     |        Parameter list area        |
3459   //        |     +-----------------------------------+
3460   //        |     |           LR save word            |
3461   //        |     +-----------------------------------+
3462   // SP-->  +---  |            Back chain             |
3463   //              +-----------------------------------+
3464   //
3465   // Specifications:
3466   //   System V Application Binary Interface PowerPC Processor Supplement
3467   //   AltiVec Technology Programming Interface Manual
3468 
3469   MachineFunction &MF = DAG.getMachineFunction();
3470   MachineFrameInfo &MFI = MF.getFrameInfo();
3471   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3472 
3473   EVT PtrVT = getPointerTy(MF.getDataLayout());
3474   // Potential tail calls could cause overwriting of argument stack slots.
3475   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3476                        (CallConv == CallingConv::Fast));
3477   unsigned PtrByteSize = 4;
3478 
3479   // Assign locations to all of the incoming arguments.
3480   SmallVector<CCValAssign, 16> ArgLocs;
3481   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3482                  *DAG.getContext());
3483 
3484   // Reserve space for the linkage area on the stack.
3485   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3486   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3487   if (useSoftFloat())
3488     CCInfo.PreAnalyzeFormalArguments(Ins);
3489 
3490   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3491   CCInfo.clearWasPPCF128();
3492 
3493   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3494     CCValAssign &VA = ArgLocs[i];
3495 
3496     // Arguments stored in registers.
3497     if (VA.isRegLoc()) {
3498       const TargetRegisterClass *RC;
3499       EVT ValVT = VA.getValVT();
3500 
3501       switch (ValVT.getSimpleVT().SimpleTy) {
3502         default:
3503           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3504         case MVT::i1:
3505         case MVT::i32:
3506           RC = &PPC::GPRCRegClass;
3507           break;
3508         case MVT::f32:
3509           if (Subtarget.hasP8Vector())
3510             RC = &PPC::VSSRCRegClass;
3511           else if (Subtarget.hasSPE())
3512             RC = &PPC::GPRCRegClass;
3513           else
3514             RC = &PPC::F4RCRegClass;
3515           break;
3516         case MVT::f64:
3517           if (Subtarget.hasVSX())
3518             RC = &PPC::VSFRCRegClass;
3519           else if (Subtarget.hasSPE())
3520             // SPE passes doubles in GPR pairs.
3521             RC = &PPC::GPRCRegClass;
3522           else
3523             RC = &PPC::F8RCRegClass;
3524           break;
3525         case MVT::v16i8:
3526         case MVT::v8i16:
3527         case MVT::v4i32:
3528           RC = &PPC::VRRCRegClass;
3529           break;
3530         case MVT::v4f32:
3531           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3532           break;
3533         case MVT::v2f64:
3534         case MVT::v2i64:
3535           RC = &PPC::VRRCRegClass;
3536           break;
3537         case MVT::v4f64:
3538           RC = &PPC::QFRCRegClass;
3539           break;
3540         case MVT::v4i1:
3541           RC = &PPC::QBRCRegClass;
3542           break;
3543       }
3544 
3545       SDValue ArgValue;
3546       // Transform the arguments stored in physical registers into
3547       // virtual ones.
3548       if (VA.getLocVT() == MVT::f64 && Subtarget.hasSPE()) {
3549         assert(i + 1 < e && "No second half of double precision argument");
3550         unsigned RegLo = MF.addLiveIn(VA.getLocReg(), RC);
3551         unsigned RegHi = MF.addLiveIn(ArgLocs[++i].getLocReg(), RC);
3552         SDValue ArgValueLo = DAG.getCopyFromReg(Chain, dl, RegLo, MVT::i32);
3553         SDValue ArgValueHi = DAG.getCopyFromReg(Chain, dl, RegHi, MVT::i32);
3554         if (!Subtarget.isLittleEndian())
3555           std::swap (ArgValueLo, ArgValueHi);
3556         ArgValue = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, ArgValueLo,
3557                                ArgValueHi);
3558       } else {
3559         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3560         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3561                                       ValVT == MVT::i1 ? MVT::i32 : ValVT);
3562         if (ValVT == MVT::i1)
3563           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3564       }
3565 
3566       InVals.push_back(ArgValue);
3567     } else {
3568       // Argument stored in memory.
3569       assert(VA.isMemLoc());
3570 
3571       // Get the extended size of the argument type in stack
3572       unsigned ArgSize = VA.getLocVT().getStoreSize();
3573       // Get the actual size of the argument type
3574       unsigned ObjSize = VA.getValVT().getStoreSize();
3575       unsigned ArgOffset = VA.getLocMemOffset();
3576       // Stack objects in PPC32 are right justified.
3577       ArgOffset += ArgSize - ObjSize;
3578       int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, isImmutable);
3579 
3580       // Create load nodes to retrieve arguments from the stack.
3581       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3582       InVals.push_back(
3583           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3584     }
3585   }
3586 
3587   // Assign locations to all of the incoming aggregate by value arguments.
3588   // Aggregates passed by value are stored in the local variable space of the
3589   // caller's stack frame, right above the parameter list area.
3590   SmallVector<CCValAssign, 16> ByValArgLocs;
3591   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3592                       ByValArgLocs, *DAG.getContext());
3593 
3594   // Reserve stack space for the allocations in CCInfo.
3595   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3596 
3597   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3598 
3599   // Area that is at least reserved in the caller of this function.
3600   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3601   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3602 
3603   // Set the size that is at least reserved in caller of this function.  Tail
3604   // call optimized function's reserved stack space needs to be aligned so that
3605   // taking the difference between two stack areas will result in an aligned
3606   // stack.
3607   MinReservedArea =
3608       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3609   FuncInfo->setMinReservedArea(MinReservedArea);
3610 
3611   SmallVector<SDValue, 8> MemOps;
3612 
3613   // If the function takes variable number of arguments, make a frame index for
3614   // the start of the first vararg value... for expansion of llvm.va_start.
3615   if (isVarArg) {
3616     static const MCPhysReg GPArgRegs[] = {
3617       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3618       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3619     };
3620     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3621 
3622     static const MCPhysReg FPArgRegs[] = {
3623       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3624       PPC::F8
3625     };
3626     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3627 
3628     if (useSoftFloat() || hasSPE())
3629        NumFPArgRegs = 0;
3630 
3631     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3632     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3633 
3634     // Make room for NumGPArgRegs and NumFPArgRegs.
3635     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3636                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3637 
3638     FuncInfo->setVarArgsStackOffset(
3639       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3640                             CCInfo.getNextStackOffset(), true));
3641 
3642     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3643     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3644 
3645     // The fixed integer arguments of a variadic function are stored to the
3646     // VarArgsFrameIndex on the stack so that they may be loaded by
3647     // dereferencing the result of va_next.
3648     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3649       // Get an existing live-in vreg, or add a new one.
3650       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3651       if (!VReg)
3652         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3653 
3654       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3655       SDValue Store =
3656           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3657       MemOps.push_back(Store);
3658       // Increment the address by four for the next argument to store
3659       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3660       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3661     }
3662 
3663     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3664     // is set.
3665     // The double arguments are stored to the VarArgsFrameIndex
3666     // on the stack.
3667     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3668       // Get an existing live-in vreg, or add a new one.
3669       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3670       if (!VReg)
3671         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3672 
3673       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3674       SDValue Store =
3675           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3676       MemOps.push_back(Store);
3677       // Increment the address by eight for the next argument to store
3678       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3679                                          PtrVT);
3680       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3681     }
3682   }
3683 
3684   if (!MemOps.empty())
3685     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3686 
3687   return Chain;
3688 }
3689 
3690 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3691 // value to MVT::i64 and then truncate to the correct register size.
3692 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3693                                              EVT ObjectVT, SelectionDAG &DAG,
3694                                              SDValue ArgVal,
3695                                              const SDLoc &dl) const {
3696   if (Flags.isSExt())
3697     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3698                          DAG.getValueType(ObjectVT));
3699   else if (Flags.isZExt())
3700     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3701                          DAG.getValueType(ObjectVT));
3702 
3703   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3704 }
3705 
3706 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3707     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3708     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3709     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3710   // TODO: add description of PPC stack frame format, or at least some docs.
3711   //
3712   bool isELFv2ABI = Subtarget.isELFv2ABI();
3713   bool isLittleEndian = Subtarget.isLittleEndian();
3714   MachineFunction &MF = DAG.getMachineFunction();
3715   MachineFrameInfo &MFI = MF.getFrameInfo();
3716   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3717 
3718   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3719          "fastcc not supported on varargs functions");
3720 
3721   EVT PtrVT = getPointerTy(MF.getDataLayout());
3722   // Potential tail calls could cause overwriting of argument stack slots.
3723   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3724                        (CallConv == CallingConv::Fast));
3725   unsigned PtrByteSize = 8;
3726   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3727 
3728   static const MCPhysReg GPR[] = {
3729     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3730     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3731   };
3732   static const MCPhysReg VR[] = {
3733     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3734     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3735   };
3736 
3737   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3738   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3739   const unsigned Num_VR_Regs  = array_lengthof(VR);
3740   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3741 
3742   // Do a first pass over the arguments to determine whether the ABI
3743   // guarantees that our caller has allocated the parameter save area
3744   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3745   // in the ELFv2 ABI, it is true if this is a vararg function or if
3746   // any parameter is located in a stack slot.
3747 
3748   bool HasParameterArea = !isELFv2ABI || isVarArg;
3749   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3750   unsigned NumBytes = LinkageSize;
3751   unsigned AvailableFPRs = Num_FPR_Regs;
3752   unsigned AvailableVRs = Num_VR_Regs;
3753   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3754     if (Ins[i].Flags.isNest())
3755       continue;
3756 
3757     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3758                                PtrByteSize, LinkageSize, ParamAreaSize,
3759                                NumBytes, AvailableFPRs, AvailableVRs,
3760                                Subtarget.hasQPX()))
3761       HasParameterArea = true;
3762   }
3763 
3764   // Add DAG nodes to load the arguments or copy them out of registers.  On
3765   // entry to a function on PPC, the arguments start after the linkage area,
3766   // although the first ones are often in registers.
3767 
3768   unsigned ArgOffset = LinkageSize;
3769   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3770   unsigned &QFPR_idx = FPR_idx;
3771   SmallVector<SDValue, 8> MemOps;
3772   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3773   unsigned CurArgIdx = 0;
3774   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3775     SDValue ArgVal;
3776     bool needsLoad = false;
3777     EVT ObjectVT = Ins[ArgNo].VT;
3778     EVT OrigVT = Ins[ArgNo].ArgVT;
3779     unsigned ObjSize = ObjectVT.getStoreSize();
3780     unsigned ArgSize = ObjSize;
3781     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3782     if (Ins[ArgNo].isOrigArg()) {
3783       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3784       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3785     }
3786     // We re-align the argument offset for each argument, except when using the
3787     // fast calling convention, when we need to make sure we do that only when
3788     // we'll actually use a stack slot.
3789     unsigned CurArgOffset, Align;
3790     auto ComputeArgOffset = [&]() {
3791       /* Respect alignment of argument on the stack.  */
3792       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3793       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3794       CurArgOffset = ArgOffset;
3795     };
3796 
3797     if (CallConv != CallingConv::Fast) {
3798       ComputeArgOffset();
3799 
3800       /* Compute GPR index associated with argument offset.  */
3801       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3802       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3803     }
3804 
3805     // FIXME the codegen can be much improved in some cases.
3806     // We do not have to keep everything in memory.
3807     if (Flags.isByVal()) {
3808       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3809 
3810       if (CallConv == CallingConv::Fast)
3811         ComputeArgOffset();
3812 
3813       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3814       ObjSize = Flags.getByValSize();
3815       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3816       // Empty aggregate parameters do not take up registers.  Examples:
3817       //   struct { } a;
3818       //   union  { } b;
3819       //   int c[0];
3820       // etc.  However, we have to provide a place-holder in InVals, so
3821       // pretend we have an 8-byte item at the current address for that
3822       // purpose.
3823       if (!ObjSize) {
3824         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3825         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3826         InVals.push_back(FIN);
3827         continue;
3828       }
3829 
3830       // Create a stack object covering all stack doublewords occupied
3831       // by the argument.  If the argument is (fully or partially) on
3832       // the stack, or if the argument is fully in registers but the
3833       // caller has allocated the parameter save anyway, we can refer
3834       // directly to the caller's stack frame.  Otherwise, create a
3835       // local copy in our own frame.
3836       int FI;
3837       if (HasParameterArea ||
3838           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3839         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3840       else
3841         FI = MFI.CreateStackObject(ArgSize, Align, false);
3842       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3843 
3844       // Handle aggregates smaller than 8 bytes.
3845       if (ObjSize < PtrByteSize) {
3846         // The value of the object is its address, which differs from the
3847         // address of the enclosing doubleword on big-endian systems.
3848         SDValue Arg = FIN;
3849         if (!isLittleEndian) {
3850           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3851           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3852         }
3853         InVals.push_back(Arg);
3854 
3855         if (GPR_idx != Num_GPR_Regs) {
3856           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3857           FuncInfo->addLiveInAttr(VReg, Flags);
3858           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3859           SDValue Store;
3860 
3861           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3862             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3863                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3864             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3865                                       MachinePointerInfo(&*FuncArg), ObjType);
3866           } else {
3867             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3868             // store the whole register as-is to the parameter save area
3869             // slot.
3870             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3871                                  MachinePointerInfo(&*FuncArg));
3872           }
3873 
3874           MemOps.push_back(Store);
3875         }
3876         // Whether we copied from a register or not, advance the offset
3877         // into the parameter save area by a full doubleword.
3878         ArgOffset += PtrByteSize;
3879         continue;
3880       }
3881 
3882       // The value of the object is its address, which is the address of
3883       // its first stack doubleword.
3884       InVals.push_back(FIN);
3885 
3886       // Store whatever pieces of the object are in registers to memory.
3887       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3888         if (GPR_idx == Num_GPR_Regs)
3889           break;
3890 
3891         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3892         FuncInfo->addLiveInAttr(VReg, Flags);
3893         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3894         SDValue Addr = FIN;
3895         if (j) {
3896           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3897           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3898         }
3899         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3900                                      MachinePointerInfo(&*FuncArg, j));
3901         MemOps.push_back(Store);
3902         ++GPR_idx;
3903       }
3904       ArgOffset += ArgSize;
3905       continue;
3906     }
3907 
3908     switch (ObjectVT.getSimpleVT().SimpleTy) {
3909     default: llvm_unreachable("Unhandled argument type!");
3910     case MVT::i1:
3911     case MVT::i32:
3912     case MVT::i64:
3913       if (Flags.isNest()) {
3914         // The 'nest' parameter, if any, is passed in R11.
3915         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3916         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3917 
3918         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3919           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3920 
3921         break;
3922       }
3923 
3924       // These can be scalar arguments or elements of an integer array type
3925       // passed directly.  Clang may use those instead of "byval" aggregate
3926       // types to avoid forcing arguments to memory unnecessarily.
3927       if (GPR_idx != Num_GPR_Regs) {
3928         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3929         FuncInfo->addLiveInAttr(VReg, Flags);
3930         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3931 
3932         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3933           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3934           // value to MVT::i64 and then truncate to the correct register size.
3935           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3936       } else {
3937         if (CallConv == CallingConv::Fast)
3938           ComputeArgOffset();
3939 
3940         needsLoad = true;
3941         ArgSize = PtrByteSize;
3942       }
3943       if (CallConv != CallingConv::Fast || needsLoad)
3944         ArgOffset += 8;
3945       break;
3946 
3947     case MVT::f32:
3948     case MVT::f64:
3949       // These can be scalar arguments or elements of a float array type
3950       // passed directly.  The latter are used to implement ELFv2 homogenous
3951       // float aggregates.
3952       if (FPR_idx != Num_FPR_Regs) {
3953         unsigned VReg;
3954 
3955         if (ObjectVT == MVT::f32)
3956           VReg = MF.addLiveIn(FPR[FPR_idx],
3957                               Subtarget.hasP8Vector()
3958                                   ? &PPC::VSSRCRegClass
3959                                   : &PPC::F4RCRegClass);
3960         else
3961           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3962                                                 ? &PPC::VSFRCRegClass
3963                                                 : &PPC::F8RCRegClass);
3964 
3965         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3966         ++FPR_idx;
3967       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3968         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3969         // once we support fp <-> gpr moves.
3970 
3971         // This can only ever happen in the presence of f32 array types,
3972         // since otherwise we never run out of FPRs before running out
3973         // of GPRs.
3974         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3975         FuncInfo->addLiveInAttr(VReg, Flags);
3976         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3977 
3978         if (ObjectVT == MVT::f32) {
3979           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3980             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3981                                  DAG.getConstant(32, dl, MVT::i32));
3982           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3983         }
3984 
3985         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3986       } else {
3987         if (CallConv == CallingConv::Fast)
3988           ComputeArgOffset();
3989 
3990         needsLoad = true;
3991       }
3992 
3993       // When passing an array of floats, the array occupies consecutive
3994       // space in the argument area; only round up to the next doubleword
3995       // at the end of the array.  Otherwise, each float takes 8 bytes.
3996       if (CallConv != CallingConv::Fast || needsLoad) {
3997         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3998         ArgOffset += ArgSize;
3999         if (Flags.isInConsecutiveRegsLast())
4000           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4001       }
4002       break;
4003     case MVT::v4f32:
4004     case MVT::v4i32:
4005     case MVT::v8i16:
4006     case MVT::v16i8:
4007     case MVT::v2f64:
4008     case MVT::v2i64:
4009     case MVT::v1i128:
4010     case MVT::f128:
4011       if (!Subtarget.hasQPX()) {
4012         // These can be scalar arguments or elements of a vector array type
4013         // passed directly.  The latter are used to implement ELFv2 homogenous
4014         // vector aggregates.
4015         if (VR_idx != Num_VR_Regs) {
4016           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4017           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4018           ++VR_idx;
4019         } else {
4020           if (CallConv == CallingConv::Fast)
4021             ComputeArgOffset();
4022           needsLoad = true;
4023         }
4024         if (CallConv != CallingConv::Fast || needsLoad)
4025           ArgOffset += 16;
4026         break;
4027       } // not QPX
4028 
4029       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
4030              "Invalid QPX parameter type");
4031       LLVM_FALLTHROUGH;
4032 
4033     case MVT::v4f64:
4034     case MVT::v4i1:
4035       // QPX vectors are treated like their scalar floating-point subregisters
4036       // (except that they're larger).
4037       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
4038       if (QFPR_idx != Num_QFPR_Regs) {
4039         const TargetRegisterClass *RC;
4040         switch (ObjectVT.getSimpleVT().SimpleTy) {
4041         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
4042         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
4043         default:         RC = &PPC::QBRCRegClass; break;
4044         }
4045 
4046         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
4047         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4048         ++QFPR_idx;
4049       } else {
4050         if (CallConv == CallingConv::Fast)
4051           ComputeArgOffset();
4052         needsLoad = true;
4053       }
4054       if (CallConv != CallingConv::Fast || needsLoad)
4055         ArgOffset += Sz;
4056       break;
4057     }
4058 
4059     // We need to load the argument to a virtual register if we determined
4060     // above that we ran out of physical registers of the appropriate type.
4061     if (needsLoad) {
4062       if (ObjSize < ArgSize && !isLittleEndian)
4063         CurArgOffset += ArgSize - ObjSize;
4064       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
4065       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4066       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4067     }
4068 
4069     InVals.push_back(ArgVal);
4070   }
4071 
4072   // Area that is at least reserved in the caller of this function.
4073   unsigned MinReservedArea;
4074   if (HasParameterArea)
4075     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
4076   else
4077     MinReservedArea = LinkageSize;
4078 
4079   // Set the size that is at least reserved in caller of this function.  Tail
4080   // call optimized functions' reserved stack space needs to be aligned so that
4081   // taking the difference between two stack areas will result in an aligned
4082   // stack.
4083   MinReservedArea =
4084       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4085   FuncInfo->setMinReservedArea(MinReservedArea);
4086 
4087   // If the function takes variable number of arguments, make a frame index for
4088   // the start of the first vararg value... for expansion of llvm.va_start.
4089   if (isVarArg) {
4090     int Depth = ArgOffset;
4091 
4092     FuncInfo->setVarArgsFrameIndex(
4093       MFI.CreateFixedObject(PtrByteSize, Depth, true));
4094     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4095 
4096     // If this function is vararg, store any remaining integer argument regs
4097     // to their spots on the stack so that they may be loaded by dereferencing
4098     // the result of va_next.
4099     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4100          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
4101       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4102       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4103       SDValue Store =
4104           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4105       MemOps.push_back(Store);
4106       // Increment the address by four for the next argument to store
4107       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
4108       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4109     }
4110   }
4111 
4112   if (!MemOps.empty())
4113     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4114 
4115   return Chain;
4116 }
4117 
4118 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
4119     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
4120     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4121     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4122   // TODO: add description of PPC stack frame format, or at least some docs.
4123   //
4124   MachineFunction &MF = DAG.getMachineFunction();
4125   MachineFrameInfo &MFI = MF.getFrameInfo();
4126   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
4127 
4128   EVT PtrVT = getPointerTy(MF.getDataLayout());
4129   bool isPPC64 = PtrVT == MVT::i64;
4130   // Potential tail calls could cause overwriting of argument stack slots.
4131   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
4132                        (CallConv == CallingConv::Fast));
4133   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4134   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4135   unsigned ArgOffset = LinkageSize;
4136   // Area that is at least reserved in caller of this function.
4137   unsigned MinReservedArea = ArgOffset;
4138 
4139   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4140     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4141     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4142   };
4143   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4144     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4145     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4146   };
4147   static const MCPhysReg VR[] = {
4148     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4149     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4150   };
4151 
4152   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
4153   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
4154   const unsigned Num_VR_Regs  = array_lengthof( VR);
4155 
4156   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4157 
4158   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4159 
4160   // In 32-bit non-varargs functions, the stack space for vectors is after the
4161   // stack space for non-vectors.  We do not use this space unless we have
4162   // too many vectors to fit in registers, something that only occurs in
4163   // constructed examples:), but we have to walk the arglist to figure
4164   // that out...for the pathological case, compute VecArgOffset as the
4165   // start of the vector parameter area.  Computing VecArgOffset is the
4166   // entire point of the following loop.
4167   unsigned VecArgOffset = ArgOffset;
4168   if (!isVarArg && !isPPC64) {
4169     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
4170          ++ArgNo) {
4171       EVT ObjectVT = Ins[ArgNo].VT;
4172       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4173 
4174       if (Flags.isByVal()) {
4175         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
4176         unsigned ObjSize = Flags.getByValSize();
4177         unsigned ArgSize =
4178                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4179         VecArgOffset += ArgSize;
4180         continue;
4181       }
4182 
4183       switch(ObjectVT.getSimpleVT().SimpleTy) {
4184       default: llvm_unreachable("Unhandled argument type!");
4185       case MVT::i1:
4186       case MVT::i32:
4187       case MVT::f32:
4188         VecArgOffset += 4;
4189         break;
4190       case MVT::i64:  // PPC64
4191       case MVT::f64:
4192         // FIXME: We are guaranteed to be !isPPC64 at this point.
4193         // Does MVT::i64 apply?
4194         VecArgOffset += 8;
4195         break;
4196       case MVT::v4f32:
4197       case MVT::v4i32:
4198       case MVT::v8i16:
4199       case MVT::v16i8:
4200         // Nothing to do, we're only looking at Nonvector args here.
4201         break;
4202       }
4203     }
4204   }
4205   // We've found where the vector parameter area in memory is.  Skip the
4206   // first 12 parameters; these don't use that memory.
4207   VecArgOffset = ((VecArgOffset+15)/16)*16;
4208   VecArgOffset += 12*16;
4209 
4210   // Add DAG nodes to load the arguments or copy them out of registers.  On
4211   // entry to a function on PPC, the arguments start after the linkage area,
4212   // although the first ones are often in registers.
4213 
4214   SmallVector<SDValue, 8> MemOps;
4215   unsigned nAltivecParamsAtEnd = 0;
4216   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4217   unsigned CurArgIdx = 0;
4218   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4219     SDValue ArgVal;
4220     bool needsLoad = false;
4221     EVT ObjectVT = Ins[ArgNo].VT;
4222     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4223     unsigned ArgSize = ObjSize;
4224     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4225     if (Ins[ArgNo].isOrigArg()) {
4226       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4227       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4228     }
4229     unsigned CurArgOffset = ArgOffset;
4230 
4231     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4232     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4233         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4234       if (isVarArg || isPPC64) {
4235         MinReservedArea = ((MinReservedArea+15)/16)*16;
4236         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4237                                                   Flags,
4238                                                   PtrByteSize);
4239       } else  nAltivecParamsAtEnd++;
4240     } else
4241       // Calculate min reserved area.
4242       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4243                                                 Flags,
4244                                                 PtrByteSize);
4245 
4246     // FIXME the codegen can be much improved in some cases.
4247     // We do not have to keep everything in memory.
4248     if (Flags.isByVal()) {
4249       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4250 
4251       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4252       ObjSize = Flags.getByValSize();
4253       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4254       // Objects of size 1 and 2 are right justified, everything else is
4255       // left justified.  This means the memory address is adjusted forwards.
4256       if (ObjSize==1 || ObjSize==2) {
4257         CurArgOffset = CurArgOffset + (4 - ObjSize);
4258       }
4259       // The value of the object is its address.
4260       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4261       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4262       InVals.push_back(FIN);
4263       if (ObjSize==1 || ObjSize==2) {
4264         if (GPR_idx != Num_GPR_Regs) {
4265           unsigned VReg;
4266           if (isPPC64)
4267             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4268           else
4269             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4270           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4271           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4272           SDValue Store =
4273               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4274                                 MachinePointerInfo(&*FuncArg), ObjType);
4275           MemOps.push_back(Store);
4276           ++GPR_idx;
4277         }
4278 
4279         ArgOffset += PtrByteSize;
4280 
4281         continue;
4282       }
4283       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4284         // Store whatever pieces of the object are in registers
4285         // to memory.  ArgOffset will be the address of the beginning
4286         // of the object.
4287         if (GPR_idx != Num_GPR_Regs) {
4288           unsigned VReg;
4289           if (isPPC64)
4290             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4291           else
4292             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4293           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4294           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4295           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4296           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4297                                        MachinePointerInfo(&*FuncArg, j));
4298           MemOps.push_back(Store);
4299           ++GPR_idx;
4300           ArgOffset += PtrByteSize;
4301         } else {
4302           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4303           break;
4304         }
4305       }
4306       continue;
4307     }
4308 
4309     switch (ObjectVT.getSimpleVT().SimpleTy) {
4310     default: llvm_unreachable("Unhandled argument type!");
4311     case MVT::i1:
4312     case MVT::i32:
4313       if (!isPPC64) {
4314         if (GPR_idx != Num_GPR_Regs) {
4315           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4316           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4317 
4318           if (ObjectVT == MVT::i1)
4319             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4320 
4321           ++GPR_idx;
4322         } else {
4323           needsLoad = true;
4324           ArgSize = PtrByteSize;
4325         }
4326         // All int arguments reserve stack space in the Darwin ABI.
4327         ArgOffset += PtrByteSize;
4328         break;
4329       }
4330       LLVM_FALLTHROUGH;
4331     case MVT::i64:  // PPC64
4332       if (GPR_idx != Num_GPR_Regs) {
4333         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4334         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4335 
4336         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4337           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4338           // value to MVT::i64 and then truncate to the correct register size.
4339           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4340 
4341         ++GPR_idx;
4342       } else {
4343         needsLoad = true;
4344         ArgSize = PtrByteSize;
4345       }
4346       // All int arguments reserve stack space in the Darwin ABI.
4347       ArgOffset += 8;
4348       break;
4349 
4350     case MVT::f32:
4351     case MVT::f64:
4352       // Every 4 bytes of argument space consumes one of the GPRs available for
4353       // argument passing.
4354       if (GPR_idx != Num_GPR_Regs) {
4355         ++GPR_idx;
4356         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4357           ++GPR_idx;
4358       }
4359       if (FPR_idx != Num_FPR_Regs) {
4360         unsigned VReg;
4361 
4362         if (ObjectVT == MVT::f32)
4363           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4364         else
4365           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4366 
4367         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4368         ++FPR_idx;
4369       } else {
4370         needsLoad = true;
4371       }
4372 
4373       // All FP arguments reserve stack space in the Darwin ABI.
4374       ArgOffset += isPPC64 ? 8 : ObjSize;
4375       break;
4376     case MVT::v4f32:
4377     case MVT::v4i32:
4378     case MVT::v8i16:
4379     case MVT::v16i8:
4380       // Note that vector arguments in registers don't reserve stack space,
4381       // except in varargs functions.
4382       if (VR_idx != Num_VR_Regs) {
4383         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4384         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4385         if (isVarArg) {
4386           while ((ArgOffset % 16) != 0) {
4387             ArgOffset += PtrByteSize;
4388             if (GPR_idx != Num_GPR_Regs)
4389               GPR_idx++;
4390           }
4391           ArgOffset += 16;
4392           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4393         }
4394         ++VR_idx;
4395       } else {
4396         if (!isVarArg && !isPPC64) {
4397           // Vectors go after all the nonvectors.
4398           CurArgOffset = VecArgOffset;
4399           VecArgOffset += 16;
4400         } else {
4401           // Vectors are aligned.
4402           ArgOffset = ((ArgOffset+15)/16)*16;
4403           CurArgOffset = ArgOffset;
4404           ArgOffset += 16;
4405         }
4406         needsLoad = true;
4407       }
4408       break;
4409     }
4410 
4411     // We need to load the argument to a virtual register if we determined above
4412     // that we ran out of physical registers of the appropriate type.
4413     if (needsLoad) {
4414       int FI = MFI.CreateFixedObject(ObjSize,
4415                                      CurArgOffset + (ArgSize - ObjSize),
4416                                      isImmutable);
4417       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4418       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4419     }
4420 
4421     InVals.push_back(ArgVal);
4422   }
4423 
4424   // Allow for Altivec parameters at the end, if needed.
4425   if (nAltivecParamsAtEnd) {
4426     MinReservedArea = ((MinReservedArea+15)/16)*16;
4427     MinReservedArea += 16*nAltivecParamsAtEnd;
4428   }
4429 
4430   // Area that is at least reserved in the caller of this function.
4431   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4432 
4433   // Set the size that is at least reserved in caller of this function.  Tail
4434   // call optimized functions' reserved stack space needs to be aligned so that
4435   // taking the difference between two stack areas will result in an aligned
4436   // stack.
4437   MinReservedArea =
4438       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4439   FuncInfo->setMinReservedArea(MinReservedArea);
4440 
4441   // If the function takes variable number of arguments, make a frame index for
4442   // the start of the first vararg value... for expansion of llvm.va_start.
4443   if (isVarArg) {
4444     int Depth = ArgOffset;
4445 
4446     FuncInfo->setVarArgsFrameIndex(
4447       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4448                             Depth, true));
4449     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4450 
4451     // If this function is vararg, store any remaining integer argument regs
4452     // to their spots on the stack so that they may be loaded by dereferencing
4453     // the result of va_next.
4454     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4455       unsigned VReg;
4456 
4457       if (isPPC64)
4458         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4459       else
4460         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4461 
4462       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4463       SDValue Store =
4464           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4465       MemOps.push_back(Store);
4466       // Increment the address by four for the next argument to store
4467       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4468       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4469     }
4470   }
4471 
4472   if (!MemOps.empty())
4473     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4474 
4475   return Chain;
4476 }
4477 
4478 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4479 /// adjusted to accommodate the arguments for the tailcall.
4480 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4481                                    unsigned ParamSize) {
4482 
4483   if (!isTailCall) return 0;
4484 
4485   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4486   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4487   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4488   // Remember only if the new adjustment is bigger.
4489   if (SPDiff < FI->getTailCallSPDelta())
4490     FI->setTailCallSPDelta(SPDiff);
4491 
4492   return SPDiff;
4493 }
4494 
4495 static bool isFunctionGlobalAddress(SDValue Callee);
4496 
4497 static bool
4498 callsShareTOCBase(const Function *Caller, SDValue Callee,
4499                     const TargetMachine &TM) {
4500    // Callee is either a GlobalAddress or an ExternalSymbol. ExternalSymbols
4501    // don't have enough information to determine if the caller and calle share
4502    // the same  TOC base, so we have to pessimistically assume they don't for
4503    // correctness.
4504    GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4505    if (!G)
4506      return false;
4507 
4508    const GlobalValue *GV = G->getGlobal();
4509   // The medium and large code models are expected to provide a sufficiently
4510   // large TOC to provide all data addressing needs of a module with a
4511   // single TOC. Since each module will be addressed with a single TOC then we
4512   // only need to check that caller and callee don't cross dso boundaries.
4513   if (CodeModel::Medium == TM.getCodeModel() ||
4514       CodeModel::Large == TM.getCodeModel())
4515     return TM.shouldAssumeDSOLocal(*Caller->getParent(), GV);
4516 
4517   // Otherwise we need to ensure callee and caller are in the same section,
4518   // since the linker may allocate multiple TOCs, and we don't know which
4519   // sections will belong to the same TOC base.
4520 
4521   if (!GV->isStrongDefinitionForLinker())
4522     return false;
4523 
4524   // Any explicitly-specified sections and section prefixes must also match.
4525   // Also, if we're using -ffunction-sections, then each function is always in
4526   // a different section (the same is true for COMDAT functions).
4527   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4528       GV->getSection() != Caller->getSection())
4529     return false;
4530   if (const auto *F = dyn_cast<Function>(GV)) {
4531     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4532       return false;
4533   }
4534 
4535   // If the callee might be interposed, then we can't assume the ultimate call
4536   // target will be in the same section. Even in cases where we can assume that
4537   // interposition won't happen, in any case where the linker might insert a
4538   // stub to allow for interposition, we must generate code as though
4539   // interposition might occur. To understand why this matters, consider a
4540   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4541   // in the same section, but a is in a different module (i.e. has a different
4542   // TOC base pointer). If the linker allows for interposition between b and c,
4543   // then it will generate a stub for the call edge between b and c which will
4544   // save the TOC pointer into the designated stack slot allocated by b. If we
4545   // return true here, and therefore allow a tail call between b and c, that
4546   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4547   // pointer into the stack slot allocated by a (where the a -> b stub saved
4548   // a's TOC base pointer). If we're not considering a tail call, but rather,
4549   // whether a nop is needed after the call instruction in b, because the linker
4550   // will insert a stub, it might complain about a missing nop if we omit it
4551   // (although many don't complain in this case).
4552   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4553     return false;
4554 
4555   return true;
4556 }
4557 
4558 static bool
4559 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4560                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4561   assert(Subtarget.is64BitELFABI());
4562 
4563   const unsigned PtrByteSize = 8;
4564   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4565 
4566   static const MCPhysReg GPR[] = {
4567     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4568     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4569   };
4570   static const MCPhysReg VR[] = {
4571     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4572     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4573   };
4574 
4575   const unsigned NumGPRs = array_lengthof(GPR);
4576   const unsigned NumFPRs = 13;
4577   const unsigned NumVRs = array_lengthof(VR);
4578   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4579 
4580   unsigned NumBytes = LinkageSize;
4581   unsigned AvailableFPRs = NumFPRs;
4582   unsigned AvailableVRs = NumVRs;
4583 
4584   for (const ISD::OutputArg& Param : Outs) {
4585     if (Param.Flags.isNest()) continue;
4586 
4587     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4588                                PtrByteSize, LinkageSize, ParamAreaSize,
4589                                NumBytes, AvailableFPRs, AvailableVRs,
4590                                Subtarget.hasQPX()))
4591       return true;
4592   }
4593   return false;
4594 }
4595 
4596 static bool
4597 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4598   if (CS.arg_size() != CallerFn->arg_size())
4599     return false;
4600 
4601   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4602   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4603   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4604 
4605   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4606     const Value* CalleeArg = *CalleeArgIter;
4607     const Value* CallerArg = &(*CallerArgIter);
4608     if (CalleeArg == CallerArg)
4609       continue;
4610 
4611     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4612     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4613     //      }
4614     // 1st argument of callee is undef and has the same type as caller.
4615     if (CalleeArg->getType() == CallerArg->getType() &&
4616         isa<UndefValue>(CalleeArg))
4617       continue;
4618 
4619     return false;
4620   }
4621 
4622   return true;
4623 }
4624 
4625 // Returns true if TCO is possible between the callers and callees
4626 // calling conventions.
4627 static bool
4628 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4629                                     CallingConv::ID CalleeCC) {
4630   // Tail calls are possible with fastcc and ccc.
4631   auto isTailCallableCC  = [] (CallingConv::ID CC){
4632       return  CC == CallingConv::C || CC == CallingConv::Fast;
4633   };
4634   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4635     return false;
4636 
4637   // We can safely tail call both fastcc and ccc callees from a c calling
4638   // convention caller. If the caller is fastcc, we may have less stack space
4639   // than a non-fastcc caller with the same signature so disable tail-calls in
4640   // that case.
4641   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4642 }
4643 
4644 bool
4645 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4646                                     SDValue Callee,
4647                                     CallingConv::ID CalleeCC,
4648                                     ImmutableCallSite CS,
4649                                     bool isVarArg,
4650                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4651                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4652                                     SelectionDAG& DAG) const {
4653   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4654 
4655   if (DisableSCO && !TailCallOpt) return false;
4656 
4657   // Variadic argument functions are not supported.
4658   if (isVarArg) return false;
4659 
4660   auto &Caller = DAG.getMachineFunction().getFunction();
4661   // Check that the calling conventions are compatible for tco.
4662   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4663     return false;
4664 
4665   // Caller contains any byval parameter is not supported.
4666   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4667     return false;
4668 
4669   // Callee contains any byval parameter is not supported, too.
4670   // Note: This is a quick work around, because in some cases, e.g.
4671   // caller's stack size > callee's stack size, we are still able to apply
4672   // sibling call optimization. For example, gcc is able to do SCO for caller1
4673   // in the following example, but not for caller2.
4674   //   struct test {
4675   //     long int a;
4676   //     char ary[56];
4677   //   } gTest;
4678   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4679   //     b->a = v.a;
4680   //     return 0;
4681   //   }
4682   //   void caller1(struct test a, struct test c, struct test *b) {
4683   //     callee(gTest, b); }
4684   //   void caller2(struct test *b) { callee(gTest, b); }
4685   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4686     return false;
4687 
4688   // If callee and caller use different calling conventions, we cannot pass
4689   // parameters on stack since offsets for the parameter area may be different.
4690   if (Caller.getCallingConv() != CalleeCC &&
4691       needStackSlotPassParameters(Subtarget, Outs))
4692     return false;
4693 
4694   // No TCO/SCO on indirect call because Caller have to restore its TOC
4695   if (!isFunctionGlobalAddress(Callee) &&
4696       !isa<ExternalSymbolSDNode>(Callee))
4697     return false;
4698 
4699   // If the caller and callee potentially have different TOC bases then we
4700   // cannot tail call since we need to restore the TOC pointer after the call.
4701   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4702   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4703     return false;
4704 
4705   // TCO allows altering callee ABI, so we don't have to check further.
4706   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4707     return true;
4708 
4709   if (DisableSCO) return false;
4710 
4711   // If callee use the same argument list that caller is using, then we can
4712   // apply SCO on this case. If it is not, then we need to check if callee needs
4713   // stack for passing arguments.
4714   if (!hasSameArgumentList(&Caller, CS) &&
4715       needStackSlotPassParameters(Subtarget, Outs)) {
4716     return false;
4717   }
4718 
4719   return true;
4720 }
4721 
4722 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4723 /// for tail call optimization. Targets which want to do tail call
4724 /// optimization should implement this function.
4725 bool
4726 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4727                                                      CallingConv::ID CalleeCC,
4728                                                      bool isVarArg,
4729                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4730                                                      SelectionDAG& DAG) const {
4731   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4732     return false;
4733 
4734   // Variable argument functions are not supported.
4735   if (isVarArg)
4736     return false;
4737 
4738   MachineFunction &MF = DAG.getMachineFunction();
4739   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4740   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4741     // Functions containing by val parameters are not supported.
4742     for (unsigned i = 0; i != Ins.size(); i++) {
4743        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4744        if (Flags.isByVal()) return false;
4745     }
4746 
4747     // Non-PIC/GOT tail calls are supported.
4748     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4749       return true;
4750 
4751     // At the moment we can only do local tail calls (in same module, hidden
4752     // or protected) if we are generating PIC.
4753     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4754       return G->getGlobal()->hasHiddenVisibility()
4755           || G->getGlobal()->hasProtectedVisibility();
4756   }
4757 
4758   return false;
4759 }
4760 
4761 /// isCallCompatibleAddress - Return the immediate to use if the specified
4762 /// 32-bit value is representable in the immediate field of a BxA instruction.
4763 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4764   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4765   if (!C) return nullptr;
4766 
4767   int Addr = C->getZExtValue();
4768   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4769       SignExtend32<26>(Addr) != Addr)
4770     return nullptr;  // Top 6 bits have to be sext of immediate.
4771 
4772   return DAG
4773       .getConstant(
4774           (int)C->getZExtValue() >> 2, SDLoc(Op),
4775           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4776       .getNode();
4777 }
4778 
4779 namespace {
4780 
4781 struct TailCallArgumentInfo {
4782   SDValue Arg;
4783   SDValue FrameIdxOp;
4784   int FrameIdx = 0;
4785 
4786   TailCallArgumentInfo() = default;
4787 };
4788 
4789 } // end anonymous namespace
4790 
4791 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4792 static void StoreTailCallArgumentsToStackSlot(
4793     SelectionDAG &DAG, SDValue Chain,
4794     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4795     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4796   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4797     SDValue Arg = TailCallArgs[i].Arg;
4798     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4799     int FI = TailCallArgs[i].FrameIdx;
4800     // Store relative to framepointer.
4801     MemOpChains.push_back(DAG.getStore(
4802         Chain, dl, Arg, FIN,
4803         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4804   }
4805 }
4806 
4807 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4808 /// the appropriate stack slot for the tail call optimized function call.
4809 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4810                                              SDValue OldRetAddr, SDValue OldFP,
4811                                              int SPDiff, const SDLoc &dl) {
4812   if (SPDiff) {
4813     // Calculate the new stack slot for the return address.
4814     MachineFunction &MF = DAG.getMachineFunction();
4815     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4816     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4817     bool isPPC64 = Subtarget.isPPC64();
4818     int SlotSize = isPPC64 ? 8 : 4;
4819     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4820     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4821                                                          NewRetAddrLoc, true);
4822     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4823     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4824     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4825                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4826 
4827     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4828     // slot as the FP is never overwritten.
4829     if (Subtarget.isDarwinABI()) {
4830       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4831       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4832                                                          true);
4833       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4834       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4835                            MachinePointerInfo::getFixedStack(
4836                                DAG.getMachineFunction(), NewFPIdx));
4837     }
4838   }
4839   return Chain;
4840 }
4841 
4842 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4843 /// the position of the argument.
4844 static void
4845 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4846                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4847                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4848   int Offset = ArgOffset + SPDiff;
4849   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4850   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4851   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4852   SDValue FIN = DAG.getFrameIndex(FI, VT);
4853   TailCallArgumentInfo Info;
4854   Info.Arg = Arg;
4855   Info.FrameIdxOp = FIN;
4856   Info.FrameIdx = FI;
4857   TailCallArguments.push_back(Info);
4858 }
4859 
4860 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4861 /// stack slot. Returns the chain as result and the loaded frame pointers in
4862 /// LROpOut/FPOpout. Used when tail calling.
4863 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4864     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4865     SDValue &FPOpOut, const SDLoc &dl) const {
4866   if (SPDiff) {
4867     // Load the LR and FP stack slot for later adjusting.
4868     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4869     LROpOut = getReturnAddrFrameIndex(DAG);
4870     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4871     Chain = SDValue(LROpOut.getNode(), 1);
4872 
4873     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4874     // slot as the FP is never overwritten.
4875     if (Subtarget.isDarwinABI()) {
4876       FPOpOut = getFramePointerFrameIndex(DAG);
4877       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4878       Chain = SDValue(FPOpOut.getNode(), 1);
4879     }
4880   }
4881   return Chain;
4882 }
4883 
4884 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4885 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4886 /// specified by the specific parameter attribute. The copy will be passed as
4887 /// a byval function parameter.
4888 /// Sometimes what we are copying is the end of a larger object, the part that
4889 /// does not fit in registers.
4890 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4891                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4892                                          SelectionDAG &DAG, const SDLoc &dl) {
4893   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4894   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4895                        false, false, false, MachinePointerInfo(),
4896                        MachinePointerInfo());
4897 }
4898 
4899 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4900 /// tail calls.
4901 static void LowerMemOpCallTo(
4902     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4903     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4904     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4905     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4906   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4907   if (!isTailCall) {
4908     if (isVector) {
4909       SDValue StackPtr;
4910       if (isPPC64)
4911         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4912       else
4913         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4914       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4915                            DAG.getConstant(ArgOffset, dl, PtrVT));
4916     }
4917     MemOpChains.push_back(
4918         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4919     // Calculate and remember argument location.
4920   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4921                                   TailCallArguments);
4922 }
4923 
4924 static void
4925 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4926                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4927                 SDValue FPOp,
4928                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4929   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4930   // might overwrite each other in case of tail call optimization.
4931   SmallVector<SDValue, 8> MemOpChains2;
4932   // Do not flag preceding copytoreg stuff together with the following stuff.
4933   InFlag = SDValue();
4934   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4935                                     MemOpChains2, dl);
4936   if (!MemOpChains2.empty())
4937     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4938 
4939   // Store the return address to the appropriate stack slot.
4940   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4941 
4942   // Emit callseq_end just before tailcall node.
4943   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4944                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4945   InFlag = Chain.getValue(1);
4946 }
4947 
4948 // Is this global address that of a function that can be called by name? (as
4949 // opposed to something that must hold a descriptor for an indirect call).
4950 static bool isFunctionGlobalAddress(SDValue Callee) {
4951   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4952     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4953         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4954       return false;
4955 
4956     return G->getGlobal()->getValueType()->isFunctionTy();
4957   }
4958 
4959   return false;
4960 }
4961 
4962 SDValue PPCTargetLowering::LowerCallResult(
4963     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4964     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4965     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4966   SmallVector<CCValAssign, 16> RVLocs;
4967   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4968                     *DAG.getContext());
4969 
4970   CCRetInfo.AnalyzeCallResult(
4971       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4972                ? RetCC_PPC_Cold
4973                : RetCC_PPC);
4974 
4975   // Copy all of the result registers out of their specified physreg.
4976   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4977     CCValAssign &VA = RVLocs[i];
4978     assert(VA.isRegLoc() && "Can only return in registers!");
4979 
4980     SDValue Val;
4981 
4982     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
4983       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4984                                       InFlag);
4985       Chain = Lo.getValue(1);
4986       InFlag = Lo.getValue(2);
4987       VA = RVLocs[++i]; // skip ahead to next loc
4988       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
4989                                       InFlag);
4990       Chain = Hi.getValue(1);
4991       InFlag = Hi.getValue(2);
4992       if (!Subtarget.isLittleEndian())
4993         std::swap (Lo, Hi);
4994       Val = DAG.getNode(PPCISD::BUILD_SPE64, dl, MVT::f64, Lo, Hi);
4995     } else {
4996       Val = DAG.getCopyFromReg(Chain, dl,
4997                                VA.getLocReg(), VA.getLocVT(), InFlag);
4998       Chain = Val.getValue(1);
4999       InFlag = Val.getValue(2);
5000     }
5001 
5002     switch (VA.getLocInfo()) {
5003     default: llvm_unreachable("Unknown loc info!");
5004     case CCValAssign::Full: break;
5005     case CCValAssign::AExt:
5006       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5007       break;
5008     case CCValAssign::ZExt:
5009       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
5010                         DAG.getValueType(VA.getValVT()));
5011       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5012       break;
5013     case CCValAssign::SExt:
5014       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5015                         DAG.getValueType(VA.getValVT()));
5016       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5017       break;
5018     }
5019 
5020     InVals.push_back(Val);
5021   }
5022 
5023   return Chain;
5024 }
5025 
5026 static bool isIndirectCall(const SDValue &Callee, SelectionDAG &DAG,
5027                            const PPCSubtarget &Subtarget, bool isPatchPoint) {
5028   // PatchPoint calls are not indirect.
5029   if (isPatchPoint)
5030     return false;
5031 
5032   if (isFunctionGlobalAddress(Callee) || dyn_cast<ExternalSymbolSDNode>(Callee))
5033     return false;
5034 
5035   // Darwin, and 32-bit ELF can use a BLA. The descriptor based ABIs can not
5036   // becuase the immediate function pointer points to a descriptor instead of
5037   // a function entry point. The ELFv2 ABI cannot use a BLA because the function
5038   // pointer immediate points to the global entry point, while the BLA would
5039   // need to jump to the local entry point (see rL211174).
5040   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI() &&
5041       isBLACompatibleAddress(Callee, DAG))
5042     return false;
5043 
5044   return true;
5045 }
5046 
5047 static unsigned getCallOpcode(bool isIndirectCall, bool isPatchPoint,
5048                               bool isTailCall, const Function &Caller,
5049                               const SDValue &Callee,
5050                               const PPCSubtarget &Subtarget,
5051                               const TargetMachine &TM) {
5052   if (isTailCall)
5053     return PPCISD::TC_RETURN;
5054 
5055   // This is a call through a function pointer.
5056   if (isIndirectCall) {
5057     // AIX and the 64-bit ELF ABIs need to maintain the TOC pointer accross
5058     // indirect calls. The save of the caller's TOC pointer to the stack will be
5059     // inserted into the DAG as part of call lowering. The restore of the TOC
5060     // pointer is modeled by using a pseudo instruction for the call opcode that
5061     // represents the 2 instruction sequence of an indirect branch and link,
5062     // immediately followed by a load of the TOC pointer from the the stack save
5063     // slot into gpr2.
5064     if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5065       return PPCISD::BCTRL_LOAD_TOC;
5066 
5067     // An indirect call that does not need a TOC restore.
5068     return PPCISD::BCTRL;
5069   }
5070 
5071   // The ABIs that maintain a TOC pointer accross calls need to have a nop
5072   // immediately following the call instruction if the caller and callee may
5073   // have different TOC bases. At link time if the linker determines the calls
5074   // may not share a TOC base, the call is redirected to a trampoline inserted
5075   // by the linker. The trampoline will (among other things) save the callers
5076   // TOC pointer at an ABI designated offset in the linkage area and the linker
5077   // will rewrite the nop to be a load of the TOC pointer from the linkage area
5078   // into gpr2.
5079   if (Subtarget.isAIXABI() || Subtarget.is64BitELFABI())
5080     return callsShareTOCBase(&Caller, Callee, TM) ? PPCISD::CALL
5081                                                   : PPCISD::CALL_NOP;
5082 
5083   return PPCISD::CALL;
5084 }
5085 static SDValue transformCallee(const SDValue &Callee, SelectionDAG &DAG,
5086                                const SDLoc &dl, const PPCSubtarget &Subtarget) {
5087   if (!Subtarget.usesFunctionDescriptors() && !Subtarget.isELFv2ABI())
5088     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG))
5089       return SDValue(Dest, 0);
5090 
5091   // Returns true if the callee is local, and false otherwise.
5092   auto isLocalCallee = [&]() {
5093     const GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
5094     const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
5095 
5096     return DAG.getTarget().shouldAssumeDSOLocal(*Mod,
5097                                                 G ? G->getGlobal() : nullptr);
5098   };
5099 
5100   bool UsePlt = Subtarget.is32BitELFABI() && !isLocalCallee();
5101 
5102   if (isFunctionGlobalAddress(Callee)) {
5103     const GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
5104     if (!Subtarget.isAIXABI())
5105       return DAG.getTargetGlobalAddress(G->getGlobal(), dl,
5106                                         Callee.getValueType(), 0,
5107                                         UsePlt ? PPCII::MO_PLT : 0);
5108 
5109     // On AIX, direct function calls reference the symbol for the function's
5110     // entry point, which is named by prepending a "." before the function's
5111     // C-linkage name.
5112     auto &Context = DAG.getMachineFunction().getMMI().getContext();
5113 
5114     const GlobalObject *GO = cast<GlobalObject>(G->getGlobal());
5115     MCSymbolXCOFF *S = cast<MCSymbolXCOFF>(
5116         Context.getOrCreateSymbol(Twine(".") + Twine(GO->getName())));
5117 
5118     if (GO && GO->isDeclaration() && !S->hasContainingCsect()) {
5119       // On AIX, an undefined symbol needs to be associated with a
5120       // MCSectionXCOFF to get the correct storage mapping class.
5121       // In this case, XCOFF::XMC_PR.
5122       const XCOFF::StorageClass SC =
5123           TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO);
5124       MCSectionXCOFF *Sec =
5125           Context.getXCOFFSection(S->getName(), XCOFF::XMC_PR, XCOFF::XTY_ER,
5126                                   SC, SectionKind::getMetadata());
5127       S->setContainingCsect(Sec);
5128     }
5129 
5130     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
5131     return DAG.getMCSymbol(S, PtrVT);
5132   }
5133 
5134   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
5135     return DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
5136                                        UsePlt ? PPCII::MO_PLT : 0);
5137 
5138   // No transformation needed.
5139   assert(Callee.getNode() && "What no callee?");
5140   return Callee;
5141 }
5142 
5143 static SDValue getOutputChainFromCallSeq(SDValue CallSeqStart) {
5144   assert(CallSeqStart.getOpcode() == ISD::CALLSEQ_START &&
5145          "Expected a CALLSEQ_STARTSDNode.");
5146 
5147   // The last operand is the chain, except when the node has glue. If the node
5148   // has glue, then the last operand is the glue, and the chain is the second
5149   // last operand.
5150   SDValue LastValue = CallSeqStart.getValue(CallSeqStart->getNumValues() - 1);
5151   if (LastValue.getValueType() != MVT::Glue)
5152     return LastValue;
5153 
5154   return CallSeqStart.getValue(CallSeqStart->getNumValues() - 2);
5155 }
5156 
5157 // Creates the node that moves a functions address into the count register
5158 // to prepare for an indirect call instruction.
5159 static void prepareIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5160                                 SDValue &Glue, SDValue &Chain,
5161                                 const SDLoc &dl) {
5162   SDValue MTCTROps[] = {Chain, Callee, Glue};
5163   EVT ReturnTypes[] = {MVT::Other, MVT::Glue};
5164   Chain = DAG.getNode(PPCISD::MTCTR, dl, makeArrayRef(ReturnTypes, 2),
5165                       makeArrayRef(MTCTROps, Glue.getNode() ? 3 : 2));
5166   // The glue is the second value produced.
5167   Glue = Chain.getValue(1);
5168 }
5169 
5170 static void prepareDescriptorIndirectCall(SelectionDAG &DAG, SDValue &Callee,
5171                                           SDValue &Glue, SDValue &Chain,
5172                                           SDValue CallSeqStart,
5173                                           ImmutableCallSite CS, const SDLoc &dl,
5174                                           bool hasNest,
5175                                           const PPCSubtarget &Subtarget) {
5176   // Function pointers in the 64-bit SVR4 ABI do not point to the function
5177   // entry point, but to the function descriptor (the function entry point
5178   // address is part of the function descriptor though).
5179   // The function descriptor is a three doubleword structure with the
5180   // following fields: function entry point, TOC base address and
5181   // environment pointer.
5182   // Thus for a call through a function pointer, the following actions need
5183   // to be performed:
5184   //   1. Save the TOC of the caller in the TOC save area of its stack
5185   //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
5186   //   2. Load the address of the function entry point from the function
5187   //      descriptor.
5188   //   3. Load the TOC of the callee from the function descriptor into r2.
5189   //   4. Load the environment pointer from the function descriptor into
5190   //      r11.
5191   //   5. Branch to the function entry point address.
5192   //   6. On return of the callee, the TOC of the caller needs to be
5193   //      restored (this is done in FinishCall()).
5194   //
5195   // The loads are scheduled at the beginning of the call sequence, and the
5196   // register copies are flagged together to ensure that no other
5197   // operations can be scheduled in between. E.g. without flagging the
5198   // copies together, a TOC access in the caller could be scheduled between
5199   // the assignment of the callee TOC and the branch to the callee, which leads
5200   // to incorrect code.
5201 
5202   // Start by loading the function address from the descriptor.
5203   SDValue LDChain = getOutputChainFromCallSeq(CallSeqStart);
5204   auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
5205                       ? (MachineMemOperand::MODereferenceable |
5206                          MachineMemOperand::MOInvariant)
5207                       : MachineMemOperand::MONone;
5208 
5209   MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
5210 
5211   // One load for the functions entry point address.
5212   SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
5213                                     /* Alignment = */ 8, MMOFlags);
5214 
5215   // One for loading the TOC anchor for the module that contains the called
5216   // function.
5217   SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
5218   SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
5219   SDValue TOCPtr =
5220       DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
5221                   /* Alignment = */ 8, MMOFlags);
5222 
5223   // One for loading the environment pointer.
5224   SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
5225   SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
5226   SDValue LoadEnvPtr =
5227       DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
5228                   /* Alignment = */ 8, MMOFlags);
5229 
5230   // Then copy the newly loaded TOC anchor to the TOC pointer.
5231   SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr, Glue);
5232   Chain = TOCVal.getValue(0);
5233   Glue = TOCVal.getValue(1);
5234 
5235   // If the function call has an explicit 'nest' parameter, it takes the
5236   // place of the environment pointer.
5237   if (!hasNest) {
5238     SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr, Glue);
5239     Chain = EnvVal.getValue(0);
5240     Glue = EnvVal.getValue(1);
5241   }
5242 
5243   // The rest of the indirect call sequence is the same as the non-descriptor
5244   // DAG.
5245   prepareIndirectCall(DAG, LoadFuncPtr, Glue, Chain, dl);
5246 }
5247 
5248 static void
5249 buildCallOperands(SmallVectorImpl<SDValue> &Ops, CallingConv::ID CallConv,
5250                   const SDLoc &dl, bool isTailCall, bool isVarArg,
5251                   bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5252                   SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
5253                   SDValue Glue, SDValue Chain, SDValue &Callee, int SPDiff,
5254                   const PPCSubtarget &Subtarget, bool isIndirect) {
5255   const bool IsPPC64 = Subtarget.isPPC64();
5256   // MVT for a general purpose register.
5257   const MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
5258 
5259   // First operand is always the chain.
5260   Ops.push_back(Chain);
5261 
5262   // If it's a direct call pass the callee as the second operand.
5263   if (!isIndirect)
5264     Ops.push_back(Callee);
5265   else {
5266     assert(!isPatchPoint && "Patch point call are not indirect.");
5267     if (Subtarget.isAIXABI())
5268       report_fatal_error("Indirect call on AIX is not implemented.");
5269 
5270     // For 64-bit ELF we have saved the TOC pointer to the linkage area on the
5271     // stack (this would have  been done in `LowerCall_64SVR4`). The call
5272     // instruction is a pseudo instruction that represents both the indirect
5273     // branch and a load that restores the TOC pointer from the linkage area.
5274     // The operand for the TOC restore is an add of the TOC save offset to the
5275     // stack pointer. This must be the second operand: after the chain input but
5276     // before any other variadic arguments.
5277     if (Subtarget.is64BitELFABI()) {
5278       SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5279       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5280       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5281       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5282       Ops.push_back(AddTOC);
5283     }
5284 
5285     // Add the register used for the environment pointer.
5286     if (Subtarget.usesFunctionDescriptors() && !hasNest)
5287       Ops.push_back(DAG.getRegister(PPC::X11, MVT::i64));
5288 
5289     // Add CTR register as callee so a bctr can be emitted later.
5290     if (isTailCall)
5291       Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::CTR8 : PPC::CTR, RegVT));
5292   }
5293 
5294   // If this is a tail call add stack pointer delta.
5295   if (isTailCall)
5296     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
5297 
5298   // Add argument registers to the end of the list so that they are known live
5299   // into the call.
5300   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
5301     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
5302                                   RegsToPass[i].second.getValueType()));
5303 
5304   // We cannot add R2/X2 as an operand here for PATCHPOINT, because there is
5305   // no way to mark dependencies as implicit here.
5306   // We will add the R2/X2 dependency in EmitInstrWithCustomInserter.
5307   if ((Subtarget.is64BitELFABI() || Subtarget.isAIXABI()) && !isPatchPoint)
5308     Ops.push_back(DAG.getRegister(IsPPC64 ? PPC::X2 : PPC::R2, RegVT));
5309 
5310   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5311   if (isVarArg && Subtarget.is32BitELFABI())
5312     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5313 
5314   // Add a register mask operand representing the call-preserved registers.
5315   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5316   const uint32_t *Mask =
5317       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5318   assert(Mask && "Missing call preserved mask for calling convention");
5319   Ops.push_back(DAG.getRegisterMask(Mask));
5320 
5321   // If the glue is valid, it is the last operand.
5322   if (Glue.getNode())
5323     Ops.push_back(Glue);
5324 }
5325 
5326 SDValue PPCTargetLowering::FinishCall(
5327     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5328     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5329     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue Glue,
5330     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5331     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5332     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5333 
5334   if (Subtarget.is64BitELFABI() || Subtarget.isAIXABI())
5335     setUsesTOCBasePtr(DAG);
5336 
5337   const bool isIndirect = isIndirectCall(Callee, DAG, Subtarget, isPatchPoint);
5338   unsigned CallOpc = getCallOpcode(isIndirect, isPatchPoint, isTailCall,
5339                                    DAG.getMachineFunction().getFunction(),
5340                                    Callee, Subtarget, DAG.getTarget());
5341 
5342   if (!isIndirect)
5343     Callee = transformCallee(Callee, DAG, dl, Subtarget);
5344   else if (Subtarget.usesFunctionDescriptors())
5345     prepareDescriptorIndirectCall(DAG, Callee, Glue, Chain, CallSeqStart, CS,
5346                                   dl, hasNest, Subtarget);
5347   else
5348     prepareIndirectCall(DAG, Callee, Glue, Chain, dl);
5349 
5350   // Build the operand list for the call instruction.
5351   SmallVector<SDValue, 8> Ops;
5352   buildCallOperands(Ops, CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5353                     hasNest, DAG, RegsToPass, Glue, Chain, Callee, SPDiff,
5354                     Subtarget, isIndirect);
5355 
5356   // Emit tail call.
5357   if (isTailCall) {
5358     assert(((Callee.getOpcode() == ISD::Register &&
5359              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5360             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5361             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5362             isa<ConstantSDNode>(Callee)) &&
5363            "Expecting a global address, external symbol, absolute value or "
5364            "register");
5365     assert(CallOpc == PPCISD::TC_RETURN &&
5366            "Unexpected call opcode for a tail call.");
5367     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5368     return DAG.getNode(CallOpc, dl, MVT::Other, Ops);
5369   }
5370 
5371   std::array<EVT, 2> ReturnTypes = {MVT::Other, MVT::Glue};
5372   Chain = DAG.getNode(CallOpc, dl, ReturnTypes, Ops);
5373   Glue = Chain.getValue(1);
5374 
5375   // When performing tail call optimization the callee pops its arguments off
5376   // the stack. Account for this here so these bytes can be pushed back on in
5377   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5378   int BytesCalleePops = (CallConv == CallingConv::Fast &&
5379                          getTargetMachine().Options.GuaranteedTailCallOpt)
5380                             ? NumBytes
5381                             : 0;
5382 
5383   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5384                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5385                              Glue, dl);
5386   Glue = Chain.getValue(1);
5387 
5388   return LowerCallResult(Chain, Glue, CallConv, isVarArg, Ins, dl, DAG, InVals);
5389 }
5390 
5391 SDValue
5392 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5393                              SmallVectorImpl<SDValue> &InVals) const {
5394   SelectionDAG &DAG                     = CLI.DAG;
5395   SDLoc &dl                             = CLI.DL;
5396   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5397   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5398   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5399   SDValue Chain                         = CLI.Chain;
5400   SDValue Callee                        = CLI.Callee;
5401   bool &isTailCall                      = CLI.IsTailCall;
5402   CallingConv::ID CallConv              = CLI.CallConv;
5403   bool isVarArg                         = CLI.IsVarArg;
5404   bool isPatchPoint                     = CLI.IsPatchPoint;
5405   ImmutableCallSite CS                  = CLI.CS;
5406 
5407   if (isTailCall) {
5408     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5409       isTailCall = false;
5410     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5411       isTailCall =
5412         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5413                                                  isVarArg, Outs, Ins, DAG);
5414     else
5415       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5416                                                      Ins, DAG);
5417     if (isTailCall) {
5418       ++NumTailCalls;
5419       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5420         ++NumSiblingCalls;
5421 
5422       assert(isa<GlobalAddressSDNode>(Callee) &&
5423              "Callee should be an llvm::Function object.");
5424       LLVM_DEBUG(
5425           const GlobalValue *GV =
5426               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5427           const unsigned Width =
5428               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5429           dbgs() << "TCO caller: "
5430                  << left_justify(DAG.getMachineFunction().getName(), Width)
5431                  << ", callee linkage: " << GV->getVisibility() << ", "
5432                  << GV->getLinkage() << "\n");
5433     }
5434   }
5435 
5436   if (!isTailCall && CS && CS.isMustTailCall())
5437     report_fatal_error("failed to perform tail call elimination on a call "
5438                        "site marked musttail");
5439 
5440   // When long calls (i.e. indirect calls) are always used, calls are always
5441   // made via function pointer. If we have a function name, first translate it
5442   // into a pointer.
5443   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5444       !isTailCall)
5445     Callee = LowerGlobalAddress(Callee, DAG);
5446 
5447   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5448     return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5449                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5450                             dl, DAG, InVals, CS);
5451 
5452   if (Subtarget.isSVR4ABI())
5453     return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5454                             isTailCall, isPatchPoint, Outs, OutVals, Ins,
5455                             dl, DAG, InVals, CS);
5456 
5457   if (Subtarget.isAIXABI())
5458     return LowerCall_AIX(Chain, Callee, CallConv, isVarArg,
5459                          isTailCall, isPatchPoint, Outs, OutVals, Ins,
5460                          dl, DAG, InVals, CS);
5461 
5462   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5463                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5464                           dl, DAG, InVals, CS);
5465 }
5466 
5467 SDValue PPCTargetLowering::LowerCall_32SVR4(
5468     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5469     bool isTailCall, bool isPatchPoint,
5470     const SmallVectorImpl<ISD::OutputArg> &Outs,
5471     const SmallVectorImpl<SDValue> &OutVals,
5472     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5473     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5474     ImmutableCallSite CS) const {
5475   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5476   // of the 32-bit SVR4 ABI stack frame layout.
5477 
5478   assert((CallConv == CallingConv::C ||
5479           CallConv == CallingConv::Cold ||
5480           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5481 
5482   unsigned PtrByteSize = 4;
5483 
5484   MachineFunction &MF = DAG.getMachineFunction();
5485 
5486   // Mark this function as potentially containing a function that contains a
5487   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5488   // and restoring the callers stack pointer in this functions epilog. This is
5489   // done because by tail calling the called function might overwrite the value
5490   // in this function's (MF) stack pointer stack slot 0(SP).
5491   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5492       CallConv == CallingConv::Fast)
5493     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5494 
5495   // Count how many bytes are to be pushed on the stack, including the linkage
5496   // area, parameter list area and the part of the local variable space which
5497   // contains copies of aggregates which are passed by value.
5498 
5499   // Assign locations to all of the outgoing arguments.
5500   SmallVector<CCValAssign, 16> ArgLocs;
5501   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5502 
5503   // Reserve space for the linkage area on the stack.
5504   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5505                        PtrByteSize);
5506   if (useSoftFloat())
5507     CCInfo.PreAnalyzeCallOperands(Outs);
5508 
5509   if (isVarArg) {
5510     // Handle fixed and variable vector arguments differently.
5511     // Fixed vector arguments go into registers as long as registers are
5512     // available. Variable vector arguments always go into memory.
5513     unsigned NumArgs = Outs.size();
5514 
5515     for (unsigned i = 0; i != NumArgs; ++i) {
5516       MVT ArgVT = Outs[i].VT;
5517       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5518       bool Result;
5519 
5520       if (Outs[i].IsFixed) {
5521         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5522                                CCInfo);
5523       } else {
5524         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5525                                       ArgFlags, CCInfo);
5526       }
5527 
5528       if (Result) {
5529 #ifndef NDEBUG
5530         errs() << "Call operand #" << i << " has unhandled type "
5531              << EVT(ArgVT).getEVTString() << "\n";
5532 #endif
5533         llvm_unreachable(nullptr);
5534       }
5535     }
5536   } else {
5537     // All arguments are treated the same.
5538     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5539   }
5540   CCInfo.clearWasPPCF128();
5541 
5542   // Assign locations to all of the outgoing aggregate by value arguments.
5543   SmallVector<CCValAssign, 16> ByValArgLocs;
5544   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5545 
5546   // Reserve stack space for the allocations in CCInfo.
5547   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5548 
5549   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5550 
5551   // Size of the linkage area, parameter list area and the part of the local
5552   // space variable where copies of aggregates which are passed by value are
5553   // stored.
5554   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5555 
5556   // Calculate by how many bytes the stack has to be adjusted in case of tail
5557   // call optimization.
5558   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5559 
5560   // Adjust the stack pointer for the new arguments...
5561   // These operations are automatically eliminated by the prolog/epilog pass
5562   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5563   SDValue CallSeqStart = Chain;
5564 
5565   // Load the return address and frame pointer so it can be moved somewhere else
5566   // later.
5567   SDValue LROp, FPOp;
5568   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5569 
5570   // Set up a copy of the stack pointer for use loading and storing any
5571   // arguments that may not fit in the registers available for argument
5572   // passing.
5573   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5574 
5575   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5576   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5577   SmallVector<SDValue, 8> MemOpChains;
5578 
5579   bool seenFloatArg = false;
5580   // Walk the register/memloc assignments, inserting copies/loads.
5581   // i - Tracks the index into the list of registers allocated for the call
5582   // RealArgIdx - Tracks the index into the list of actual function arguments
5583   // j - Tracks the index into the list of byval arguments
5584   for (unsigned i = 0, RealArgIdx = 0, j = 0, e = ArgLocs.size();
5585        i != e;
5586        ++i, ++RealArgIdx) {
5587     CCValAssign &VA = ArgLocs[i];
5588     SDValue Arg = OutVals[RealArgIdx];
5589     ISD::ArgFlagsTy Flags = Outs[RealArgIdx].Flags;
5590 
5591     if (Flags.isByVal()) {
5592       // Argument is an aggregate which is passed by value, thus we need to
5593       // create a copy of it in the local variable space of the current stack
5594       // frame (which is the stack frame of the caller) and pass the address of
5595       // this copy to the callee.
5596       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5597       CCValAssign &ByValVA = ByValArgLocs[j++];
5598       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5599 
5600       // Memory reserved in the local variable space of the callers stack frame.
5601       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5602 
5603       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5604       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5605                            StackPtr, PtrOff);
5606 
5607       // Create a copy of the argument in the local area of the current
5608       // stack frame.
5609       SDValue MemcpyCall =
5610         CreateCopyOfByValArgument(Arg, PtrOff,
5611                                   CallSeqStart.getNode()->getOperand(0),
5612                                   Flags, DAG, dl);
5613 
5614       // This must go outside the CALLSEQ_START..END.
5615       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5616                                                      SDLoc(MemcpyCall));
5617       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5618                              NewCallSeqStart.getNode());
5619       Chain = CallSeqStart = NewCallSeqStart;
5620 
5621       // Pass the address of the aggregate copy on the stack either in a
5622       // physical register or in the parameter list area of the current stack
5623       // frame to the callee.
5624       Arg = PtrOff;
5625     }
5626 
5627     // When useCRBits() is true, there can be i1 arguments.
5628     // It is because getRegisterType(MVT::i1) => MVT::i1,
5629     // and for other integer types getRegisterType() => MVT::i32.
5630     // Extend i1 and ensure callee will get i32.
5631     if (Arg.getValueType() == MVT::i1)
5632       Arg = DAG.getNode(Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
5633                         dl, MVT::i32, Arg);
5634 
5635     if (VA.isRegLoc()) {
5636       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5637       // Put argument in a physical register.
5638       if (Subtarget.hasSPE() && Arg.getValueType() == MVT::f64) {
5639         bool IsLE = Subtarget.isLittleEndian();
5640         SDValue SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5641                         DAG.getIntPtrConstant(IsLE ? 0 : 1, dl));
5642         RegsToPass.push_back(std::make_pair(VA.getLocReg(), SVal.getValue(0)));
5643         SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
5644                            DAG.getIntPtrConstant(IsLE ? 1 : 0, dl));
5645         RegsToPass.push_back(std::make_pair(ArgLocs[++i].getLocReg(),
5646                              SVal.getValue(0)));
5647       } else
5648         RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5649     } else {
5650       // Put argument in the parameter list area of the current stack frame.
5651       assert(VA.isMemLoc());
5652       unsigned LocMemOffset = VA.getLocMemOffset();
5653 
5654       if (!isTailCall) {
5655         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5656         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5657                              StackPtr, PtrOff);
5658 
5659         MemOpChains.push_back(
5660             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5661       } else {
5662         // Calculate and remember argument location.
5663         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5664                                  TailCallArguments);
5665       }
5666     }
5667   }
5668 
5669   if (!MemOpChains.empty())
5670     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5671 
5672   // Build a sequence of copy-to-reg nodes chained together with token chain
5673   // and flag operands which copy the outgoing args into the appropriate regs.
5674   SDValue InFlag;
5675   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5676     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5677                              RegsToPass[i].second, InFlag);
5678     InFlag = Chain.getValue(1);
5679   }
5680 
5681   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5682   // registers.
5683   if (isVarArg) {
5684     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5685     SDValue Ops[] = { Chain, InFlag };
5686 
5687     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5688                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5689 
5690     InFlag = Chain.getValue(1);
5691   }
5692 
5693   if (isTailCall)
5694     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5695                     TailCallArguments);
5696 
5697   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5698                     /* unused except on PPC64 ELFv1 */ false, DAG,
5699                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5700                     NumBytes, Ins, InVals, CS);
5701 }
5702 
5703 // Copy an argument into memory, being careful to do this outside the
5704 // call sequence for the call to which the argument belongs.
5705 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5706     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5707     SelectionDAG &DAG, const SDLoc &dl) const {
5708   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5709                         CallSeqStart.getNode()->getOperand(0),
5710                         Flags, DAG, dl);
5711   // The MEMCPY must go outside the CALLSEQ_START..END.
5712   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5713   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5714                                                  SDLoc(MemcpyCall));
5715   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5716                          NewCallSeqStart.getNode());
5717   return NewCallSeqStart;
5718 }
5719 
5720 SDValue PPCTargetLowering::LowerCall_64SVR4(
5721     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5722     bool isTailCall, bool isPatchPoint,
5723     const SmallVectorImpl<ISD::OutputArg> &Outs,
5724     const SmallVectorImpl<SDValue> &OutVals,
5725     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5726     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5727     ImmutableCallSite CS) const {
5728   bool isELFv2ABI = Subtarget.isELFv2ABI();
5729   bool isLittleEndian = Subtarget.isLittleEndian();
5730   unsigned NumOps = Outs.size();
5731   bool hasNest = false;
5732   bool IsSibCall = false;
5733 
5734   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5735   unsigned PtrByteSize = 8;
5736 
5737   MachineFunction &MF = DAG.getMachineFunction();
5738 
5739   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5740     IsSibCall = true;
5741 
5742   // Mark this function as potentially containing a function that contains a
5743   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5744   // and restoring the callers stack pointer in this functions epilog. This is
5745   // done because by tail calling the called function might overwrite the value
5746   // in this function's (MF) stack pointer stack slot 0(SP).
5747   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5748       CallConv == CallingConv::Fast)
5749     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5750 
5751   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5752          "fastcc not supported on varargs functions");
5753 
5754   // Count how many bytes are to be pushed on the stack, including the linkage
5755   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5756   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5757   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5758   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5759   unsigned NumBytes = LinkageSize;
5760   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5761   unsigned &QFPR_idx = FPR_idx;
5762 
5763   static const MCPhysReg GPR[] = {
5764     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5765     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5766   };
5767   static const MCPhysReg VR[] = {
5768     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5769     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5770   };
5771 
5772   const unsigned NumGPRs = array_lengthof(GPR);
5773   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5774   const unsigned NumVRs  = array_lengthof(VR);
5775   const unsigned NumQFPRs = NumFPRs;
5776 
5777   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5778   // can be passed to the callee in registers.
5779   // For the fast calling convention, there is another check below.
5780   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5781   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5782   if (!HasParameterArea) {
5783     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5784     unsigned AvailableFPRs = NumFPRs;
5785     unsigned AvailableVRs = NumVRs;
5786     unsigned NumBytesTmp = NumBytes;
5787     for (unsigned i = 0; i != NumOps; ++i) {
5788       if (Outs[i].Flags.isNest()) continue;
5789       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5790                                 PtrByteSize, LinkageSize, ParamAreaSize,
5791                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5792                                 Subtarget.hasQPX()))
5793         HasParameterArea = true;
5794     }
5795   }
5796 
5797   // When using the fast calling convention, we don't provide backing for
5798   // arguments that will be in registers.
5799   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5800 
5801   // Avoid allocating parameter area for fastcc functions if all the arguments
5802   // can be passed in the registers.
5803   if (CallConv == CallingConv::Fast)
5804     HasParameterArea = false;
5805 
5806   // Add up all the space actually used.
5807   for (unsigned i = 0; i != NumOps; ++i) {
5808     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5809     EVT ArgVT = Outs[i].VT;
5810     EVT OrigVT = Outs[i].ArgVT;
5811 
5812     if (Flags.isNest())
5813       continue;
5814 
5815     if (CallConv == CallingConv::Fast) {
5816       if (Flags.isByVal()) {
5817         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5818         if (NumGPRsUsed > NumGPRs)
5819           HasParameterArea = true;
5820       } else {
5821         switch (ArgVT.getSimpleVT().SimpleTy) {
5822         default: llvm_unreachable("Unexpected ValueType for argument!");
5823         case MVT::i1:
5824         case MVT::i32:
5825         case MVT::i64:
5826           if (++NumGPRsUsed <= NumGPRs)
5827             continue;
5828           break;
5829         case MVT::v4i32:
5830         case MVT::v8i16:
5831         case MVT::v16i8:
5832         case MVT::v2f64:
5833         case MVT::v2i64:
5834         case MVT::v1i128:
5835         case MVT::f128:
5836           if (++NumVRsUsed <= NumVRs)
5837             continue;
5838           break;
5839         case MVT::v4f32:
5840           // When using QPX, this is handled like a FP register, otherwise, it
5841           // is an Altivec register.
5842           if (Subtarget.hasQPX()) {
5843             if (++NumFPRsUsed <= NumFPRs)
5844               continue;
5845           } else {
5846             if (++NumVRsUsed <= NumVRs)
5847               continue;
5848           }
5849           break;
5850         case MVT::f32:
5851         case MVT::f64:
5852         case MVT::v4f64: // QPX
5853         case MVT::v4i1:  // QPX
5854           if (++NumFPRsUsed <= NumFPRs)
5855             continue;
5856           break;
5857         }
5858         HasParameterArea = true;
5859       }
5860     }
5861 
5862     /* Respect alignment of argument on the stack.  */
5863     unsigned Align =
5864       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5865     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5866 
5867     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5868     if (Flags.isInConsecutiveRegsLast())
5869       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5870   }
5871 
5872   unsigned NumBytesActuallyUsed = NumBytes;
5873 
5874   // In the old ELFv1 ABI,
5875   // the prolog code of the callee may store up to 8 GPR argument registers to
5876   // the stack, allowing va_start to index over them in memory if its varargs.
5877   // Because we cannot tell if this is needed on the caller side, we have to
5878   // conservatively assume that it is needed.  As such, make sure we have at
5879   // least enough stack space for the caller to store the 8 GPRs.
5880   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5881   // really requires memory operands, e.g. a vararg function.
5882   if (HasParameterArea)
5883     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5884   else
5885     NumBytes = LinkageSize;
5886 
5887   // Tail call needs the stack to be aligned.
5888   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5889       CallConv == CallingConv::Fast)
5890     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5891 
5892   int SPDiff = 0;
5893 
5894   // Calculate by how many bytes the stack has to be adjusted in case of tail
5895   // call optimization.
5896   if (!IsSibCall)
5897     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5898 
5899   // To protect arguments on the stack from being clobbered in a tail call,
5900   // force all the loads to happen before doing any other lowering.
5901   if (isTailCall)
5902     Chain = DAG.getStackArgumentTokenFactor(Chain);
5903 
5904   // Adjust the stack pointer for the new arguments...
5905   // These operations are automatically eliminated by the prolog/epilog pass
5906   if (!IsSibCall)
5907     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5908   SDValue CallSeqStart = Chain;
5909 
5910   // Load the return address and frame pointer so it can be move somewhere else
5911   // later.
5912   SDValue LROp, FPOp;
5913   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5914 
5915   // Set up a copy of the stack pointer for use loading and storing any
5916   // arguments that may not fit in the registers available for argument
5917   // passing.
5918   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5919 
5920   // Figure out which arguments are going to go in registers, and which in
5921   // memory.  Also, if this is a vararg function, floating point operations
5922   // must be stored to our stack, and loaded into integer regs as well, if
5923   // any integer regs are available for argument passing.
5924   unsigned ArgOffset = LinkageSize;
5925 
5926   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5927   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5928 
5929   SmallVector<SDValue, 8> MemOpChains;
5930   for (unsigned i = 0; i != NumOps; ++i) {
5931     SDValue Arg = OutVals[i];
5932     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5933     EVT ArgVT = Outs[i].VT;
5934     EVT OrigVT = Outs[i].ArgVT;
5935 
5936     // PtrOff will be used to store the current argument to the stack if a
5937     // register cannot be found for it.
5938     SDValue PtrOff;
5939 
5940     // We re-align the argument offset for each argument, except when using the
5941     // fast calling convention, when we need to make sure we do that only when
5942     // we'll actually use a stack slot.
5943     auto ComputePtrOff = [&]() {
5944       /* Respect alignment of argument on the stack.  */
5945       unsigned Align =
5946         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5947       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5948 
5949       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5950 
5951       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5952     };
5953 
5954     if (CallConv != CallingConv::Fast) {
5955       ComputePtrOff();
5956 
5957       /* Compute GPR index associated with argument offset.  */
5958       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5959       GPR_idx = std::min(GPR_idx, NumGPRs);
5960     }
5961 
5962     // Promote integers to 64-bit values.
5963     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5964       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5965       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5966       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5967     }
5968 
5969     // FIXME memcpy is used way more than necessary.  Correctness first.
5970     // Note: "by value" is code for passing a structure by value, not
5971     // basic types.
5972     if (Flags.isByVal()) {
5973       // Note: Size includes alignment padding, so
5974       //   struct x { short a; char b; }
5975       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5976       // These are the proper values we need for right-justifying the
5977       // aggregate in a parameter register.
5978       unsigned Size = Flags.getByValSize();
5979 
5980       // An empty aggregate parameter takes up no storage and no
5981       // registers.
5982       if (Size == 0)
5983         continue;
5984 
5985       if (CallConv == CallingConv::Fast)
5986         ComputePtrOff();
5987 
5988       // All aggregates smaller than 8 bytes must be passed right-justified.
5989       if (Size==1 || Size==2 || Size==4) {
5990         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5991         if (GPR_idx != NumGPRs) {
5992           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5993                                         MachinePointerInfo(), VT);
5994           MemOpChains.push_back(Load.getValue(1));
5995           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5996 
5997           ArgOffset += PtrByteSize;
5998           continue;
5999         }
6000       }
6001 
6002       if (GPR_idx == NumGPRs && Size < 8) {
6003         SDValue AddPtr = PtrOff;
6004         if (!isLittleEndian) {
6005           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6006                                           PtrOff.getValueType());
6007           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6008         }
6009         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6010                                                           CallSeqStart,
6011                                                           Flags, DAG, dl);
6012         ArgOffset += PtrByteSize;
6013         continue;
6014       }
6015       // Copy entire object into memory.  There are cases where gcc-generated
6016       // code assumes it is there, even if it could be put entirely into
6017       // registers.  (This is not what the doc says.)
6018 
6019       // FIXME: The above statement is likely due to a misunderstanding of the
6020       // documents.  All arguments must be copied into the parameter area BY
6021       // THE CALLEE in the event that the callee takes the address of any
6022       // formal argument.  That has not yet been implemented.  However, it is
6023       // reasonable to use the stack area as a staging area for the register
6024       // load.
6025 
6026       // Skip this for small aggregates, as we will use the same slot for a
6027       // right-justified copy, below.
6028       if (Size >= 8)
6029         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6030                                                           CallSeqStart,
6031                                                           Flags, DAG, dl);
6032 
6033       // When a register is available, pass a small aggregate right-justified.
6034       if (Size < 8 && GPR_idx != NumGPRs) {
6035         // The easiest way to get this right-justified in a register
6036         // is to copy the structure into the rightmost portion of a
6037         // local variable slot, then load the whole slot into the
6038         // register.
6039         // FIXME: The memcpy seems to produce pretty awful code for
6040         // small aggregates, particularly for packed ones.
6041         // FIXME: It would be preferable to use the slot in the
6042         // parameter save area instead of a new local variable.
6043         SDValue AddPtr = PtrOff;
6044         if (!isLittleEndian) {
6045           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
6046           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6047         }
6048         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6049                                                           CallSeqStart,
6050                                                           Flags, DAG, dl);
6051 
6052         // Load the slot into the register.
6053         SDValue Load =
6054             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
6055         MemOpChains.push_back(Load.getValue(1));
6056         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6057 
6058         // Done with this argument.
6059         ArgOffset += PtrByteSize;
6060         continue;
6061       }
6062 
6063       // For aggregates larger than PtrByteSize, copy the pieces of the
6064       // object that fit into registers from the parameter save area.
6065       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6066         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6067         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6068         if (GPR_idx != NumGPRs) {
6069           SDValue Load =
6070               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6071           MemOpChains.push_back(Load.getValue(1));
6072           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6073           ArgOffset += PtrByteSize;
6074         } else {
6075           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6076           break;
6077         }
6078       }
6079       continue;
6080     }
6081 
6082     switch (Arg.getSimpleValueType().SimpleTy) {
6083     default: llvm_unreachable("Unexpected ValueType for argument!");
6084     case MVT::i1:
6085     case MVT::i32:
6086     case MVT::i64:
6087       if (Flags.isNest()) {
6088         // The 'nest' parameter, if any, is passed in R11.
6089         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
6090         hasNest = true;
6091         break;
6092       }
6093 
6094       // These can be scalar arguments or elements of an integer array type
6095       // passed directly.  Clang may use those instead of "byval" aggregate
6096       // types to avoid forcing arguments to memory unnecessarily.
6097       if (GPR_idx != NumGPRs) {
6098         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6099       } else {
6100         if (CallConv == CallingConv::Fast)
6101           ComputePtrOff();
6102 
6103         assert(HasParameterArea &&
6104                "Parameter area must exist to pass an argument in memory.");
6105         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6106                          true, isTailCall, false, MemOpChains,
6107                          TailCallArguments, dl);
6108         if (CallConv == CallingConv::Fast)
6109           ArgOffset += PtrByteSize;
6110       }
6111       if (CallConv != CallingConv::Fast)
6112         ArgOffset += PtrByteSize;
6113       break;
6114     case MVT::f32:
6115     case MVT::f64: {
6116       // These can be scalar arguments or elements of a float array type
6117       // passed directly.  The latter are used to implement ELFv2 homogenous
6118       // float aggregates.
6119 
6120       // Named arguments go into FPRs first, and once they overflow, the
6121       // remaining arguments go into GPRs and then the parameter save area.
6122       // Unnamed arguments for vararg functions always go to GPRs and
6123       // then the parameter save area.  For now, put all arguments to vararg
6124       // routines always in both locations (FPR *and* GPR or stack slot).
6125       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
6126       bool NeededLoad = false;
6127 
6128       // First load the argument into the next available FPR.
6129       if (FPR_idx != NumFPRs)
6130         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6131 
6132       // Next, load the argument into GPR or stack slot if needed.
6133       if (!NeedGPROrStack)
6134         ;
6135       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
6136         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
6137         // once we support fp <-> gpr moves.
6138 
6139         // In the non-vararg case, this can only ever happen in the
6140         // presence of f32 array types, since otherwise we never run
6141         // out of FPRs before running out of GPRs.
6142         SDValue ArgVal;
6143 
6144         // Double values are always passed in a single GPR.
6145         if (Arg.getValueType() != MVT::f32) {
6146           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
6147 
6148         // Non-array float values are extended and passed in a GPR.
6149         } else if (!Flags.isInConsecutiveRegs()) {
6150           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6151           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6152 
6153         // If we have an array of floats, we collect every odd element
6154         // together with its predecessor into one GPR.
6155         } else if (ArgOffset % PtrByteSize != 0) {
6156           SDValue Lo, Hi;
6157           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
6158           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6159           if (!isLittleEndian)
6160             std::swap(Lo, Hi);
6161           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
6162 
6163         // The final element, if even, goes into the first half of a GPR.
6164         } else if (Flags.isInConsecutiveRegsLast()) {
6165           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
6166           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
6167           if (!isLittleEndian)
6168             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
6169                                  DAG.getConstant(32, dl, MVT::i32));
6170 
6171         // Non-final even elements are skipped; they will be handled
6172         // together the with subsequent argument on the next go-around.
6173         } else
6174           ArgVal = SDValue();
6175 
6176         if (ArgVal.getNode())
6177           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
6178       } else {
6179         if (CallConv == CallingConv::Fast)
6180           ComputePtrOff();
6181 
6182         // Single-precision floating-point values are mapped to the
6183         // second (rightmost) word of the stack doubleword.
6184         if (Arg.getValueType() == MVT::f32 &&
6185             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
6186           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6187           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6188         }
6189 
6190         assert(HasParameterArea &&
6191                "Parameter area must exist to pass an argument in memory.");
6192         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6193                          true, isTailCall, false, MemOpChains,
6194                          TailCallArguments, dl);
6195 
6196         NeededLoad = true;
6197       }
6198       // When passing an array of floats, the array occupies consecutive
6199       // space in the argument area; only round up to the next doubleword
6200       // at the end of the array.  Otherwise, each float takes 8 bytes.
6201       if (CallConv != CallingConv::Fast || NeededLoad) {
6202         ArgOffset += (Arg.getValueType() == MVT::f32 &&
6203                       Flags.isInConsecutiveRegs()) ? 4 : 8;
6204         if (Flags.isInConsecutiveRegsLast())
6205           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
6206       }
6207       break;
6208     }
6209     case MVT::v4f32:
6210     case MVT::v4i32:
6211     case MVT::v8i16:
6212     case MVT::v16i8:
6213     case MVT::v2f64:
6214     case MVT::v2i64:
6215     case MVT::v1i128:
6216     case MVT::f128:
6217       if (!Subtarget.hasQPX()) {
6218       // These can be scalar arguments or elements of a vector array type
6219       // passed directly.  The latter are used to implement ELFv2 homogenous
6220       // vector aggregates.
6221 
6222       // For a varargs call, named arguments go into VRs or on the stack as
6223       // usual; unnamed arguments always go to the stack or the corresponding
6224       // GPRs when within range.  For now, we always put the value in both
6225       // locations (or even all three).
6226       if (isVarArg) {
6227         assert(HasParameterArea &&
6228                "Parameter area must exist if we have a varargs call.");
6229         // We could elide this store in the case where the object fits
6230         // entirely in R registers.  Maybe later.
6231         SDValue Store =
6232             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6233         MemOpChains.push_back(Store);
6234         if (VR_idx != NumVRs) {
6235           SDValue Load =
6236               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6237           MemOpChains.push_back(Load.getValue(1));
6238           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6239         }
6240         ArgOffset += 16;
6241         for (unsigned i=0; i<16; i+=PtrByteSize) {
6242           if (GPR_idx == NumGPRs)
6243             break;
6244           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6245                                    DAG.getConstant(i, dl, PtrVT));
6246           SDValue Load =
6247               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6248           MemOpChains.push_back(Load.getValue(1));
6249           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6250         }
6251         break;
6252       }
6253 
6254       // Non-varargs Altivec params go into VRs or on the stack.
6255       if (VR_idx != NumVRs) {
6256         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6257       } else {
6258         if (CallConv == CallingConv::Fast)
6259           ComputePtrOff();
6260 
6261         assert(HasParameterArea &&
6262                "Parameter area must exist to pass an argument in memory.");
6263         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6264                          true, isTailCall, true, MemOpChains,
6265                          TailCallArguments, dl);
6266         if (CallConv == CallingConv::Fast)
6267           ArgOffset += 16;
6268       }
6269 
6270       if (CallConv != CallingConv::Fast)
6271         ArgOffset += 16;
6272       break;
6273       } // not QPX
6274 
6275       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
6276              "Invalid QPX parameter type");
6277 
6278       LLVM_FALLTHROUGH;
6279     case MVT::v4f64:
6280     case MVT::v4i1: {
6281       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
6282       if (isVarArg) {
6283         assert(HasParameterArea &&
6284                "Parameter area must exist if we have a varargs call.");
6285         // We could elide this store in the case where the object fits
6286         // entirely in R registers.  Maybe later.
6287         SDValue Store =
6288             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6289         MemOpChains.push_back(Store);
6290         if (QFPR_idx != NumQFPRs) {
6291           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
6292                                      PtrOff, MachinePointerInfo());
6293           MemOpChains.push_back(Load.getValue(1));
6294           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
6295         }
6296         ArgOffset += (IsF32 ? 16 : 32);
6297         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
6298           if (GPR_idx == NumGPRs)
6299             break;
6300           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6301                                    DAG.getConstant(i, dl, PtrVT));
6302           SDValue Load =
6303               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6304           MemOpChains.push_back(Load.getValue(1));
6305           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6306         }
6307         break;
6308       }
6309 
6310       // Non-varargs QPX params go into registers or on the stack.
6311       if (QFPR_idx != NumQFPRs) {
6312         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6313       } else {
6314         if (CallConv == CallingConv::Fast)
6315           ComputePtrOff();
6316 
6317         assert(HasParameterArea &&
6318                "Parameter area must exist to pass an argument in memory.");
6319         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6320                          true, isTailCall, true, MemOpChains,
6321                          TailCallArguments, dl);
6322         if (CallConv == CallingConv::Fast)
6323           ArgOffset += (IsF32 ? 16 : 32);
6324       }
6325 
6326       if (CallConv != CallingConv::Fast)
6327         ArgOffset += (IsF32 ? 16 : 32);
6328       break;
6329       }
6330     }
6331   }
6332 
6333   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6334          "mismatch in size of parameter area");
6335   (void)NumBytesActuallyUsed;
6336 
6337   if (!MemOpChains.empty())
6338     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6339 
6340   // Check if this is an indirect call (MTCTR/BCTRL).
6341   // See prepareDescriptorIndirectCall and buildCallOperands for more
6342   // information about calls through function pointers in the 64-bit SVR4 ABI.
6343   if (!isTailCall && !isPatchPoint &&
6344       !isFunctionGlobalAddress(Callee) &&
6345       !isa<ExternalSymbolSDNode>(Callee)) {
6346     // Load r2 into a virtual register and store it to the TOC save area.
6347     setUsesTOCBasePtr(DAG);
6348     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6349     // TOC save area offset.
6350     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6351     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6352     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6353     Chain = DAG.getStore(
6354         Val.getValue(1), dl, Val, AddPtr,
6355         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6356     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6357     // This does not mean the MTCTR instruction must use R12; it's easier
6358     // to model this as an extra parameter, so do that.
6359     if (isELFv2ABI && !isPatchPoint)
6360       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6361   }
6362 
6363   // Build a sequence of copy-to-reg nodes chained together with token chain
6364   // and flag operands which copy the outgoing args into the appropriate regs.
6365   SDValue InFlag;
6366   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6367     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6368                              RegsToPass[i].second, InFlag);
6369     InFlag = Chain.getValue(1);
6370   }
6371 
6372   if (isTailCall && !IsSibCall)
6373     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6374                     TailCallArguments);
6375 
6376   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6377                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6378                     SPDiff, NumBytes, Ins, InVals, CS);
6379 }
6380 
6381 SDValue PPCTargetLowering::LowerCall_Darwin(
6382     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6383     bool isTailCall, bool isPatchPoint,
6384     const SmallVectorImpl<ISD::OutputArg> &Outs,
6385     const SmallVectorImpl<SDValue> &OutVals,
6386     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6387     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6388     ImmutableCallSite CS) const {
6389   unsigned NumOps = Outs.size();
6390 
6391   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6392   bool isPPC64 = PtrVT == MVT::i64;
6393   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6394 
6395   MachineFunction &MF = DAG.getMachineFunction();
6396 
6397   // Mark this function as potentially containing a function that contains a
6398   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6399   // and restoring the callers stack pointer in this functions epilog. This is
6400   // done because by tail calling the called function might overwrite the value
6401   // in this function's (MF) stack pointer stack slot 0(SP).
6402   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6403       CallConv == CallingConv::Fast)
6404     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6405 
6406   // Count how many bytes are to be pushed on the stack, including the linkage
6407   // area, and parameter passing area.  We start with 24/48 bytes, which is
6408   // prereserved space for [SP][CR][LR][3 x unused].
6409   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6410   unsigned NumBytes = LinkageSize;
6411 
6412   // Add up all the space actually used.
6413   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6414   // they all go in registers, but we must reserve stack space for them for
6415   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6416   // assigned stack space in order, with padding so Altivec parameters are
6417   // 16-byte aligned.
6418   unsigned nAltivecParamsAtEnd = 0;
6419   for (unsigned i = 0; i != NumOps; ++i) {
6420     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6421     EVT ArgVT = Outs[i].VT;
6422     // Varargs Altivec parameters are padded to a 16 byte boundary.
6423     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6424         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6425         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6426       if (!isVarArg && !isPPC64) {
6427         // Non-varargs Altivec parameters go after all the non-Altivec
6428         // parameters; handle those later so we know how much padding we need.
6429         nAltivecParamsAtEnd++;
6430         continue;
6431       }
6432       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6433       NumBytes = ((NumBytes+15)/16)*16;
6434     }
6435     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6436   }
6437 
6438   // Allow for Altivec parameters at the end, if needed.
6439   if (nAltivecParamsAtEnd) {
6440     NumBytes = ((NumBytes+15)/16)*16;
6441     NumBytes += 16*nAltivecParamsAtEnd;
6442   }
6443 
6444   // The prolog code of the callee may store up to 8 GPR argument registers to
6445   // the stack, allowing va_start to index over them in memory if its varargs.
6446   // Because we cannot tell if this is needed on the caller side, we have to
6447   // conservatively assume that it is needed.  As such, make sure we have at
6448   // least enough stack space for the caller to store the 8 GPRs.
6449   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6450 
6451   // Tail call needs the stack to be aligned.
6452   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6453       CallConv == CallingConv::Fast)
6454     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6455 
6456   // Calculate by how many bytes the stack has to be adjusted in case of tail
6457   // call optimization.
6458   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6459 
6460   // To protect arguments on the stack from being clobbered in a tail call,
6461   // force all the loads to happen before doing any other lowering.
6462   if (isTailCall)
6463     Chain = DAG.getStackArgumentTokenFactor(Chain);
6464 
6465   // Adjust the stack pointer for the new arguments...
6466   // These operations are automatically eliminated by the prolog/epilog pass
6467   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6468   SDValue CallSeqStart = Chain;
6469 
6470   // Load the return address and frame pointer so it can be move somewhere else
6471   // later.
6472   SDValue LROp, FPOp;
6473   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6474 
6475   // Set up a copy of the stack pointer for use loading and storing any
6476   // arguments that may not fit in the registers available for argument
6477   // passing.
6478   SDValue StackPtr;
6479   if (isPPC64)
6480     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6481   else
6482     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6483 
6484   // Figure out which arguments are going to go in registers, and which in
6485   // memory.  Also, if this is a vararg function, floating point operations
6486   // must be stored to our stack, and loaded into integer regs as well, if
6487   // any integer regs are available for argument passing.
6488   unsigned ArgOffset = LinkageSize;
6489   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6490 
6491   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6492     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6493     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6494   };
6495   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6496     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6497     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6498   };
6499   static const MCPhysReg VR[] = {
6500     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6501     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6502   };
6503   const unsigned NumGPRs = array_lengthof(GPR_32);
6504   const unsigned NumFPRs = 13;
6505   const unsigned NumVRs  = array_lengthof(VR);
6506 
6507   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6508 
6509   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6510   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6511 
6512   SmallVector<SDValue, 8> MemOpChains;
6513   for (unsigned i = 0; i != NumOps; ++i) {
6514     SDValue Arg = OutVals[i];
6515     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6516 
6517     // PtrOff will be used to store the current argument to the stack if a
6518     // register cannot be found for it.
6519     SDValue PtrOff;
6520 
6521     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6522 
6523     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6524 
6525     // On PPC64, promote integers to 64-bit values.
6526     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6527       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6528       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6529       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6530     }
6531 
6532     // FIXME memcpy is used way more than necessary.  Correctness first.
6533     // Note: "by value" is code for passing a structure by value, not
6534     // basic types.
6535     if (Flags.isByVal()) {
6536       unsigned Size = Flags.getByValSize();
6537       // Very small objects are passed right-justified.  Everything else is
6538       // passed left-justified.
6539       if (Size==1 || Size==2) {
6540         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6541         if (GPR_idx != NumGPRs) {
6542           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6543                                         MachinePointerInfo(), VT);
6544           MemOpChains.push_back(Load.getValue(1));
6545           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6546 
6547           ArgOffset += PtrByteSize;
6548         } else {
6549           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6550                                           PtrOff.getValueType());
6551           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6552           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6553                                                             CallSeqStart,
6554                                                             Flags, DAG, dl);
6555           ArgOffset += PtrByteSize;
6556         }
6557         continue;
6558       }
6559       // Copy entire object into memory.  There are cases where gcc-generated
6560       // code assumes it is there, even if it could be put entirely into
6561       // registers.  (This is not what the doc says.)
6562       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6563                                                         CallSeqStart,
6564                                                         Flags, DAG, dl);
6565 
6566       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6567       // copy the pieces of the object that fit into registers from the
6568       // parameter save area.
6569       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6570         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6571         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6572         if (GPR_idx != NumGPRs) {
6573           SDValue Load =
6574               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6575           MemOpChains.push_back(Load.getValue(1));
6576           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6577           ArgOffset += PtrByteSize;
6578         } else {
6579           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6580           break;
6581         }
6582       }
6583       continue;
6584     }
6585 
6586     switch (Arg.getSimpleValueType().SimpleTy) {
6587     default: llvm_unreachable("Unexpected ValueType for argument!");
6588     case MVT::i1:
6589     case MVT::i32:
6590     case MVT::i64:
6591       if (GPR_idx != NumGPRs) {
6592         if (Arg.getValueType() == MVT::i1)
6593           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6594 
6595         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6596       } else {
6597         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6598                          isPPC64, isTailCall, false, MemOpChains,
6599                          TailCallArguments, dl);
6600       }
6601       ArgOffset += PtrByteSize;
6602       break;
6603     case MVT::f32:
6604     case MVT::f64:
6605       if (FPR_idx != NumFPRs) {
6606         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6607 
6608         if (isVarArg) {
6609           SDValue Store =
6610               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6611           MemOpChains.push_back(Store);
6612 
6613           // Float varargs are always shadowed in available integer registers
6614           if (GPR_idx != NumGPRs) {
6615             SDValue Load =
6616                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6617             MemOpChains.push_back(Load.getValue(1));
6618             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6619           }
6620           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6621             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6622             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6623             SDValue Load =
6624                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6625             MemOpChains.push_back(Load.getValue(1));
6626             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6627           }
6628         } else {
6629           // If we have any FPRs remaining, we may also have GPRs remaining.
6630           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6631           // GPRs.
6632           if (GPR_idx != NumGPRs)
6633             ++GPR_idx;
6634           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6635               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6636             ++GPR_idx;
6637         }
6638       } else
6639         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6640                          isPPC64, isTailCall, false, MemOpChains,
6641                          TailCallArguments, dl);
6642       if (isPPC64)
6643         ArgOffset += 8;
6644       else
6645         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6646       break;
6647     case MVT::v4f32:
6648     case MVT::v4i32:
6649     case MVT::v8i16:
6650     case MVT::v16i8:
6651       if (isVarArg) {
6652         // These go aligned on the stack, or in the corresponding R registers
6653         // when within range.  The Darwin PPC ABI doc claims they also go in
6654         // V registers; in fact gcc does this only for arguments that are
6655         // prototyped, not for those that match the ...  We do it for all
6656         // arguments, seems to work.
6657         while (ArgOffset % 16 !=0) {
6658           ArgOffset += PtrByteSize;
6659           if (GPR_idx != NumGPRs)
6660             GPR_idx++;
6661         }
6662         // We could elide this store in the case where the object fits
6663         // entirely in R registers.  Maybe later.
6664         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6665                              DAG.getConstant(ArgOffset, dl, PtrVT));
6666         SDValue Store =
6667             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6668         MemOpChains.push_back(Store);
6669         if (VR_idx != NumVRs) {
6670           SDValue Load =
6671               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6672           MemOpChains.push_back(Load.getValue(1));
6673           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6674         }
6675         ArgOffset += 16;
6676         for (unsigned i=0; i<16; i+=PtrByteSize) {
6677           if (GPR_idx == NumGPRs)
6678             break;
6679           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6680                                    DAG.getConstant(i, dl, PtrVT));
6681           SDValue Load =
6682               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6683           MemOpChains.push_back(Load.getValue(1));
6684           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6685         }
6686         break;
6687       }
6688 
6689       // Non-varargs Altivec params generally go in registers, but have
6690       // stack space allocated at the end.
6691       if (VR_idx != NumVRs) {
6692         // Doesn't have GPR space allocated.
6693         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6694       } else if (nAltivecParamsAtEnd==0) {
6695         // We are emitting Altivec params in order.
6696         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6697                          isPPC64, isTailCall, true, MemOpChains,
6698                          TailCallArguments, dl);
6699         ArgOffset += 16;
6700       }
6701       break;
6702     }
6703   }
6704   // If all Altivec parameters fit in registers, as they usually do,
6705   // they get stack space following the non-Altivec parameters.  We
6706   // don't track this here because nobody below needs it.
6707   // If there are more Altivec parameters than fit in registers emit
6708   // the stores here.
6709   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6710     unsigned j = 0;
6711     // Offset is aligned; skip 1st 12 params which go in V registers.
6712     ArgOffset = ((ArgOffset+15)/16)*16;
6713     ArgOffset += 12*16;
6714     for (unsigned i = 0; i != NumOps; ++i) {
6715       SDValue Arg = OutVals[i];
6716       EVT ArgType = Outs[i].VT;
6717       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6718           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6719         if (++j > NumVRs) {
6720           SDValue PtrOff;
6721           // We are emitting Altivec params in order.
6722           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6723                            isPPC64, isTailCall, true, MemOpChains,
6724                            TailCallArguments, dl);
6725           ArgOffset += 16;
6726         }
6727       }
6728     }
6729   }
6730 
6731   if (!MemOpChains.empty())
6732     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6733 
6734   // On Darwin, R12 must contain the address of an indirect callee.  This does
6735   // not mean the MTCTR instruction must use R12; it's easier to model this as
6736   // an extra parameter, so do that.
6737   if (!isTailCall &&
6738       !isFunctionGlobalAddress(Callee) &&
6739       !isa<ExternalSymbolSDNode>(Callee) &&
6740       !isBLACompatibleAddress(Callee, DAG))
6741     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6742                                                    PPC::R12), Callee));
6743 
6744   // Build a sequence of copy-to-reg nodes chained together with token chain
6745   // and flag operands which copy the outgoing args into the appropriate regs.
6746   SDValue InFlag;
6747   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6748     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6749                              RegsToPass[i].second, InFlag);
6750     InFlag = Chain.getValue(1);
6751   }
6752 
6753   if (isTailCall)
6754     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6755                     TailCallArguments);
6756 
6757   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6758                     /* unused except on PPC64 ELFv1 */ false, DAG,
6759                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6760                     NumBytes, Ins, InVals, CS);
6761 }
6762 
6763 static bool CC_AIX(unsigned ValNo, MVT ValVT, MVT LocVT,
6764                    CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
6765                    CCState &State) {
6766 
6767   if (ValVT == MVT::f128)
6768     report_fatal_error("f128 is unimplemented on AIX.");
6769 
6770   if (ArgFlags.isByVal())
6771     report_fatal_error("Passing structure by value is unimplemented.");
6772 
6773   if (ArgFlags.isSRet())
6774     report_fatal_error("Struct return arguments are unimplemented.");
6775 
6776   if (ArgFlags.isNest())
6777     report_fatal_error("Nest arguments are unimplemented.");
6778 
6779   const PPCSubtarget &Subtarget = static_cast<const PPCSubtarget &>(
6780       State.getMachineFunction().getSubtarget());
6781   const bool IsPPC64 = Subtarget.isPPC64();
6782   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6783 
6784   static const MCPhysReg GPR_32[] = {// 32-bit registers.
6785                                      PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6786                                      PPC::R7, PPC::R8, PPC::R9, PPC::R10};
6787   static const MCPhysReg GPR_64[] = {// 64-bit registers.
6788                                      PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6789                                      PPC::X7, PPC::X8, PPC::X9, PPC::X10};
6790 
6791   // Arguments always reserve parameter save area.
6792   switch (ValVT.SimpleTy) {
6793   default:
6794     report_fatal_error("Unhandled value type for argument.");
6795   case MVT::i64:
6796     // i64 arguments should have been split to i32 for PPC32.
6797     assert(IsPPC64 && "PPC32 should have split i64 values.");
6798     LLVM_FALLTHROUGH;
6799   case MVT::i1:
6800   case MVT::i32:
6801     State.AllocateStack(PtrByteSize, PtrByteSize);
6802     if (unsigned Reg = State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32)) {
6803       MVT RegVT = IsPPC64 ? MVT::i64 : MVT::i32;
6804       // Promote integers if needed.
6805       if (ValVT.getSizeInBits() < RegVT.getSizeInBits())
6806         LocInfo = ArgFlags.isSExt() ? CCValAssign::LocInfo::SExt
6807                                     : CCValAssign::LocInfo::ZExt;
6808       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, RegVT, LocInfo));
6809     }
6810     else
6811       report_fatal_error("Handling of placing parameters on the stack is "
6812                          "unimplemented!");
6813     return false;
6814 
6815   case MVT::f32:
6816   case MVT::f64: {
6817     // Parameter save area (PSA) is reserved even if the float passes in fpr.
6818     const unsigned StoreSize = LocVT.getStoreSize();
6819     // Floats are always 4-byte aligned in the PSA on AIX.
6820     // This includes f64 in 64-bit mode for ABI compatibility.
6821     State.AllocateStack(IsPPC64 ? 8 : StoreSize, 4);
6822     if (unsigned Reg = State.AllocateReg(FPR))
6823       State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, MVT::f64, LocInfo));
6824     else
6825       report_fatal_error("Handling of placing parameters on the stack is "
6826                          "unimplemented!");
6827 
6828     // f32 reserves 1 GPR in both PPC32 and PPC64.
6829     // f64 reserves 2 GPRs in PPC32 and 1 GPR in PPC64.
6830     for (unsigned i = 0; i < StoreSize; i += PtrByteSize)
6831       State.AllocateReg(IsPPC64 ? GPR_64 : GPR_32);
6832     return false;
6833   }
6834   }
6835 }
6836 
6837 static const TargetRegisterClass *getRegClassForSVT(MVT::SimpleValueType SVT,
6838                                                     bool IsPPC64) {
6839   assert((IsPPC64 || SVT != MVT::i64) &&
6840          "i64 should have been split for 32-bit codegen.");
6841 
6842   switch (SVT) {
6843   default:
6844     report_fatal_error("Unexpected value type for formal argument");
6845   case MVT::i1:
6846   case MVT::i32:
6847   case MVT::i64:
6848     return IsPPC64 ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6849   case MVT::f32:
6850     return &PPC::F4RCRegClass;
6851   case MVT::f64:
6852     return &PPC::F8RCRegClass;
6853   }
6854 }
6855 
6856 static SDValue truncateScalarIntegerArg(ISD::ArgFlagsTy Flags, EVT ValVT,
6857                                         SelectionDAG &DAG, SDValue ArgValue,
6858                                         MVT LocVT, const SDLoc &dl) {
6859   assert(ValVT.isScalarInteger() && LocVT.isScalarInteger());
6860   assert(ValVT.getSizeInBits() < LocVT.getSizeInBits());
6861 
6862   if (Flags.isSExt())
6863     ArgValue = DAG.getNode(ISD::AssertSext, dl, LocVT, ArgValue,
6864                            DAG.getValueType(ValVT));
6865   else if (Flags.isZExt())
6866     ArgValue = DAG.getNode(ISD::AssertZext, dl, LocVT, ArgValue,
6867                            DAG.getValueType(ValVT));
6868 
6869   return DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
6870 }
6871 
6872 SDValue PPCTargetLowering::LowerFormalArguments_AIX(
6873     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
6874     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6875     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
6876 
6877   assert((CallConv == CallingConv::C || CallConv == CallingConv::Cold ||
6878           CallConv == CallingConv::Fast) &&
6879          "Unexpected calling convention!");
6880 
6881   if (isVarArg)
6882     report_fatal_error("This call type is unimplemented on AIX.");
6883 
6884   if (getTargetMachine().Options.GuaranteedTailCallOpt)
6885     report_fatal_error("Tail call support is unimplemented on AIX.");
6886 
6887   if (useSoftFloat())
6888     report_fatal_error("Soft float support is unimplemented on AIX.");
6889 
6890   const PPCSubtarget &Subtarget =
6891       static_cast<const PPCSubtarget &>(DAG.getSubtarget());
6892   if (Subtarget.hasQPX())
6893     report_fatal_error("QPX support is not supported on AIX.");
6894 
6895   const bool IsPPC64 = Subtarget.isPPC64();
6896   const unsigned PtrByteSize = IsPPC64 ? 8 : 4;
6897 
6898   // Assign locations to all of the incoming arguments.
6899   SmallVector<CCValAssign, 16> ArgLocs;
6900   MachineFunction &MF = DAG.getMachineFunction();
6901   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6902 
6903   // Reserve space for the linkage area on the stack.
6904   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6905   // On AIX a minimum of 8 words is saved to the parameter save area.
6906   const unsigned MinParameterSaveArea = 8 * PtrByteSize;
6907   CCInfo.AllocateStack(LinkageSize + MinParameterSaveArea, PtrByteSize);
6908   CCInfo.AnalyzeFormalArguments(Ins, CC_AIX);
6909 
6910   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
6911     CCValAssign &VA = ArgLocs[i];
6912     SDValue ArgValue;
6913     ISD::ArgFlagsTy Flags = Ins[i].Flags;
6914     if (VA.isRegLoc()) {
6915       EVT ValVT = VA.getValVT();
6916       MVT LocVT = VA.getLocVT();
6917       MVT::SimpleValueType SVT = ValVT.getSimpleVT().SimpleTy;
6918       unsigned VReg =
6919           MF.addLiveIn(VA.getLocReg(), getRegClassForSVT(SVT, IsPPC64));
6920       ArgValue = DAG.getCopyFromReg(Chain, dl, VReg, LocVT);
6921       if (ValVT.isScalarInteger() &&
6922           (ValVT.getSizeInBits() < LocVT.getSizeInBits())) {
6923         ArgValue =
6924             truncateScalarIntegerArg(Flags, ValVT, DAG, ArgValue, LocVT, dl);
6925       }
6926       InVals.push_back(ArgValue);
6927     } else {
6928       report_fatal_error("Handling of formal arguments on the stack is "
6929                          "unimplemented!");
6930     }
6931   }
6932 
6933   // Area that is at least reserved in the caller of this function.
6934   unsigned MinReservedArea = CCInfo.getNextStackOffset();
6935 
6936   // Set the size that is at least reserved in caller of this function. Tail
6937   // call optimized function's reserved stack space needs to be aligned so
6938   // that taking the difference between two stack areas will result in an
6939   // aligned stack.
6940   MinReservedArea =
6941       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
6942   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6943   FuncInfo->setMinReservedArea(MinReservedArea);
6944 
6945   return Chain;
6946 }
6947 
6948 SDValue PPCTargetLowering::LowerCall_AIX(
6949     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6950     bool isTailCall, bool isPatchPoint,
6951     const SmallVectorImpl<ISD::OutputArg> &Outs,
6952     const SmallVectorImpl<SDValue> &OutVals,
6953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6955     ImmutableCallSite CS) const {
6956 
6957   assert((CallConv == CallingConv::C ||
6958           CallConv == CallingConv::Cold ||
6959           CallConv == CallingConv::Fast) && "Unexpected calling convention!");
6960 
6961   if (isVarArg || isPatchPoint)
6962     report_fatal_error("This call type is unimplemented on AIX.");
6963 
6964   if (!isFunctionGlobalAddress(Callee) && !isa<ExternalSymbolSDNode>(Callee))
6965     report_fatal_error("Handling of indirect call is unimplemented!");
6966 
6967   const PPCSubtarget& Subtarget =
6968       static_cast<const PPCSubtarget&>(DAG.getSubtarget());
6969   if (Subtarget.hasQPX())
6970     report_fatal_error("QPX is not supported on AIX.");
6971   if (Subtarget.hasAltivec())
6972     report_fatal_error("Altivec support is unimplemented on AIX.");
6973 
6974   MachineFunction &MF = DAG.getMachineFunction();
6975   SmallVector<CCValAssign, 16> ArgLocs;
6976   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
6977 
6978   // Reserve space for the linkage save area (LSA) on the stack.
6979   // In both PPC32 and PPC64 there are 6 reserved slots in the LSA:
6980   //   [SP][CR][LR][2 x reserved][TOC].
6981   // The LSA is 24 bytes (6x4) in PPC32 and 48 bytes (6x8) in PPC64.
6982   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6983   const unsigned PtrByteSize = Subtarget.isPPC64() ? 8 : 4;
6984   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
6985   CCInfo.AnalyzeCallOperands(Outs, CC_AIX);
6986 
6987   // The prolog code of the callee may store up to 8 GPR argument registers to
6988   // the stack, allowing va_start to index over them in memory if the callee
6989   // is variadic.
6990   // Because we cannot tell if this is needed on the caller side, we have to
6991   // conservatively assume that it is needed.  As such, make sure we have at
6992   // least enough stack space for the caller to store the 8 GPRs.
6993   const unsigned MinParameterSaveAreaSize = 8 * PtrByteSize;
6994   const unsigned NumBytes = LinkageSize + MinParameterSaveAreaSize;
6995 
6996   // Adjust the stack pointer for the new arguments...
6997   // These operations are automatically eliminated by the prolog/epilog pass.
6998   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6999   SDValue CallSeqStart = Chain;
7000 
7001   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
7002 
7003   for (CCValAssign &VA : ArgLocs) {
7004     SDValue Arg = OutVals[VA.getValNo()];
7005 
7006     switch (VA.getLocInfo()) {
7007     default: report_fatal_error("Unexpected argument extension type.");
7008     case CCValAssign::Full: break;
7009     case CCValAssign::ZExt:
7010       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7011       break;
7012     case CCValAssign::SExt:
7013       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7014       break;
7015     }
7016 
7017     if (VA.isRegLoc())
7018       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
7019 
7020     if (VA.isMemLoc())
7021       report_fatal_error("Handling of placing parameters on the stack is "
7022                          "unimplemented!");
7023   }
7024 
7025   // Build a sequence of copy-to-reg nodes chained together with token chain
7026   // and flag operands which copy the outgoing args into the appropriate regs.
7027   SDValue InFlag;
7028   for (auto Reg : RegsToPass) {
7029     Chain = DAG.getCopyToReg(Chain, dl, Reg.first, Reg.second, InFlag);
7030     InFlag = Chain.getValue(1);
7031   }
7032 
7033   const int SPDiff = 0;
7034   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
7035                     /* unused except on PPC64 ELFv1 */ false, DAG, RegsToPass,
7036                     InFlag, Chain, CallSeqStart, Callee, SPDiff, NumBytes, Ins,
7037                     InVals, CS);
7038 }
7039 
7040 bool
7041 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
7042                                   MachineFunction &MF, bool isVarArg,
7043                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
7044                                   LLVMContext &Context) const {
7045   SmallVector<CCValAssign, 16> RVLocs;
7046   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
7047   return CCInfo.CheckReturn(
7048       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7049                 ? RetCC_PPC_Cold
7050                 : RetCC_PPC);
7051 }
7052 
7053 SDValue
7054 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
7055                                bool isVarArg,
7056                                const SmallVectorImpl<ISD::OutputArg> &Outs,
7057                                const SmallVectorImpl<SDValue> &OutVals,
7058                                const SDLoc &dl, SelectionDAG &DAG) const {
7059   SmallVector<CCValAssign, 16> RVLocs;
7060   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
7061                  *DAG.getContext());
7062   CCInfo.AnalyzeReturn(Outs,
7063                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
7064                            ? RetCC_PPC_Cold
7065                            : RetCC_PPC);
7066 
7067   SDValue Flag;
7068   SmallVector<SDValue, 4> RetOps(1, Chain);
7069 
7070   // Copy the result values into the output registers.
7071   for (unsigned i = 0, RealResIdx = 0; i != RVLocs.size(); ++i, ++RealResIdx) {
7072     CCValAssign &VA = RVLocs[i];
7073     assert(VA.isRegLoc() && "Can only return in registers!");
7074 
7075     SDValue Arg = OutVals[RealResIdx];
7076 
7077     switch (VA.getLocInfo()) {
7078     default: llvm_unreachable("Unknown loc info!");
7079     case CCValAssign::Full: break;
7080     case CCValAssign::AExt:
7081       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
7082       break;
7083     case CCValAssign::ZExt:
7084       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
7085       break;
7086     case CCValAssign::SExt:
7087       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
7088       break;
7089     }
7090     if (Subtarget.hasSPE() && VA.getLocVT() == MVT::f64) {
7091       bool isLittleEndian = Subtarget.isLittleEndian();
7092       // Legalize ret f64 -> ret 2 x i32.
7093       SDValue SVal =
7094           DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7095                       DAG.getIntPtrConstant(isLittleEndian ? 0 : 1, dl));
7096       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7097       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7098       SVal = DAG.getNode(PPCISD::EXTRACT_SPE, dl, MVT::i32, Arg,
7099                          DAG.getIntPtrConstant(isLittleEndian ? 1 : 0, dl));
7100       Flag = Chain.getValue(1);
7101       VA = RVLocs[++i]; // skip ahead to next loc
7102       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), SVal, Flag);
7103     } else
7104       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
7105     Flag = Chain.getValue(1);
7106     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
7107   }
7108 
7109   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
7110   const MCPhysReg *I =
7111     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
7112   if (I) {
7113     for (; *I; ++I) {
7114 
7115       if (PPC::G8RCRegClass.contains(*I))
7116         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
7117       else if (PPC::F8RCRegClass.contains(*I))
7118         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
7119       else if (PPC::CRRCRegClass.contains(*I))
7120         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
7121       else if (PPC::VRRCRegClass.contains(*I))
7122         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
7123       else
7124         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
7125     }
7126   }
7127 
7128   RetOps[0] = Chain;  // Update chain.
7129 
7130   // Add the flag if we have it.
7131   if (Flag.getNode())
7132     RetOps.push_back(Flag);
7133 
7134   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
7135 }
7136 
7137 SDValue
7138 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
7139                                                 SelectionDAG &DAG) const {
7140   SDLoc dl(Op);
7141 
7142   // Get the correct type for integers.
7143   EVT IntVT = Op.getValueType();
7144 
7145   // Get the inputs.
7146   SDValue Chain = Op.getOperand(0);
7147   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7148   // Build a DYNAREAOFFSET node.
7149   SDValue Ops[2] = {Chain, FPSIdx};
7150   SDVTList VTs = DAG.getVTList(IntVT);
7151   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
7152 }
7153 
7154 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
7155                                              SelectionDAG &DAG) const {
7156   // When we pop the dynamic allocation we need to restore the SP link.
7157   SDLoc dl(Op);
7158 
7159   // Get the correct type for pointers.
7160   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7161 
7162   // Construct the stack pointer operand.
7163   bool isPPC64 = Subtarget.isPPC64();
7164   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
7165   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
7166 
7167   // Get the operands for the STACKRESTORE.
7168   SDValue Chain = Op.getOperand(0);
7169   SDValue SaveSP = Op.getOperand(1);
7170 
7171   // Load the old link SP.
7172   SDValue LoadLinkSP =
7173       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
7174 
7175   // Restore the stack pointer.
7176   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
7177 
7178   // Store the old link SP.
7179   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
7180 }
7181 
7182 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
7183   MachineFunction &MF = DAG.getMachineFunction();
7184   bool isPPC64 = Subtarget.isPPC64();
7185   EVT PtrVT = getPointerTy(MF.getDataLayout());
7186 
7187   // Get current frame pointer save index.  The users of this index will be
7188   // primarily DYNALLOC instructions.
7189   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7190   int RASI = FI->getReturnAddrSaveIndex();
7191 
7192   // If the frame pointer save index hasn't been defined yet.
7193   if (!RASI) {
7194     // Find out what the fix offset of the frame pointer save area.
7195     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
7196     // Allocate the frame index for frame pointer save area.
7197     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
7198     // Save the result.
7199     FI->setReturnAddrSaveIndex(RASI);
7200   }
7201   return DAG.getFrameIndex(RASI, PtrVT);
7202 }
7203 
7204 SDValue
7205 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
7206   MachineFunction &MF = DAG.getMachineFunction();
7207   bool isPPC64 = Subtarget.isPPC64();
7208   EVT PtrVT = getPointerTy(MF.getDataLayout());
7209 
7210   // Get current frame pointer save index.  The users of this index will be
7211   // primarily DYNALLOC instructions.
7212   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
7213   int FPSI = FI->getFramePointerSaveIndex();
7214 
7215   // If the frame pointer save index hasn't been defined yet.
7216   if (!FPSI) {
7217     // Find out what the fix offset of the frame pointer save area.
7218     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
7219     // Allocate the frame index for frame pointer save area.
7220     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
7221     // Save the result.
7222     FI->setFramePointerSaveIndex(FPSI);
7223   }
7224   return DAG.getFrameIndex(FPSI, PtrVT);
7225 }
7226 
7227 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7228                                                    SelectionDAG &DAG) const {
7229   // Get the inputs.
7230   SDValue Chain = Op.getOperand(0);
7231   SDValue Size  = Op.getOperand(1);
7232   SDLoc dl(Op);
7233 
7234   // Get the correct type for pointers.
7235   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7236   // Negate the size.
7237   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
7238                                 DAG.getConstant(0, dl, PtrVT), Size);
7239   // Construct a node for the frame pointer save index.
7240   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
7241   // Build a DYNALLOC node.
7242   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
7243   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
7244   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
7245 }
7246 
7247 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
7248                                                      SelectionDAG &DAG) const {
7249   MachineFunction &MF = DAG.getMachineFunction();
7250 
7251   bool isPPC64 = Subtarget.isPPC64();
7252   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7253 
7254   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
7255   return DAG.getFrameIndex(FI, PtrVT);
7256 }
7257 
7258 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
7259                                                SelectionDAG &DAG) const {
7260   SDLoc DL(Op);
7261   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
7262                      DAG.getVTList(MVT::i32, MVT::Other),
7263                      Op.getOperand(0), Op.getOperand(1));
7264 }
7265 
7266 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
7267                                                 SelectionDAG &DAG) const {
7268   SDLoc DL(Op);
7269   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
7270                      Op.getOperand(0), Op.getOperand(1));
7271 }
7272 
7273 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7274   if (Op.getValueType().isVector())
7275     return LowerVectorLoad(Op, DAG);
7276 
7277   assert(Op.getValueType() == MVT::i1 &&
7278          "Custom lowering only for i1 loads");
7279 
7280   // First, load 8 bits into 32 bits, then truncate to 1 bit.
7281 
7282   SDLoc dl(Op);
7283   LoadSDNode *LD = cast<LoadSDNode>(Op);
7284 
7285   SDValue Chain = LD->getChain();
7286   SDValue BasePtr = LD->getBasePtr();
7287   MachineMemOperand *MMO = LD->getMemOperand();
7288 
7289   SDValue NewLD =
7290       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
7291                      BasePtr, MVT::i8, MMO);
7292   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
7293 
7294   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
7295   return DAG.getMergeValues(Ops, dl);
7296 }
7297 
7298 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7299   if (Op.getOperand(1).getValueType().isVector())
7300     return LowerVectorStore(Op, DAG);
7301 
7302   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
7303          "Custom lowering only for i1 stores");
7304 
7305   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
7306 
7307   SDLoc dl(Op);
7308   StoreSDNode *ST = cast<StoreSDNode>(Op);
7309 
7310   SDValue Chain = ST->getChain();
7311   SDValue BasePtr = ST->getBasePtr();
7312   SDValue Value = ST->getValue();
7313   MachineMemOperand *MMO = ST->getMemOperand();
7314 
7315   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
7316                       Value);
7317   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
7318 }
7319 
7320 // FIXME: Remove this once the ANDI glue bug is fixed:
7321 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
7322   assert(Op.getValueType() == MVT::i1 &&
7323          "Custom lowering only for i1 results");
7324 
7325   SDLoc DL(Op);
7326   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
7327                      Op.getOperand(0));
7328 }
7329 
7330 SDValue PPCTargetLowering::LowerTRUNCATEVector(SDValue Op,
7331                                                SelectionDAG &DAG) const {
7332 
7333   // Implements a vector truncate that fits in a vector register as a shuffle.
7334   // We want to legalize vector truncates down to where the source fits in
7335   // a vector register (and target is therefore smaller than vector register
7336   // size).  At that point legalization will try to custom lower the sub-legal
7337   // result and get here - where we can contain the truncate as a single target
7338   // operation.
7339 
7340   // For example a trunc <2 x i16> to <2 x i8> could be visualized as follows:
7341   //   <MSB1|LSB1, MSB2|LSB2> to <LSB1, LSB2>
7342   //
7343   // We will implement it for big-endian ordering as this (where x denotes
7344   // undefined):
7345   //   < MSB1|LSB1, MSB2|LSB2, uu, uu, uu, uu, uu, uu> to
7346   //   < LSB1, LSB2, u, u, u, u, u, u, u, u, u, u, u, u, u, u>
7347   //
7348   // The same operation in little-endian ordering will be:
7349   //   <uu, uu, uu, uu, uu, uu, LSB2|MSB2, LSB1|MSB1> to
7350   //   <u, u, u, u, u, u, u, u, u, u, u, u, u, u, LSB2, LSB1>
7351 
7352   assert(Op.getValueType().isVector() && "Vector type expected.");
7353 
7354   SDLoc DL(Op);
7355   SDValue N1 = Op.getOperand(0);
7356   unsigned SrcSize = N1.getValueType().getSizeInBits();
7357   assert(SrcSize <= 128 && "Source must fit in an Altivec/VSX vector");
7358   SDValue WideSrc = SrcSize == 128 ? N1 : widenVec(DAG, N1, DL);
7359 
7360   EVT TrgVT = Op.getValueType();
7361   unsigned TrgNumElts = TrgVT.getVectorNumElements();
7362   EVT EltVT = TrgVT.getVectorElementType();
7363   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7364   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7365 
7366   // First list the elements we want to keep.
7367   unsigned SizeMult = SrcSize / TrgVT.getSizeInBits();
7368   SmallVector<int, 16> ShuffV;
7369   if (Subtarget.isLittleEndian())
7370     for (unsigned i = 0; i < TrgNumElts; ++i)
7371       ShuffV.push_back(i * SizeMult);
7372   else
7373     for (unsigned i = 1; i <= TrgNumElts; ++i)
7374       ShuffV.push_back(i * SizeMult - 1);
7375 
7376   // Populate the remaining elements with undefs.
7377   for (unsigned i = TrgNumElts; i < WideNumElts; ++i)
7378     // ShuffV.push_back(i + WideNumElts);
7379     ShuffV.push_back(WideNumElts + 1);
7380 
7381   SDValue Conv = DAG.getNode(ISD::BITCAST, DL, WideVT, WideSrc);
7382   return DAG.getVectorShuffle(WideVT, DL, Conv, DAG.getUNDEF(WideVT), ShuffV);
7383 }
7384 
7385 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
7386 /// possible.
7387 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
7388   // Not FP? Not a fsel.
7389   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
7390       !Op.getOperand(2).getValueType().isFloatingPoint())
7391     return Op;
7392 
7393   bool HasNoInfs = DAG.getTarget().Options.NoInfsFPMath;
7394   bool HasNoNaNs = DAG.getTarget().Options.NoNaNsFPMath;
7395   // We might be able to do better than this under some circumstances, but in
7396   // general, fsel-based lowering of select is a finite-math-only optimization.
7397   // For more information, see section F.3 of the 2.06 ISA specification.
7398   // With ISA 3.0, we have xsmaxcdp/xsmincdp which are OK to emit even in the
7399   // presence of infinities.
7400   if (!Subtarget.hasP9Vector() && (!HasNoInfs || !HasNoNaNs))
7401     return Op;
7402   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
7403 
7404   EVT ResVT = Op.getValueType();
7405   EVT CmpVT = Op.getOperand(0).getValueType();
7406   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
7407   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
7408   SDLoc dl(Op);
7409 
7410   if (Subtarget.hasP9Vector() && LHS == TV && RHS == FV) {
7411     switch (CC) {
7412     default:
7413       // Not a min/max but with finite math, we may still be able to use fsel.
7414       if (HasNoInfs && HasNoNaNs)
7415         break;
7416       return Op;
7417     case ISD::SETOGT:
7418     case ISD::SETGT:
7419       return DAG.getNode(PPCISD::XSMAXCDP, dl, Op.getValueType(), LHS, RHS);
7420     case ISD::SETOLT:
7421     case ISD::SETLT:
7422       return DAG.getNode(PPCISD::XSMINCDP, dl, Op.getValueType(), LHS, RHS);
7423     }
7424   }
7425 
7426   // TODO: Propagate flags from the select rather than global settings.
7427   SDNodeFlags Flags;
7428   Flags.setNoInfs(true);
7429   Flags.setNoNaNs(true);
7430 
7431   // If the RHS of the comparison is a 0.0, we don't need to do the
7432   // subtraction at all.
7433   SDValue Sel1;
7434   if (isFloatingPointZero(RHS))
7435     switch (CC) {
7436     default: break;       // SETUO etc aren't handled by fsel.
7437     case ISD::SETNE:
7438       std::swap(TV, FV);
7439       LLVM_FALLTHROUGH;
7440     case ISD::SETEQ:
7441       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7442         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7443       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7444       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7445         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7446       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7447                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
7448     case ISD::SETULT:
7449     case ISD::SETLT:
7450       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7451       LLVM_FALLTHROUGH;
7452     case ISD::SETOGE:
7453     case ISD::SETGE:
7454       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7455         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7456       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
7457     case ISD::SETUGT:
7458     case ISD::SETGT:
7459       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
7460       LLVM_FALLTHROUGH;
7461     case ISD::SETOLE:
7462     case ISD::SETLE:
7463       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
7464         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
7465       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7466                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
7467     }
7468 
7469   SDValue Cmp;
7470   switch (CC) {
7471   default: break;       // SETUO etc aren't handled by fsel.
7472   case ISD::SETNE:
7473     std::swap(TV, FV);
7474     LLVM_FALLTHROUGH;
7475   case ISD::SETEQ:
7476     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7477     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7478       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7479     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7480     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
7481       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
7482     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
7483                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
7484   case ISD::SETULT:
7485   case ISD::SETLT:
7486     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7487     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7488       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7489     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7490   case ISD::SETOGE:
7491   case ISD::SETGE:
7492     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
7493     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7494       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7495     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7496   case ISD::SETUGT:
7497   case ISD::SETGT:
7498     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7499     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7500       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7501     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
7502   case ISD::SETOLE:
7503   case ISD::SETLE:
7504     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
7505     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
7506       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
7507     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
7508   }
7509   return Op;
7510 }
7511 
7512 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
7513                                                SelectionDAG &DAG,
7514                                                const SDLoc &dl) const {
7515   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7516   SDValue Src = Op.getOperand(0);
7517   if (Src.getValueType() == MVT::f32)
7518     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7519 
7520   SDValue Tmp;
7521   switch (Op.getSimpleValueType().SimpleTy) {
7522   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7523   case MVT::i32:
7524     Tmp = DAG.getNode(
7525         Op.getOpcode() == ISD::FP_TO_SINT
7526             ? PPCISD::FCTIWZ
7527             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7528         dl, MVT::f64, Src);
7529     break;
7530   case MVT::i64:
7531     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7532            "i64 FP_TO_UINT is supported only with FPCVT");
7533     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7534                                                         PPCISD::FCTIDUZ,
7535                       dl, MVT::f64, Src);
7536     break;
7537   }
7538 
7539   // Convert the FP value to an int value through memory.
7540   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
7541     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
7542   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
7543   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
7544   MachinePointerInfo MPI =
7545       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
7546 
7547   // Emit a store to the stack slot.
7548   SDValue Chain;
7549   if (i32Stack) {
7550     MachineFunction &MF = DAG.getMachineFunction();
7551     MachineMemOperand *MMO =
7552       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
7553     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
7554     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7555               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
7556   } else
7557     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
7558 
7559   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
7560   // add in a bias on big endian.
7561   if (Op.getValueType() == MVT::i32 && !i32Stack) {
7562     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
7563                         DAG.getConstant(4, dl, FIPtr.getValueType()));
7564     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
7565   }
7566 
7567   RLI.Chain = Chain;
7568   RLI.Ptr = FIPtr;
7569   RLI.MPI = MPI;
7570 }
7571 
7572 /// Custom lowers floating point to integer conversions to use
7573 /// the direct move instructions available in ISA 2.07 to avoid the
7574 /// need for load/store combinations.
7575 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
7576                                                     SelectionDAG &DAG,
7577                                                     const SDLoc &dl) const {
7578   assert(Op.getOperand(0).getValueType().isFloatingPoint());
7579   SDValue Src = Op.getOperand(0);
7580 
7581   if (Src.getValueType() == MVT::f32)
7582     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
7583 
7584   SDValue Tmp;
7585   switch (Op.getSimpleValueType().SimpleTy) {
7586   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
7587   case MVT::i32:
7588     Tmp = DAG.getNode(
7589         Op.getOpcode() == ISD::FP_TO_SINT
7590             ? PPCISD::FCTIWZ
7591             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
7592         dl, MVT::f64, Src);
7593     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
7594     break;
7595   case MVT::i64:
7596     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
7597            "i64 FP_TO_UINT is supported only with FPCVT");
7598     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
7599                                                         PPCISD::FCTIDUZ,
7600                       dl, MVT::f64, Src);
7601     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
7602     break;
7603   }
7604   return Tmp;
7605 }
7606 
7607 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
7608                                           const SDLoc &dl) const {
7609 
7610   // FP to INT conversions are legal for f128.
7611   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
7612     return Op;
7613 
7614   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
7615   // PPC (the libcall is not available).
7616   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
7617     if (Op.getValueType() == MVT::i32) {
7618       if (Op.getOpcode() == ISD::FP_TO_SINT) {
7619         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7620                                  MVT::f64, Op.getOperand(0),
7621                                  DAG.getIntPtrConstant(0, dl));
7622         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
7623                                  MVT::f64, Op.getOperand(0),
7624                                  DAG.getIntPtrConstant(1, dl));
7625 
7626         // Add the two halves of the long double in round-to-zero mode.
7627         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
7628 
7629         // Now use a smaller FP_TO_SINT.
7630         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
7631       }
7632       if (Op.getOpcode() == ISD::FP_TO_UINT) {
7633         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
7634         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
7635         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
7636         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
7637         // FIXME: generated code sucks.
7638         // TODO: Are there fast-math-flags to propagate to this FSUB?
7639         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
7640                                    Op.getOperand(0), Tmp);
7641         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
7642         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
7643                            DAG.getConstant(0x80000000, dl, MVT::i32));
7644         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
7645                                     Op.getOperand(0));
7646         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
7647                                ISD::SETGE);
7648       }
7649     }
7650 
7651     return SDValue();
7652   }
7653 
7654   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
7655     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
7656 
7657   ReuseLoadInfo RLI;
7658   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7659 
7660   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7661                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7662 }
7663 
7664 // We're trying to insert a regular store, S, and then a load, L. If the
7665 // incoming value, O, is a load, we might just be able to have our load use the
7666 // address used by O. However, we don't know if anything else will store to
7667 // that address before we can load from it. To prevent this situation, we need
7668 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7669 // the same chain operand as O, we create a token factor from the chain results
7670 // of O and L, and we replace all uses of O's chain result with that token
7671 // factor (see spliceIntoChain below for this last part).
7672 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7673                                             ReuseLoadInfo &RLI,
7674                                             SelectionDAG &DAG,
7675                                             ISD::LoadExtType ET) const {
7676   SDLoc dl(Op);
7677   if (ET == ISD::NON_EXTLOAD &&
7678       (Op.getOpcode() == ISD::FP_TO_UINT ||
7679        Op.getOpcode() == ISD::FP_TO_SINT) &&
7680       isOperationLegalOrCustom(Op.getOpcode(),
7681                                Op.getOperand(0).getValueType())) {
7682 
7683     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7684     return true;
7685   }
7686 
7687   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7688   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7689       LD->isNonTemporal())
7690     return false;
7691   if (LD->getMemoryVT() != MemVT)
7692     return false;
7693 
7694   RLI.Ptr = LD->getBasePtr();
7695   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7696     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7697            "Non-pre-inc AM on PPC?");
7698     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7699                           LD->getOffset());
7700   }
7701 
7702   RLI.Chain = LD->getChain();
7703   RLI.MPI = LD->getPointerInfo();
7704   RLI.IsDereferenceable = LD->isDereferenceable();
7705   RLI.IsInvariant = LD->isInvariant();
7706   RLI.Alignment = LD->getAlignment();
7707   RLI.AAInfo = LD->getAAInfo();
7708   RLI.Ranges = LD->getRanges();
7709 
7710   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7711   return true;
7712 }
7713 
7714 // Given the head of the old chain, ResChain, insert a token factor containing
7715 // it and NewResChain, and make users of ResChain now be users of that token
7716 // factor.
7717 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7718 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7719                                         SDValue NewResChain,
7720                                         SelectionDAG &DAG) const {
7721   if (!ResChain)
7722     return;
7723 
7724   SDLoc dl(NewResChain);
7725 
7726   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7727                            NewResChain, DAG.getUNDEF(MVT::Other));
7728   assert(TF.getNode() != NewResChain.getNode() &&
7729          "A new TF really is required here");
7730 
7731   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7732   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7733 }
7734 
7735 /// Analyze profitability of direct move
7736 /// prefer float load to int load plus direct move
7737 /// when there is no integer use of int load
7738 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7739   SDNode *Origin = Op.getOperand(0).getNode();
7740   if (Origin->getOpcode() != ISD::LOAD)
7741     return true;
7742 
7743   // If there is no LXSIBZX/LXSIHZX, like Power8,
7744   // prefer direct move if the memory size is 1 or 2 bytes.
7745   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7746   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7747     return true;
7748 
7749   for (SDNode::use_iterator UI = Origin->use_begin(),
7750                             UE = Origin->use_end();
7751        UI != UE; ++UI) {
7752 
7753     // Only look at the users of the loaded value.
7754     if (UI.getUse().get().getResNo() != 0)
7755       continue;
7756 
7757     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7758         UI->getOpcode() != ISD::UINT_TO_FP)
7759       return true;
7760   }
7761 
7762   return false;
7763 }
7764 
7765 /// Custom lowers integer to floating point conversions to use
7766 /// the direct move instructions available in ISA 2.07 to avoid the
7767 /// need for load/store combinations.
7768 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7769                                                     SelectionDAG &DAG,
7770                                                     const SDLoc &dl) const {
7771   assert((Op.getValueType() == MVT::f32 ||
7772           Op.getValueType() == MVT::f64) &&
7773          "Invalid floating point type as target of conversion");
7774   assert(Subtarget.hasFPCVT() &&
7775          "Int to FP conversions with direct moves require FPCVT");
7776   SDValue FP;
7777   SDValue Src = Op.getOperand(0);
7778   bool SinglePrec = Op.getValueType() == MVT::f32;
7779   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7780   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7781   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7782                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7783 
7784   if (WordInt) {
7785     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7786                      dl, MVT::f64, Src);
7787     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7788   }
7789   else {
7790     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7791     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7792   }
7793 
7794   return FP;
7795 }
7796 
7797 static SDValue widenVec(SelectionDAG &DAG, SDValue Vec, const SDLoc &dl) {
7798 
7799   EVT VecVT = Vec.getValueType();
7800   assert(VecVT.isVector() && "Expected a vector type.");
7801   assert(VecVT.getSizeInBits() < 128 && "Vector is already full width.");
7802 
7803   EVT EltVT = VecVT.getVectorElementType();
7804   unsigned WideNumElts = 128 / EltVT.getSizeInBits();
7805   EVT WideVT = EVT::getVectorVT(*DAG.getContext(), EltVT, WideNumElts);
7806 
7807   unsigned NumConcat = WideNumElts / VecVT.getVectorNumElements();
7808   SmallVector<SDValue, 16> Ops(NumConcat);
7809   Ops[0] = Vec;
7810   SDValue UndefVec = DAG.getUNDEF(VecVT);
7811   for (unsigned i = 1; i < NumConcat; ++i)
7812     Ops[i] = UndefVec;
7813 
7814   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WideVT, Ops);
7815 }
7816 
7817 SDValue PPCTargetLowering::LowerINT_TO_FPVector(SDValue Op, SelectionDAG &DAG,
7818                                                 const SDLoc &dl) const {
7819 
7820   unsigned Opc = Op.getOpcode();
7821   assert((Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP) &&
7822          "Unexpected conversion type");
7823   assert((Op.getValueType() == MVT::v2f64 || Op.getValueType() == MVT::v4f32) &&
7824          "Supports conversions to v2f64/v4f32 only.");
7825 
7826   bool SignedConv = Opc == ISD::SINT_TO_FP;
7827   bool FourEltRes = Op.getValueType() == MVT::v4f32;
7828 
7829   SDValue Wide = widenVec(DAG, Op.getOperand(0), dl);
7830   EVT WideVT = Wide.getValueType();
7831   unsigned WideNumElts = WideVT.getVectorNumElements();
7832   MVT IntermediateVT = FourEltRes ? MVT::v4i32 : MVT::v2i64;
7833 
7834   SmallVector<int, 16> ShuffV;
7835   for (unsigned i = 0; i < WideNumElts; ++i)
7836     ShuffV.push_back(i + WideNumElts);
7837 
7838   int Stride = FourEltRes ? WideNumElts / 4 : WideNumElts / 2;
7839   int SaveElts = FourEltRes ? 4 : 2;
7840   if (Subtarget.isLittleEndian())
7841     for (int i = 0; i < SaveElts; i++)
7842       ShuffV[i * Stride] = i;
7843   else
7844     for (int i = 1; i <= SaveElts; i++)
7845       ShuffV[i * Stride - 1] = i - 1;
7846 
7847   SDValue ShuffleSrc2 =
7848       SignedConv ? DAG.getUNDEF(WideVT) : DAG.getConstant(0, dl, WideVT);
7849   SDValue Arrange = DAG.getVectorShuffle(WideVT, dl, Wide, ShuffleSrc2, ShuffV);
7850   unsigned ExtendOp =
7851       SignedConv ? (unsigned)PPCISD::SExtVElems : (unsigned)ISD::BITCAST;
7852 
7853   SDValue Extend;
7854   if (!Subtarget.hasP9Altivec() && SignedConv) {
7855     Arrange = DAG.getBitcast(IntermediateVT, Arrange);
7856     Extend = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, IntermediateVT, Arrange,
7857                          DAG.getValueType(Op.getOperand(0).getValueType()));
7858   } else
7859     Extend = DAG.getNode(ExtendOp, dl, IntermediateVT, Arrange);
7860 
7861   return DAG.getNode(Opc, dl, Op.getValueType(), Extend);
7862 }
7863 
7864 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7865                                           SelectionDAG &DAG) const {
7866   SDLoc dl(Op);
7867 
7868   EVT InVT = Op.getOperand(0).getValueType();
7869   EVT OutVT = Op.getValueType();
7870   if (OutVT.isVector() && OutVT.isFloatingPoint() &&
7871       isOperationCustom(Op.getOpcode(), InVT))
7872     return LowerINT_TO_FPVector(Op, DAG, dl);
7873 
7874   // Conversions to f128 are legal.
7875   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7876     return Op;
7877 
7878   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7879     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7880       return SDValue();
7881 
7882     SDValue Value = Op.getOperand(0);
7883     // The values are now known to be -1 (false) or 1 (true). To convert this
7884     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7885     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7886     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7887 
7888     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7889 
7890     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7891 
7892     if (Op.getValueType() != MVT::v4f64)
7893       Value = DAG.getNode(ISD::FP_ROUND, dl,
7894                           Op.getValueType(), Value,
7895                           DAG.getIntPtrConstant(1, dl));
7896     return Value;
7897   }
7898 
7899   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7900   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7901     return SDValue();
7902 
7903   if (Op.getOperand(0).getValueType() == MVT::i1)
7904     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7905                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7906                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7907 
7908   // If we have direct moves, we can do all the conversion, skip the store/load
7909   // however, without FPCVT we can't do most conversions.
7910   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7911       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7912     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7913 
7914   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7915          "UINT_TO_FP is supported only with FPCVT");
7916 
7917   // If we have FCFIDS, then use it when converting to single-precision.
7918   // Otherwise, convert to double-precision and then round.
7919   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7920                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7921                                                             : PPCISD::FCFIDS)
7922                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7923                                                             : PPCISD::FCFID);
7924   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7925                   ? MVT::f32
7926                   : MVT::f64;
7927 
7928   if (Op.getOperand(0).getValueType() == MVT::i64) {
7929     SDValue SINT = Op.getOperand(0);
7930     // When converting to single-precision, we actually need to convert
7931     // to double-precision first and then round to single-precision.
7932     // To avoid double-rounding effects during that operation, we have
7933     // to prepare the input operand.  Bits that might be truncated when
7934     // converting to double-precision are replaced by a bit that won't
7935     // be lost at this stage, but is below the single-precision rounding
7936     // position.
7937     //
7938     // However, if -enable-unsafe-fp-math is in effect, accept double
7939     // rounding to avoid the extra overhead.
7940     if (Op.getValueType() == MVT::f32 &&
7941         !Subtarget.hasFPCVT() &&
7942         !DAG.getTarget().Options.UnsafeFPMath) {
7943 
7944       // Twiddle input to make sure the low 11 bits are zero.  (If this
7945       // is the case, we are guaranteed the value will fit into the 53 bit
7946       // mantissa of an IEEE double-precision value without rounding.)
7947       // If any of those low 11 bits were not zero originally, make sure
7948       // bit 12 (value 2048) is set instead, so that the final rounding
7949       // to single-precision gets the correct result.
7950       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7951                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7952       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7953                           Round, DAG.getConstant(2047, dl, MVT::i64));
7954       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7955       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7956                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7957 
7958       // However, we cannot use that value unconditionally: if the magnitude
7959       // of the input value is small, the bit-twiddling we did above might
7960       // end up visibly changing the output.  Fortunately, in that case, we
7961       // don't need to twiddle bits since the original input will convert
7962       // exactly to double-precision floating-point already.  Therefore,
7963       // construct a conditional to use the original value if the top 11
7964       // bits are all sign-bit copies, and use the rounded value computed
7965       // above otherwise.
7966       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7967                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7968       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7969                          Cond, DAG.getConstant(1, dl, MVT::i64));
7970       Cond = DAG.getSetCC(dl, MVT::i32,
7971                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7972 
7973       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7974     }
7975 
7976     ReuseLoadInfo RLI;
7977     SDValue Bits;
7978 
7979     MachineFunction &MF = DAG.getMachineFunction();
7980     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7981       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7982                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7983       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7984     } else if (Subtarget.hasLFIWAX() &&
7985                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7986       MachineMemOperand *MMO =
7987         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7988                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7989       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7990       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7991                                      DAG.getVTList(MVT::f64, MVT::Other),
7992                                      Ops, MVT::i32, MMO);
7993       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7994     } else if (Subtarget.hasFPCVT() &&
7995                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7996       MachineMemOperand *MMO =
7997         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7998                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7999       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8000       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
8001                                      DAG.getVTList(MVT::f64, MVT::Other),
8002                                      Ops, MVT::i32, MMO);
8003       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
8004     } else if (((Subtarget.hasLFIWAX() &&
8005                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
8006                 (Subtarget.hasFPCVT() &&
8007                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
8008                SINT.getOperand(0).getValueType() == MVT::i32) {
8009       MachineFrameInfo &MFI = MF.getFrameInfo();
8010       EVT PtrVT = getPointerTy(DAG.getDataLayout());
8011 
8012       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8013       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8014 
8015       SDValue Store =
8016           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
8017                        MachinePointerInfo::getFixedStack(
8018                            DAG.getMachineFunction(), FrameIdx));
8019 
8020       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8021              "Expected an i32 store");
8022 
8023       RLI.Ptr = FIdx;
8024       RLI.Chain = Store;
8025       RLI.MPI =
8026           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8027       RLI.Alignment = 4;
8028 
8029       MachineMemOperand *MMO =
8030         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8031                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8032       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8033       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
8034                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
8035                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
8036                                      Ops, MVT::i32, MMO);
8037     } else
8038       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
8039 
8040     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
8041 
8042     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8043       FP = DAG.getNode(ISD::FP_ROUND, dl,
8044                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
8045     return FP;
8046   }
8047 
8048   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
8049          "Unhandled INT_TO_FP type in custom expander!");
8050   // Since we only generate this in 64-bit mode, we can take advantage of
8051   // 64-bit registers.  In particular, sign extend the input value into the
8052   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
8053   // then lfd it and fcfid it.
8054   MachineFunction &MF = DAG.getMachineFunction();
8055   MachineFrameInfo &MFI = MF.getFrameInfo();
8056   EVT PtrVT = getPointerTy(MF.getDataLayout());
8057 
8058   SDValue Ld;
8059   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
8060     ReuseLoadInfo RLI;
8061     bool ReusingLoad;
8062     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
8063                                             DAG))) {
8064       int FrameIdx = MFI.CreateStackObject(4, 4, false);
8065       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8066 
8067       SDValue Store =
8068           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8069                        MachinePointerInfo::getFixedStack(
8070                            DAG.getMachineFunction(), FrameIdx));
8071 
8072       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
8073              "Expected an i32 store");
8074 
8075       RLI.Ptr = FIdx;
8076       RLI.Chain = Store;
8077       RLI.MPI =
8078           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8079       RLI.Alignment = 4;
8080     }
8081 
8082     MachineMemOperand *MMO =
8083       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
8084                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
8085     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
8086     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
8087                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
8088                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
8089                                  Ops, MVT::i32, MMO);
8090     if (ReusingLoad)
8091       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
8092   } else {
8093     assert(Subtarget.isPPC64() &&
8094            "i32->FP without LFIWAX supported only on PPC64");
8095 
8096     int FrameIdx = MFI.CreateStackObject(8, 8, false);
8097     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8098 
8099     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
8100                                 Op.getOperand(0));
8101 
8102     // STD the extended value into the stack slot.
8103     SDValue Store = DAG.getStore(
8104         DAG.getEntryNode(), dl, Ext64, FIdx,
8105         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8106 
8107     // Load the value as a double.
8108     Ld = DAG.getLoad(
8109         MVT::f64, dl, Store, FIdx,
8110         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
8111   }
8112 
8113   // FCFID it and return it.
8114   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
8115   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
8116     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
8117                      DAG.getIntPtrConstant(0, dl));
8118   return FP;
8119 }
8120 
8121 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8122                                             SelectionDAG &DAG) const {
8123   SDLoc dl(Op);
8124   /*
8125    The rounding mode is in bits 30:31 of FPSR, and has the following
8126    settings:
8127      00 Round to nearest
8128      01 Round to 0
8129      10 Round to +inf
8130      11 Round to -inf
8131 
8132   FLT_ROUNDS, on the other hand, expects the following:
8133     -1 Undefined
8134      0 Round to 0
8135      1 Round to nearest
8136      2 Round to +inf
8137      3 Round to -inf
8138 
8139   To perform the conversion, we do:
8140     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
8141   */
8142 
8143   MachineFunction &MF = DAG.getMachineFunction();
8144   EVT VT = Op.getValueType();
8145   EVT PtrVT = getPointerTy(MF.getDataLayout());
8146 
8147   // Save FP Control Word to register
8148   EVT NodeTys[] = {
8149     MVT::f64,    // return register
8150     MVT::Glue    // unused in this context
8151   };
8152   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
8153 
8154   // Save FP register to stack slot
8155   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
8156   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
8157   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
8158                                MachinePointerInfo());
8159 
8160   // Load FP Control Word from low 32 bits of stack slot.
8161   SDValue Four = DAG.getConstant(4, dl, PtrVT);
8162   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
8163   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
8164 
8165   // Transform as necessary
8166   SDValue CWD1 =
8167     DAG.getNode(ISD::AND, dl, MVT::i32,
8168                 CWD, DAG.getConstant(3, dl, MVT::i32));
8169   SDValue CWD2 =
8170     DAG.getNode(ISD::SRL, dl, MVT::i32,
8171                 DAG.getNode(ISD::AND, dl, MVT::i32,
8172                             DAG.getNode(ISD::XOR, dl, MVT::i32,
8173                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
8174                             DAG.getConstant(3, dl, MVT::i32)),
8175                 DAG.getConstant(1, dl, MVT::i32));
8176 
8177   SDValue RetVal =
8178     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
8179 
8180   return DAG.getNode((VT.getSizeInBits() < 16 ?
8181                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8182 }
8183 
8184 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8185   EVT VT = Op.getValueType();
8186   unsigned BitWidth = VT.getSizeInBits();
8187   SDLoc dl(Op);
8188   assert(Op.getNumOperands() == 3 &&
8189          VT == Op.getOperand(1).getValueType() &&
8190          "Unexpected SHL!");
8191 
8192   // Expand into a bunch of logical ops.  Note that these ops
8193   // depend on the PPC behavior for oversized shift amounts.
8194   SDValue Lo = Op.getOperand(0);
8195   SDValue Hi = Op.getOperand(1);
8196   SDValue Amt = Op.getOperand(2);
8197   EVT AmtVT = Amt.getValueType();
8198 
8199   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8200                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8201   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
8202   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
8203   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
8204   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8205                              DAG.getConstant(-BitWidth, dl, AmtVT));
8206   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
8207   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8208   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
8209   SDValue OutOps[] = { OutLo, OutHi };
8210   return DAG.getMergeValues(OutOps, dl);
8211 }
8212 
8213 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
8214   EVT VT = Op.getValueType();
8215   SDLoc dl(Op);
8216   unsigned BitWidth = VT.getSizeInBits();
8217   assert(Op.getNumOperands() == 3 &&
8218          VT == Op.getOperand(1).getValueType() &&
8219          "Unexpected SRL!");
8220 
8221   // Expand into a bunch of logical ops.  Note that these ops
8222   // depend on the PPC behavior for oversized shift amounts.
8223   SDValue Lo = Op.getOperand(0);
8224   SDValue Hi = Op.getOperand(1);
8225   SDValue Amt = Op.getOperand(2);
8226   EVT AmtVT = Amt.getValueType();
8227 
8228   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
8229                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
8230   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
8231   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
8232   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8233   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
8234                              DAG.getConstant(-BitWidth, dl, AmtVT));
8235   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
8236   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
8237   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
8238   SDValue OutOps[] = { OutLo, OutHi };
8239   return DAG.getMergeValues(OutOps, dl);
8240 }
8241 
8242 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
8243   SDLoc dl(Op);
8244   EVT VT = Op.getValueType();
8245   unsigned BitWidth = VT.getSizeInBits();
8246   assert(Op.getNumOperands() == 3 &&
8247          VT == Op.getOperand(1).getValueType() &&
8248          "Unexpected SRA!");
8249 
8250   // Expand into a bunch of logical ops, followed by a select_cc.
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::SRL, dl, VT, Lo, Amt);
8259   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, 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::SRA, dl, VT, Hi, Tmp5);
8264   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
8265   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
8266                                   Tmp4, Tmp6, ISD::SETLE);
8267   SDValue OutOps[] = { OutLo, OutHi };
8268   return DAG.getMergeValues(OutOps, dl);
8269 }
8270 
8271 //===----------------------------------------------------------------------===//
8272 // Vector related lowering.
8273 //
8274 
8275 /// BuildSplatI - Build a canonical splati of Val with an element size of
8276 /// SplatSize.  Cast the result to VT.
8277 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
8278                            SelectionDAG &DAG, const SDLoc &dl) {
8279   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
8280 
8281   static const MVT VTys[] = { // canonical VT to use for each size.
8282     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
8283   };
8284 
8285   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
8286 
8287   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
8288   if (Val == -1)
8289     SplatSize = 1;
8290 
8291   EVT CanonicalVT = VTys[SplatSize-1];
8292 
8293   // Build a canonical splat for this value.
8294   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
8295 }
8296 
8297 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
8298 /// specified intrinsic ID.
8299 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
8300                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
8301   if (DestVT == MVT::Other) DestVT = Op.getValueType();
8302   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8303                      DAG.getConstant(IID, dl, MVT::i32), Op);
8304 }
8305 
8306 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
8307 /// specified intrinsic ID.
8308 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
8309                                 SelectionDAG &DAG, const SDLoc &dl,
8310                                 EVT DestVT = MVT::Other) {
8311   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
8312   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8313                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
8314 }
8315 
8316 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
8317 /// specified intrinsic ID.
8318 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
8319                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
8320                                 EVT DestVT = MVT::Other) {
8321   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
8322   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
8323                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
8324 }
8325 
8326 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
8327 /// amount.  The result has the specified value type.
8328 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
8329                            SelectionDAG &DAG, const SDLoc &dl) {
8330   // Force LHS/RHS to be the right type.
8331   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
8332   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
8333 
8334   int Ops[16];
8335   for (unsigned i = 0; i != 16; ++i)
8336     Ops[i] = i + Amt;
8337   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
8338   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8339 }
8340 
8341 /// Do we have an efficient pattern in a .td file for this node?
8342 ///
8343 /// \param V - pointer to the BuildVectorSDNode being matched
8344 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
8345 ///
8346 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
8347 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
8348 /// the opposite is true (expansion is beneficial) are:
8349 /// - The node builds a vector out of integers that are not 32 or 64-bits
8350 /// - The node builds a vector out of constants
8351 /// - The node is a "load-and-splat"
8352 /// In all other cases, we will choose to keep the BUILD_VECTOR.
8353 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
8354                                             bool HasDirectMove,
8355                                             bool HasP8Vector) {
8356   EVT VecVT = V->getValueType(0);
8357   bool RightType = VecVT == MVT::v2f64 ||
8358     (HasP8Vector && VecVT == MVT::v4f32) ||
8359     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
8360   if (!RightType)
8361     return false;
8362 
8363   bool IsSplat = true;
8364   bool IsLoad = false;
8365   SDValue Op0 = V->getOperand(0);
8366 
8367   // This function is called in a block that confirms the node is not a constant
8368   // splat. So a constant BUILD_VECTOR here means the vector is built out of
8369   // different constants.
8370   if (V->isConstant())
8371     return false;
8372   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
8373     if (V->getOperand(i).isUndef())
8374       return false;
8375     // We want to expand nodes that represent load-and-splat even if the
8376     // loaded value is a floating point truncation or conversion to int.
8377     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
8378         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
8379          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8380         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
8381          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
8382         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
8383          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
8384       IsLoad = true;
8385     // If the operands are different or the input is not a load and has more
8386     // uses than just this BV node, then it isn't a splat.
8387     if (V->getOperand(i) != Op0 ||
8388         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
8389       IsSplat = false;
8390   }
8391   return !(IsSplat && IsLoad);
8392 }
8393 
8394 // Lower BITCAST(f128, (build_pair i64, i64)) to BUILD_FP128.
8395 SDValue PPCTargetLowering::LowerBITCAST(SDValue Op, SelectionDAG &DAG) const {
8396 
8397   SDLoc dl(Op);
8398   SDValue Op0 = Op->getOperand(0);
8399 
8400   if (!EnableQuadPrecision ||
8401       (Op.getValueType() != MVT::f128 ) ||
8402       (Op0.getOpcode() != ISD::BUILD_PAIR) ||
8403       (Op0.getOperand(0).getValueType() !=  MVT::i64) ||
8404       (Op0.getOperand(1).getValueType() != MVT::i64))
8405     return SDValue();
8406 
8407   return DAG.getNode(PPCISD::BUILD_FP128, dl, MVT::f128, Op0.getOperand(0),
8408                      Op0.getOperand(1));
8409 }
8410 
8411 static const SDValue *getNormalLoadInput(const SDValue &Op) {
8412   const SDValue *InputLoad = &Op;
8413   if (InputLoad->getOpcode() == ISD::BITCAST)
8414     InputLoad = &InputLoad->getOperand(0);
8415   if (InputLoad->getOpcode() == ISD::SCALAR_TO_VECTOR)
8416     InputLoad = &InputLoad->getOperand(0);
8417   if (InputLoad->getOpcode() != ISD::LOAD)
8418     return nullptr;
8419   LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8420   return ISD::isNormalLoad(LD) ? InputLoad : nullptr;
8421 }
8422 
8423 // If this is a case we can't handle, return null and let the default
8424 // expansion code take care of it.  If we CAN select this case, and if it
8425 // selects to a single instruction, return Op.  Otherwise, if we can codegen
8426 // this case more efficiently than a constant pool load, lower it to the
8427 // sequence of ops that should be used.
8428 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
8429                                              SelectionDAG &DAG) const {
8430   SDLoc dl(Op);
8431   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
8432   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
8433 
8434   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
8435     // We first build an i32 vector, load it into a QPX register,
8436     // then convert it to a floating-point vector and compare it
8437     // to a zero vector to get the boolean result.
8438     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8439     int FrameIdx = MFI.CreateStackObject(16, 16, false);
8440     MachinePointerInfo PtrInfo =
8441         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8442     EVT PtrVT = getPointerTy(DAG.getDataLayout());
8443     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8444 
8445     assert(BVN->getNumOperands() == 4 &&
8446       "BUILD_VECTOR for v4i1 does not have 4 operands");
8447 
8448     bool IsConst = true;
8449     for (unsigned i = 0; i < 4; ++i) {
8450       if (BVN->getOperand(i).isUndef()) continue;
8451       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
8452         IsConst = false;
8453         break;
8454       }
8455     }
8456 
8457     if (IsConst) {
8458       Constant *One =
8459         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
8460       Constant *NegOne =
8461         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
8462 
8463       Constant *CV[4];
8464       for (unsigned i = 0; i < 4; ++i) {
8465         if (BVN->getOperand(i).isUndef())
8466           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
8467         else if (isNullConstant(BVN->getOperand(i)))
8468           CV[i] = NegOne;
8469         else
8470           CV[i] = One;
8471       }
8472 
8473       Constant *CP = ConstantVector::get(CV);
8474       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
8475                                           16 /* alignment */);
8476 
8477       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
8478       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
8479       return DAG.getMemIntrinsicNode(
8480           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
8481           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
8482     }
8483 
8484     SmallVector<SDValue, 4> Stores;
8485     for (unsigned i = 0; i < 4; ++i) {
8486       if (BVN->getOperand(i).isUndef()) continue;
8487 
8488       unsigned Offset = 4*i;
8489       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8490       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8491 
8492       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
8493       if (StoreSize > 4) {
8494         Stores.push_back(
8495             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
8496                               PtrInfo.getWithOffset(Offset), MVT::i32));
8497       } else {
8498         SDValue StoreValue = BVN->getOperand(i);
8499         if (StoreSize < 4)
8500           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
8501 
8502         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
8503                                       PtrInfo.getWithOffset(Offset)));
8504       }
8505     }
8506 
8507     SDValue StoreChain;
8508     if (!Stores.empty())
8509       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8510     else
8511       StoreChain = DAG.getEntryNode();
8512 
8513     // Now load from v4i32 into the QPX register; this will extend it to
8514     // v4i64 but not yet convert it to a floating point. Nevertheless, this
8515     // is typed as v4f64 because the QPX register integer states are not
8516     // explicitly represented.
8517 
8518     SDValue Ops[] = {StoreChain,
8519                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
8520                      FIdx};
8521     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
8522 
8523     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
8524       dl, VTs, Ops, MVT::v4i32, PtrInfo);
8525     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8526       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
8527       LoadedVect);
8528 
8529     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
8530 
8531     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
8532   }
8533 
8534   // All other QPX vectors are handled by generic code.
8535   if (Subtarget.hasQPX())
8536     return SDValue();
8537 
8538   // Check if this is a splat of a constant value.
8539   APInt APSplatBits, APSplatUndef;
8540   unsigned SplatBitSize;
8541   bool HasAnyUndefs;
8542   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
8543                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
8544       SplatBitSize > 32) {
8545 
8546     const SDValue *InputLoad = getNormalLoadInput(Op.getOperand(0));
8547     // Handle load-and-splat patterns as we have instructions that will do this
8548     // in one go.
8549     if (InputLoad && DAG.isSplatValue(Op, true)) {
8550       LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
8551 
8552       // We have handling for 4 and 8 byte elements.
8553       unsigned ElementSize = LD->getMemoryVT().getScalarSizeInBits();
8554 
8555       // Checking for a single use of this load, we have to check for vector
8556       // width (128 bits) / ElementSize uses (since each operand of the
8557       // BUILD_VECTOR is a separate use of the value.
8558       if (InputLoad->getNode()->hasNUsesOfValue(128 / ElementSize, 0) &&
8559           ((Subtarget.hasVSX() && ElementSize == 64) ||
8560            (Subtarget.hasP9Vector() && ElementSize == 32))) {
8561         SDValue Ops[] = {
8562           LD->getChain(),    // Chain
8563           LD->getBasePtr(),  // Ptr
8564           DAG.getValueType(Op.getValueType()) // VT
8565         };
8566         return
8567           DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl,
8568                                   DAG.getVTList(Op.getValueType(), MVT::Other),
8569                                   Ops, LD->getMemoryVT(), LD->getMemOperand());
8570       }
8571     }
8572 
8573     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
8574     // lowered to VSX instructions under certain conditions.
8575     // Without VSX, there is no pattern more efficient than expanding the node.
8576     if (Subtarget.hasVSX() &&
8577         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
8578                                         Subtarget.hasP8Vector()))
8579       return Op;
8580     return SDValue();
8581   }
8582 
8583   unsigned SplatBits = APSplatBits.getZExtValue();
8584   unsigned SplatUndef = APSplatUndef.getZExtValue();
8585   unsigned SplatSize = SplatBitSize / 8;
8586 
8587   // First, handle single instruction cases.
8588 
8589   // All zeros?
8590   if (SplatBits == 0) {
8591     // Canonicalize all zero vectors to be v4i32.
8592     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
8593       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
8594       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
8595     }
8596     return Op;
8597   }
8598 
8599   // We have XXSPLTIB for constant splats one byte wide
8600   if (Subtarget.hasP9Vector() && SplatSize == 1) {
8601     // This is a splat of 1-byte elements with some elements potentially undef.
8602     // Rather than trying to match undef in the SDAG patterns, ensure that all
8603     // elements are the same constant.
8604     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
8605       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
8606                                                        dl, MVT::i32));
8607       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
8608       if (Op.getValueType() != MVT::v16i8)
8609         return DAG.getBitcast(Op.getValueType(), NewBV);
8610       return NewBV;
8611     }
8612 
8613     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
8614     // detect that constant splats like v8i16: 0xABAB are really just splats
8615     // of a 1-byte constant. In this case, we need to convert the node to a
8616     // splat of v16i8 and a bitcast.
8617     if (Op.getValueType() != MVT::v16i8)
8618       return DAG.getBitcast(Op.getValueType(),
8619                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
8620 
8621     return Op;
8622   }
8623 
8624   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
8625   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
8626                     (32-SplatBitSize));
8627   if (SextVal >= -16 && SextVal <= 15)
8628     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
8629 
8630   // Two instruction sequences.
8631 
8632   // If this value is in the range [-32,30] and is even, use:
8633   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
8634   // If this value is in the range [17,31] and is odd, use:
8635   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
8636   // If this value is in the range [-31,-17] and is odd, use:
8637   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
8638   // Note the last two are three-instruction sequences.
8639   if (SextVal >= -32 && SextVal <= 31) {
8640     // To avoid having these optimizations undone by constant folding,
8641     // we convert to a pseudo that will be expanded later into one of
8642     // the above forms.
8643     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
8644     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
8645               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
8646     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
8647     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
8648     if (VT == Op.getValueType())
8649       return RetVal;
8650     else
8651       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
8652   }
8653 
8654   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
8655   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
8656   // for fneg/fabs.
8657   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
8658     // Make -1 and vspltisw -1:
8659     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
8660 
8661     // Make the VSLW intrinsic, computing 0x8000_0000.
8662     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
8663                                    OnesV, DAG, dl);
8664 
8665     // xor by OnesV to invert it.
8666     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
8667     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8668   }
8669 
8670   // Check to see if this is a wide variety of vsplti*, binop self cases.
8671   static const signed char SplatCsts[] = {
8672     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
8673     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
8674   };
8675 
8676   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
8677     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
8678     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
8679     int i = SplatCsts[idx];
8680 
8681     // Figure out what shift amount will be used by altivec if shifted by i in
8682     // this splat size.
8683     unsigned TypeShiftAmt = i & (SplatBitSize-1);
8684 
8685     // vsplti + shl self.
8686     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
8687       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8688       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8689         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
8690         Intrinsic::ppc_altivec_vslw
8691       };
8692       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8693       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8694     }
8695 
8696     // vsplti + srl self.
8697     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8698       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8699       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8700         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
8701         Intrinsic::ppc_altivec_vsrw
8702       };
8703       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8704       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8705     }
8706 
8707     // vsplti + sra self.
8708     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
8709       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8710       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8711         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
8712         Intrinsic::ppc_altivec_vsraw
8713       };
8714       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8715       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8716     }
8717 
8718     // vsplti + rol self.
8719     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
8720                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
8721       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
8722       static const unsigned IIDs[] = { // Intrinsic to use for each size.
8723         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
8724         Intrinsic::ppc_altivec_vrlw
8725       };
8726       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
8727       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
8728     }
8729 
8730     // t = vsplti c, result = vsldoi t, t, 1
8731     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
8732       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8733       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
8734       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8735     }
8736     // t = vsplti c, result = vsldoi t, t, 2
8737     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
8738       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8739       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
8740       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8741     }
8742     // t = vsplti c, result = vsldoi t, t, 3
8743     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
8744       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
8745       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
8746       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
8747     }
8748   }
8749 
8750   return SDValue();
8751 }
8752 
8753 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
8754 /// the specified operations to build the shuffle.
8755 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
8756                                       SDValue RHS, SelectionDAG &DAG,
8757                                       const SDLoc &dl) {
8758   unsigned OpNum = (PFEntry >> 26) & 0x0F;
8759   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
8760   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
8761 
8762   enum {
8763     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
8764     OP_VMRGHW,
8765     OP_VMRGLW,
8766     OP_VSPLTISW0,
8767     OP_VSPLTISW1,
8768     OP_VSPLTISW2,
8769     OP_VSPLTISW3,
8770     OP_VSLDOI4,
8771     OP_VSLDOI8,
8772     OP_VSLDOI12
8773   };
8774 
8775   if (OpNum == OP_COPY) {
8776     if (LHSID == (1*9+2)*9+3) return LHS;
8777     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
8778     return RHS;
8779   }
8780 
8781   SDValue OpLHS, OpRHS;
8782   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
8783   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
8784 
8785   int ShufIdxs[16];
8786   switch (OpNum) {
8787   default: llvm_unreachable("Unknown i32 permute!");
8788   case OP_VMRGHW:
8789     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
8790     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
8791     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
8792     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
8793     break;
8794   case OP_VMRGLW:
8795     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
8796     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8797     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8798     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8799     break;
8800   case OP_VSPLTISW0:
8801     for (unsigned i = 0; i != 16; ++i)
8802       ShufIdxs[i] = (i&3)+0;
8803     break;
8804   case OP_VSPLTISW1:
8805     for (unsigned i = 0; i != 16; ++i)
8806       ShufIdxs[i] = (i&3)+4;
8807     break;
8808   case OP_VSPLTISW2:
8809     for (unsigned i = 0; i != 16; ++i)
8810       ShufIdxs[i] = (i&3)+8;
8811     break;
8812   case OP_VSPLTISW3:
8813     for (unsigned i = 0; i != 16; ++i)
8814       ShufIdxs[i] = (i&3)+12;
8815     break;
8816   case OP_VSLDOI4:
8817     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8818   case OP_VSLDOI8:
8819     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8820   case OP_VSLDOI12:
8821     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8822   }
8823   EVT VT = OpLHS.getValueType();
8824   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8825   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8826   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8827   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8828 }
8829 
8830 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8831 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8832 /// SDValue.
8833 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8834                                            SelectionDAG &DAG) const {
8835   const unsigned BytesInVector = 16;
8836   bool IsLE = Subtarget.isLittleEndian();
8837   SDLoc dl(N);
8838   SDValue V1 = N->getOperand(0);
8839   SDValue V2 = N->getOperand(1);
8840   unsigned ShiftElts = 0, InsertAtByte = 0;
8841   bool Swap = false;
8842 
8843   // Shifts required to get the byte we want at element 7.
8844   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8845                                    0, 15, 14, 13, 12, 11, 10, 9};
8846   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8847                                 1, 2,  3,  4,  5,  6,  7,  8};
8848 
8849   ArrayRef<int> Mask = N->getMask();
8850   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8851 
8852   // For each mask element, find out if we're just inserting something
8853   // from V2 into V1 or vice versa.
8854   // Possible permutations inserting an element from V2 into V1:
8855   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8856   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8857   //   ...
8858   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8859   // Inserting from V1 into V2 will be similar, except mask range will be
8860   // [16,31].
8861 
8862   bool FoundCandidate = false;
8863   // If both vector operands for the shuffle are the same vector, the mask
8864   // will contain only elements from the first one and the second one will be
8865   // undef.
8866   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8867   // Go through the mask of half-words to find an element that's being moved
8868   // from one vector to the other.
8869   for (unsigned i = 0; i < BytesInVector; ++i) {
8870     unsigned CurrentElement = Mask[i];
8871     // If 2nd operand is undefined, we should only look for element 7 in the
8872     // Mask.
8873     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8874       continue;
8875 
8876     bool OtherElementsInOrder = true;
8877     // Examine the other elements in the Mask to see if they're in original
8878     // order.
8879     for (unsigned j = 0; j < BytesInVector; ++j) {
8880       if (j == i)
8881         continue;
8882       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8883       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8884       // in which we always assume we're always picking from the 1st operand.
8885       int MaskOffset =
8886           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8887       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8888         OtherElementsInOrder = false;
8889         break;
8890       }
8891     }
8892     // If other elements are in original order, we record the number of shifts
8893     // we need to get the element we want into element 7. Also record which byte
8894     // in the vector we should insert into.
8895     if (OtherElementsInOrder) {
8896       // If 2nd operand is undefined, we assume no shifts and no swapping.
8897       if (V2.isUndef()) {
8898         ShiftElts = 0;
8899         Swap = false;
8900       } else {
8901         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8902         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8903                          : BigEndianShifts[CurrentElement & 0xF];
8904         Swap = CurrentElement < BytesInVector;
8905       }
8906       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8907       FoundCandidate = true;
8908       break;
8909     }
8910   }
8911 
8912   if (!FoundCandidate)
8913     return SDValue();
8914 
8915   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8916   // optionally with VECSHL if shift is required.
8917   if (Swap)
8918     std::swap(V1, V2);
8919   if (V2.isUndef())
8920     V2 = V1;
8921   if (ShiftElts) {
8922     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8923                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8924     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8925                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8926   }
8927   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8928                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8929 }
8930 
8931 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8932 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8933 /// SDValue.
8934 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8935                                            SelectionDAG &DAG) const {
8936   const unsigned NumHalfWords = 8;
8937   const unsigned BytesInVector = NumHalfWords * 2;
8938   // Check that the shuffle is on half-words.
8939   if (!isNByteElemShuffleMask(N, 2, 1))
8940     return SDValue();
8941 
8942   bool IsLE = Subtarget.isLittleEndian();
8943   SDLoc dl(N);
8944   SDValue V1 = N->getOperand(0);
8945   SDValue V2 = N->getOperand(1);
8946   unsigned ShiftElts = 0, InsertAtByte = 0;
8947   bool Swap = false;
8948 
8949   // Shifts required to get the half-word we want at element 3.
8950   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8951   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8952 
8953   uint32_t Mask = 0;
8954   uint32_t OriginalOrderLow = 0x1234567;
8955   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8956   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8957   // 32-bit space, only need 4-bit nibbles per element.
8958   for (unsigned i = 0; i < NumHalfWords; ++i) {
8959     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8960     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8961   }
8962 
8963   // For each mask element, find out if we're just inserting something
8964   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8965   // from V2 into V1:
8966   //   X, 1, 2, 3, 4, 5, 6, 7
8967   //   0, X, 2, 3, 4, 5, 6, 7
8968   //   0, 1, X, 3, 4, 5, 6, 7
8969   //   0, 1, 2, X, 4, 5, 6, 7
8970   //   0, 1, 2, 3, X, 5, 6, 7
8971   //   0, 1, 2, 3, 4, X, 6, 7
8972   //   0, 1, 2, 3, 4, 5, X, 7
8973   //   0, 1, 2, 3, 4, 5, 6, X
8974   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8975 
8976   bool FoundCandidate = false;
8977   // Go through the mask of half-words to find an element that's being moved
8978   // from one vector to the other.
8979   for (unsigned i = 0; i < NumHalfWords; ++i) {
8980     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8981     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8982     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8983     uint32_t TargetOrder = 0x0;
8984 
8985     // If both vector operands for the shuffle are the same vector, the mask
8986     // will contain only elements from the first one and the second one will be
8987     // undef.
8988     if (V2.isUndef()) {
8989       ShiftElts = 0;
8990       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8991       TargetOrder = OriginalOrderLow;
8992       Swap = false;
8993       // Skip if not the correct element or mask of other elements don't equal
8994       // to our expected order.
8995       if (MaskOneElt == VINSERTHSrcElem &&
8996           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8997         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8998         FoundCandidate = true;
8999         break;
9000       }
9001     } else { // If both operands are defined.
9002       // Target order is [8,15] if the current mask is between [0,7].
9003       TargetOrder =
9004           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
9005       // Skip if mask of other elements don't equal our expected order.
9006       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
9007         // We only need the last 3 bits for the number of shifts.
9008         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
9009                          : BigEndianShifts[MaskOneElt & 0x7];
9010         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
9011         Swap = MaskOneElt < NumHalfWords;
9012         FoundCandidate = true;
9013         break;
9014       }
9015     }
9016   }
9017 
9018   if (!FoundCandidate)
9019     return SDValue();
9020 
9021   // Candidate found, construct the proper SDAG sequence with VINSERTH,
9022   // optionally with VECSHL if shift is required.
9023   if (Swap)
9024     std::swap(V1, V2);
9025   if (V2.isUndef())
9026     V2 = V1;
9027   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9028   if (ShiftElts) {
9029     // Double ShiftElts because we're left shifting on v16i8 type.
9030     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
9031                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
9032     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
9033     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9034                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9035     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9036   }
9037   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9038   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
9039                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
9040   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9041 }
9042 
9043 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
9044 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
9045 /// return the code it can be lowered into.  Worst case, it can always be
9046 /// lowered into a vperm.
9047 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
9048                                                SelectionDAG &DAG) const {
9049   SDLoc dl(Op);
9050   SDValue V1 = Op.getOperand(0);
9051   SDValue V2 = Op.getOperand(1);
9052   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9053   EVT VT = Op.getValueType();
9054   bool isLittleEndian = Subtarget.isLittleEndian();
9055 
9056   unsigned ShiftElts, InsertAtByte;
9057   bool Swap = false;
9058 
9059   // If this is a load-and-splat, we can do that with a single instruction
9060   // in some cases. However if the load has multiple uses, we don't want to
9061   // combine it because that will just produce multiple loads.
9062   const SDValue *InputLoad = getNormalLoadInput(V1);
9063   if (InputLoad && Subtarget.hasVSX() && V2.isUndef() &&
9064       (PPC::isSplatShuffleMask(SVOp, 4) || PPC::isSplatShuffleMask(SVOp, 8)) &&
9065       InputLoad->hasOneUse()) {
9066     bool IsFourByte = PPC::isSplatShuffleMask(SVOp, 4);
9067     int SplatIdx =
9068       PPC::getSplatIdxForPPCMnemonics(SVOp, IsFourByte ? 4 : 8, DAG);
9069 
9070     LoadSDNode *LD = cast<LoadSDNode>(*InputLoad);
9071     // For 4-byte load-and-splat, we need Power9.
9072     if ((IsFourByte && Subtarget.hasP9Vector()) || !IsFourByte) {
9073       uint64_t Offset = 0;
9074       if (IsFourByte)
9075         Offset = isLittleEndian ? (3 - SplatIdx) * 4 : SplatIdx * 4;
9076       else
9077         Offset = isLittleEndian ? (1 - SplatIdx) * 8 : SplatIdx * 8;
9078       SDValue BasePtr = LD->getBasePtr();
9079       if (Offset != 0)
9080         BasePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
9081                               BasePtr, DAG.getIntPtrConstant(Offset, dl));
9082       SDValue Ops[] = {
9083         LD->getChain(),    // Chain
9084         BasePtr,           // BasePtr
9085         DAG.getValueType(Op.getValueType()) // VT
9086       };
9087       SDVTList VTL =
9088         DAG.getVTList(IsFourByte ? MVT::v4i32 : MVT::v2i64, MVT::Other);
9089       SDValue LdSplt =
9090         DAG.getMemIntrinsicNode(PPCISD::LD_SPLAT, dl, VTL,
9091                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
9092       if (LdSplt.getValueType() != SVOp->getValueType(0))
9093         LdSplt = DAG.getBitcast(SVOp->getValueType(0), LdSplt);
9094       return LdSplt;
9095     }
9096   }
9097   if (Subtarget.hasP9Vector() &&
9098       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
9099                            isLittleEndian)) {
9100     if (Swap)
9101       std::swap(V1, V2);
9102     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9103     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
9104     if (ShiftElts) {
9105       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
9106                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
9107       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
9108                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
9109       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9110     }
9111     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
9112                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
9113     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
9114   }
9115 
9116   if (Subtarget.hasP9Altivec()) {
9117     SDValue NewISDNode;
9118     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
9119       return NewISDNode;
9120 
9121     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
9122       return NewISDNode;
9123   }
9124 
9125   if (Subtarget.hasVSX() &&
9126       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9127     if (Swap)
9128       std::swap(V1, V2);
9129     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9130     SDValue Conv2 =
9131         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
9132 
9133     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
9134                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9135     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
9136   }
9137 
9138   if (Subtarget.hasVSX() &&
9139     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
9140     if (Swap)
9141       std::swap(V1, V2);
9142     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9143     SDValue Conv2 =
9144         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
9145 
9146     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
9147                               DAG.getConstant(ShiftElts, dl, MVT::i32));
9148     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
9149   }
9150 
9151   if (Subtarget.hasP9Vector()) {
9152      if (PPC::isXXBRHShuffleMask(SVOp)) {
9153       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9154       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
9155       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
9156     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
9157       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9158       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
9159       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
9160     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
9161       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
9162       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
9163       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
9164     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
9165       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
9166       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
9167       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
9168     }
9169   }
9170 
9171   if (Subtarget.hasVSX()) {
9172     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
9173       int SplatIdx = PPC::getSplatIdxForPPCMnemonics(SVOp, 4, DAG);
9174 
9175       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
9176       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
9177                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
9178       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
9179     }
9180 
9181     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
9182     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
9183       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9184       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
9185       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
9186     }
9187   }
9188 
9189   if (Subtarget.hasQPX()) {
9190     if (VT.getVectorNumElements() != 4)
9191       return SDValue();
9192 
9193     if (V2.isUndef()) V2 = V1;
9194 
9195     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
9196     if (AlignIdx != -1) {
9197       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
9198                          DAG.getConstant(AlignIdx, dl, MVT::i32));
9199     } else if (SVOp->isSplat()) {
9200       int SplatIdx = SVOp->getSplatIndex();
9201       if (SplatIdx >= 4) {
9202         std::swap(V1, V2);
9203         SplatIdx -= 4;
9204       }
9205 
9206       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
9207                          DAG.getConstant(SplatIdx, dl, MVT::i32));
9208     }
9209 
9210     // Lower this into a qvgpci/qvfperm pair.
9211 
9212     // Compute the qvgpci literal
9213     unsigned idx = 0;
9214     for (unsigned i = 0; i < 4; ++i) {
9215       int m = SVOp->getMaskElt(i);
9216       unsigned mm = m >= 0 ? (unsigned) m : i;
9217       idx |= mm << (3-i)*3;
9218     }
9219 
9220     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
9221                              DAG.getConstant(idx, dl, MVT::i32));
9222     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
9223   }
9224 
9225   // Cases that are handled by instructions that take permute immediates
9226   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
9227   // selected by the instruction selector.
9228   if (V2.isUndef()) {
9229     if (PPC::isSplatShuffleMask(SVOp, 1) ||
9230         PPC::isSplatShuffleMask(SVOp, 2) ||
9231         PPC::isSplatShuffleMask(SVOp, 4) ||
9232         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
9233         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
9234         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
9235         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
9236         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
9237         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
9238         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
9239         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
9240         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
9241         (Subtarget.hasP8Altivec() && (
9242          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
9243          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
9244          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
9245       return Op;
9246     }
9247   }
9248 
9249   // Altivec has a variety of "shuffle immediates" that take two vector inputs
9250   // and produce a fixed permutation.  If any of these match, do not lower to
9251   // VPERM.
9252   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
9253   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9254       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9255       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
9256       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9257       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9258       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9259       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
9260       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
9261       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
9262       (Subtarget.hasP8Altivec() && (
9263        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
9264        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
9265        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
9266     return Op;
9267 
9268   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
9269   // perfect shuffle table to emit an optimal matching sequence.
9270   ArrayRef<int> PermMask = SVOp->getMask();
9271 
9272   unsigned PFIndexes[4];
9273   bool isFourElementShuffle = true;
9274   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
9275     unsigned EltNo = 8;   // Start out undef.
9276     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
9277       if (PermMask[i*4+j] < 0)
9278         continue;   // Undef, ignore it.
9279 
9280       unsigned ByteSource = PermMask[i*4+j];
9281       if ((ByteSource & 3) != j) {
9282         isFourElementShuffle = false;
9283         break;
9284       }
9285 
9286       if (EltNo == 8) {
9287         EltNo = ByteSource/4;
9288       } else if (EltNo != ByteSource/4) {
9289         isFourElementShuffle = false;
9290         break;
9291       }
9292     }
9293     PFIndexes[i] = EltNo;
9294   }
9295 
9296   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
9297   // perfect shuffle vector to determine if it is cost effective to do this as
9298   // discrete instructions, or whether we should use a vperm.
9299   // For now, we skip this for little endian until such time as we have a
9300   // little-endian perfect shuffle table.
9301   if (isFourElementShuffle && !isLittleEndian) {
9302     // Compute the index in the perfect shuffle table.
9303     unsigned PFTableIndex =
9304       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
9305 
9306     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
9307     unsigned Cost  = (PFEntry >> 30);
9308 
9309     // Determining when to avoid vperm is tricky.  Many things affect the cost
9310     // of vperm, particularly how many times the perm mask needs to be computed.
9311     // For example, if the perm mask can be hoisted out of a loop or is already
9312     // used (perhaps because there are multiple permutes with the same shuffle
9313     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
9314     // the loop requires an extra register.
9315     //
9316     // As a compromise, we only emit discrete instructions if the shuffle can be
9317     // generated in 3 or fewer operations.  When we have loop information
9318     // available, if this block is within a loop, we should avoid using vperm
9319     // for 3-operation perms and use a constant pool load instead.
9320     if (Cost < 3)
9321       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
9322   }
9323 
9324   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
9325   // vector that will get spilled to the constant pool.
9326   if (V2.isUndef()) V2 = V1;
9327 
9328   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
9329   // that it is in input element units, not in bytes.  Convert now.
9330 
9331   // For little endian, the order of the input vectors is reversed, and
9332   // the permutation mask is complemented with respect to 31.  This is
9333   // necessary to produce proper semantics with the big-endian-biased vperm
9334   // instruction.
9335   EVT EltVT = V1.getValueType().getVectorElementType();
9336   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
9337 
9338   SmallVector<SDValue, 16> ResultMask;
9339   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
9340     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
9341 
9342     for (unsigned j = 0; j != BytesPerElement; ++j)
9343       if (isLittleEndian)
9344         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
9345                                              dl, MVT::i32));
9346       else
9347         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
9348                                              MVT::i32));
9349   }
9350 
9351   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
9352   if (isLittleEndian)
9353     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9354                        V2, V1, VPermMask);
9355   else
9356     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
9357                        V1, V2, VPermMask);
9358 }
9359 
9360 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
9361 /// vector comparison.  If it is, return true and fill in Opc/isDot with
9362 /// information about the intrinsic.
9363 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
9364                                  bool &isDot, const PPCSubtarget &Subtarget) {
9365   unsigned IntrinsicID =
9366       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
9367   CompareOpc = -1;
9368   isDot = false;
9369   switch (IntrinsicID) {
9370   default:
9371     return false;
9372   // Comparison predicates.
9373   case Intrinsic::ppc_altivec_vcmpbfp_p:
9374     CompareOpc = 966;
9375     isDot = true;
9376     break;
9377   case Intrinsic::ppc_altivec_vcmpeqfp_p:
9378     CompareOpc = 198;
9379     isDot = true;
9380     break;
9381   case Intrinsic::ppc_altivec_vcmpequb_p:
9382     CompareOpc = 6;
9383     isDot = true;
9384     break;
9385   case Intrinsic::ppc_altivec_vcmpequh_p:
9386     CompareOpc = 70;
9387     isDot = true;
9388     break;
9389   case Intrinsic::ppc_altivec_vcmpequw_p:
9390     CompareOpc = 134;
9391     isDot = true;
9392     break;
9393   case Intrinsic::ppc_altivec_vcmpequd_p:
9394     if (Subtarget.hasP8Altivec()) {
9395       CompareOpc = 199;
9396       isDot = true;
9397     } else
9398       return false;
9399     break;
9400   case Intrinsic::ppc_altivec_vcmpneb_p:
9401   case Intrinsic::ppc_altivec_vcmpneh_p:
9402   case Intrinsic::ppc_altivec_vcmpnew_p:
9403   case Intrinsic::ppc_altivec_vcmpnezb_p:
9404   case Intrinsic::ppc_altivec_vcmpnezh_p:
9405   case Intrinsic::ppc_altivec_vcmpnezw_p:
9406     if (Subtarget.hasP9Altivec()) {
9407       switch (IntrinsicID) {
9408       default:
9409         llvm_unreachable("Unknown comparison intrinsic.");
9410       case Intrinsic::ppc_altivec_vcmpneb_p:
9411         CompareOpc = 7;
9412         break;
9413       case Intrinsic::ppc_altivec_vcmpneh_p:
9414         CompareOpc = 71;
9415         break;
9416       case Intrinsic::ppc_altivec_vcmpnew_p:
9417         CompareOpc = 135;
9418         break;
9419       case Intrinsic::ppc_altivec_vcmpnezb_p:
9420         CompareOpc = 263;
9421         break;
9422       case Intrinsic::ppc_altivec_vcmpnezh_p:
9423         CompareOpc = 327;
9424         break;
9425       case Intrinsic::ppc_altivec_vcmpnezw_p:
9426         CompareOpc = 391;
9427         break;
9428       }
9429       isDot = true;
9430     } else
9431       return false;
9432     break;
9433   case Intrinsic::ppc_altivec_vcmpgefp_p:
9434     CompareOpc = 454;
9435     isDot = true;
9436     break;
9437   case Intrinsic::ppc_altivec_vcmpgtfp_p:
9438     CompareOpc = 710;
9439     isDot = true;
9440     break;
9441   case Intrinsic::ppc_altivec_vcmpgtsb_p:
9442     CompareOpc = 774;
9443     isDot = true;
9444     break;
9445   case Intrinsic::ppc_altivec_vcmpgtsh_p:
9446     CompareOpc = 838;
9447     isDot = true;
9448     break;
9449   case Intrinsic::ppc_altivec_vcmpgtsw_p:
9450     CompareOpc = 902;
9451     isDot = true;
9452     break;
9453   case Intrinsic::ppc_altivec_vcmpgtsd_p:
9454     if (Subtarget.hasP8Altivec()) {
9455       CompareOpc = 967;
9456       isDot = true;
9457     } else
9458       return false;
9459     break;
9460   case Intrinsic::ppc_altivec_vcmpgtub_p:
9461     CompareOpc = 518;
9462     isDot = true;
9463     break;
9464   case Intrinsic::ppc_altivec_vcmpgtuh_p:
9465     CompareOpc = 582;
9466     isDot = true;
9467     break;
9468   case Intrinsic::ppc_altivec_vcmpgtuw_p:
9469     CompareOpc = 646;
9470     isDot = true;
9471     break;
9472   case Intrinsic::ppc_altivec_vcmpgtud_p:
9473     if (Subtarget.hasP8Altivec()) {
9474       CompareOpc = 711;
9475       isDot = true;
9476     } else
9477       return false;
9478     break;
9479 
9480   // VSX predicate comparisons use the same infrastructure
9481   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9482   case Intrinsic::ppc_vsx_xvcmpgedp_p:
9483   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9484   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9485   case Intrinsic::ppc_vsx_xvcmpgesp_p:
9486   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9487     if (Subtarget.hasVSX()) {
9488       switch (IntrinsicID) {
9489       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
9490         CompareOpc = 99;
9491         break;
9492       case Intrinsic::ppc_vsx_xvcmpgedp_p:
9493         CompareOpc = 115;
9494         break;
9495       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
9496         CompareOpc = 107;
9497         break;
9498       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
9499         CompareOpc = 67;
9500         break;
9501       case Intrinsic::ppc_vsx_xvcmpgesp_p:
9502         CompareOpc = 83;
9503         break;
9504       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
9505         CompareOpc = 75;
9506         break;
9507       }
9508       isDot = true;
9509     } else
9510       return false;
9511     break;
9512 
9513   // Normal Comparisons.
9514   case Intrinsic::ppc_altivec_vcmpbfp:
9515     CompareOpc = 966;
9516     break;
9517   case Intrinsic::ppc_altivec_vcmpeqfp:
9518     CompareOpc = 198;
9519     break;
9520   case Intrinsic::ppc_altivec_vcmpequb:
9521     CompareOpc = 6;
9522     break;
9523   case Intrinsic::ppc_altivec_vcmpequh:
9524     CompareOpc = 70;
9525     break;
9526   case Intrinsic::ppc_altivec_vcmpequw:
9527     CompareOpc = 134;
9528     break;
9529   case Intrinsic::ppc_altivec_vcmpequd:
9530     if (Subtarget.hasP8Altivec())
9531       CompareOpc = 199;
9532     else
9533       return false;
9534     break;
9535   case Intrinsic::ppc_altivec_vcmpneb:
9536   case Intrinsic::ppc_altivec_vcmpneh:
9537   case Intrinsic::ppc_altivec_vcmpnew:
9538   case Intrinsic::ppc_altivec_vcmpnezb:
9539   case Intrinsic::ppc_altivec_vcmpnezh:
9540   case Intrinsic::ppc_altivec_vcmpnezw:
9541     if (Subtarget.hasP9Altivec())
9542       switch (IntrinsicID) {
9543       default:
9544         llvm_unreachable("Unknown comparison intrinsic.");
9545       case Intrinsic::ppc_altivec_vcmpneb:
9546         CompareOpc = 7;
9547         break;
9548       case Intrinsic::ppc_altivec_vcmpneh:
9549         CompareOpc = 71;
9550         break;
9551       case Intrinsic::ppc_altivec_vcmpnew:
9552         CompareOpc = 135;
9553         break;
9554       case Intrinsic::ppc_altivec_vcmpnezb:
9555         CompareOpc = 263;
9556         break;
9557       case Intrinsic::ppc_altivec_vcmpnezh:
9558         CompareOpc = 327;
9559         break;
9560       case Intrinsic::ppc_altivec_vcmpnezw:
9561         CompareOpc = 391;
9562         break;
9563       }
9564     else
9565       return false;
9566     break;
9567   case Intrinsic::ppc_altivec_vcmpgefp:
9568     CompareOpc = 454;
9569     break;
9570   case Intrinsic::ppc_altivec_vcmpgtfp:
9571     CompareOpc = 710;
9572     break;
9573   case Intrinsic::ppc_altivec_vcmpgtsb:
9574     CompareOpc = 774;
9575     break;
9576   case Intrinsic::ppc_altivec_vcmpgtsh:
9577     CompareOpc = 838;
9578     break;
9579   case Intrinsic::ppc_altivec_vcmpgtsw:
9580     CompareOpc = 902;
9581     break;
9582   case Intrinsic::ppc_altivec_vcmpgtsd:
9583     if (Subtarget.hasP8Altivec())
9584       CompareOpc = 967;
9585     else
9586       return false;
9587     break;
9588   case Intrinsic::ppc_altivec_vcmpgtub:
9589     CompareOpc = 518;
9590     break;
9591   case Intrinsic::ppc_altivec_vcmpgtuh:
9592     CompareOpc = 582;
9593     break;
9594   case Intrinsic::ppc_altivec_vcmpgtuw:
9595     CompareOpc = 646;
9596     break;
9597   case Intrinsic::ppc_altivec_vcmpgtud:
9598     if (Subtarget.hasP8Altivec())
9599       CompareOpc = 711;
9600     else
9601       return false;
9602     break;
9603   }
9604   return true;
9605 }
9606 
9607 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
9608 /// lower, do it, otherwise return null.
9609 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
9610                                                    SelectionDAG &DAG) const {
9611   unsigned IntrinsicID =
9612     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9613 
9614   SDLoc dl(Op);
9615 
9616   if (IntrinsicID == Intrinsic::thread_pointer) {
9617     // Reads the thread pointer register, used for __builtin_thread_pointer.
9618     if (Subtarget.isPPC64())
9619       return DAG.getRegister(PPC::X13, MVT::i64);
9620     return DAG.getRegister(PPC::R2, MVT::i32);
9621   }
9622 
9623   // If this is a lowered altivec predicate compare, CompareOpc is set to the
9624   // opcode number of the comparison.
9625   int CompareOpc;
9626   bool isDot;
9627   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
9628     return SDValue();    // Don't custom lower most intrinsics.
9629 
9630   // If this is a non-dot comparison, make the VCMP node and we are done.
9631   if (!isDot) {
9632     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
9633                               Op.getOperand(1), Op.getOperand(2),
9634                               DAG.getConstant(CompareOpc, dl, MVT::i32));
9635     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
9636   }
9637 
9638   // Create the PPCISD altivec 'dot' comparison node.
9639   SDValue Ops[] = {
9640     Op.getOperand(2),  // LHS
9641     Op.getOperand(3),  // RHS
9642     DAG.getConstant(CompareOpc, dl, MVT::i32)
9643   };
9644   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
9645   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9646 
9647   // Now that we have the comparison, emit a copy from the CR to a GPR.
9648   // This is flagged to the above dot comparison.
9649   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
9650                                 DAG.getRegister(PPC::CR6, MVT::i32),
9651                                 CompNode.getValue(1));
9652 
9653   // Unpack the result based on how the target uses it.
9654   unsigned BitNo;   // Bit # of CR6.
9655   bool InvertBit;   // Invert result?
9656   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
9657   default:  // Can't happen, don't crash on invalid number though.
9658   case 0:   // Return the value of the EQ bit of CR6.
9659     BitNo = 0; InvertBit = false;
9660     break;
9661   case 1:   // Return the inverted value of the EQ bit of CR6.
9662     BitNo = 0; InvertBit = true;
9663     break;
9664   case 2:   // Return the value of the LT bit of CR6.
9665     BitNo = 2; InvertBit = false;
9666     break;
9667   case 3:   // Return the inverted value of the LT bit of CR6.
9668     BitNo = 2; InvertBit = true;
9669     break;
9670   }
9671 
9672   // Shift the bit into the low position.
9673   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
9674                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
9675   // Isolate the bit.
9676   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
9677                       DAG.getConstant(1, dl, MVT::i32));
9678 
9679   // If we are supposed to, toggle the bit.
9680   if (InvertBit)
9681     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
9682                         DAG.getConstant(1, dl, MVT::i32));
9683   return Flags;
9684 }
9685 
9686 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
9687                                                SelectionDAG &DAG) const {
9688   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
9689   // the beginning of the argument list.
9690   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
9691   SDLoc DL(Op);
9692   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
9693   case Intrinsic::ppc_cfence: {
9694     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
9695     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
9696     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
9697                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
9698                                                   Op.getOperand(ArgStart + 1)),
9699                                       Op.getOperand(0)),
9700                    0);
9701   }
9702   default:
9703     break;
9704   }
9705   return SDValue();
9706 }
9707 
9708 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
9709   // Check for a DIV with the same operands as this REM.
9710   for (auto UI : Op.getOperand(1)->uses()) {
9711     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
9712         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
9713       if (UI->getOperand(0) == Op.getOperand(0) &&
9714           UI->getOperand(1) == Op.getOperand(1))
9715         return SDValue();
9716   }
9717   return Op;
9718 }
9719 
9720 // Lower scalar BSWAP64 to xxbrd.
9721 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
9722   SDLoc dl(Op);
9723   // MTVSRDD
9724   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
9725                    Op.getOperand(0));
9726   // XXBRD
9727   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
9728   // MFVSRD
9729   int VectorIndex = 0;
9730   if (Subtarget.isLittleEndian())
9731     VectorIndex = 1;
9732   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
9733                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
9734   return Op;
9735 }
9736 
9737 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
9738 // compared to a value that is atomically loaded (atomic loads zero-extend).
9739 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
9740                                                 SelectionDAG &DAG) const {
9741   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
9742          "Expecting an atomic compare-and-swap here.");
9743   SDLoc dl(Op);
9744   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
9745   EVT MemVT = AtomicNode->getMemoryVT();
9746   if (MemVT.getSizeInBits() >= 32)
9747     return Op;
9748 
9749   SDValue CmpOp = Op.getOperand(2);
9750   // If this is already correctly zero-extended, leave it alone.
9751   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
9752   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
9753     return Op;
9754 
9755   // Clear the high bits of the compare operand.
9756   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
9757   SDValue NewCmpOp =
9758     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
9759                 DAG.getConstant(MaskVal, dl, MVT::i32));
9760 
9761   // Replace the existing compare operand with the properly zero-extended one.
9762   SmallVector<SDValue, 4> Ops;
9763   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
9764     Ops.push_back(AtomicNode->getOperand(i));
9765   Ops[2] = NewCmpOp;
9766   MachineMemOperand *MMO = AtomicNode->getMemOperand();
9767   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
9768   auto NodeTy =
9769     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
9770   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
9771 }
9772 
9773 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9774                                                  SelectionDAG &DAG) const {
9775   SDLoc dl(Op);
9776   // Create a stack slot that is 16-byte aligned.
9777   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9778   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9779   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9780   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9781 
9782   // Store the input value into Value#0 of the stack slot.
9783   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9784                                MachinePointerInfo());
9785   // Load it out.
9786   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9787 }
9788 
9789 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9790                                                   SelectionDAG &DAG) const {
9791   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9792          "Should only be called for ISD::INSERT_VECTOR_ELT");
9793 
9794   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9795   // We have legal lowering for constant indices but not for variable ones.
9796   if (!C)
9797     return SDValue();
9798 
9799   EVT VT = Op.getValueType();
9800   SDLoc dl(Op);
9801   SDValue V1 = Op.getOperand(0);
9802   SDValue V2 = Op.getOperand(1);
9803   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9804   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9805     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9806     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9807     unsigned InsertAtElement = C->getZExtValue();
9808     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9809     if (Subtarget.isLittleEndian()) {
9810       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9811     }
9812     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9813                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9814   }
9815   return Op;
9816 }
9817 
9818 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9819                                                    SelectionDAG &DAG) const {
9820   SDLoc dl(Op);
9821   SDNode *N = Op.getNode();
9822 
9823   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9824          "Unknown extract_vector_elt type");
9825 
9826   SDValue Value = N->getOperand(0);
9827 
9828   // The first part of this is like the store lowering except that we don't
9829   // need to track the chain.
9830 
9831   // The values are now known to be -1 (false) or 1 (true). To convert this
9832   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9833   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9834   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9835 
9836   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9837   // understand how to form the extending load.
9838   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9839 
9840   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9841 
9842   // Now convert to an integer and store.
9843   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9844     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9845     Value);
9846 
9847   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9848   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9849   MachinePointerInfo PtrInfo =
9850       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9851   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9852   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9853 
9854   SDValue StoreChain = DAG.getEntryNode();
9855   SDValue Ops[] = {StoreChain,
9856                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9857                    Value, FIdx};
9858   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9859 
9860   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9861     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9862 
9863   // Extract the value requested.
9864   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9865   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9866   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9867 
9868   SDValue IntVal =
9869       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9870 
9871   if (!Subtarget.useCRBits())
9872     return IntVal;
9873 
9874   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9875 }
9876 
9877 /// Lowering for QPX v4i1 loads
9878 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9879                                            SelectionDAG &DAG) const {
9880   SDLoc dl(Op);
9881   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9882   SDValue LoadChain = LN->getChain();
9883   SDValue BasePtr = LN->getBasePtr();
9884 
9885   if (Op.getValueType() == MVT::v4f64 ||
9886       Op.getValueType() == MVT::v4f32) {
9887     EVT MemVT = LN->getMemoryVT();
9888     unsigned Alignment = LN->getAlignment();
9889 
9890     // If this load is properly aligned, then it is legal.
9891     if (Alignment >= MemVT.getStoreSize())
9892       return Op;
9893 
9894     EVT ScalarVT = Op.getValueType().getScalarType(),
9895         ScalarMemVT = MemVT.getScalarType();
9896     unsigned Stride = ScalarMemVT.getStoreSize();
9897 
9898     SDValue Vals[4], LoadChains[4];
9899     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9900       SDValue Load;
9901       if (ScalarVT != ScalarMemVT)
9902         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9903                               BasePtr,
9904                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9905                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9906                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9907       else
9908         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9909                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9910                            MinAlign(Alignment, Idx * Stride),
9911                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9912 
9913       if (Idx == 0 && LN->isIndexed()) {
9914         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9915                "Unknown addressing mode on vector load");
9916         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9917                                   LN->getAddressingMode());
9918       }
9919 
9920       Vals[Idx] = Load;
9921       LoadChains[Idx] = Load.getValue(1);
9922 
9923       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9924                             DAG.getConstant(Stride, dl,
9925                                             BasePtr.getValueType()));
9926     }
9927 
9928     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9929     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9930 
9931     if (LN->isIndexed()) {
9932       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9933       return DAG.getMergeValues(RetOps, dl);
9934     }
9935 
9936     SDValue RetOps[] = { Value, TF };
9937     return DAG.getMergeValues(RetOps, dl);
9938   }
9939 
9940   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9941   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9942 
9943   // To lower v4i1 from a byte array, we load the byte elements of the
9944   // vector and then reuse the BUILD_VECTOR logic.
9945 
9946   SDValue VectElmts[4], VectElmtChains[4];
9947   for (unsigned i = 0; i < 4; ++i) {
9948     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9949     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9950 
9951     VectElmts[i] = DAG.getExtLoad(
9952         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9953         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9954         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9955     VectElmtChains[i] = VectElmts[i].getValue(1);
9956   }
9957 
9958   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9959   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9960 
9961   SDValue RVals[] = { Value, LoadChain };
9962   return DAG.getMergeValues(RVals, dl);
9963 }
9964 
9965 /// Lowering for QPX v4i1 stores
9966 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9967                                             SelectionDAG &DAG) const {
9968   SDLoc dl(Op);
9969   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9970   SDValue StoreChain = SN->getChain();
9971   SDValue BasePtr = SN->getBasePtr();
9972   SDValue Value = SN->getValue();
9973 
9974   if (Value.getValueType() == MVT::v4f64 ||
9975       Value.getValueType() == MVT::v4f32) {
9976     EVT MemVT = SN->getMemoryVT();
9977     unsigned Alignment = SN->getAlignment();
9978 
9979     // If this store is properly aligned, then it is legal.
9980     if (Alignment >= MemVT.getStoreSize())
9981       return Op;
9982 
9983     EVT ScalarVT = Value.getValueType().getScalarType(),
9984         ScalarMemVT = MemVT.getScalarType();
9985     unsigned Stride = ScalarMemVT.getStoreSize();
9986 
9987     SDValue Stores[4];
9988     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9989       SDValue Ex = DAG.getNode(
9990           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9991           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9992       SDValue Store;
9993       if (ScalarVT != ScalarMemVT)
9994         Store =
9995             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9996                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9997                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9998                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9999       else
10000         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
10001                              SN->getPointerInfo().getWithOffset(Idx * Stride),
10002                              MinAlign(Alignment, Idx * Stride),
10003                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
10004 
10005       if (Idx == 0 && SN->isIndexed()) {
10006         assert(SN->getAddressingMode() == ISD::PRE_INC &&
10007                "Unknown addressing mode on vector store");
10008         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
10009                                     SN->getAddressingMode());
10010       }
10011 
10012       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
10013                             DAG.getConstant(Stride, dl,
10014                                             BasePtr.getValueType()));
10015       Stores[Idx] = Store;
10016     }
10017 
10018     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10019 
10020     if (SN->isIndexed()) {
10021       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
10022       return DAG.getMergeValues(RetOps, dl);
10023     }
10024 
10025     return TF;
10026   }
10027 
10028   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
10029   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
10030 
10031   // The values are now known to be -1 (false) or 1 (true). To convert this
10032   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
10033   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
10034   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
10035 
10036   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
10037   // understand how to form the extending load.
10038   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
10039 
10040   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
10041 
10042   // Now convert to an integer and store.
10043   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
10044     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
10045     Value);
10046 
10047   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10048   int FrameIdx = MFI.CreateStackObject(16, 16, false);
10049   MachinePointerInfo PtrInfo =
10050       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
10051   EVT PtrVT = getPointerTy(DAG.getDataLayout());
10052   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
10053 
10054   SDValue Ops[] = {StoreChain,
10055                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
10056                    Value, FIdx};
10057   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
10058 
10059   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
10060     dl, VTs, Ops, MVT::v4i32, PtrInfo);
10061 
10062   // Move data into the byte array.
10063   SDValue Loads[4], LoadChains[4];
10064   for (unsigned i = 0; i < 4; ++i) {
10065     unsigned Offset = 4*i;
10066     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
10067     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
10068 
10069     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
10070                            PtrInfo.getWithOffset(Offset));
10071     LoadChains[i] = Loads[i].getValue(1);
10072   }
10073 
10074   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
10075 
10076   SDValue Stores[4];
10077   for (unsigned i = 0; i < 4; ++i) {
10078     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
10079     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
10080 
10081     Stores[i] = DAG.getTruncStore(
10082         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
10083         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
10084         SN->getAAInfo());
10085   }
10086 
10087   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
10088 
10089   return StoreChain;
10090 }
10091 
10092 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
10093   SDLoc dl(Op);
10094   if (Op.getValueType() == MVT::v4i32) {
10095     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10096 
10097     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
10098     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
10099 
10100     SDValue RHSSwap =   // = vrlw RHS, 16
10101       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
10102 
10103     // Shrinkify inputs to v8i16.
10104     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
10105     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
10106     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
10107 
10108     // Low parts multiplied together, generating 32-bit results (we ignore the
10109     // top parts).
10110     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
10111                                         LHS, RHS, DAG, dl, MVT::v4i32);
10112 
10113     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
10114                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
10115     // Shift the high parts up 16 bits.
10116     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
10117                               Neg16, DAG, dl);
10118     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
10119   } else if (Op.getValueType() == MVT::v8i16) {
10120     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10121 
10122     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
10123 
10124     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
10125                             LHS, RHS, Zero, DAG, dl);
10126   } else if (Op.getValueType() == MVT::v16i8) {
10127     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
10128     bool isLittleEndian = Subtarget.isLittleEndian();
10129 
10130     // Multiply the even 8-bit parts, producing 16-bit sums.
10131     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
10132                                            LHS, RHS, DAG, dl, MVT::v8i16);
10133     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
10134 
10135     // Multiply the odd 8-bit parts, producing 16-bit sums.
10136     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
10137                                           LHS, RHS, DAG, dl, MVT::v8i16);
10138     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
10139 
10140     // Merge the results together.  Because vmuleub and vmuloub are
10141     // instructions with a big-endian bias, we must reverse the
10142     // element numbering and reverse the meaning of "odd" and "even"
10143     // when generating little endian code.
10144     int Ops[16];
10145     for (unsigned i = 0; i != 8; ++i) {
10146       if (isLittleEndian) {
10147         Ops[i*2  ] = 2*i;
10148         Ops[i*2+1] = 2*i+16;
10149       } else {
10150         Ops[i*2  ] = 2*i+1;
10151         Ops[i*2+1] = 2*i+1+16;
10152       }
10153     }
10154     if (isLittleEndian)
10155       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
10156     else
10157       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
10158   } else {
10159     llvm_unreachable("Unknown mul to lower!");
10160   }
10161 }
10162 
10163 SDValue PPCTargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
10164 
10165   assert(Op.getOpcode() == ISD::ABS && "Should only be called for ISD::ABS");
10166 
10167   EVT VT = Op.getValueType();
10168   assert(VT.isVector() &&
10169          "Only set vector abs as custom, scalar abs shouldn't reach here!");
10170   assert((VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
10171           VT == MVT::v16i8) &&
10172          "Unexpected vector element type!");
10173   assert((VT != MVT::v2i64 || Subtarget.hasP8Altivec()) &&
10174          "Current subtarget doesn't support smax v2i64!");
10175 
10176   // For vector abs, it can be lowered to:
10177   // abs x
10178   // ==>
10179   // y = -x
10180   // smax(x, y)
10181 
10182   SDLoc dl(Op);
10183   SDValue X = Op.getOperand(0);
10184   SDValue Zero = DAG.getConstant(0, dl, VT);
10185   SDValue Y = DAG.getNode(ISD::SUB, dl, VT, Zero, X);
10186 
10187   // SMAX patch https://reviews.llvm.org/D47332
10188   // hasn't landed yet, so use intrinsic first here.
10189   // TODO: Should use SMAX directly once SMAX patch landed
10190   Intrinsic::ID BifID = Intrinsic::ppc_altivec_vmaxsw;
10191   if (VT == MVT::v2i64)
10192     BifID = Intrinsic::ppc_altivec_vmaxsd;
10193   else if (VT == MVT::v8i16)
10194     BifID = Intrinsic::ppc_altivec_vmaxsh;
10195   else if (VT == MVT::v16i8)
10196     BifID = Intrinsic::ppc_altivec_vmaxsb;
10197 
10198   return BuildIntrinsicOp(BifID, X, Y, DAG, dl, VT);
10199 }
10200 
10201 // Custom lowering for fpext vf32 to v2f64
10202 SDValue PPCTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
10203 
10204   assert(Op.getOpcode() == ISD::FP_EXTEND &&
10205          "Should only be called for ISD::FP_EXTEND");
10206 
10207   // We only want to custom lower an extend from v2f32 to v2f64.
10208   if (Op.getValueType() != MVT::v2f64 ||
10209       Op.getOperand(0).getValueType() != MVT::v2f32)
10210     return SDValue();
10211 
10212   SDLoc dl(Op);
10213   SDValue Op0 = Op.getOperand(0);
10214 
10215   switch (Op0.getOpcode()) {
10216   default:
10217     return SDValue();
10218   case ISD::EXTRACT_SUBVECTOR: {
10219     assert(Op0.getNumOperands() == 2 &&
10220            isa<ConstantSDNode>(Op0->getOperand(1)) &&
10221            "Node should have 2 operands with second one being a constant!");
10222 
10223     if (Op0.getOperand(0).getValueType() != MVT::v4f32)
10224       return SDValue();
10225 
10226     // Custom lower is only done for high or low doubleword.
10227     int Idx = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
10228     if (Idx % 2 != 0)
10229       return SDValue();
10230 
10231     // Since input is v4f32, at this point Idx is either 0 or 2.
10232     // Shift to get the doubleword position we want.
10233     int DWord = Idx >> 1;
10234 
10235     // High and low word positions are different on little endian.
10236     if (Subtarget.isLittleEndian())
10237       DWord ^= 0x1;
10238 
10239     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64,
10240                        Op0.getOperand(0), DAG.getConstant(DWord, dl, MVT::i32));
10241   }
10242   case ISD::FADD:
10243   case ISD::FMUL:
10244   case ISD::FSUB: {
10245     SDValue NewLoad[2];
10246     for (unsigned i = 0, ie = Op0.getNumOperands(); i != ie; ++i) {
10247       // Ensure both input are loads.
10248       SDValue LdOp = Op0.getOperand(i);
10249       if (LdOp.getOpcode() != ISD::LOAD)
10250         return SDValue();
10251       // Generate new load node.
10252       LoadSDNode *LD = cast<LoadSDNode>(LdOp);
10253       SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10254       NewLoad[i] = DAG.getMemIntrinsicNode(
10255           PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10256           LD->getMemoryVT(), LD->getMemOperand());
10257     }
10258     SDValue NewOp =
10259         DAG.getNode(Op0.getOpcode(), SDLoc(Op0), MVT::v4f32, NewLoad[0],
10260                     NewLoad[1], Op0.getNode()->getFlags());
10261     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewOp,
10262                        DAG.getConstant(0, dl, MVT::i32));
10263   }
10264   case ISD::LOAD: {
10265     LoadSDNode *LD = cast<LoadSDNode>(Op0);
10266     SDValue LoadOps[] = {LD->getChain(), LD->getBasePtr()};
10267     SDValue NewLd = DAG.getMemIntrinsicNode(
10268         PPCISD::LD_VSX_LH, dl, DAG.getVTList(MVT::v4f32, MVT::Other), LoadOps,
10269         LD->getMemoryVT(), LD->getMemOperand());
10270     return DAG.getNode(PPCISD::FP_EXTEND_HALF, dl, MVT::v2f64, NewLd,
10271                        DAG.getConstant(0, dl, MVT::i32));
10272   }
10273   }
10274   llvm_unreachable("ERROR:Should return for all cases within swtich.");
10275 }
10276 
10277 /// LowerOperation - Provide custom lowering hooks for some operations.
10278 ///
10279 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10280   switch (Op.getOpcode()) {
10281   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
10282   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
10283   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
10284   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
10285   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
10286   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
10287   case ISD::SETCC:              return LowerSETCC(Op, DAG);
10288   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
10289   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
10290 
10291   // Variable argument lowering.
10292   case ISD::VASTART:            return LowerVASTART(Op, DAG);
10293   case ISD::VAARG:              return LowerVAARG(Op, DAG);
10294   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
10295 
10296   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
10297   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
10298   case ISD::GET_DYNAMIC_AREA_OFFSET:
10299     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
10300 
10301   // Exception handling lowering.
10302   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
10303   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
10304   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
10305 
10306   case ISD::LOAD:               return LowerLOAD(Op, DAG);
10307   case ISD::STORE:              return LowerSTORE(Op, DAG);
10308   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
10309   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
10310   case ISD::FP_TO_UINT:
10311   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
10312   case ISD::UINT_TO_FP:
10313   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
10314   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
10315 
10316   // Lower 64-bit shifts.
10317   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
10318   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
10319   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
10320 
10321   // Vector-related lowering.
10322   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
10323   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
10324   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
10325   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
10326   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
10327   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
10328   case ISD::MUL:                return LowerMUL(Op, DAG);
10329   case ISD::ABS:                return LowerABS(Op, DAG);
10330   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
10331 
10332   // For counter-based loop handling.
10333   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
10334 
10335   case ISD::BITCAST:            return LowerBITCAST(Op, DAG);
10336 
10337   // Frame & Return address.
10338   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
10339   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
10340 
10341   case ISD::INTRINSIC_VOID:
10342     return LowerINTRINSIC_VOID(Op, DAG);
10343   case ISD::SREM:
10344   case ISD::UREM:
10345     return LowerREM(Op, DAG);
10346   case ISD::BSWAP:
10347     return LowerBSWAP(Op, DAG);
10348   case ISD::ATOMIC_CMP_SWAP:
10349     return LowerATOMIC_CMP_SWAP(Op, DAG);
10350   }
10351 }
10352 
10353 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
10354                                            SmallVectorImpl<SDValue>&Results,
10355                                            SelectionDAG &DAG) const {
10356   SDLoc dl(N);
10357   switch (N->getOpcode()) {
10358   default:
10359     llvm_unreachable("Do not know how to custom type legalize this operation!");
10360   case ISD::READCYCLECOUNTER: {
10361     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
10362     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
10363 
10364     Results.push_back(RTB);
10365     Results.push_back(RTB.getValue(1));
10366     Results.push_back(RTB.getValue(2));
10367     break;
10368   }
10369   case ISD::INTRINSIC_W_CHAIN: {
10370     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
10371         Intrinsic::loop_decrement)
10372       break;
10373 
10374     assert(N->getValueType(0) == MVT::i1 &&
10375            "Unexpected result type for CTR decrement intrinsic");
10376     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
10377                                  N->getValueType(0));
10378     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
10379     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
10380                                  N->getOperand(1));
10381 
10382     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
10383     Results.push_back(NewInt.getValue(1));
10384     break;
10385   }
10386   case ISD::VAARG: {
10387     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
10388       return;
10389 
10390     EVT VT = N->getValueType(0);
10391 
10392     if (VT == MVT::i64) {
10393       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
10394 
10395       Results.push_back(NewNode);
10396       Results.push_back(NewNode.getValue(1));
10397     }
10398     return;
10399   }
10400   case ISD::FP_TO_SINT:
10401   case ISD::FP_TO_UINT:
10402     // LowerFP_TO_INT() can only handle f32 and f64.
10403     if (N->getOperand(0).getValueType() == MVT::ppcf128)
10404       return;
10405     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
10406     return;
10407   case ISD::TRUNCATE: {
10408     EVT TrgVT = N->getValueType(0);
10409     EVT OpVT = N->getOperand(0).getValueType();
10410     if (TrgVT.isVector() &&
10411         isOperationCustom(N->getOpcode(), TrgVT) &&
10412         OpVT.getSizeInBits() <= 128 &&
10413         isPowerOf2_32(OpVT.getVectorElementType().getSizeInBits()))
10414       Results.push_back(LowerTRUNCATEVector(SDValue(N, 0), DAG));
10415     return;
10416   }
10417   case ISD::BITCAST:
10418     // Don't handle bitcast here.
10419     return;
10420   }
10421 }
10422 
10423 //===----------------------------------------------------------------------===//
10424 //  Other Lowering Code
10425 //===----------------------------------------------------------------------===//
10426 
10427 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
10428   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10429   Function *Func = Intrinsic::getDeclaration(M, Id);
10430   return Builder.CreateCall(Func, {});
10431 }
10432 
10433 // The mappings for emitLeading/TrailingFence is taken from
10434 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
10435 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
10436                                                  Instruction *Inst,
10437                                                  AtomicOrdering Ord) const {
10438   if (Ord == AtomicOrdering::SequentiallyConsistent)
10439     return callIntrinsic(Builder, Intrinsic::ppc_sync);
10440   if (isReleaseOrStronger(Ord))
10441     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10442   return nullptr;
10443 }
10444 
10445 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
10446                                                   Instruction *Inst,
10447                                                   AtomicOrdering Ord) const {
10448   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
10449     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
10450     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
10451     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
10452     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
10453       return Builder.CreateCall(
10454           Intrinsic::getDeclaration(
10455               Builder.GetInsertBlock()->getParent()->getParent(),
10456               Intrinsic::ppc_cfence, {Inst->getType()}),
10457           {Inst});
10458     // FIXME: Can use isync for rmw operation.
10459     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
10460   }
10461   return nullptr;
10462 }
10463 
10464 MachineBasicBlock *
10465 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
10466                                     unsigned AtomicSize,
10467                                     unsigned BinOpcode,
10468                                     unsigned CmpOpcode,
10469                                     unsigned CmpPred) const {
10470   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10471   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10472 
10473   auto LoadMnemonic = PPC::LDARX;
10474   auto StoreMnemonic = PPC::STDCX;
10475   switch (AtomicSize) {
10476   default:
10477     llvm_unreachable("Unexpected size of atomic entity");
10478   case 1:
10479     LoadMnemonic = PPC::LBARX;
10480     StoreMnemonic = PPC::STBCX;
10481     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10482     break;
10483   case 2:
10484     LoadMnemonic = PPC::LHARX;
10485     StoreMnemonic = PPC::STHCX;
10486     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
10487     break;
10488   case 4:
10489     LoadMnemonic = PPC::LWARX;
10490     StoreMnemonic = PPC::STWCX;
10491     break;
10492   case 8:
10493     LoadMnemonic = PPC::LDARX;
10494     StoreMnemonic = PPC::STDCX;
10495     break;
10496   }
10497 
10498   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10499   MachineFunction *F = BB->getParent();
10500   MachineFunction::iterator It = ++BB->getIterator();
10501 
10502   Register dest = MI.getOperand(0).getReg();
10503   Register ptrA = MI.getOperand(1).getReg();
10504   Register ptrB = MI.getOperand(2).getReg();
10505   Register incr = MI.getOperand(3).getReg();
10506   DebugLoc dl = MI.getDebugLoc();
10507 
10508   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10509   MachineBasicBlock *loop2MBB =
10510     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10511   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10512   F->insert(It, loopMBB);
10513   if (CmpOpcode)
10514     F->insert(It, loop2MBB);
10515   F->insert(It, exitMBB);
10516   exitMBB->splice(exitMBB->begin(), BB,
10517                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10518   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10519 
10520   MachineRegisterInfo &RegInfo = F->getRegInfo();
10521   Register TmpReg = (!BinOpcode) ? incr :
10522     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
10523                                            : &PPC::GPRCRegClass);
10524 
10525   //  thisMBB:
10526   //   ...
10527   //   fallthrough --> loopMBB
10528   BB->addSuccessor(loopMBB);
10529 
10530   //  loopMBB:
10531   //   l[wd]arx dest, ptr
10532   //   add r0, dest, incr
10533   //   st[wd]cx. r0, ptr
10534   //   bne- loopMBB
10535   //   fallthrough --> exitMBB
10536 
10537   // For max/min...
10538   //  loopMBB:
10539   //   l[wd]arx dest, ptr
10540   //   cmpl?[wd] incr, dest
10541   //   bgt exitMBB
10542   //  loop2MBB:
10543   //   st[wd]cx. dest, ptr
10544   //   bne- loopMBB
10545   //   fallthrough --> exitMBB
10546 
10547   BB = loopMBB;
10548   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10549     .addReg(ptrA).addReg(ptrB);
10550   if (BinOpcode)
10551     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
10552   if (CmpOpcode) {
10553     // Signed comparisons of byte or halfword values must be sign-extended.
10554     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
10555       Register ExtReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10556       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
10557               ExtReg).addReg(dest);
10558       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10559         .addReg(incr).addReg(ExtReg);
10560     } else
10561       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10562         .addReg(incr).addReg(dest);
10563 
10564     BuildMI(BB, dl, TII->get(PPC::BCC))
10565       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
10566     BB->addSuccessor(loop2MBB);
10567     BB->addSuccessor(exitMBB);
10568     BB = loop2MBB;
10569   }
10570   BuildMI(BB, dl, TII->get(StoreMnemonic))
10571     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
10572   BuildMI(BB, dl, TII->get(PPC::BCC))
10573     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
10574   BB->addSuccessor(loopMBB);
10575   BB->addSuccessor(exitMBB);
10576 
10577   //  exitMBB:
10578   //   ...
10579   BB = exitMBB;
10580   return BB;
10581 }
10582 
10583 MachineBasicBlock *PPCTargetLowering::EmitPartwordAtomicBinary(
10584     MachineInstr &MI, MachineBasicBlock *BB,
10585     bool is8bit, // operation
10586     unsigned BinOpcode, unsigned CmpOpcode, unsigned CmpPred) const {
10587   // If we support part-word atomic mnemonics, just use them
10588   if (Subtarget.hasPartwordAtomics())
10589     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode, CmpOpcode,
10590                             CmpPred);
10591 
10592   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
10593   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10594   // In 64 bit mode we have to use 64 bits for addresses, even though the
10595   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
10596   // registers without caring whether they're 32 or 64, but here we're
10597   // doing actual arithmetic on the addresses.
10598   bool is64bit = Subtarget.isPPC64();
10599   bool isLittleEndian = Subtarget.isLittleEndian();
10600   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10601 
10602   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10603   MachineFunction *F = BB->getParent();
10604   MachineFunction::iterator It = ++BB->getIterator();
10605 
10606   Register dest = MI.getOperand(0).getReg();
10607   Register ptrA = MI.getOperand(1).getReg();
10608   Register ptrB = MI.getOperand(2).getReg();
10609   Register incr = MI.getOperand(3).getReg();
10610   DebugLoc dl = MI.getDebugLoc();
10611 
10612   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
10613   MachineBasicBlock *loop2MBB =
10614       CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
10615   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10616   F->insert(It, loopMBB);
10617   if (CmpOpcode)
10618     F->insert(It, loop2MBB);
10619   F->insert(It, exitMBB);
10620   exitMBB->splice(exitMBB->begin(), BB,
10621                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
10622   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10623 
10624   MachineRegisterInfo &RegInfo = F->getRegInfo();
10625   const TargetRegisterClass *RC =
10626       is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10627   const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
10628 
10629   Register PtrReg = RegInfo.createVirtualRegister(RC);
10630   Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
10631   Register ShiftReg =
10632       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
10633   Register Incr2Reg = RegInfo.createVirtualRegister(GPRC);
10634   Register MaskReg = RegInfo.createVirtualRegister(GPRC);
10635   Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
10636   Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
10637   Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
10638   Register Tmp3Reg = RegInfo.createVirtualRegister(GPRC);
10639   Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
10640   Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
10641   Register Ptr1Reg;
10642   Register TmpReg =
10643       (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(GPRC);
10644 
10645   //  thisMBB:
10646   //   ...
10647   //   fallthrough --> loopMBB
10648   BB->addSuccessor(loopMBB);
10649 
10650   // The 4-byte load must be aligned, while a char or short may be
10651   // anywhere in the word.  Hence all this nasty bookkeeping code.
10652   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10653   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10654   //   xori shift, shift1, 24 [16]
10655   //   rlwinm ptr, ptr1, 0, 0, 29
10656   //   slw incr2, incr, shift
10657   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10658   //   slw mask, mask2, shift
10659   //  loopMBB:
10660   //   lwarx tmpDest, ptr
10661   //   add tmp, tmpDest, incr2
10662   //   andc tmp2, tmpDest, mask
10663   //   and tmp3, tmp, mask
10664   //   or tmp4, tmp3, tmp2
10665   //   stwcx. tmp4, ptr
10666   //   bne- loopMBB
10667   //   fallthrough --> exitMBB
10668   //   srw dest, tmpDest, shift
10669   if (ptrA != ZeroReg) {
10670     Ptr1Reg = RegInfo.createVirtualRegister(RC);
10671     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10672         .addReg(ptrA)
10673         .addReg(ptrB);
10674   } else {
10675     Ptr1Reg = ptrB;
10676   }
10677   // We need use 32-bit subregister to avoid mismatch register class in 64-bit
10678   // mode.
10679   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
10680       .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
10681       .addImm(3)
10682       .addImm(27)
10683       .addImm(is8bit ? 28 : 27);
10684   if (!isLittleEndian)
10685     BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
10686         .addReg(Shift1Reg)
10687         .addImm(is8bit ? 24 : 16);
10688   if (is64bit)
10689     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10690         .addReg(Ptr1Reg)
10691         .addImm(0)
10692         .addImm(61);
10693   else
10694     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10695         .addReg(Ptr1Reg)
10696         .addImm(0)
10697         .addImm(0)
10698         .addImm(29);
10699   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg).addReg(incr).addReg(ShiftReg);
10700   if (is8bit)
10701     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10702   else {
10703     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10704     BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10705         .addReg(Mask3Reg)
10706         .addImm(65535);
10707   }
10708   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10709       .addReg(Mask2Reg)
10710       .addReg(ShiftReg);
10711 
10712   BB = loopMBB;
10713   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10714       .addReg(ZeroReg)
10715       .addReg(PtrReg);
10716   if (BinOpcode)
10717     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
10718         .addReg(Incr2Reg)
10719         .addReg(TmpDestReg);
10720   BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
10721       .addReg(TmpDestReg)
10722       .addReg(MaskReg);
10723   BuildMI(BB, dl, TII->get(PPC::AND), Tmp3Reg).addReg(TmpReg).addReg(MaskReg);
10724   if (CmpOpcode) {
10725     // For unsigned comparisons, we can directly compare the shifted values.
10726     // For signed comparisons we shift and sign extend.
10727     Register SReg = RegInfo.createVirtualRegister(GPRC);
10728     BuildMI(BB, dl, TII->get(PPC::AND), SReg)
10729         .addReg(TmpDestReg)
10730         .addReg(MaskReg);
10731     unsigned ValueReg = SReg;
10732     unsigned CmpReg = Incr2Reg;
10733     if (CmpOpcode == PPC::CMPW) {
10734       ValueReg = RegInfo.createVirtualRegister(GPRC);
10735       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
10736           .addReg(SReg)
10737           .addReg(ShiftReg);
10738       Register ValueSReg = RegInfo.createVirtualRegister(GPRC);
10739       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
10740           .addReg(ValueReg);
10741       ValueReg = ValueSReg;
10742       CmpReg = incr;
10743     }
10744     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
10745         .addReg(CmpReg)
10746         .addReg(ValueReg);
10747     BuildMI(BB, dl, TII->get(PPC::BCC))
10748         .addImm(CmpPred)
10749         .addReg(PPC::CR0)
10750         .addMBB(exitMBB);
10751     BB->addSuccessor(loop2MBB);
10752     BB->addSuccessor(exitMBB);
10753     BB = loop2MBB;
10754   }
10755   BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg).addReg(Tmp3Reg).addReg(Tmp2Reg);
10756   BuildMI(BB, dl, TII->get(PPC::STWCX))
10757       .addReg(Tmp4Reg)
10758       .addReg(ZeroReg)
10759       .addReg(PtrReg);
10760   BuildMI(BB, dl, TII->get(PPC::BCC))
10761       .addImm(PPC::PRED_NE)
10762       .addReg(PPC::CR0)
10763       .addMBB(loopMBB);
10764   BB->addSuccessor(loopMBB);
10765   BB->addSuccessor(exitMBB);
10766 
10767   //  exitMBB:
10768   //   ...
10769   BB = exitMBB;
10770   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
10771       .addReg(TmpDestReg)
10772       .addReg(ShiftReg);
10773   return BB;
10774 }
10775 
10776 llvm::MachineBasicBlock *
10777 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
10778                                     MachineBasicBlock *MBB) const {
10779   DebugLoc DL = MI.getDebugLoc();
10780   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10781   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
10782 
10783   MachineFunction *MF = MBB->getParent();
10784   MachineRegisterInfo &MRI = MF->getRegInfo();
10785 
10786   const BasicBlock *BB = MBB->getBasicBlock();
10787   MachineFunction::iterator I = ++MBB->getIterator();
10788 
10789   Register DstReg = MI.getOperand(0).getReg();
10790   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
10791   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
10792   Register mainDstReg = MRI.createVirtualRegister(RC);
10793   Register restoreDstReg = MRI.createVirtualRegister(RC);
10794 
10795   MVT PVT = getPointerTy(MF->getDataLayout());
10796   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10797          "Invalid Pointer Size!");
10798   // For v = setjmp(buf), we generate
10799   //
10800   // thisMBB:
10801   //  SjLjSetup mainMBB
10802   //  bl mainMBB
10803   //  v_restore = 1
10804   //  b sinkMBB
10805   //
10806   // mainMBB:
10807   //  buf[LabelOffset] = LR
10808   //  v_main = 0
10809   //
10810   // sinkMBB:
10811   //  v = phi(main, restore)
10812   //
10813 
10814   MachineBasicBlock *thisMBB = MBB;
10815   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
10816   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
10817   MF->insert(I, mainMBB);
10818   MF->insert(I, sinkMBB);
10819 
10820   MachineInstrBuilder MIB;
10821 
10822   // Transfer the remainder of BB and its successor edges to sinkMBB.
10823   sinkMBB->splice(sinkMBB->begin(), MBB,
10824                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
10825   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
10826 
10827   // Note that the structure of the jmp_buf used here is not compatible
10828   // with that used by libc, and is not designed to be. Specifically, it
10829   // stores only those 'reserved' registers that LLVM does not otherwise
10830   // understand how to spill. Also, by convention, by the time this
10831   // intrinsic is called, Clang has already stored the frame address in the
10832   // first slot of the buffer and stack address in the third. Following the
10833   // X86 target code, we'll store the jump address in the second slot. We also
10834   // need to save the TOC pointer (R2) to handle jumps between shared
10835   // libraries, and that will be stored in the fourth slot. The thread
10836   // identifier (R13) is not affected.
10837 
10838   // thisMBB:
10839   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10840   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10841   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10842 
10843   // Prepare IP either in reg.
10844   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
10845   Register LabelReg = MRI.createVirtualRegister(PtrRC);
10846   Register BufReg = MI.getOperand(1).getReg();
10847 
10848   if (Subtarget.is64BitELFABI()) {
10849     setUsesTOCBasePtr(*MBB->getParent());
10850     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
10851               .addReg(PPC::X2)
10852               .addImm(TOCOffset)
10853               .addReg(BufReg)
10854               .cloneMemRefs(MI);
10855   }
10856 
10857   // Naked functions never have a base pointer, and so we use r1. For all
10858   // other functions, this decision must be delayed until during PEI.
10859   unsigned BaseReg;
10860   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
10861     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
10862   else
10863     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
10864 
10865   MIB = BuildMI(*thisMBB, MI, DL,
10866                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
10867             .addReg(BaseReg)
10868             .addImm(BPOffset)
10869             .addReg(BufReg)
10870             .cloneMemRefs(MI);
10871 
10872   // Setup
10873   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
10874   MIB.addRegMask(TRI->getNoPreservedMask());
10875 
10876   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
10877 
10878   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
10879           .addMBB(mainMBB);
10880   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
10881 
10882   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
10883   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
10884 
10885   // mainMBB:
10886   //  mainDstReg = 0
10887   MIB =
10888       BuildMI(mainMBB, DL,
10889               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
10890 
10891   // Store IP
10892   if (Subtarget.isPPC64()) {
10893     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
10894             .addReg(LabelReg)
10895             .addImm(LabelOffset)
10896             .addReg(BufReg);
10897   } else {
10898     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
10899             .addReg(LabelReg)
10900             .addImm(LabelOffset)
10901             .addReg(BufReg);
10902   }
10903   MIB.cloneMemRefs(MI);
10904 
10905   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
10906   mainMBB->addSuccessor(sinkMBB);
10907 
10908   // sinkMBB:
10909   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
10910           TII->get(PPC::PHI), DstReg)
10911     .addReg(mainDstReg).addMBB(mainMBB)
10912     .addReg(restoreDstReg).addMBB(thisMBB);
10913 
10914   MI.eraseFromParent();
10915   return sinkMBB;
10916 }
10917 
10918 MachineBasicBlock *
10919 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
10920                                      MachineBasicBlock *MBB) const {
10921   DebugLoc DL = MI.getDebugLoc();
10922   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10923 
10924   MachineFunction *MF = MBB->getParent();
10925   MachineRegisterInfo &MRI = MF->getRegInfo();
10926 
10927   MVT PVT = getPointerTy(MF->getDataLayout());
10928   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10929          "Invalid Pointer Size!");
10930 
10931   const TargetRegisterClass *RC =
10932     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10933   Register Tmp = MRI.createVirtualRegister(RC);
10934   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10935   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10936   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10937   unsigned BP =
10938       (PVT == MVT::i64)
10939           ? PPC::X30
10940           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10941                                                               : PPC::R30);
10942 
10943   MachineInstrBuilder MIB;
10944 
10945   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10946   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10947   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10948   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10949 
10950   Register BufReg = MI.getOperand(0).getReg();
10951 
10952   // Reload FP (the jumped-to function may not have had a
10953   // frame pointer, and if so, then its r31 will be restored
10954   // as necessary).
10955   if (PVT == MVT::i64) {
10956     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10957             .addImm(0)
10958             .addReg(BufReg);
10959   } else {
10960     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10961             .addImm(0)
10962             .addReg(BufReg);
10963   }
10964   MIB.cloneMemRefs(MI);
10965 
10966   // Reload IP
10967   if (PVT == MVT::i64) {
10968     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10969             .addImm(LabelOffset)
10970             .addReg(BufReg);
10971   } else {
10972     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10973             .addImm(LabelOffset)
10974             .addReg(BufReg);
10975   }
10976   MIB.cloneMemRefs(MI);
10977 
10978   // Reload SP
10979   if (PVT == MVT::i64) {
10980     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10981             .addImm(SPOffset)
10982             .addReg(BufReg);
10983   } else {
10984     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10985             .addImm(SPOffset)
10986             .addReg(BufReg);
10987   }
10988   MIB.cloneMemRefs(MI);
10989 
10990   // Reload BP
10991   if (PVT == MVT::i64) {
10992     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10993             .addImm(BPOffset)
10994             .addReg(BufReg);
10995   } else {
10996     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10997             .addImm(BPOffset)
10998             .addReg(BufReg);
10999   }
11000   MIB.cloneMemRefs(MI);
11001 
11002   // Reload TOC
11003   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
11004     setUsesTOCBasePtr(*MBB->getParent());
11005     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
11006               .addImm(TOCOffset)
11007               .addReg(BufReg)
11008               .cloneMemRefs(MI);
11009   }
11010 
11011   // Jump
11012   BuildMI(*MBB, MI, DL,
11013           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
11014   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
11015 
11016   MI.eraseFromParent();
11017   return MBB;
11018 }
11019 
11020 MachineBasicBlock *
11021 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
11022                                                MachineBasicBlock *BB) const {
11023   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
11024       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11025     if (Subtarget.is64BitELFABI() &&
11026         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
11027       // Call lowering should have added an r2 operand to indicate a dependence
11028       // on the TOC base pointer value. It can't however, because there is no
11029       // way to mark the dependence as implicit there, and so the stackmap code
11030       // will confuse it with a regular operand. Instead, add the dependence
11031       // here.
11032       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
11033     }
11034 
11035     return emitPatchPoint(MI, BB);
11036   }
11037 
11038   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
11039       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
11040     return emitEHSjLjSetJmp(MI, BB);
11041   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
11042              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
11043     return emitEHSjLjLongJmp(MI, BB);
11044   }
11045 
11046   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
11047 
11048   // To "insert" these instructions we actually have to insert their
11049   // control-flow patterns.
11050   const BasicBlock *LLVM_BB = BB->getBasicBlock();
11051   MachineFunction::iterator It = ++BB->getIterator();
11052 
11053   MachineFunction *F = BB->getParent();
11054 
11055   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11056       MI.getOpcode() == PPC::SELECT_CC_I8 || MI.getOpcode() == PPC::SELECT_I4 ||
11057       MI.getOpcode() == PPC::SELECT_I8) {
11058     SmallVector<MachineOperand, 2> Cond;
11059     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11060         MI.getOpcode() == PPC::SELECT_CC_I8)
11061       Cond.push_back(MI.getOperand(4));
11062     else
11063       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
11064     Cond.push_back(MI.getOperand(1));
11065 
11066     DebugLoc dl = MI.getDebugLoc();
11067     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
11068                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
11069   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
11070              MI.getOpcode() == PPC::SELECT_CC_I8 ||
11071              MI.getOpcode() == PPC::SELECT_CC_F4 ||
11072              MI.getOpcode() == PPC::SELECT_CC_F8 ||
11073              MI.getOpcode() == PPC::SELECT_CC_F16 ||
11074              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
11075              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
11076              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
11077              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
11078              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
11079              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
11080              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
11081              MI.getOpcode() == PPC::SELECT_CC_SPE4 ||
11082              MI.getOpcode() == PPC::SELECT_CC_SPE ||
11083              MI.getOpcode() == PPC::SELECT_I4 ||
11084              MI.getOpcode() == PPC::SELECT_I8 ||
11085              MI.getOpcode() == PPC::SELECT_F4 ||
11086              MI.getOpcode() == PPC::SELECT_F8 ||
11087              MI.getOpcode() == PPC::SELECT_F16 ||
11088              MI.getOpcode() == PPC::SELECT_QFRC ||
11089              MI.getOpcode() == PPC::SELECT_QSRC ||
11090              MI.getOpcode() == PPC::SELECT_QBRC ||
11091              MI.getOpcode() == PPC::SELECT_SPE ||
11092              MI.getOpcode() == PPC::SELECT_SPE4 ||
11093              MI.getOpcode() == PPC::SELECT_VRRC ||
11094              MI.getOpcode() == PPC::SELECT_VSFRC ||
11095              MI.getOpcode() == PPC::SELECT_VSSRC ||
11096              MI.getOpcode() == PPC::SELECT_VSRC) {
11097     // The incoming instruction knows the destination vreg to set, the
11098     // condition code register to branch on, the true/false values to
11099     // select between, and a branch opcode to use.
11100 
11101     //  thisMBB:
11102     //  ...
11103     //   TrueVal = ...
11104     //   cmpTY ccX, r1, r2
11105     //   bCC copy1MBB
11106     //   fallthrough --> copy0MBB
11107     MachineBasicBlock *thisMBB = BB;
11108     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
11109     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11110     DebugLoc dl = MI.getDebugLoc();
11111     F->insert(It, copy0MBB);
11112     F->insert(It, sinkMBB);
11113 
11114     // Transfer the remainder of BB and its successor edges to sinkMBB.
11115     sinkMBB->splice(sinkMBB->begin(), BB,
11116                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11117     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11118 
11119     // Next, add the true and fallthrough blocks as its successors.
11120     BB->addSuccessor(copy0MBB);
11121     BB->addSuccessor(sinkMBB);
11122 
11123     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
11124         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
11125         MI.getOpcode() == PPC::SELECT_F16 ||
11126         MI.getOpcode() == PPC::SELECT_SPE4 ||
11127         MI.getOpcode() == PPC::SELECT_SPE ||
11128         MI.getOpcode() == PPC::SELECT_QFRC ||
11129         MI.getOpcode() == PPC::SELECT_QSRC ||
11130         MI.getOpcode() == PPC::SELECT_QBRC ||
11131         MI.getOpcode() == PPC::SELECT_VRRC ||
11132         MI.getOpcode() == PPC::SELECT_VSFRC ||
11133         MI.getOpcode() == PPC::SELECT_VSSRC ||
11134         MI.getOpcode() == PPC::SELECT_VSRC) {
11135       BuildMI(BB, dl, TII->get(PPC::BC))
11136           .addReg(MI.getOperand(1).getReg())
11137           .addMBB(sinkMBB);
11138     } else {
11139       unsigned SelectPred = MI.getOperand(4).getImm();
11140       BuildMI(BB, dl, TII->get(PPC::BCC))
11141           .addImm(SelectPred)
11142           .addReg(MI.getOperand(1).getReg())
11143           .addMBB(sinkMBB);
11144     }
11145 
11146     //  copy0MBB:
11147     //   %FalseValue = ...
11148     //   # fallthrough to sinkMBB
11149     BB = copy0MBB;
11150 
11151     // Update machine-CFG edges
11152     BB->addSuccessor(sinkMBB);
11153 
11154     //  sinkMBB:
11155     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
11156     //  ...
11157     BB = sinkMBB;
11158     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
11159         .addReg(MI.getOperand(3).getReg())
11160         .addMBB(copy0MBB)
11161         .addReg(MI.getOperand(2).getReg())
11162         .addMBB(thisMBB);
11163   } else if (MI.getOpcode() == PPC::ReadTB) {
11164     // To read the 64-bit time-base register on a 32-bit target, we read the
11165     // two halves. Should the counter have wrapped while it was being read, we
11166     // need to try again.
11167     // ...
11168     // readLoop:
11169     // mfspr Rx,TBU # load from TBU
11170     // mfspr Ry,TB  # load from TB
11171     // mfspr Rz,TBU # load from TBU
11172     // cmpw crX,Rx,Rz # check if 'old'='new'
11173     // bne readLoop   # branch if they're not equal
11174     // ...
11175 
11176     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
11177     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
11178     DebugLoc dl = MI.getDebugLoc();
11179     F->insert(It, readMBB);
11180     F->insert(It, sinkMBB);
11181 
11182     // Transfer the remainder of BB and its successor edges to sinkMBB.
11183     sinkMBB->splice(sinkMBB->begin(), BB,
11184                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11185     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
11186 
11187     BB->addSuccessor(readMBB);
11188     BB = readMBB;
11189 
11190     MachineRegisterInfo &RegInfo = F->getRegInfo();
11191     Register ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
11192     Register LoReg = MI.getOperand(0).getReg();
11193     Register HiReg = MI.getOperand(1).getReg();
11194 
11195     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
11196     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
11197     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
11198 
11199     Register CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11200 
11201     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
11202         .addReg(HiReg)
11203         .addReg(ReadAgainReg);
11204     BuildMI(BB, dl, TII->get(PPC::BCC))
11205         .addImm(PPC::PRED_NE)
11206         .addReg(CmpReg)
11207         .addMBB(readMBB);
11208 
11209     BB->addSuccessor(readMBB);
11210     BB->addSuccessor(sinkMBB);
11211   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
11212     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
11213   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
11214     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
11215   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
11216     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
11217   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
11218     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
11219 
11220   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
11221     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
11222   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
11223     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
11224   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
11225     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
11226   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
11227     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
11228 
11229   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
11230     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
11231   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
11232     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
11233   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
11234     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
11235   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
11236     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
11237 
11238   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
11239     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
11240   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
11241     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
11242   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
11243     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
11244   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
11245     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
11246 
11247   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
11248     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
11249   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
11250     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
11251   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
11252     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
11253   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
11254     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
11255 
11256   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
11257     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
11258   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
11259     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
11260   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
11261     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
11262   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
11263     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
11264 
11265   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
11266     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
11267   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
11268     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
11269   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
11270     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
11271   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
11272     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
11273 
11274   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
11275     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
11276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
11277     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
11278   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
11279     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
11280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
11281     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
11282 
11283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
11284     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
11285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
11286     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
11287   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
11288     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
11289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
11290     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
11291 
11292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
11293     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
11294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
11295     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
11296   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
11297     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
11298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
11299     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
11300 
11301   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
11302     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
11303   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
11304     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
11305   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
11306     BB = EmitAtomicBinary(MI, BB, 4, 0);
11307   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
11308     BB = EmitAtomicBinary(MI, BB, 8, 0);
11309   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
11310            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
11311            (Subtarget.hasPartwordAtomics() &&
11312             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
11313            (Subtarget.hasPartwordAtomics() &&
11314             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
11315     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
11316 
11317     auto LoadMnemonic = PPC::LDARX;
11318     auto StoreMnemonic = PPC::STDCX;
11319     switch (MI.getOpcode()) {
11320     default:
11321       llvm_unreachable("Compare and swap of unknown size");
11322     case PPC::ATOMIC_CMP_SWAP_I8:
11323       LoadMnemonic = PPC::LBARX;
11324       StoreMnemonic = PPC::STBCX;
11325       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11326       break;
11327     case PPC::ATOMIC_CMP_SWAP_I16:
11328       LoadMnemonic = PPC::LHARX;
11329       StoreMnemonic = PPC::STHCX;
11330       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
11331       break;
11332     case PPC::ATOMIC_CMP_SWAP_I32:
11333       LoadMnemonic = PPC::LWARX;
11334       StoreMnemonic = PPC::STWCX;
11335       break;
11336     case PPC::ATOMIC_CMP_SWAP_I64:
11337       LoadMnemonic = PPC::LDARX;
11338       StoreMnemonic = PPC::STDCX;
11339       break;
11340     }
11341     Register dest = MI.getOperand(0).getReg();
11342     Register ptrA = MI.getOperand(1).getReg();
11343     Register ptrB = MI.getOperand(2).getReg();
11344     Register oldval = MI.getOperand(3).getReg();
11345     Register newval = MI.getOperand(4).getReg();
11346     DebugLoc dl = MI.getDebugLoc();
11347 
11348     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11349     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11350     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11351     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11352     F->insert(It, loop1MBB);
11353     F->insert(It, loop2MBB);
11354     F->insert(It, midMBB);
11355     F->insert(It, exitMBB);
11356     exitMBB->splice(exitMBB->begin(), BB,
11357                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11358     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11359 
11360     //  thisMBB:
11361     //   ...
11362     //   fallthrough --> loopMBB
11363     BB->addSuccessor(loop1MBB);
11364 
11365     // loop1MBB:
11366     //   l[bhwd]arx dest, ptr
11367     //   cmp[wd] dest, oldval
11368     //   bne- midMBB
11369     // loop2MBB:
11370     //   st[bhwd]cx. newval, ptr
11371     //   bne- loopMBB
11372     //   b exitBB
11373     // midMBB:
11374     //   st[bhwd]cx. dest, ptr
11375     // exitBB:
11376     BB = loop1MBB;
11377     BuildMI(BB, dl, TII->get(LoadMnemonic), dest).addReg(ptrA).addReg(ptrB);
11378     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
11379         .addReg(oldval)
11380         .addReg(dest);
11381     BuildMI(BB, dl, TII->get(PPC::BCC))
11382         .addImm(PPC::PRED_NE)
11383         .addReg(PPC::CR0)
11384         .addMBB(midMBB);
11385     BB->addSuccessor(loop2MBB);
11386     BB->addSuccessor(midMBB);
11387 
11388     BB = loop2MBB;
11389     BuildMI(BB, dl, TII->get(StoreMnemonic))
11390         .addReg(newval)
11391         .addReg(ptrA)
11392         .addReg(ptrB);
11393     BuildMI(BB, dl, TII->get(PPC::BCC))
11394         .addImm(PPC::PRED_NE)
11395         .addReg(PPC::CR0)
11396         .addMBB(loop1MBB);
11397     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11398     BB->addSuccessor(loop1MBB);
11399     BB->addSuccessor(exitMBB);
11400 
11401     BB = midMBB;
11402     BuildMI(BB, dl, TII->get(StoreMnemonic))
11403         .addReg(dest)
11404         .addReg(ptrA)
11405         .addReg(ptrB);
11406     BB->addSuccessor(exitMBB);
11407 
11408     //  exitMBB:
11409     //   ...
11410     BB = exitMBB;
11411   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
11412              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
11413     // We must use 64-bit registers for addresses when targeting 64-bit,
11414     // since we're actually doing arithmetic on them.  Other registers
11415     // can be 32-bit.
11416     bool is64bit = Subtarget.isPPC64();
11417     bool isLittleEndian = Subtarget.isLittleEndian();
11418     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
11419 
11420     Register dest = MI.getOperand(0).getReg();
11421     Register ptrA = MI.getOperand(1).getReg();
11422     Register ptrB = MI.getOperand(2).getReg();
11423     Register oldval = MI.getOperand(3).getReg();
11424     Register newval = MI.getOperand(4).getReg();
11425     DebugLoc dl = MI.getDebugLoc();
11426 
11427     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
11428     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
11429     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
11430     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
11431     F->insert(It, loop1MBB);
11432     F->insert(It, loop2MBB);
11433     F->insert(It, midMBB);
11434     F->insert(It, exitMBB);
11435     exitMBB->splice(exitMBB->begin(), BB,
11436                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
11437     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
11438 
11439     MachineRegisterInfo &RegInfo = F->getRegInfo();
11440     const TargetRegisterClass *RC =
11441         is64bit ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
11442     const TargetRegisterClass *GPRC = &PPC::GPRCRegClass;
11443 
11444     Register PtrReg = RegInfo.createVirtualRegister(RC);
11445     Register Shift1Reg = RegInfo.createVirtualRegister(GPRC);
11446     Register ShiftReg =
11447         isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(GPRC);
11448     Register NewVal2Reg = RegInfo.createVirtualRegister(GPRC);
11449     Register NewVal3Reg = RegInfo.createVirtualRegister(GPRC);
11450     Register OldVal2Reg = RegInfo.createVirtualRegister(GPRC);
11451     Register OldVal3Reg = RegInfo.createVirtualRegister(GPRC);
11452     Register MaskReg = RegInfo.createVirtualRegister(GPRC);
11453     Register Mask2Reg = RegInfo.createVirtualRegister(GPRC);
11454     Register Mask3Reg = RegInfo.createVirtualRegister(GPRC);
11455     Register Tmp2Reg = RegInfo.createVirtualRegister(GPRC);
11456     Register Tmp4Reg = RegInfo.createVirtualRegister(GPRC);
11457     Register TmpDestReg = RegInfo.createVirtualRegister(GPRC);
11458     Register Ptr1Reg;
11459     Register TmpReg = RegInfo.createVirtualRegister(GPRC);
11460     Register ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
11461     //  thisMBB:
11462     //   ...
11463     //   fallthrough --> loopMBB
11464     BB->addSuccessor(loop1MBB);
11465 
11466     // The 4-byte load must be aligned, while a char or short may be
11467     // anywhere in the word.  Hence all this nasty bookkeeping code.
11468     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
11469     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
11470     //   xori shift, shift1, 24 [16]
11471     //   rlwinm ptr, ptr1, 0, 0, 29
11472     //   slw newval2, newval, shift
11473     //   slw oldval2, oldval,shift
11474     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
11475     //   slw mask, mask2, shift
11476     //   and newval3, newval2, mask
11477     //   and oldval3, oldval2, mask
11478     // loop1MBB:
11479     //   lwarx tmpDest, ptr
11480     //   and tmp, tmpDest, mask
11481     //   cmpw tmp, oldval3
11482     //   bne- midMBB
11483     // loop2MBB:
11484     //   andc tmp2, tmpDest, mask
11485     //   or tmp4, tmp2, newval3
11486     //   stwcx. tmp4, ptr
11487     //   bne- loop1MBB
11488     //   b exitBB
11489     // midMBB:
11490     //   stwcx. tmpDest, ptr
11491     // exitBB:
11492     //   srw dest, tmpDest, shift
11493     if (ptrA != ZeroReg) {
11494       Ptr1Reg = RegInfo.createVirtualRegister(RC);
11495       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
11496           .addReg(ptrA)
11497           .addReg(ptrB);
11498     } else {
11499       Ptr1Reg = ptrB;
11500     }
11501 
11502     // We need use 32-bit subregister to avoid mismatch register class in 64-bit
11503     // mode.
11504     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg)
11505         .addReg(Ptr1Reg, 0, is64bit ? PPC::sub_32 : 0)
11506         .addImm(3)
11507         .addImm(27)
11508         .addImm(is8bit ? 28 : 27);
11509     if (!isLittleEndian)
11510       BuildMI(BB, dl, TII->get(PPC::XORI), ShiftReg)
11511           .addReg(Shift1Reg)
11512           .addImm(is8bit ? 24 : 16);
11513     if (is64bit)
11514       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
11515           .addReg(Ptr1Reg)
11516           .addImm(0)
11517           .addImm(61);
11518     else
11519       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
11520           .addReg(Ptr1Reg)
11521           .addImm(0)
11522           .addImm(0)
11523           .addImm(29);
11524     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
11525         .addReg(newval)
11526         .addReg(ShiftReg);
11527     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
11528         .addReg(oldval)
11529         .addReg(ShiftReg);
11530     if (is8bit)
11531       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
11532     else {
11533       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
11534       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
11535           .addReg(Mask3Reg)
11536           .addImm(65535);
11537     }
11538     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
11539         .addReg(Mask2Reg)
11540         .addReg(ShiftReg);
11541     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
11542         .addReg(NewVal2Reg)
11543         .addReg(MaskReg);
11544     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
11545         .addReg(OldVal2Reg)
11546         .addReg(MaskReg);
11547 
11548     BB = loop1MBB;
11549     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
11550         .addReg(ZeroReg)
11551         .addReg(PtrReg);
11552     BuildMI(BB, dl, TII->get(PPC::AND), TmpReg)
11553         .addReg(TmpDestReg)
11554         .addReg(MaskReg);
11555     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
11556         .addReg(TmpReg)
11557         .addReg(OldVal3Reg);
11558     BuildMI(BB, dl, TII->get(PPC::BCC))
11559         .addImm(PPC::PRED_NE)
11560         .addReg(PPC::CR0)
11561         .addMBB(midMBB);
11562     BB->addSuccessor(loop2MBB);
11563     BB->addSuccessor(midMBB);
11564 
11565     BB = loop2MBB;
11566     BuildMI(BB, dl, TII->get(PPC::ANDC), Tmp2Reg)
11567         .addReg(TmpDestReg)
11568         .addReg(MaskReg);
11569     BuildMI(BB, dl, TII->get(PPC::OR), Tmp4Reg)
11570         .addReg(Tmp2Reg)
11571         .addReg(NewVal3Reg);
11572     BuildMI(BB, dl, TII->get(PPC::STWCX))
11573         .addReg(Tmp4Reg)
11574         .addReg(ZeroReg)
11575         .addReg(PtrReg);
11576     BuildMI(BB, dl, TII->get(PPC::BCC))
11577         .addImm(PPC::PRED_NE)
11578         .addReg(PPC::CR0)
11579         .addMBB(loop1MBB);
11580     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
11581     BB->addSuccessor(loop1MBB);
11582     BB->addSuccessor(exitMBB);
11583 
11584     BB = midMBB;
11585     BuildMI(BB, dl, TII->get(PPC::STWCX))
11586         .addReg(TmpDestReg)
11587         .addReg(ZeroReg)
11588         .addReg(PtrReg);
11589     BB->addSuccessor(exitMBB);
11590 
11591     //  exitMBB:
11592     //   ...
11593     BB = exitMBB;
11594     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest)
11595         .addReg(TmpReg)
11596         .addReg(ShiftReg);
11597   } else if (MI.getOpcode() == PPC::FADDrtz) {
11598     // This pseudo performs an FADD with rounding mode temporarily forced
11599     // to round-to-zero.  We emit this via custom inserter since the FPSCR
11600     // is not modeled at the SelectionDAG level.
11601     Register Dest = MI.getOperand(0).getReg();
11602     Register Src1 = MI.getOperand(1).getReg();
11603     Register Src2 = MI.getOperand(2).getReg();
11604     DebugLoc dl = MI.getDebugLoc();
11605 
11606     MachineRegisterInfo &RegInfo = F->getRegInfo();
11607     Register MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11608 
11609     // Save FPSCR value.
11610     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
11611 
11612     // Set rounding mode to round-to-zero.
11613     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
11614     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
11615 
11616     // Perform addition.
11617     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
11618 
11619     // Restore FPSCR value.
11620     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
11621   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11622              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
11623              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11624              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
11625     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
11626                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
11627                           ? PPC::ANDI8o
11628                           : PPC::ANDIo;
11629     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
11630                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
11631 
11632     MachineRegisterInfo &RegInfo = F->getRegInfo();
11633     Register Dest = RegInfo.createVirtualRegister(
11634         Opcode == PPC::ANDIo ? &PPC::GPRCRegClass : &PPC::G8RCRegClass);
11635 
11636     DebugLoc dl = MI.getDebugLoc();
11637     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
11638         .addReg(MI.getOperand(1).getReg())
11639         .addImm(1);
11640     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
11641             MI.getOperand(0).getReg())
11642         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
11643   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
11644     DebugLoc Dl = MI.getDebugLoc();
11645     MachineRegisterInfo &RegInfo = F->getRegInfo();
11646     Register CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
11647     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
11648     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11649             MI.getOperand(0).getReg())
11650         .addReg(CRReg);
11651   } else if (MI.getOpcode() == PPC::TBEGIN_RET) {
11652     DebugLoc Dl = MI.getDebugLoc();
11653     unsigned Imm = MI.getOperand(1).getImm();
11654     BuildMI(*BB, MI, Dl, TII->get(PPC::TBEGIN)).addImm(Imm);
11655     BuildMI(*BB, MI, Dl, TII->get(TargetOpcode::COPY),
11656             MI.getOperand(0).getReg())
11657         .addReg(PPC::CR0EQ);
11658   } else if (MI.getOpcode() == PPC::SETRNDi) {
11659     DebugLoc dl = MI.getDebugLoc();
11660     Register OldFPSCRReg = MI.getOperand(0).getReg();
11661 
11662     // Save FPSCR value.
11663     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11664 
11665     // The floating point rounding mode is in the bits 62:63 of FPCSR, and has
11666     // the following settings:
11667     //   00 Round to nearest
11668     //   01 Round to 0
11669     //   10 Round to +inf
11670     //   11 Round to -inf
11671 
11672     // When the operand is immediate, using the two least significant bits of
11673     // the immediate to set the bits 62:63 of FPSCR.
11674     unsigned Mode = MI.getOperand(1).getImm();
11675     BuildMI(*BB, MI, dl, TII->get((Mode & 1) ? PPC::MTFSB1 : PPC::MTFSB0))
11676       .addImm(31);
11677 
11678     BuildMI(*BB, MI, dl, TII->get((Mode & 2) ? PPC::MTFSB1 : PPC::MTFSB0))
11679       .addImm(30);
11680   } else if (MI.getOpcode() == PPC::SETRND) {
11681     DebugLoc dl = MI.getDebugLoc();
11682 
11683     // Copy register from F8RCRegClass::SrcReg to G8RCRegClass::DestReg
11684     // or copy register from G8RCRegClass::SrcReg to F8RCRegClass::DestReg.
11685     // If the target doesn't have DirectMove, we should use stack to do the
11686     // conversion, because the target doesn't have the instructions like mtvsrd
11687     // or mfvsrd to do this conversion directly.
11688     auto copyRegFromG8RCOrF8RC = [&] (unsigned DestReg, unsigned SrcReg) {
11689       if (Subtarget.hasDirectMove()) {
11690         BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), DestReg)
11691           .addReg(SrcReg);
11692       } else {
11693         // Use stack to do the register copy.
11694         unsigned StoreOp = PPC::STD, LoadOp = PPC::LFD;
11695         MachineRegisterInfo &RegInfo = F->getRegInfo();
11696         const TargetRegisterClass *RC = RegInfo.getRegClass(SrcReg);
11697         if (RC == &PPC::F8RCRegClass) {
11698           // Copy register from F8RCRegClass to G8RCRegclass.
11699           assert((RegInfo.getRegClass(DestReg) == &PPC::G8RCRegClass) &&
11700                  "Unsupported RegClass.");
11701 
11702           StoreOp = PPC::STFD;
11703           LoadOp = PPC::LD;
11704         } else {
11705           // Copy register from G8RCRegClass to F8RCRegclass.
11706           assert((RegInfo.getRegClass(SrcReg) == &PPC::G8RCRegClass) &&
11707                  (RegInfo.getRegClass(DestReg) == &PPC::F8RCRegClass) &&
11708                  "Unsupported RegClass.");
11709         }
11710 
11711         MachineFrameInfo &MFI = F->getFrameInfo();
11712         int FrameIdx = MFI.CreateStackObject(8, 8, false);
11713 
11714         MachineMemOperand *MMOStore = F->getMachineMemOperand(
11715           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11716           MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx),
11717           MFI.getObjectAlignment(FrameIdx));
11718 
11719         // Store the SrcReg into the stack.
11720         BuildMI(*BB, MI, dl, TII->get(StoreOp))
11721           .addReg(SrcReg)
11722           .addImm(0)
11723           .addFrameIndex(FrameIdx)
11724           .addMemOperand(MMOStore);
11725 
11726         MachineMemOperand *MMOLoad = F->getMachineMemOperand(
11727           MachinePointerInfo::getFixedStack(*F, FrameIdx, 0),
11728           MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx),
11729           MFI.getObjectAlignment(FrameIdx));
11730 
11731         // Load from the stack where SrcReg is stored, and save to DestReg,
11732         // so we have done the RegClass conversion from RegClass::SrcReg to
11733         // RegClass::DestReg.
11734         BuildMI(*BB, MI, dl, TII->get(LoadOp), DestReg)
11735           .addImm(0)
11736           .addFrameIndex(FrameIdx)
11737           .addMemOperand(MMOLoad);
11738       }
11739     };
11740 
11741     Register OldFPSCRReg = MI.getOperand(0).getReg();
11742 
11743     // Save FPSCR value.
11744     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), OldFPSCRReg);
11745 
11746     // When the operand is gprc register, use two least significant bits of the
11747     // register and mtfsf instruction to set the bits 62:63 of FPSCR.
11748     //
11749     // copy OldFPSCRTmpReg, OldFPSCRReg
11750     // (INSERT_SUBREG ExtSrcReg, (IMPLICIT_DEF ImDefReg), SrcOp, 1)
11751     // rldimi NewFPSCRTmpReg, ExtSrcReg, OldFPSCRReg, 0, 62
11752     // copy NewFPSCRReg, NewFPSCRTmpReg
11753     // mtfsf 255, NewFPSCRReg
11754     MachineOperand SrcOp = MI.getOperand(1);
11755     MachineRegisterInfo &RegInfo = F->getRegInfo();
11756     Register OldFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11757 
11758     copyRegFromG8RCOrF8RC(OldFPSCRTmpReg, OldFPSCRReg);
11759 
11760     Register ImDefReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11761     Register ExtSrcReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11762 
11763     // The first operand of INSERT_SUBREG should be a register which has
11764     // subregisters, we only care about its RegClass, so we should use an
11765     // IMPLICIT_DEF register.
11766     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::IMPLICIT_DEF), ImDefReg);
11767     BuildMI(*BB, MI, dl, TII->get(PPC::INSERT_SUBREG), ExtSrcReg)
11768       .addReg(ImDefReg)
11769       .add(SrcOp)
11770       .addImm(1);
11771 
11772     Register NewFPSCRTmpReg = RegInfo.createVirtualRegister(&PPC::G8RCRegClass);
11773     BuildMI(*BB, MI, dl, TII->get(PPC::RLDIMI), NewFPSCRTmpReg)
11774       .addReg(OldFPSCRTmpReg)
11775       .addReg(ExtSrcReg)
11776       .addImm(0)
11777       .addImm(62);
11778 
11779     Register NewFPSCRReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
11780     copyRegFromG8RCOrF8RC(NewFPSCRReg, NewFPSCRTmpReg);
11781 
11782     // The mask 255 means that put the 32:63 bits of NewFPSCRReg to the 32:63
11783     // bits of FPSCR.
11784     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF))
11785       .addImm(255)
11786       .addReg(NewFPSCRReg)
11787       .addImm(0)
11788       .addImm(0);
11789   } else {
11790     llvm_unreachable("Unexpected instr type to insert");
11791   }
11792 
11793   MI.eraseFromParent(); // The pseudo instruction is gone now.
11794   return BB;
11795 }
11796 
11797 //===----------------------------------------------------------------------===//
11798 // Target Optimization Hooks
11799 //===----------------------------------------------------------------------===//
11800 
11801 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
11802   // For the estimates, convergence is quadratic, so we essentially double the
11803   // number of digits correct after every iteration. For both FRE and FRSQRTE,
11804   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
11805   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
11806   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
11807   if (VT.getScalarType() == MVT::f64)
11808     RefinementSteps++;
11809   return RefinementSteps;
11810 }
11811 
11812 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
11813                                            int Enabled, int &RefinementSteps,
11814                                            bool &UseOneConstNR,
11815                                            bool Reciprocal) const {
11816   EVT VT = Operand.getValueType();
11817   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
11818       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
11819       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11820       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11821       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11822       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11823     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11824       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11825 
11826     // The Newton-Raphson computation with a single constant does not provide
11827     // enough accuracy on some CPUs.
11828     UseOneConstNR = !Subtarget.needsTwoConstNR();
11829     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
11830   }
11831   return SDValue();
11832 }
11833 
11834 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
11835                                             int Enabled,
11836                                             int &RefinementSteps) const {
11837   EVT VT = Operand.getValueType();
11838   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
11839       (VT == MVT::f64 && Subtarget.hasFRE()) ||
11840       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
11841       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
11842       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
11843       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
11844     if (RefinementSteps == ReciprocalEstimate::Unspecified)
11845       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
11846     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
11847   }
11848   return SDValue();
11849 }
11850 
11851 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
11852   // Note: This functionality is used only when unsafe-fp-math is enabled, and
11853   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
11854   // enabled for division), this functionality is redundant with the default
11855   // combiner logic (once the division -> reciprocal/multiply transformation
11856   // has taken place). As a result, this matters more for older cores than for
11857   // newer ones.
11858 
11859   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11860   // reciprocal if there are two or more FDIVs (for embedded cores with only
11861   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
11862   switch (Subtarget.getCPUDirective()) {
11863   default:
11864     return 3;
11865   case PPC::DIR_440:
11866   case PPC::DIR_A2:
11867   case PPC::DIR_E500:
11868   case PPC::DIR_E500mc:
11869   case PPC::DIR_E5500:
11870     return 2;
11871   }
11872 }
11873 
11874 // isConsecutiveLSLoc needs to work even if all adds have not yet been
11875 // collapsed, and so we need to look through chains of them.
11876 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
11877                                      int64_t& Offset, SelectionDAG &DAG) {
11878   if (DAG.isBaseWithConstantOffset(Loc)) {
11879     Base = Loc.getOperand(0);
11880     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
11881 
11882     // The base might itself be a base plus an offset, and if so, accumulate
11883     // that as well.
11884     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
11885   }
11886 }
11887 
11888 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
11889                             unsigned Bytes, int Dist,
11890                             SelectionDAG &DAG) {
11891   if (VT.getSizeInBits() / 8 != Bytes)
11892     return false;
11893 
11894   SDValue BaseLoc = Base->getBasePtr();
11895   if (Loc.getOpcode() == ISD::FrameIndex) {
11896     if (BaseLoc.getOpcode() != ISD::FrameIndex)
11897       return false;
11898     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
11899     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
11900     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
11901     int FS  = MFI.getObjectSize(FI);
11902     int BFS = MFI.getObjectSize(BFI);
11903     if (FS != BFS || FS != (int)Bytes) return false;
11904     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
11905   }
11906 
11907   SDValue Base1 = Loc, Base2 = BaseLoc;
11908   int64_t Offset1 = 0, Offset2 = 0;
11909   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
11910   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
11911   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
11912     return true;
11913 
11914   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11915   const GlobalValue *GV1 = nullptr;
11916   const GlobalValue *GV2 = nullptr;
11917   Offset1 = 0;
11918   Offset2 = 0;
11919   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
11920   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
11921   if (isGA1 && isGA2 && GV1 == GV2)
11922     return Offset1 == (Offset2 + Dist*Bytes);
11923   return false;
11924 }
11925 
11926 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
11927 // not enforce equality of the chain operands.
11928 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
11929                             unsigned Bytes, int Dist,
11930                             SelectionDAG &DAG) {
11931   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
11932     EVT VT = LS->getMemoryVT();
11933     SDValue Loc = LS->getBasePtr();
11934     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
11935   }
11936 
11937   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
11938     EVT VT;
11939     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11940     default: return false;
11941     case Intrinsic::ppc_qpx_qvlfd:
11942     case Intrinsic::ppc_qpx_qvlfda:
11943       VT = MVT::v4f64;
11944       break;
11945     case Intrinsic::ppc_qpx_qvlfs:
11946     case Intrinsic::ppc_qpx_qvlfsa:
11947       VT = MVT::v4f32;
11948       break;
11949     case Intrinsic::ppc_qpx_qvlfcd:
11950     case Intrinsic::ppc_qpx_qvlfcda:
11951       VT = MVT::v2f64;
11952       break;
11953     case Intrinsic::ppc_qpx_qvlfcs:
11954     case Intrinsic::ppc_qpx_qvlfcsa:
11955       VT = MVT::v2f32;
11956       break;
11957     case Intrinsic::ppc_qpx_qvlfiwa:
11958     case Intrinsic::ppc_qpx_qvlfiwz:
11959     case Intrinsic::ppc_altivec_lvx:
11960     case Intrinsic::ppc_altivec_lvxl:
11961     case Intrinsic::ppc_vsx_lxvw4x:
11962     case Intrinsic::ppc_vsx_lxvw4x_be:
11963       VT = MVT::v4i32;
11964       break;
11965     case Intrinsic::ppc_vsx_lxvd2x:
11966     case Intrinsic::ppc_vsx_lxvd2x_be:
11967       VT = MVT::v2f64;
11968       break;
11969     case Intrinsic::ppc_altivec_lvebx:
11970       VT = MVT::i8;
11971       break;
11972     case Intrinsic::ppc_altivec_lvehx:
11973       VT = MVT::i16;
11974       break;
11975     case Intrinsic::ppc_altivec_lvewx:
11976       VT = MVT::i32;
11977       break;
11978     }
11979 
11980     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
11981   }
11982 
11983   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
11984     EVT VT;
11985     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11986     default: return false;
11987     case Intrinsic::ppc_qpx_qvstfd:
11988     case Intrinsic::ppc_qpx_qvstfda:
11989       VT = MVT::v4f64;
11990       break;
11991     case Intrinsic::ppc_qpx_qvstfs:
11992     case Intrinsic::ppc_qpx_qvstfsa:
11993       VT = MVT::v4f32;
11994       break;
11995     case Intrinsic::ppc_qpx_qvstfcd:
11996     case Intrinsic::ppc_qpx_qvstfcda:
11997       VT = MVT::v2f64;
11998       break;
11999     case Intrinsic::ppc_qpx_qvstfcs:
12000     case Intrinsic::ppc_qpx_qvstfcsa:
12001       VT = MVT::v2f32;
12002       break;
12003     case Intrinsic::ppc_qpx_qvstfiw:
12004     case Intrinsic::ppc_qpx_qvstfiwa:
12005     case Intrinsic::ppc_altivec_stvx:
12006     case Intrinsic::ppc_altivec_stvxl:
12007     case Intrinsic::ppc_vsx_stxvw4x:
12008       VT = MVT::v4i32;
12009       break;
12010     case Intrinsic::ppc_vsx_stxvd2x:
12011       VT = MVT::v2f64;
12012       break;
12013     case Intrinsic::ppc_vsx_stxvw4x_be:
12014       VT = MVT::v4i32;
12015       break;
12016     case Intrinsic::ppc_vsx_stxvd2x_be:
12017       VT = MVT::v2f64;
12018       break;
12019     case Intrinsic::ppc_altivec_stvebx:
12020       VT = MVT::i8;
12021       break;
12022     case Intrinsic::ppc_altivec_stvehx:
12023       VT = MVT::i16;
12024       break;
12025     case Intrinsic::ppc_altivec_stvewx:
12026       VT = MVT::i32;
12027       break;
12028     }
12029 
12030     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
12031   }
12032 
12033   return false;
12034 }
12035 
12036 // Return true is there is a nearyby consecutive load to the one provided
12037 // (regardless of alignment). We search up and down the chain, looking though
12038 // token factors and other loads (but nothing else). As a result, a true result
12039 // indicates that it is safe to create a new consecutive load adjacent to the
12040 // load provided.
12041 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
12042   SDValue Chain = LD->getChain();
12043   EVT VT = LD->getMemoryVT();
12044 
12045   SmallSet<SDNode *, 16> LoadRoots;
12046   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
12047   SmallSet<SDNode *, 16> Visited;
12048 
12049   // First, search up the chain, branching to follow all token-factor operands.
12050   // If we find a consecutive load, then we're done, otherwise, record all
12051   // nodes just above the top-level loads and token factors.
12052   while (!Queue.empty()) {
12053     SDNode *ChainNext = Queue.pop_back_val();
12054     if (!Visited.insert(ChainNext).second)
12055       continue;
12056 
12057     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
12058       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12059         return true;
12060 
12061       if (!Visited.count(ChainLD->getChain().getNode()))
12062         Queue.push_back(ChainLD->getChain().getNode());
12063     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
12064       for (const SDUse &O : ChainNext->ops())
12065         if (!Visited.count(O.getNode()))
12066           Queue.push_back(O.getNode());
12067     } else
12068       LoadRoots.insert(ChainNext);
12069   }
12070 
12071   // Second, search down the chain, starting from the top-level nodes recorded
12072   // in the first phase. These top-level nodes are the nodes just above all
12073   // loads and token factors. Starting with their uses, recursively look though
12074   // all loads (just the chain uses) and token factors to find a consecutive
12075   // load.
12076   Visited.clear();
12077   Queue.clear();
12078 
12079   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
12080        IE = LoadRoots.end(); I != IE; ++I) {
12081     Queue.push_back(*I);
12082 
12083     while (!Queue.empty()) {
12084       SDNode *LoadRoot = Queue.pop_back_val();
12085       if (!Visited.insert(LoadRoot).second)
12086         continue;
12087 
12088       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
12089         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
12090           return true;
12091 
12092       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
12093            UE = LoadRoot->use_end(); UI != UE; ++UI)
12094         if (((isa<MemSDNode>(*UI) &&
12095             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
12096             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
12097           Queue.push_back(*UI);
12098     }
12099   }
12100 
12101   return false;
12102 }
12103 
12104 /// This function is called when we have proved that a SETCC node can be replaced
12105 /// by subtraction (and other supporting instructions) so that the result of
12106 /// comparison is kept in a GPR instead of CR. This function is purely for
12107 /// codegen purposes and has some flags to guide the codegen process.
12108 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
12109                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
12110   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12111 
12112   // Zero extend the operands to the largest legal integer. Originally, they
12113   // must be of a strictly smaller size.
12114   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
12115                          DAG.getConstant(Size, DL, MVT::i32));
12116   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
12117                          DAG.getConstant(Size, DL, MVT::i32));
12118 
12119   // Swap if needed. Depends on the condition code.
12120   if (Swap)
12121     std::swap(Op0, Op1);
12122 
12123   // Subtract extended integers.
12124   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
12125 
12126   // Move the sign bit to the least significant position and zero out the rest.
12127   // Now the least significant bit carries the result of original comparison.
12128   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
12129                              DAG.getConstant(Size - 1, DL, MVT::i32));
12130   auto Final = Shifted;
12131 
12132   // Complement the result if needed. Based on the condition code.
12133   if (Complement)
12134     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
12135                         DAG.getConstant(1, DL, MVT::i64));
12136 
12137   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
12138 }
12139 
12140 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
12141                                                   DAGCombinerInfo &DCI) const {
12142   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
12143 
12144   SelectionDAG &DAG = DCI.DAG;
12145   SDLoc DL(N);
12146 
12147   // Size of integers being compared has a critical role in the following
12148   // analysis, so we prefer to do this when all types are legal.
12149   if (!DCI.isAfterLegalizeDAG())
12150     return SDValue();
12151 
12152   // If all users of SETCC extend its value to a legal integer type
12153   // then we replace SETCC with a subtraction
12154   for (SDNode::use_iterator UI = N->use_begin(),
12155        UE = N->use_end(); UI != UE; ++UI) {
12156     if (UI->getOpcode() != ISD::ZERO_EXTEND)
12157       return SDValue();
12158   }
12159 
12160   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12161   auto OpSize = N->getOperand(0).getValueSizeInBits();
12162 
12163   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
12164 
12165   if (OpSize < Size) {
12166     switch (CC) {
12167     default: break;
12168     case ISD::SETULT:
12169       return generateEquivalentSub(N, Size, false, false, DL, DAG);
12170     case ISD::SETULE:
12171       return generateEquivalentSub(N, Size, true, true, DL, DAG);
12172     case ISD::SETUGT:
12173       return generateEquivalentSub(N, Size, false, true, DL, DAG);
12174     case ISD::SETUGE:
12175       return generateEquivalentSub(N, Size, true, false, DL, DAG);
12176     }
12177   }
12178 
12179   return SDValue();
12180 }
12181 
12182 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
12183                                                   DAGCombinerInfo &DCI) const {
12184   SelectionDAG &DAG = DCI.DAG;
12185   SDLoc dl(N);
12186 
12187   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
12188   // If we're tracking CR bits, we need to be careful that we don't have:
12189   //   trunc(binary-ops(zext(x), zext(y)))
12190   // or
12191   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
12192   // such that we're unnecessarily moving things into GPRs when it would be
12193   // better to keep them in CR bits.
12194 
12195   // Note that trunc here can be an actual i1 trunc, or can be the effective
12196   // truncation that comes from a setcc or select_cc.
12197   if (N->getOpcode() == ISD::TRUNCATE &&
12198       N->getValueType(0) != MVT::i1)
12199     return SDValue();
12200 
12201   if (N->getOperand(0).getValueType() != MVT::i32 &&
12202       N->getOperand(0).getValueType() != MVT::i64)
12203     return SDValue();
12204 
12205   if (N->getOpcode() == ISD::SETCC ||
12206       N->getOpcode() == ISD::SELECT_CC) {
12207     // If we're looking at a comparison, then we need to make sure that the
12208     // high bits (all except for the first) don't matter the result.
12209     ISD::CondCode CC =
12210       cast<CondCodeSDNode>(N->getOperand(
12211         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
12212     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
12213 
12214     if (ISD::isSignedIntSetCC(CC)) {
12215       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
12216           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
12217         return SDValue();
12218     } else if (ISD::isUnsignedIntSetCC(CC)) {
12219       if (!DAG.MaskedValueIsZero(N->getOperand(0),
12220                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
12221           !DAG.MaskedValueIsZero(N->getOperand(1),
12222                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
12223         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
12224                                              : SDValue());
12225     } else {
12226       // This is neither a signed nor an unsigned comparison, just make sure
12227       // that the high bits are equal.
12228       KnownBits Op1Known = DAG.computeKnownBits(N->getOperand(0));
12229       KnownBits Op2Known = DAG.computeKnownBits(N->getOperand(1));
12230 
12231       // We don't really care about what is known about the first bit (if
12232       // anything), so clear it in all masks prior to comparing them.
12233       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
12234       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
12235 
12236       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
12237         return SDValue();
12238     }
12239   }
12240 
12241   // We now know that the higher-order bits are irrelevant, we just need to
12242   // make sure that all of the intermediate operations are bit operations, and
12243   // all inputs are extensions.
12244   if (N->getOperand(0).getOpcode() != ISD::AND &&
12245       N->getOperand(0).getOpcode() != ISD::OR  &&
12246       N->getOperand(0).getOpcode() != ISD::XOR &&
12247       N->getOperand(0).getOpcode() != ISD::SELECT &&
12248       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
12249       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
12250       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
12251       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
12252       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
12253     return SDValue();
12254 
12255   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
12256       N->getOperand(1).getOpcode() != ISD::AND &&
12257       N->getOperand(1).getOpcode() != ISD::OR  &&
12258       N->getOperand(1).getOpcode() != ISD::XOR &&
12259       N->getOperand(1).getOpcode() != ISD::SELECT &&
12260       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
12261       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
12262       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
12263       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
12264       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
12265     return SDValue();
12266 
12267   SmallVector<SDValue, 4> Inputs;
12268   SmallVector<SDValue, 8> BinOps, PromOps;
12269   SmallPtrSet<SDNode *, 16> Visited;
12270 
12271   for (unsigned i = 0; i < 2; ++i) {
12272     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12273           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12274           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12275           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12276         isa<ConstantSDNode>(N->getOperand(i)))
12277       Inputs.push_back(N->getOperand(i));
12278     else
12279       BinOps.push_back(N->getOperand(i));
12280 
12281     if (N->getOpcode() == ISD::TRUNCATE)
12282       break;
12283   }
12284 
12285   // Visit all inputs, collect all binary operations (and, or, xor and
12286   // select) that are all fed by extensions.
12287   while (!BinOps.empty()) {
12288     SDValue BinOp = BinOps.back();
12289     BinOps.pop_back();
12290 
12291     if (!Visited.insert(BinOp.getNode()).second)
12292       continue;
12293 
12294     PromOps.push_back(BinOp);
12295 
12296     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12297       // The condition of the select is not promoted.
12298       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12299         continue;
12300       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12301         continue;
12302 
12303       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12304             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12305             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
12306            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
12307           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12308         Inputs.push_back(BinOp.getOperand(i));
12309       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12310                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12311                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12312                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12313                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
12314                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12315                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
12316                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
12317                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
12318         BinOps.push_back(BinOp.getOperand(i));
12319       } else {
12320         // We have an input that is not an extension or another binary
12321         // operation; we'll abort this transformation.
12322         return SDValue();
12323       }
12324     }
12325   }
12326 
12327   // Make sure that this is a self-contained cluster of operations (which
12328   // is not quite the same thing as saying that everything has only one
12329   // use).
12330   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12331     if (isa<ConstantSDNode>(Inputs[i]))
12332       continue;
12333 
12334     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12335                               UE = Inputs[i].getNode()->use_end();
12336          UI != UE; ++UI) {
12337       SDNode *User = *UI;
12338       if (User != N && !Visited.count(User))
12339         return SDValue();
12340 
12341       // Make sure that we're not going to promote the non-output-value
12342       // operand(s) or SELECT or SELECT_CC.
12343       // FIXME: Although we could sometimes handle this, and it does occur in
12344       // practice that one of the condition inputs to the select is also one of
12345       // the outputs, we currently can't deal with this.
12346       if (User->getOpcode() == ISD::SELECT) {
12347         if (User->getOperand(0) == Inputs[i])
12348           return SDValue();
12349       } else if (User->getOpcode() == ISD::SELECT_CC) {
12350         if (User->getOperand(0) == Inputs[i] ||
12351             User->getOperand(1) == Inputs[i])
12352           return SDValue();
12353       }
12354     }
12355   }
12356 
12357   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12358     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12359                               UE = PromOps[i].getNode()->use_end();
12360          UI != UE; ++UI) {
12361       SDNode *User = *UI;
12362       if (User != N && !Visited.count(User))
12363         return SDValue();
12364 
12365       // Make sure that we're not going to promote the non-output-value
12366       // operand(s) or SELECT or SELECT_CC.
12367       // FIXME: Although we could sometimes handle this, and it does occur in
12368       // practice that one of the condition inputs to the select is also one of
12369       // the outputs, we currently can't deal with this.
12370       if (User->getOpcode() == ISD::SELECT) {
12371         if (User->getOperand(0) == PromOps[i])
12372           return SDValue();
12373       } else if (User->getOpcode() == ISD::SELECT_CC) {
12374         if (User->getOperand(0) == PromOps[i] ||
12375             User->getOperand(1) == PromOps[i])
12376           return SDValue();
12377       }
12378     }
12379   }
12380 
12381   // Replace all inputs with the extension operand.
12382   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12383     // Constants may have users outside the cluster of to-be-promoted nodes,
12384     // and so we need to replace those as we do the promotions.
12385     if (isa<ConstantSDNode>(Inputs[i]))
12386       continue;
12387     else
12388       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
12389   }
12390 
12391   std::list<HandleSDNode> PromOpHandles;
12392   for (auto &PromOp : PromOps)
12393     PromOpHandles.emplace_back(PromOp);
12394 
12395   // Replace all operations (these are all the same, but have a different
12396   // (i1) return type). DAG.getNode will validate that the types of
12397   // a binary operator match, so go through the list in reverse so that
12398   // we've likely promoted both operands first. Any intermediate truncations or
12399   // extensions disappear.
12400   while (!PromOpHandles.empty()) {
12401     SDValue PromOp = PromOpHandles.back().getValue();
12402     PromOpHandles.pop_back();
12403 
12404     if (PromOp.getOpcode() == ISD::TRUNCATE ||
12405         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
12406         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
12407         PromOp.getOpcode() == ISD::ANY_EXTEND) {
12408       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
12409           PromOp.getOperand(0).getValueType() != MVT::i1) {
12410         // The operand is not yet ready (see comment below).
12411         PromOpHandles.emplace_front(PromOp);
12412         continue;
12413       }
12414 
12415       SDValue RepValue = PromOp.getOperand(0);
12416       if (isa<ConstantSDNode>(RepValue))
12417         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
12418 
12419       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
12420       continue;
12421     }
12422 
12423     unsigned C;
12424     switch (PromOp.getOpcode()) {
12425     default:             C = 0; break;
12426     case ISD::SELECT:    C = 1; break;
12427     case ISD::SELECT_CC: C = 2; break;
12428     }
12429 
12430     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12431          PromOp.getOperand(C).getValueType() != MVT::i1) ||
12432         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12433          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
12434       // The to-be-promoted operands of this node have not yet been
12435       // promoted (this should be rare because we're going through the
12436       // list backward, but if one of the operands has several users in
12437       // this cluster of to-be-promoted nodes, it is possible).
12438       PromOpHandles.emplace_front(PromOp);
12439       continue;
12440     }
12441 
12442     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12443                                 PromOp.getNode()->op_end());
12444 
12445     // If there are any constant inputs, make sure they're replaced now.
12446     for (unsigned i = 0; i < 2; ++i)
12447       if (isa<ConstantSDNode>(Ops[C+i]))
12448         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
12449 
12450     DAG.ReplaceAllUsesOfValueWith(PromOp,
12451       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
12452   }
12453 
12454   // Now we're left with the initial truncation itself.
12455   if (N->getOpcode() == ISD::TRUNCATE)
12456     return N->getOperand(0);
12457 
12458   // Otherwise, this is a comparison. The operands to be compared have just
12459   // changed type (to i1), but everything else is the same.
12460   return SDValue(N, 0);
12461 }
12462 
12463 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
12464                                                   DAGCombinerInfo &DCI) const {
12465   SelectionDAG &DAG = DCI.DAG;
12466   SDLoc dl(N);
12467 
12468   // If we're tracking CR bits, we need to be careful that we don't have:
12469   //   zext(binary-ops(trunc(x), trunc(y)))
12470   // or
12471   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
12472   // such that we're unnecessarily moving things into CR bits that can more
12473   // efficiently stay in GPRs. Note that if we're not certain that the high
12474   // bits are set as required by the final extension, we still may need to do
12475   // some masking to get the proper behavior.
12476 
12477   // This same functionality is important on PPC64 when dealing with
12478   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
12479   // the return values of functions. Because it is so similar, it is handled
12480   // here as well.
12481 
12482   if (N->getValueType(0) != MVT::i32 &&
12483       N->getValueType(0) != MVT::i64)
12484     return SDValue();
12485 
12486   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
12487         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
12488     return SDValue();
12489 
12490   if (N->getOperand(0).getOpcode() != ISD::AND &&
12491       N->getOperand(0).getOpcode() != ISD::OR  &&
12492       N->getOperand(0).getOpcode() != ISD::XOR &&
12493       N->getOperand(0).getOpcode() != ISD::SELECT &&
12494       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
12495     return SDValue();
12496 
12497   SmallVector<SDValue, 4> Inputs;
12498   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
12499   SmallPtrSet<SDNode *, 16> Visited;
12500 
12501   // Visit all inputs, collect all binary operations (and, or, xor and
12502   // select) that are all fed by truncations.
12503   while (!BinOps.empty()) {
12504     SDValue BinOp = BinOps.back();
12505     BinOps.pop_back();
12506 
12507     if (!Visited.insert(BinOp.getNode()).second)
12508       continue;
12509 
12510     PromOps.push_back(BinOp);
12511 
12512     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
12513       // The condition of the select is not promoted.
12514       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
12515         continue;
12516       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
12517         continue;
12518 
12519       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
12520           isa<ConstantSDNode>(BinOp.getOperand(i))) {
12521         Inputs.push_back(BinOp.getOperand(i));
12522       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
12523                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
12524                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
12525                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
12526                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
12527         BinOps.push_back(BinOp.getOperand(i));
12528       } else {
12529         // We have an input that is not a truncation or another binary
12530         // operation; we'll abort this transformation.
12531         return SDValue();
12532       }
12533     }
12534   }
12535 
12536   // The operands of a select that must be truncated when the select is
12537   // promoted because the operand is actually part of the to-be-promoted set.
12538   DenseMap<SDNode *, EVT> SelectTruncOp[2];
12539 
12540   // Make sure that this is a self-contained cluster of operations (which
12541   // is not quite the same thing as saying that everything has only one
12542   // use).
12543   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12544     if (isa<ConstantSDNode>(Inputs[i]))
12545       continue;
12546 
12547     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
12548                               UE = Inputs[i].getNode()->use_end();
12549          UI != UE; ++UI) {
12550       SDNode *User = *UI;
12551       if (User != N && !Visited.count(User))
12552         return SDValue();
12553 
12554       // If we're going to promote the non-output-value operand(s) or SELECT or
12555       // SELECT_CC, record them for truncation.
12556       if (User->getOpcode() == ISD::SELECT) {
12557         if (User->getOperand(0) == Inputs[i])
12558           SelectTruncOp[0].insert(std::make_pair(User,
12559                                     User->getOperand(0).getValueType()));
12560       } else if (User->getOpcode() == ISD::SELECT_CC) {
12561         if (User->getOperand(0) == Inputs[i])
12562           SelectTruncOp[0].insert(std::make_pair(User,
12563                                     User->getOperand(0).getValueType()));
12564         if (User->getOperand(1) == Inputs[i])
12565           SelectTruncOp[1].insert(std::make_pair(User,
12566                                     User->getOperand(1).getValueType()));
12567       }
12568     }
12569   }
12570 
12571   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
12572     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
12573                               UE = PromOps[i].getNode()->use_end();
12574          UI != UE; ++UI) {
12575       SDNode *User = *UI;
12576       if (User != N && !Visited.count(User))
12577         return SDValue();
12578 
12579       // If we're going to promote the non-output-value operand(s) or SELECT or
12580       // SELECT_CC, record them for truncation.
12581       if (User->getOpcode() == ISD::SELECT) {
12582         if (User->getOperand(0) == PromOps[i])
12583           SelectTruncOp[0].insert(std::make_pair(User,
12584                                     User->getOperand(0).getValueType()));
12585       } else if (User->getOpcode() == ISD::SELECT_CC) {
12586         if (User->getOperand(0) == PromOps[i])
12587           SelectTruncOp[0].insert(std::make_pair(User,
12588                                     User->getOperand(0).getValueType()));
12589         if (User->getOperand(1) == PromOps[i])
12590           SelectTruncOp[1].insert(std::make_pair(User,
12591                                     User->getOperand(1).getValueType()));
12592       }
12593     }
12594   }
12595 
12596   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
12597   bool ReallyNeedsExt = false;
12598   if (N->getOpcode() != ISD::ANY_EXTEND) {
12599     // If all of the inputs are not already sign/zero extended, then
12600     // we'll still need to do that at the end.
12601     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12602       if (isa<ConstantSDNode>(Inputs[i]))
12603         continue;
12604 
12605       unsigned OpBits =
12606         Inputs[i].getOperand(0).getValueSizeInBits();
12607       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
12608 
12609       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
12610            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
12611                                   APInt::getHighBitsSet(OpBits,
12612                                                         OpBits-PromBits))) ||
12613           (N->getOpcode() == ISD::SIGN_EXTEND &&
12614            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
12615              (OpBits-(PromBits-1)))) {
12616         ReallyNeedsExt = true;
12617         break;
12618       }
12619     }
12620   }
12621 
12622   // Replace all inputs, either with the truncation operand, or a
12623   // truncation or extension to the final output type.
12624   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
12625     // Constant inputs need to be replaced with the to-be-promoted nodes that
12626     // use them because they might have users outside of the cluster of
12627     // promoted nodes.
12628     if (isa<ConstantSDNode>(Inputs[i]))
12629       continue;
12630 
12631     SDValue InSrc = Inputs[i].getOperand(0);
12632     if (Inputs[i].getValueType() == N->getValueType(0))
12633       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
12634     else if (N->getOpcode() == ISD::SIGN_EXTEND)
12635       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12636         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
12637     else if (N->getOpcode() == ISD::ZERO_EXTEND)
12638       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12639         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
12640     else
12641       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
12642         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
12643   }
12644 
12645   std::list<HandleSDNode> PromOpHandles;
12646   for (auto &PromOp : PromOps)
12647     PromOpHandles.emplace_back(PromOp);
12648 
12649   // Replace all operations (these are all the same, but have a different
12650   // (promoted) return type). DAG.getNode will validate that the types of
12651   // a binary operator match, so go through the list in reverse so that
12652   // we've likely promoted both operands first.
12653   while (!PromOpHandles.empty()) {
12654     SDValue PromOp = PromOpHandles.back().getValue();
12655     PromOpHandles.pop_back();
12656 
12657     unsigned C;
12658     switch (PromOp.getOpcode()) {
12659     default:             C = 0; break;
12660     case ISD::SELECT:    C = 1; break;
12661     case ISD::SELECT_CC: C = 2; break;
12662     }
12663 
12664     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
12665          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
12666         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
12667          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
12668       // The to-be-promoted operands of this node have not yet been
12669       // promoted (this should be rare because we're going through the
12670       // list backward, but if one of the operands has several users in
12671       // this cluster of to-be-promoted nodes, it is possible).
12672       PromOpHandles.emplace_front(PromOp);
12673       continue;
12674     }
12675 
12676     // For SELECT and SELECT_CC nodes, we do a similar check for any
12677     // to-be-promoted comparison inputs.
12678     if (PromOp.getOpcode() == ISD::SELECT ||
12679         PromOp.getOpcode() == ISD::SELECT_CC) {
12680       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
12681            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
12682           (SelectTruncOp[1].count(PromOp.getNode()) &&
12683            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
12684         PromOpHandles.emplace_front(PromOp);
12685         continue;
12686       }
12687     }
12688 
12689     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
12690                                 PromOp.getNode()->op_end());
12691 
12692     // If this node has constant inputs, then they'll need to be promoted here.
12693     for (unsigned i = 0; i < 2; ++i) {
12694       if (!isa<ConstantSDNode>(Ops[C+i]))
12695         continue;
12696       if (Ops[C+i].getValueType() == N->getValueType(0))
12697         continue;
12698 
12699       if (N->getOpcode() == ISD::SIGN_EXTEND)
12700         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12701       else if (N->getOpcode() == ISD::ZERO_EXTEND)
12702         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12703       else
12704         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
12705     }
12706 
12707     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
12708     // truncate them again to the original value type.
12709     if (PromOp.getOpcode() == ISD::SELECT ||
12710         PromOp.getOpcode() == ISD::SELECT_CC) {
12711       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
12712       if (SI0 != SelectTruncOp[0].end())
12713         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
12714       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
12715       if (SI1 != SelectTruncOp[1].end())
12716         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
12717     }
12718 
12719     DAG.ReplaceAllUsesOfValueWith(PromOp,
12720       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
12721   }
12722 
12723   // Now we're left with the initial extension itself.
12724   if (!ReallyNeedsExt)
12725     return N->getOperand(0);
12726 
12727   // To zero extend, just mask off everything except for the first bit (in the
12728   // i1 case).
12729   if (N->getOpcode() == ISD::ZERO_EXTEND)
12730     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
12731                        DAG.getConstant(APInt::getLowBitsSet(
12732                                          N->getValueSizeInBits(0), PromBits),
12733                                        dl, N->getValueType(0)));
12734 
12735   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
12736          "Invalid extension type");
12737   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
12738   SDValue ShiftCst =
12739       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
12740   return DAG.getNode(
12741       ISD::SRA, dl, N->getValueType(0),
12742       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
12743       ShiftCst);
12744 }
12745 
12746 SDValue PPCTargetLowering::combineSetCC(SDNode *N,
12747                                         DAGCombinerInfo &DCI) const {
12748   assert(N->getOpcode() == ISD::SETCC &&
12749          "Should be called with a SETCC node");
12750 
12751   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
12752   if (CC == ISD::SETNE || CC == ISD::SETEQ) {
12753     SDValue LHS = N->getOperand(0);
12754     SDValue RHS = N->getOperand(1);
12755 
12756     // If there is a '0 - y' pattern, canonicalize the pattern to the RHS.
12757     if (LHS.getOpcode() == ISD::SUB && isNullConstant(LHS.getOperand(0)) &&
12758         LHS.hasOneUse())
12759       std::swap(LHS, RHS);
12760 
12761     // x == 0-y --> x+y == 0
12762     // x != 0-y --> x+y != 0
12763     if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
12764         RHS.hasOneUse()) {
12765       SDLoc DL(N);
12766       SelectionDAG &DAG = DCI.DAG;
12767       EVT VT = N->getValueType(0);
12768       EVT OpVT = LHS.getValueType();
12769       SDValue Add = DAG.getNode(ISD::ADD, DL, OpVT, LHS, RHS.getOperand(1));
12770       return DAG.getSetCC(DL, VT, Add, DAG.getConstant(0, DL, OpVT), CC);
12771     }
12772   }
12773 
12774   return DAGCombineTruncBoolExt(N, DCI);
12775 }
12776 
12777 // Is this an extending load from an f32 to an f64?
12778 static bool isFPExtLoad(SDValue Op) {
12779   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode()))
12780     return LD->getExtensionType() == ISD::EXTLOAD &&
12781       Op.getValueType() == MVT::f64;
12782   return false;
12783 }
12784 
12785 /// Reduces the number of fp-to-int conversion when building a vector.
12786 ///
12787 /// If this vector is built out of floating to integer conversions,
12788 /// transform it to a vector built out of floating point values followed by a
12789 /// single floating to integer conversion of the vector.
12790 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
12791 /// becomes (fptosi (build_vector ($A, $B, ...)))
12792 SDValue PPCTargetLowering::
12793 combineElementTruncationToVectorTruncation(SDNode *N,
12794                                            DAGCombinerInfo &DCI) const {
12795   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12796          "Should be called with a BUILD_VECTOR node");
12797 
12798   SelectionDAG &DAG = DCI.DAG;
12799   SDLoc dl(N);
12800 
12801   SDValue FirstInput = N->getOperand(0);
12802   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
12803          "The input operand must be an fp-to-int conversion.");
12804 
12805   // This combine happens after legalization so the fp_to_[su]i nodes are
12806   // already converted to PPCSISD nodes.
12807   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
12808   if (FirstConversion == PPCISD::FCTIDZ ||
12809       FirstConversion == PPCISD::FCTIDUZ ||
12810       FirstConversion == PPCISD::FCTIWZ ||
12811       FirstConversion == PPCISD::FCTIWUZ) {
12812     bool IsSplat = true;
12813     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
12814       FirstConversion == PPCISD::FCTIWUZ;
12815     EVT SrcVT = FirstInput.getOperand(0).getValueType();
12816     SmallVector<SDValue, 4> Ops;
12817     EVT TargetVT = N->getValueType(0);
12818     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12819       SDValue NextOp = N->getOperand(i);
12820       if (NextOp.getOpcode() != PPCISD::MFVSR)
12821         return SDValue();
12822       unsigned NextConversion = NextOp.getOperand(0).getOpcode();
12823       if (NextConversion != FirstConversion)
12824         return SDValue();
12825       // If we are converting to 32-bit integers, we need to add an FP_ROUND.
12826       // This is not valid if the input was originally double precision. It is
12827       // also not profitable to do unless this is an extending load in which
12828       // case doing this combine will allow us to combine consecutive loads.
12829       if (Is32Bit && !isFPExtLoad(NextOp.getOperand(0).getOperand(0)))
12830         return SDValue();
12831       if (N->getOperand(i) != FirstInput)
12832         IsSplat = false;
12833     }
12834 
12835     // If this is a splat, we leave it as-is since there will be only a single
12836     // fp-to-int conversion followed by a splat of the integer. This is better
12837     // for 32-bit and smaller ints and neutral for 64-bit ints.
12838     if (IsSplat)
12839       return SDValue();
12840 
12841     // Now that we know we have the right type of node, get its operands
12842     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
12843       SDValue In = N->getOperand(i).getOperand(0);
12844       if (Is32Bit) {
12845         // For 32-bit values, we need to add an FP_ROUND node (if we made it
12846         // here, we know that all inputs are extending loads so this is safe).
12847         if (In.isUndef())
12848           Ops.push_back(DAG.getUNDEF(SrcVT));
12849         else {
12850           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
12851                                       MVT::f32, In.getOperand(0),
12852                                       DAG.getIntPtrConstant(1, dl));
12853           Ops.push_back(Trunc);
12854         }
12855       } else
12856         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
12857     }
12858 
12859     unsigned Opcode;
12860     if (FirstConversion == PPCISD::FCTIDZ ||
12861         FirstConversion == PPCISD::FCTIWZ)
12862       Opcode = ISD::FP_TO_SINT;
12863     else
12864       Opcode = ISD::FP_TO_UINT;
12865 
12866     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
12867     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
12868     return DAG.getNode(Opcode, dl, TargetVT, BV);
12869   }
12870   return SDValue();
12871 }
12872 
12873 /// Reduce the number of loads when building a vector.
12874 ///
12875 /// Building a vector out of multiple loads can be converted to a load
12876 /// of the vector type if the loads are consecutive. If the loads are
12877 /// consecutive but in descending order, a shuffle is added at the end
12878 /// to reorder the vector.
12879 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
12880   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
12881          "Should be called with a BUILD_VECTOR node");
12882 
12883   SDLoc dl(N);
12884 
12885   // Return early for non byte-sized type, as they can't be consecutive.
12886   if (!N->getValueType(0).getVectorElementType().isByteSized())
12887     return SDValue();
12888 
12889   bool InputsAreConsecutiveLoads = true;
12890   bool InputsAreReverseConsecutive = true;
12891   unsigned ElemSize = N->getValueType(0).getScalarType().getStoreSize();
12892   SDValue FirstInput = N->getOperand(0);
12893   bool IsRoundOfExtLoad = false;
12894 
12895   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
12896       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
12897     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
12898     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
12899   }
12900   // Not a build vector of (possibly fp_rounded) loads.
12901   if ((!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD) ||
12902       N->getNumOperands() == 1)
12903     return SDValue();
12904 
12905   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
12906     // If any inputs are fp_round(extload), they all must be.
12907     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
12908       return SDValue();
12909 
12910     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
12911       N->getOperand(i);
12912     if (NextInput.getOpcode() != ISD::LOAD)
12913       return SDValue();
12914 
12915     SDValue PreviousInput =
12916       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
12917     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
12918     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
12919 
12920     // If any inputs are fp_round(extload), they all must be.
12921     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
12922       return SDValue();
12923 
12924     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
12925       InputsAreConsecutiveLoads = false;
12926     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
12927       InputsAreReverseConsecutive = false;
12928 
12929     // Exit early if the loads are neither consecutive nor reverse consecutive.
12930     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
12931       return SDValue();
12932   }
12933 
12934   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
12935          "The loads cannot be both consecutive and reverse consecutive.");
12936 
12937   SDValue FirstLoadOp =
12938     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
12939   SDValue LastLoadOp =
12940     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
12941                        N->getOperand(N->getNumOperands()-1);
12942 
12943   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
12944   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
12945   if (InputsAreConsecutiveLoads) {
12946     assert(LD1 && "Input needs to be a LoadSDNode.");
12947     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
12948                        LD1->getBasePtr(), LD1->getPointerInfo(),
12949                        LD1->getAlignment());
12950   }
12951   if (InputsAreReverseConsecutive) {
12952     assert(LDL && "Input needs to be a LoadSDNode.");
12953     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
12954                                LDL->getBasePtr(), LDL->getPointerInfo(),
12955                                LDL->getAlignment());
12956     SmallVector<int, 16> Ops;
12957     for (int i = N->getNumOperands() - 1; i >= 0; i--)
12958       Ops.push_back(i);
12959 
12960     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
12961                                 DAG.getUNDEF(N->getValueType(0)), Ops);
12962   }
12963   return SDValue();
12964 }
12965 
12966 // This function adds the required vector_shuffle needed to get
12967 // the elements of the vector extract in the correct position
12968 // as specified by the CorrectElems encoding.
12969 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
12970                                       SDValue Input, uint64_t Elems,
12971                                       uint64_t CorrectElems) {
12972   SDLoc dl(N);
12973 
12974   unsigned NumElems = Input.getValueType().getVectorNumElements();
12975   SmallVector<int, 16> ShuffleMask(NumElems, -1);
12976 
12977   // Knowing the element indices being extracted from the original
12978   // vector and the order in which they're being inserted, just put
12979   // them at element indices required for the instruction.
12980   for (unsigned i = 0; i < N->getNumOperands(); i++) {
12981     if (DAG.getDataLayout().isLittleEndian())
12982       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
12983     else
12984       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
12985     CorrectElems = CorrectElems >> 8;
12986     Elems = Elems >> 8;
12987   }
12988 
12989   SDValue Shuffle =
12990       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
12991                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
12992 
12993   EVT Ty = N->getValueType(0);
12994   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
12995   return BV;
12996 }
12997 
12998 // Look for build vector patterns where input operands come from sign
12999 // extended vector_extract elements of specific indices. If the correct indices
13000 // aren't used, add a vector shuffle to fix up the indices and create a new
13001 // PPCISD:SExtVElems node which selects the vector sign extend instructions
13002 // during instruction selection.
13003 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
13004   // This array encodes the indices that the vector sign extend instructions
13005   // extract from when extending from one type to another for both BE and LE.
13006   // The right nibble of each byte corresponds to the LE incides.
13007   // and the left nibble of each byte corresponds to the BE incides.
13008   // For example: 0x3074B8FC  byte->word
13009   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
13010   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
13011   // For example: 0x000070F8  byte->double word
13012   // For LE: the allowed indices are: 0x0,0x8
13013   // For BE: the allowed indices are: 0x7,0xF
13014   uint64_t TargetElems[] = {
13015       0x3074B8FC, // b->w
13016       0x000070F8, // b->d
13017       0x10325476, // h->w
13018       0x00003074, // h->d
13019       0x00001032, // w->d
13020   };
13021 
13022   uint64_t Elems = 0;
13023   int Index;
13024   SDValue Input;
13025 
13026   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
13027     if (!Op)
13028       return false;
13029     if (Op.getOpcode() != ISD::SIGN_EXTEND &&
13030         Op.getOpcode() != ISD::SIGN_EXTEND_INREG)
13031       return false;
13032 
13033     // A SIGN_EXTEND_INREG might be fed by an ANY_EXTEND to produce a value
13034     // of the right width.
13035     SDValue Extract = Op.getOperand(0);
13036     if (Extract.getOpcode() == ISD::ANY_EXTEND)
13037       Extract = Extract.getOperand(0);
13038     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13039       return false;
13040 
13041     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
13042     if (!ExtOp)
13043       return false;
13044 
13045     Index = ExtOp->getZExtValue();
13046     if (Input && Input != Extract.getOperand(0))
13047       return false;
13048 
13049     if (!Input)
13050       Input = Extract.getOperand(0);
13051 
13052     Elems = Elems << 8;
13053     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
13054     Elems |= Index;
13055 
13056     return true;
13057   };
13058 
13059   // If the build vector operands aren't sign extended vector extracts,
13060   // of the same input vector, then return.
13061   for (unsigned i = 0; i < N->getNumOperands(); i++) {
13062     if (!isSExtOfVecExtract(N->getOperand(i))) {
13063       return SDValue();
13064     }
13065   }
13066 
13067   // If the vector extract indicies are not correct, add the appropriate
13068   // vector_shuffle.
13069   int TgtElemArrayIdx;
13070   int InputSize = Input.getValueType().getScalarSizeInBits();
13071   int OutputSize = N->getValueType(0).getScalarSizeInBits();
13072   if (InputSize + OutputSize == 40)
13073     TgtElemArrayIdx = 0;
13074   else if (InputSize + OutputSize == 72)
13075     TgtElemArrayIdx = 1;
13076   else if (InputSize + OutputSize == 48)
13077     TgtElemArrayIdx = 2;
13078   else if (InputSize + OutputSize == 80)
13079     TgtElemArrayIdx = 3;
13080   else if (InputSize + OutputSize == 96)
13081     TgtElemArrayIdx = 4;
13082   else
13083     return SDValue();
13084 
13085   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
13086   CorrectElems = DAG.getDataLayout().isLittleEndian()
13087                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
13088                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
13089   if (Elems != CorrectElems) {
13090     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
13091   }
13092 
13093   // Regular lowering will catch cases where a shuffle is not needed.
13094   return SDValue();
13095 }
13096 
13097 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
13098                                                  DAGCombinerInfo &DCI) const {
13099   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
13100          "Should be called with a BUILD_VECTOR node");
13101 
13102   SelectionDAG &DAG = DCI.DAG;
13103   SDLoc dl(N);
13104 
13105   if (!Subtarget.hasVSX())
13106     return SDValue();
13107 
13108   // The target independent DAG combiner will leave a build_vector of
13109   // float-to-int conversions intact. We can generate MUCH better code for
13110   // a float-to-int conversion of a vector of floats.
13111   SDValue FirstInput = N->getOperand(0);
13112   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
13113     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
13114     if (Reduced)
13115       return Reduced;
13116   }
13117 
13118   // If we're building a vector out of consecutive loads, just load that
13119   // vector type.
13120   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
13121   if (Reduced)
13122     return Reduced;
13123 
13124   // If we're building a vector out of extended elements from another vector
13125   // we have P9 vector integer extend instructions. The code assumes legal
13126   // input types (i.e. it can't handle things like v4i16) so do not run before
13127   // legalization.
13128   if (Subtarget.hasP9Altivec() && !DCI.isBeforeLegalize()) {
13129     Reduced = combineBVOfVecSExt(N, DAG);
13130     if (Reduced)
13131       return Reduced;
13132   }
13133 
13134 
13135   if (N->getValueType(0) != MVT::v2f64)
13136     return SDValue();
13137 
13138   // Looking for:
13139   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
13140   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
13141       FirstInput.getOpcode() != ISD::UINT_TO_FP)
13142     return SDValue();
13143   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
13144       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
13145     return SDValue();
13146   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
13147     return SDValue();
13148 
13149   SDValue Ext1 = FirstInput.getOperand(0);
13150   SDValue Ext2 = N->getOperand(1).getOperand(0);
13151   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
13152      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13153     return SDValue();
13154 
13155   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
13156   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
13157   if (!Ext1Op || !Ext2Op)
13158     return SDValue();
13159   if (Ext1.getOperand(0).getValueType() != MVT::v4i32 ||
13160       Ext1.getOperand(0) != Ext2.getOperand(0))
13161     return SDValue();
13162 
13163   int FirstElem = Ext1Op->getZExtValue();
13164   int SecondElem = Ext2Op->getZExtValue();
13165   int SubvecIdx;
13166   if (FirstElem == 0 && SecondElem == 1)
13167     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
13168   else if (FirstElem == 2 && SecondElem == 3)
13169     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
13170   else
13171     return SDValue();
13172 
13173   SDValue SrcVec = Ext1.getOperand(0);
13174   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
13175     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
13176   return DAG.getNode(NodeType, dl, MVT::v2f64,
13177                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
13178 }
13179 
13180 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
13181                                               DAGCombinerInfo &DCI) const {
13182   assert((N->getOpcode() == ISD::SINT_TO_FP ||
13183           N->getOpcode() == ISD::UINT_TO_FP) &&
13184          "Need an int -> FP conversion node here");
13185 
13186   if (useSoftFloat() || !Subtarget.has64BitSupport())
13187     return SDValue();
13188 
13189   SelectionDAG &DAG = DCI.DAG;
13190   SDLoc dl(N);
13191   SDValue Op(N, 0);
13192 
13193   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
13194   // from the hardware.
13195   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
13196     return SDValue();
13197   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
13198       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
13199     return SDValue();
13200 
13201   SDValue FirstOperand(Op.getOperand(0));
13202   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
13203     (FirstOperand.getValueType() == MVT::i8 ||
13204      FirstOperand.getValueType() == MVT::i16);
13205   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
13206     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
13207     bool DstDouble = Op.getValueType() == MVT::f64;
13208     unsigned ConvOp = Signed ?
13209       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
13210       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
13211     SDValue WidthConst =
13212       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
13213                             dl, false);
13214     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
13215     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
13216     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
13217                                          DAG.getVTList(MVT::f64, MVT::Other),
13218                                          Ops, MVT::i8, LDN->getMemOperand());
13219 
13220     // For signed conversion, we need to sign-extend the value in the VSR
13221     if (Signed) {
13222       SDValue ExtOps[] = { Ld, WidthConst };
13223       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
13224       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
13225     } else
13226       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
13227   }
13228 
13229 
13230   // For i32 intermediate values, unfortunately, the conversion functions
13231   // leave the upper 32 bits of the value are undefined. Within the set of
13232   // scalar instructions, we have no method for zero- or sign-extending the
13233   // value. Thus, we cannot handle i32 intermediate values here.
13234   if (Op.getOperand(0).getValueType() == MVT::i32)
13235     return SDValue();
13236 
13237   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
13238          "UINT_TO_FP is supported only with FPCVT");
13239 
13240   // If we have FCFIDS, then use it when converting to single-precision.
13241   // Otherwise, convert to double-precision and then round.
13242   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13243                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
13244                                                             : PPCISD::FCFIDS)
13245                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
13246                                                             : PPCISD::FCFID);
13247   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
13248                   ? MVT::f32
13249                   : MVT::f64;
13250 
13251   // If we're converting from a float, to an int, and back to a float again,
13252   // then we don't need the store/load pair at all.
13253   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
13254        Subtarget.hasFPCVT()) ||
13255       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
13256     SDValue Src = Op.getOperand(0).getOperand(0);
13257     if (Src.getValueType() == MVT::f32) {
13258       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
13259       DCI.AddToWorklist(Src.getNode());
13260     } else if (Src.getValueType() != MVT::f64) {
13261       // Make sure that we don't pick up a ppc_fp128 source value.
13262       return SDValue();
13263     }
13264 
13265     unsigned FCTOp =
13266       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
13267                                                         PPCISD::FCTIDUZ;
13268 
13269     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
13270     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
13271 
13272     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
13273       FP = DAG.getNode(ISD::FP_ROUND, dl,
13274                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
13275       DCI.AddToWorklist(FP.getNode());
13276     }
13277 
13278     return FP;
13279   }
13280 
13281   return SDValue();
13282 }
13283 
13284 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
13285 // builtins) into loads with swaps.
13286 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
13287                                               DAGCombinerInfo &DCI) const {
13288   SelectionDAG &DAG = DCI.DAG;
13289   SDLoc dl(N);
13290   SDValue Chain;
13291   SDValue Base;
13292   MachineMemOperand *MMO;
13293 
13294   switch (N->getOpcode()) {
13295   default:
13296     llvm_unreachable("Unexpected opcode for little endian VSX load");
13297   case ISD::LOAD: {
13298     LoadSDNode *LD = cast<LoadSDNode>(N);
13299     Chain = LD->getChain();
13300     Base = LD->getBasePtr();
13301     MMO = LD->getMemOperand();
13302     // If the MMO suggests this isn't a load of a full vector, leave
13303     // things alone.  For a built-in, we have to make the change for
13304     // correctness, so if there is a size problem that will be a bug.
13305     if (MMO->getSize() < 16)
13306       return SDValue();
13307     break;
13308   }
13309   case ISD::INTRINSIC_W_CHAIN: {
13310     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13311     Chain = Intrin->getChain();
13312     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
13313     // us what we want. Get operand 2 instead.
13314     Base = Intrin->getOperand(2);
13315     MMO = Intrin->getMemOperand();
13316     break;
13317   }
13318   }
13319 
13320   MVT VecTy = N->getValueType(0).getSimpleVT();
13321 
13322   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
13323   // aligned and the type is a vector with elements up to 4 bytes
13324   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13325       && VecTy.getScalarSizeInBits() <= 32 ) {
13326     return SDValue();
13327   }
13328 
13329   SDValue LoadOps[] = { Chain, Base };
13330   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
13331                                          DAG.getVTList(MVT::v2f64, MVT::Other),
13332                                          LoadOps, MVT::v2f64, MMO);
13333 
13334   DCI.AddToWorklist(Load.getNode());
13335   Chain = Load.getValue(1);
13336   SDValue Swap = DAG.getNode(
13337       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
13338   DCI.AddToWorklist(Swap.getNode());
13339 
13340   // Add a bitcast if the resulting load type doesn't match v2f64.
13341   if (VecTy != MVT::v2f64) {
13342     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
13343     DCI.AddToWorklist(N.getNode());
13344     // Package {bitcast value, swap's chain} to match Load's shape.
13345     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
13346                        N, Swap.getValue(1));
13347   }
13348 
13349   return Swap;
13350 }
13351 
13352 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
13353 // builtins) into stores with swaps.
13354 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
13355                                                DAGCombinerInfo &DCI) const {
13356   SelectionDAG &DAG = DCI.DAG;
13357   SDLoc dl(N);
13358   SDValue Chain;
13359   SDValue Base;
13360   unsigned SrcOpnd;
13361   MachineMemOperand *MMO;
13362 
13363   switch (N->getOpcode()) {
13364   default:
13365     llvm_unreachable("Unexpected opcode for little endian VSX store");
13366   case ISD::STORE: {
13367     StoreSDNode *ST = cast<StoreSDNode>(N);
13368     Chain = ST->getChain();
13369     Base = ST->getBasePtr();
13370     MMO = ST->getMemOperand();
13371     SrcOpnd = 1;
13372     // If the MMO suggests this isn't a store of a full vector, leave
13373     // things alone.  For a built-in, we have to make the change for
13374     // correctness, so if there is a size problem that will be a bug.
13375     if (MMO->getSize() < 16)
13376       return SDValue();
13377     break;
13378   }
13379   case ISD::INTRINSIC_VOID: {
13380     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
13381     Chain = Intrin->getChain();
13382     // Intrin->getBasePtr() oddly does not get what we want.
13383     Base = Intrin->getOperand(3);
13384     MMO = Intrin->getMemOperand();
13385     SrcOpnd = 2;
13386     break;
13387   }
13388   }
13389 
13390   SDValue Src = N->getOperand(SrcOpnd);
13391   MVT VecTy = Src.getValueType().getSimpleVT();
13392 
13393   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
13394   // aligned and the type is a vector with elements up to 4 bytes
13395   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
13396       && VecTy.getScalarSizeInBits() <= 32 ) {
13397     return SDValue();
13398   }
13399 
13400   // All stores are done as v2f64 and possible bit cast.
13401   if (VecTy != MVT::v2f64) {
13402     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
13403     DCI.AddToWorklist(Src.getNode());
13404   }
13405 
13406   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
13407                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
13408   DCI.AddToWorklist(Swap.getNode());
13409   Chain = Swap.getValue(1);
13410   SDValue StoreOps[] = { Chain, Swap, Base };
13411   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
13412                                           DAG.getVTList(MVT::Other),
13413                                           StoreOps, VecTy, MMO);
13414   DCI.AddToWorklist(Store.getNode());
13415   return Store;
13416 }
13417 
13418 // Handle DAG combine for STORE (FP_TO_INT F).
13419 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
13420                                                DAGCombinerInfo &DCI) const {
13421 
13422   SelectionDAG &DAG = DCI.DAG;
13423   SDLoc dl(N);
13424   unsigned Opcode = N->getOperand(1).getOpcode();
13425 
13426   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
13427          && "Not a FP_TO_INT Instruction!");
13428 
13429   SDValue Val = N->getOperand(1).getOperand(0);
13430   EVT Op1VT = N->getOperand(1).getValueType();
13431   EVT ResVT = Val.getValueType();
13432 
13433   // Floating point types smaller than 32 bits are not legal on Power.
13434   if (ResVT.getScalarSizeInBits() < 32)
13435     return SDValue();
13436 
13437   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
13438   bool ValidTypeForStoreFltAsInt =
13439         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
13440          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
13441 
13442   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
13443       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
13444     return SDValue();
13445 
13446   // Extend f32 values to f64
13447   if (ResVT.getScalarSizeInBits() == 32) {
13448     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
13449     DCI.AddToWorklist(Val.getNode());
13450   }
13451 
13452   // Set signed or unsigned conversion opcode.
13453   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
13454                           PPCISD::FP_TO_SINT_IN_VSR :
13455                           PPCISD::FP_TO_UINT_IN_VSR;
13456 
13457   Val = DAG.getNode(ConvOpcode,
13458                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
13459   DCI.AddToWorklist(Val.getNode());
13460 
13461   // Set number of bytes being converted.
13462   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
13463   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
13464                     DAG.getIntPtrConstant(ByteSize, dl, false),
13465                     DAG.getValueType(Op1VT) };
13466 
13467   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
13468           DAG.getVTList(MVT::Other), Ops,
13469           cast<StoreSDNode>(N)->getMemoryVT(),
13470           cast<StoreSDNode>(N)->getMemOperand());
13471 
13472   DCI.AddToWorklist(Val.getNode());
13473   return Val;
13474 }
13475 
13476 SDValue PPCTargetLowering::combineVReverseMemOP(ShuffleVectorSDNode *SVN,
13477                                                 LSBaseSDNode *LSBase,
13478                                                 DAGCombinerInfo &DCI) const {
13479   assert((ISD::isNormalLoad(LSBase) || ISD::isNormalStore(LSBase)) &&
13480         "Not a reverse memop pattern!");
13481 
13482   auto IsElementReverse = [](const ShuffleVectorSDNode *SVN) -> bool {
13483     auto Mask = SVN->getMask();
13484     int i = 0;
13485     auto I = Mask.rbegin();
13486     auto E = Mask.rend();
13487 
13488     for (; I != E; ++I) {
13489       if (*I != i)
13490         return false;
13491       i++;
13492     }
13493     return true;
13494   };
13495 
13496   SelectionDAG &DAG = DCI.DAG;
13497   EVT VT = SVN->getValueType(0);
13498 
13499   if (!isTypeLegal(VT) || !Subtarget.isLittleEndian() || !Subtarget.hasVSX())
13500     return SDValue();
13501 
13502   // Before P9, we have PPCVSXSwapRemoval pass to hack the element order.
13503   // See comment in PPCVSXSwapRemoval.cpp.
13504   // It is conflict with PPCVSXSwapRemoval opt. So we don't do it.
13505   if (!Subtarget.hasP9Vector())
13506     return SDValue();
13507 
13508   if(!IsElementReverse(SVN))
13509     return SDValue();
13510 
13511   if (LSBase->getOpcode() == ISD::LOAD) {
13512     SDLoc dl(SVN);
13513     SDValue LoadOps[] = {LSBase->getChain(), LSBase->getBasePtr()};
13514     return DAG.getMemIntrinsicNode(
13515         PPCISD::LOAD_VEC_BE, dl, DAG.getVTList(VT, MVT::Other), LoadOps,
13516         LSBase->getMemoryVT(), LSBase->getMemOperand());
13517   }
13518 
13519   if (LSBase->getOpcode() == ISD::STORE) {
13520     SDLoc dl(LSBase);
13521     SDValue StoreOps[] = {LSBase->getChain(), SVN->getOperand(0),
13522                           LSBase->getBasePtr()};
13523     return DAG.getMemIntrinsicNode(
13524         PPCISD::STORE_VEC_BE, dl, DAG.getVTList(MVT::Other), StoreOps,
13525         LSBase->getMemoryVT(), LSBase->getMemOperand());
13526   }
13527 
13528   llvm_unreachable("Expected a load or store node here");
13529 }
13530 
13531 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
13532                                              DAGCombinerInfo &DCI) const {
13533   SelectionDAG &DAG = DCI.DAG;
13534   SDLoc dl(N);
13535   switch (N->getOpcode()) {
13536   default: break;
13537   case ISD::ADD:
13538     return combineADD(N, DCI);
13539   case ISD::SHL:
13540     return combineSHL(N, DCI);
13541   case ISD::SRA:
13542     return combineSRA(N, DCI);
13543   case ISD::SRL:
13544     return combineSRL(N, DCI);
13545   case ISD::MUL:
13546     return combineMUL(N, DCI);
13547   case PPCISD::SHL:
13548     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
13549         return N->getOperand(0);
13550     break;
13551   case PPCISD::SRL:
13552     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
13553         return N->getOperand(0);
13554     break;
13555   case PPCISD::SRA:
13556     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
13557       if (C->isNullValue() ||   //  0 >>s V -> 0.
13558           C->isAllOnesValue())    // -1 >>s V -> -1.
13559         return N->getOperand(0);
13560     }
13561     break;
13562   case ISD::SIGN_EXTEND:
13563   case ISD::ZERO_EXTEND:
13564   case ISD::ANY_EXTEND:
13565     return DAGCombineExtBoolTrunc(N, DCI);
13566   case ISD::TRUNCATE:
13567     return combineTRUNCATE(N, DCI);
13568   case ISD::SETCC:
13569     if (SDValue CSCC = combineSetCC(N, DCI))
13570       return CSCC;
13571     LLVM_FALLTHROUGH;
13572   case ISD::SELECT_CC:
13573     return DAGCombineTruncBoolExt(N, DCI);
13574   case ISD::SINT_TO_FP:
13575   case ISD::UINT_TO_FP:
13576     return combineFPToIntToFP(N, DCI);
13577   case ISD::VECTOR_SHUFFLE:
13578     if (ISD::isNormalLoad(N->getOperand(0).getNode())) {
13579       LSBaseSDNode* LSBase = cast<LSBaseSDNode>(N->getOperand(0));
13580       return combineVReverseMemOP(cast<ShuffleVectorSDNode>(N), LSBase, DCI);
13581     }
13582     break;
13583   case ISD::STORE: {
13584 
13585     EVT Op1VT = N->getOperand(1).getValueType();
13586     unsigned Opcode = N->getOperand(1).getOpcode();
13587 
13588     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
13589       SDValue Val= combineStoreFPToInt(N, DCI);
13590       if (Val)
13591         return Val;
13592     }
13593 
13594     if (Opcode == ISD::VECTOR_SHUFFLE && ISD::isNormalStore(N)) {
13595       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N->getOperand(1));
13596       SDValue Val= combineVReverseMemOP(SVN, cast<LSBaseSDNode>(N), DCI);
13597       if (Val)
13598         return Val;
13599     }
13600 
13601     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
13602     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
13603         N->getOperand(1).getNode()->hasOneUse() &&
13604         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
13605          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
13606 
13607       // STBRX can only handle simple types and it makes no sense to store less
13608       // two bytes in byte-reversed order.
13609       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
13610       if (mVT.isExtended() || mVT.getSizeInBits() < 16)
13611         break;
13612 
13613       SDValue BSwapOp = N->getOperand(1).getOperand(0);
13614       // Do an any-extend to 32-bits if this is a half-word input.
13615       if (BSwapOp.getValueType() == MVT::i16)
13616         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
13617 
13618       // If the type of BSWAP operand is wider than stored memory width
13619       // it need to be shifted to the right side before STBRX.
13620       if (Op1VT.bitsGT(mVT)) {
13621         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
13622         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
13623                               DAG.getConstant(Shift, dl, MVT::i32));
13624         // Need to truncate if this is a bswap of i64 stored as i32/i16.
13625         if (Op1VT == MVT::i64)
13626           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
13627       }
13628 
13629       SDValue Ops[] = {
13630         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
13631       };
13632       return
13633         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
13634                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
13635                                 cast<StoreSDNode>(N)->getMemOperand());
13636     }
13637 
13638     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
13639     // So it can increase the chance of CSE constant construction.
13640     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
13641         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
13642       // Need to sign-extended to 64-bits to handle negative values.
13643       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
13644       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
13645                                     MemVT.getSizeInBits());
13646       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
13647 
13648       // DAG.getTruncStore() can't be used here because it doesn't accept
13649       // the general (base + offset) addressing mode.
13650       // So we use UpdateNodeOperands and setTruncatingStore instead.
13651       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
13652                              N->getOperand(3));
13653       cast<StoreSDNode>(N)->setTruncatingStore(true);
13654       return SDValue(N, 0);
13655     }
13656 
13657     // For little endian, VSX stores require generating xxswapd/lxvd2x.
13658     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
13659     if (Op1VT.isSimple()) {
13660       MVT StoreVT = Op1VT.getSimpleVT();
13661       if (Subtarget.needsSwapsForVSXMemOps() &&
13662           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
13663            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
13664         return expandVSXStoreForLE(N, DCI);
13665     }
13666     break;
13667   }
13668   case ISD::LOAD: {
13669     LoadSDNode *LD = cast<LoadSDNode>(N);
13670     EVT VT = LD->getValueType(0);
13671 
13672     // For little endian, VSX loads require generating lxvd2x/xxswapd.
13673     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
13674     if (VT.isSimple()) {
13675       MVT LoadVT = VT.getSimpleVT();
13676       if (Subtarget.needsSwapsForVSXMemOps() &&
13677           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
13678            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
13679         return expandVSXLoadForLE(N, DCI);
13680     }
13681 
13682     // We sometimes end up with a 64-bit integer load, from which we extract
13683     // two single-precision floating-point numbers. This happens with
13684     // std::complex<float>, and other similar structures, because of the way we
13685     // canonicalize structure copies. However, if we lack direct moves,
13686     // then the final bitcasts from the extracted integer values to the
13687     // floating-point numbers turn into store/load pairs. Even with direct moves,
13688     // just loading the two floating-point numbers is likely better.
13689     auto ReplaceTwoFloatLoad = [&]() {
13690       if (VT != MVT::i64)
13691         return false;
13692 
13693       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
13694           LD->isVolatile())
13695         return false;
13696 
13697       //  We're looking for a sequence like this:
13698       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
13699       //      t16: i64 = srl t13, Constant:i32<32>
13700       //    t17: i32 = truncate t16
13701       //  t18: f32 = bitcast t17
13702       //    t19: i32 = truncate t13
13703       //  t20: f32 = bitcast t19
13704 
13705       if (!LD->hasNUsesOfValue(2, 0))
13706         return false;
13707 
13708       auto UI = LD->use_begin();
13709       while (UI.getUse().getResNo() != 0) ++UI;
13710       SDNode *Trunc = *UI++;
13711       while (UI.getUse().getResNo() != 0) ++UI;
13712       SDNode *RightShift = *UI;
13713       if (Trunc->getOpcode() != ISD::TRUNCATE)
13714         std::swap(Trunc, RightShift);
13715 
13716       if (Trunc->getOpcode() != ISD::TRUNCATE ||
13717           Trunc->getValueType(0) != MVT::i32 ||
13718           !Trunc->hasOneUse())
13719         return false;
13720       if (RightShift->getOpcode() != ISD::SRL ||
13721           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
13722           RightShift->getConstantOperandVal(1) != 32 ||
13723           !RightShift->hasOneUse())
13724         return false;
13725 
13726       SDNode *Trunc2 = *RightShift->use_begin();
13727       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
13728           Trunc2->getValueType(0) != MVT::i32 ||
13729           !Trunc2->hasOneUse())
13730         return false;
13731 
13732       SDNode *Bitcast = *Trunc->use_begin();
13733       SDNode *Bitcast2 = *Trunc2->use_begin();
13734 
13735       if (Bitcast->getOpcode() != ISD::BITCAST ||
13736           Bitcast->getValueType(0) != MVT::f32)
13737         return false;
13738       if (Bitcast2->getOpcode() != ISD::BITCAST ||
13739           Bitcast2->getValueType(0) != MVT::f32)
13740         return false;
13741 
13742       if (Subtarget.isLittleEndian())
13743         std::swap(Bitcast, Bitcast2);
13744 
13745       // Bitcast has the second float (in memory-layout order) and Bitcast2
13746       // has the first one.
13747 
13748       SDValue BasePtr = LD->getBasePtr();
13749       if (LD->isIndexed()) {
13750         assert(LD->getAddressingMode() == ISD::PRE_INC &&
13751                "Non-pre-inc AM on PPC?");
13752         BasePtr =
13753           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
13754                       LD->getOffset());
13755       }
13756 
13757       auto MMOFlags =
13758           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
13759       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
13760                                       LD->getPointerInfo(), LD->getAlignment(),
13761                                       MMOFlags, LD->getAAInfo());
13762       SDValue AddPtr =
13763         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
13764                     BasePtr, DAG.getIntPtrConstant(4, dl));
13765       SDValue FloatLoad2 = DAG.getLoad(
13766           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
13767           LD->getPointerInfo().getWithOffset(4),
13768           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
13769 
13770       if (LD->isIndexed()) {
13771         // Note that DAGCombine should re-form any pre-increment load(s) from
13772         // what is produced here if that makes sense.
13773         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
13774       }
13775 
13776       DCI.CombineTo(Bitcast2, FloatLoad);
13777       DCI.CombineTo(Bitcast, FloatLoad2);
13778 
13779       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
13780                                     SDValue(FloatLoad2.getNode(), 1));
13781       return true;
13782     };
13783 
13784     if (ReplaceTwoFloatLoad())
13785       return SDValue(N, 0);
13786 
13787     EVT MemVT = LD->getMemoryVT();
13788     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
13789     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
13790     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
13791     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
13792     if (LD->isUnindexed() && VT.isVector() &&
13793         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
13794           // P8 and later hardware should just use LOAD.
13795           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
13796                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
13797          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
13798           LD->getAlignment() >= ScalarABIAlignment)) &&
13799         LD->getAlignment() < ABIAlignment) {
13800       // This is a type-legal unaligned Altivec or QPX load.
13801       SDValue Chain = LD->getChain();
13802       SDValue Ptr = LD->getBasePtr();
13803       bool isLittleEndian = Subtarget.isLittleEndian();
13804 
13805       // This implements the loading of unaligned vectors as described in
13806       // the venerable Apple Velocity Engine overview. Specifically:
13807       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
13808       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
13809       //
13810       // The general idea is to expand a sequence of one or more unaligned
13811       // loads into an alignment-based permutation-control instruction (lvsl
13812       // or lvsr), a series of regular vector loads (which always truncate
13813       // their input address to an aligned address), and a series of
13814       // permutations.  The results of these permutations are the requested
13815       // loaded values.  The trick is that the last "extra" load is not taken
13816       // from the address you might suspect (sizeof(vector) bytes after the
13817       // last requested load), but rather sizeof(vector) - 1 bytes after the
13818       // last requested vector. The point of this is to avoid a page fault if
13819       // the base address happened to be aligned. This works because if the
13820       // base address is aligned, then adding less than a full vector length
13821       // will cause the last vector in the sequence to be (re)loaded.
13822       // Otherwise, the next vector will be fetched as you might suspect was
13823       // necessary.
13824 
13825       // We might be able to reuse the permutation generation from
13826       // a different base address offset from this one by an aligned amount.
13827       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
13828       // optimization later.
13829       Intrinsic::ID Intr, IntrLD, IntrPerm;
13830       MVT PermCntlTy, PermTy, LDTy;
13831       if (Subtarget.hasAltivec()) {
13832         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
13833                                  Intrinsic::ppc_altivec_lvsl;
13834         IntrLD = Intrinsic::ppc_altivec_lvx;
13835         IntrPerm = Intrinsic::ppc_altivec_vperm;
13836         PermCntlTy = MVT::v16i8;
13837         PermTy = MVT::v4i32;
13838         LDTy = MVT::v4i32;
13839       } else {
13840         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
13841                                        Intrinsic::ppc_qpx_qvlpcls;
13842         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
13843                                        Intrinsic::ppc_qpx_qvlfs;
13844         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
13845         PermCntlTy = MVT::v4f64;
13846         PermTy = MVT::v4f64;
13847         LDTy = MemVT.getSimpleVT();
13848       }
13849 
13850       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
13851 
13852       // Create the new MMO for the new base load. It is like the original MMO,
13853       // but represents an area in memory almost twice the vector size centered
13854       // on the original address. If the address is unaligned, we might start
13855       // reading up to (sizeof(vector)-1) bytes below the address of the
13856       // original unaligned load.
13857       MachineFunction &MF = DAG.getMachineFunction();
13858       MachineMemOperand *BaseMMO =
13859         MF.getMachineMemOperand(LD->getMemOperand(),
13860                                 -(long)MemVT.getStoreSize()+1,
13861                                 2*MemVT.getStoreSize()-1);
13862 
13863       // Create the new base load.
13864       SDValue LDXIntID =
13865           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
13866       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
13867       SDValue BaseLoad =
13868         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13869                                 DAG.getVTList(PermTy, MVT::Other),
13870                                 BaseLoadOps, LDTy, BaseMMO);
13871 
13872       // Note that the value of IncOffset (which is provided to the next
13873       // load's pointer info offset value, and thus used to calculate the
13874       // alignment), and the value of IncValue (which is actually used to
13875       // increment the pointer value) are different! This is because we
13876       // require the next load to appear to be aligned, even though it
13877       // is actually offset from the base pointer by a lesser amount.
13878       int IncOffset = VT.getSizeInBits() / 8;
13879       int IncValue = IncOffset;
13880 
13881       // Walk (both up and down) the chain looking for another load at the real
13882       // (aligned) offset (the alignment of the other load does not matter in
13883       // this case). If found, then do not use the offset reduction trick, as
13884       // that will prevent the loads from being later combined (as they would
13885       // otherwise be duplicates).
13886       if (!findConsecutiveLoad(LD, DAG))
13887         --IncValue;
13888 
13889       SDValue Increment =
13890           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
13891       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13892 
13893       MachineMemOperand *ExtraMMO =
13894         MF.getMachineMemOperand(LD->getMemOperand(),
13895                                 1, 2*MemVT.getStoreSize()-1);
13896       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
13897       SDValue ExtraLoad =
13898         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
13899                                 DAG.getVTList(PermTy, MVT::Other),
13900                                 ExtraLoadOps, LDTy, ExtraMMO);
13901 
13902       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
13903         BaseLoad.getValue(1), ExtraLoad.getValue(1));
13904 
13905       // Because vperm has a big-endian bias, we must reverse the order
13906       // of the input vectors and complement the permute control vector
13907       // when generating little endian code.  We have already handled the
13908       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
13909       // and ExtraLoad here.
13910       SDValue Perm;
13911       if (isLittleEndian)
13912         Perm = BuildIntrinsicOp(IntrPerm,
13913                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
13914       else
13915         Perm = BuildIntrinsicOp(IntrPerm,
13916                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
13917 
13918       if (VT != PermTy)
13919         Perm = Subtarget.hasAltivec() ?
13920                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
13921                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
13922                                DAG.getTargetConstant(1, dl, MVT::i64));
13923                                // second argument is 1 because this rounding
13924                                // is always exact.
13925 
13926       // The output of the permutation is our loaded result, the TokenFactor is
13927       // our new chain.
13928       DCI.CombineTo(N, Perm, TF);
13929       return SDValue(N, 0);
13930     }
13931     }
13932     break;
13933     case ISD::INTRINSIC_WO_CHAIN: {
13934       bool isLittleEndian = Subtarget.isLittleEndian();
13935       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
13936       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
13937                                            : Intrinsic::ppc_altivec_lvsl);
13938       if ((IID == Intr ||
13939            IID == Intrinsic::ppc_qpx_qvlpcld  ||
13940            IID == Intrinsic::ppc_qpx_qvlpcls) &&
13941         N->getOperand(1)->getOpcode() == ISD::ADD) {
13942         SDValue Add = N->getOperand(1);
13943 
13944         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
13945                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
13946 
13947         if (DAG.MaskedValueIsZero(Add->getOperand(1),
13948                                   APInt::getAllOnesValue(Bits /* alignment */)
13949                                       .zext(Add.getScalarValueSizeInBits()))) {
13950           SDNode *BasePtr = Add->getOperand(0).getNode();
13951           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13952                                     UE = BasePtr->use_end();
13953                UI != UE; ++UI) {
13954             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13955                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
13956               // We've found another LVSL/LVSR, and this address is an aligned
13957               // multiple of that one. The results will be the same, so use the
13958               // one we've just found instead.
13959 
13960               return SDValue(*UI, 0);
13961             }
13962           }
13963         }
13964 
13965         if (isa<ConstantSDNode>(Add->getOperand(1))) {
13966           SDNode *BasePtr = Add->getOperand(0).getNode();
13967           for (SDNode::use_iterator UI = BasePtr->use_begin(),
13968                UE = BasePtr->use_end(); UI != UE; ++UI) {
13969             if (UI->getOpcode() == ISD::ADD &&
13970                 isa<ConstantSDNode>(UI->getOperand(1)) &&
13971                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
13972                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
13973                 (1ULL << Bits) == 0) {
13974               SDNode *OtherAdd = *UI;
13975               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
13976                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
13977                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
13978                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
13979                   return SDValue(*VI, 0);
13980                 }
13981               }
13982             }
13983           }
13984         }
13985       }
13986 
13987       // Combine vmaxsw/h/b(a, a's negation) to abs(a)
13988       // Expose the vabsduw/h/b opportunity for down stream
13989       if (!DCI.isAfterLegalizeDAG() && Subtarget.hasP9Altivec() &&
13990           (IID == Intrinsic::ppc_altivec_vmaxsw ||
13991            IID == Intrinsic::ppc_altivec_vmaxsh ||
13992            IID == Intrinsic::ppc_altivec_vmaxsb)) {
13993         SDValue V1 = N->getOperand(1);
13994         SDValue V2 = N->getOperand(2);
13995         if ((V1.getSimpleValueType() == MVT::v4i32 ||
13996              V1.getSimpleValueType() == MVT::v8i16 ||
13997              V1.getSimpleValueType() == MVT::v16i8) &&
13998             V1.getSimpleValueType() == V2.getSimpleValueType()) {
13999           // (0-a, a)
14000           if (V1.getOpcode() == ISD::SUB &&
14001               ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
14002               V1.getOperand(1) == V2) {
14003             return DAG.getNode(ISD::ABS, dl, V2.getValueType(), V2);
14004           }
14005           // (a, 0-a)
14006           if (V2.getOpcode() == ISD::SUB &&
14007               ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
14008               V2.getOperand(1) == V1) {
14009             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14010           }
14011           // (x-y, y-x)
14012           if (V1.getOpcode() == ISD::SUB && V2.getOpcode() == ISD::SUB &&
14013               V1.getOperand(0) == V2.getOperand(1) &&
14014               V1.getOperand(1) == V2.getOperand(0)) {
14015             return DAG.getNode(ISD::ABS, dl, V1.getValueType(), V1);
14016           }
14017         }
14018       }
14019     }
14020 
14021     break;
14022   case ISD::INTRINSIC_W_CHAIN:
14023     // For little endian, VSX loads require generating lxvd2x/xxswapd.
14024     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
14025     if (Subtarget.needsSwapsForVSXMemOps()) {
14026       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14027       default:
14028         break;
14029       case Intrinsic::ppc_vsx_lxvw4x:
14030       case Intrinsic::ppc_vsx_lxvd2x:
14031         return expandVSXLoadForLE(N, DCI);
14032       }
14033     }
14034     break;
14035   case ISD::INTRINSIC_VOID:
14036     // For little endian, VSX stores require generating xxswapd/stxvd2x.
14037     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
14038     if (Subtarget.needsSwapsForVSXMemOps()) {
14039       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
14040       default:
14041         break;
14042       case Intrinsic::ppc_vsx_stxvw4x:
14043       case Intrinsic::ppc_vsx_stxvd2x:
14044         return expandVSXStoreForLE(N, DCI);
14045       }
14046     }
14047     break;
14048   case ISD::BSWAP:
14049     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
14050     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
14051         N->getOperand(0).hasOneUse() &&
14052         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
14053          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
14054           N->getValueType(0) == MVT::i64))) {
14055       SDValue Load = N->getOperand(0);
14056       LoadSDNode *LD = cast<LoadSDNode>(Load);
14057       // Create the byte-swapping load.
14058       SDValue Ops[] = {
14059         LD->getChain(),    // Chain
14060         LD->getBasePtr(),  // Ptr
14061         DAG.getValueType(N->getValueType(0)) // VT
14062       };
14063       SDValue BSLoad =
14064         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
14065                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
14066                                               MVT::i64 : MVT::i32, MVT::Other),
14067                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
14068 
14069       // If this is an i16 load, insert the truncate.
14070       SDValue ResVal = BSLoad;
14071       if (N->getValueType(0) == MVT::i16)
14072         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
14073 
14074       // First, combine the bswap away.  This makes the value produced by the
14075       // load dead.
14076       DCI.CombineTo(N, ResVal);
14077 
14078       // Next, combine the load away, we give it a bogus result value but a real
14079       // chain result.  The result value is dead because the bswap is dead.
14080       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
14081 
14082       // Return N so it doesn't get rechecked!
14083       return SDValue(N, 0);
14084     }
14085     break;
14086   case PPCISD::VCMP:
14087     // If a VCMPo node already exists with exactly the same operands as this
14088     // node, use its result instead of this node (VCMPo computes both a CR6 and
14089     // a normal output).
14090     //
14091     if (!N->getOperand(0).hasOneUse() &&
14092         !N->getOperand(1).hasOneUse() &&
14093         !N->getOperand(2).hasOneUse()) {
14094 
14095       // Scan all of the users of the LHS, looking for VCMPo's that match.
14096       SDNode *VCMPoNode = nullptr;
14097 
14098       SDNode *LHSN = N->getOperand(0).getNode();
14099       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
14100            UI != E; ++UI)
14101         if (UI->getOpcode() == PPCISD::VCMPo &&
14102             UI->getOperand(1) == N->getOperand(1) &&
14103             UI->getOperand(2) == N->getOperand(2) &&
14104             UI->getOperand(0) == N->getOperand(0)) {
14105           VCMPoNode = *UI;
14106           break;
14107         }
14108 
14109       // If there is no VCMPo node, or if the flag value has a single use, don't
14110       // transform this.
14111       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
14112         break;
14113 
14114       // Look at the (necessarily single) use of the flag value.  If it has a
14115       // chain, this transformation is more complex.  Note that multiple things
14116       // could use the value result, which we should ignore.
14117       SDNode *FlagUser = nullptr;
14118       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
14119            FlagUser == nullptr; ++UI) {
14120         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
14121         SDNode *User = *UI;
14122         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
14123           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
14124             FlagUser = User;
14125             break;
14126           }
14127         }
14128       }
14129 
14130       // If the user is a MFOCRF instruction, we know this is safe.
14131       // Otherwise we give up for right now.
14132       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
14133         return SDValue(VCMPoNode, 0);
14134     }
14135     break;
14136   case ISD::BRCOND: {
14137     SDValue Cond = N->getOperand(1);
14138     SDValue Target = N->getOperand(2);
14139 
14140     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14141         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
14142           Intrinsic::loop_decrement) {
14143 
14144       // We now need to make the intrinsic dead (it cannot be instruction
14145       // selected).
14146       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
14147       assert(Cond.getNode()->hasOneUse() &&
14148              "Counter decrement has more than one use");
14149 
14150       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
14151                          N->getOperand(0), Target);
14152     }
14153   }
14154   break;
14155   case ISD::BR_CC: {
14156     // If this is a branch on an altivec predicate comparison, lower this so
14157     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
14158     // lowering is done pre-legalize, because the legalizer lowers the predicate
14159     // compare down to code that is difficult to reassemble.
14160     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
14161     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
14162 
14163     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
14164     // value. If so, pass-through the AND to get to the intrinsic.
14165     if (LHS.getOpcode() == ISD::AND &&
14166         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14167         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
14168           Intrinsic::loop_decrement &&
14169         isa<ConstantSDNode>(LHS.getOperand(1)) &&
14170         !isNullConstant(LHS.getOperand(1)))
14171       LHS = LHS.getOperand(0);
14172 
14173     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
14174         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
14175           Intrinsic::loop_decrement &&
14176         isa<ConstantSDNode>(RHS)) {
14177       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
14178              "Counter decrement comparison is not EQ or NE");
14179 
14180       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14181       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
14182                     (CC == ISD::SETNE && !Val);
14183 
14184       // We now need to make the intrinsic dead (it cannot be instruction
14185       // selected).
14186       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
14187       assert(LHS.getNode()->hasOneUse() &&
14188              "Counter decrement has more than one use");
14189 
14190       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
14191                          N->getOperand(0), N->getOperand(4));
14192     }
14193 
14194     int CompareOpc;
14195     bool isDot;
14196 
14197     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
14198         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
14199         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
14200       assert(isDot && "Can't compare against a vector result!");
14201 
14202       // If this is a comparison against something other than 0/1, then we know
14203       // that the condition is never/always true.
14204       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
14205       if (Val != 0 && Val != 1) {
14206         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
14207           return N->getOperand(0);
14208         // Always !=, turn it into an unconditional branch.
14209         return DAG.getNode(ISD::BR, dl, MVT::Other,
14210                            N->getOperand(0), N->getOperand(4));
14211       }
14212 
14213       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
14214 
14215       // Create the PPCISD altivec 'dot' comparison node.
14216       SDValue Ops[] = {
14217         LHS.getOperand(2),  // LHS of compare
14218         LHS.getOperand(3),  // RHS of compare
14219         DAG.getConstant(CompareOpc, dl, MVT::i32)
14220       };
14221       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
14222       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
14223 
14224       // Unpack the result based on how the target uses it.
14225       PPC::Predicate CompOpc;
14226       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
14227       default:  // Can't happen, don't crash on invalid number though.
14228       case 0:   // Branch on the value of the EQ bit of CR6.
14229         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
14230         break;
14231       case 1:   // Branch on the inverted value of the EQ bit of CR6.
14232         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
14233         break;
14234       case 2:   // Branch on the value of the LT bit of CR6.
14235         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
14236         break;
14237       case 3:   // Branch on the inverted value of the LT bit of CR6.
14238         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
14239         break;
14240       }
14241 
14242       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
14243                          DAG.getConstant(CompOpc, dl, MVT::i32),
14244                          DAG.getRegister(PPC::CR6, MVT::i32),
14245                          N->getOperand(4), CompNode.getValue(1));
14246     }
14247     break;
14248   }
14249   case ISD::BUILD_VECTOR:
14250     return DAGCombineBuildVector(N, DCI);
14251   case ISD::ABS:
14252     return combineABS(N, DCI);
14253   case ISD::VSELECT:
14254     return combineVSelect(N, DCI);
14255   }
14256 
14257   return SDValue();
14258 }
14259 
14260 SDValue
14261 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
14262                                  SelectionDAG &DAG,
14263                                  SmallVectorImpl<SDNode *> &Created) const {
14264   // fold (sdiv X, pow2)
14265   EVT VT = N->getValueType(0);
14266   if (VT == MVT::i64 && !Subtarget.isPPC64())
14267     return SDValue();
14268   if ((VT != MVT::i32 && VT != MVT::i64) ||
14269       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
14270     return SDValue();
14271 
14272   SDLoc DL(N);
14273   SDValue N0 = N->getOperand(0);
14274 
14275   bool IsNegPow2 = (-Divisor).isPowerOf2();
14276   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
14277   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
14278 
14279   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
14280   Created.push_back(Op.getNode());
14281 
14282   if (IsNegPow2) {
14283     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
14284     Created.push_back(Op.getNode());
14285   }
14286 
14287   return Op;
14288 }
14289 
14290 //===----------------------------------------------------------------------===//
14291 // Inline Assembly Support
14292 //===----------------------------------------------------------------------===//
14293 
14294 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
14295                                                       KnownBits &Known,
14296                                                       const APInt &DemandedElts,
14297                                                       const SelectionDAG &DAG,
14298                                                       unsigned Depth) const {
14299   Known.resetAll();
14300   switch (Op.getOpcode()) {
14301   default: break;
14302   case PPCISD::LBRX: {
14303     // lhbrx is known to have the top bits cleared out.
14304     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
14305       Known.Zero = 0xFFFF0000;
14306     break;
14307   }
14308   case ISD::INTRINSIC_WO_CHAIN: {
14309     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
14310     default: break;
14311     case Intrinsic::ppc_altivec_vcmpbfp_p:
14312     case Intrinsic::ppc_altivec_vcmpeqfp_p:
14313     case Intrinsic::ppc_altivec_vcmpequb_p:
14314     case Intrinsic::ppc_altivec_vcmpequh_p:
14315     case Intrinsic::ppc_altivec_vcmpequw_p:
14316     case Intrinsic::ppc_altivec_vcmpequd_p:
14317     case Intrinsic::ppc_altivec_vcmpgefp_p:
14318     case Intrinsic::ppc_altivec_vcmpgtfp_p:
14319     case Intrinsic::ppc_altivec_vcmpgtsb_p:
14320     case Intrinsic::ppc_altivec_vcmpgtsh_p:
14321     case Intrinsic::ppc_altivec_vcmpgtsw_p:
14322     case Intrinsic::ppc_altivec_vcmpgtsd_p:
14323     case Intrinsic::ppc_altivec_vcmpgtub_p:
14324     case Intrinsic::ppc_altivec_vcmpgtuh_p:
14325     case Intrinsic::ppc_altivec_vcmpgtuw_p:
14326     case Intrinsic::ppc_altivec_vcmpgtud_p:
14327       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
14328       break;
14329     }
14330   }
14331   }
14332 }
14333 
14334 Align PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
14335   switch (Subtarget.getCPUDirective()) {
14336   default: break;
14337   case PPC::DIR_970:
14338   case PPC::DIR_PWR4:
14339   case PPC::DIR_PWR5:
14340   case PPC::DIR_PWR5X:
14341   case PPC::DIR_PWR6:
14342   case PPC::DIR_PWR6X:
14343   case PPC::DIR_PWR7:
14344   case PPC::DIR_PWR8:
14345   case PPC::DIR_PWR9:
14346   case PPC::DIR_PWR_FUTURE: {
14347     if (!ML)
14348       break;
14349 
14350     if (!DisableInnermostLoopAlign32) {
14351       // If the nested loop is an innermost loop, prefer to a 32-byte alignment,
14352       // so that we can decrease cache misses and branch-prediction misses.
14353       // Actual alignment of the loop will depend on the hotness check and other
14354       // logic in alignBlocks.
14355       if (ML->getLoopDepth() > 1 && ML->getSubLoops().empty())
14356         return Align(32);
14357     }
14358 
14359     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
14360 
14361     // For small loops (between 5 and 8 instructions), align to a 32-byte
14362     // boundary so that the entire loop fits in one instruction-cache line.
14363     uint64_t LoopSize = 0;
14364     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
14365       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
14366         LoopSize += TII->getInstSizeInBytes(*J);
14367         if (LoopSize > 32)
14368           break;
14369       }
14370 
14371     if (LoopSize > 16 && LoopSize <= 32)
14372       return Align(32);
14373 
14374     break;
14375   }
14376   }
14377 
14378   return TargetLowering::getPrefLoopAlignment(ML);
14379 }
14380 
14381 /// getConstraintType - Given a constraint, return the type of
14382 /// constraint it is for this target.
14383 PPCTargetLowering::ConstraintType
14384 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
14385   if (Constraint.size() == 1) {
14386     switch (Constraint[0]) {
14387     default: break;
14388     case 'b':
14389     case 'r':
14390     case 'f':
14391     case 'd':
14392     case 'v':
14393     case 'y':
14394       return C_RegisterClass;
14395     case 'Z':
14396       // FIXME: While Z does indicate a memory constraint, it specifically
14397       // indicates an r+r address (used in conjunction with the 'y' modifier
14398       // in the replacement string). Currently, we're forcing the base
14399       // register to be r0 in the asm printer (which is interpreted as zero)
14400       // and forming the complete address in the second register. This is
14401       // suboptimal.
14402       return C_Memory;
14403     }
14404   } else if (Constraint == "wc") { // individual CR bits.
14405     return C_RegisterClass;
14406   } else if (Constraint == "wa" || Constraint == "wd" ||
14407              Constraint == "wf" || Constraint == "ws" ||
14408              Constraint == "wi" || Constraint == "ww") {
14409     return C_RegisterClass; // VSX registers.
14410   }
14411   return TargetLowering::getConstraintType(Constraint);
14412 }
14413 
14414 /// Examine constraint type and operand type and determine a weight value.
14415 /// This object must already have been set up with the operand type
14416 /// and the current alternative constraint selected.
14417 TargetLowering::ConstraintWeight
14418 PPCTargetLowering::getSingleConstraintMatchWeight(
14419     AsmOperandInfo &info, const char *constraint) const {
14420   ConstraintWeight weight = CW_Invalid;
14421   Value *CallOperandVal = info.CallOperandVal;
14422     // If we don't have a value, we can't do a match,
14423     // but allow it at the lowest weight.
14424   if (!CallOperandVal)
14425     return CW_Default;
14426   Type *type = CallOperandVal->getType();
14427 
14428   // Look at the constraint type.
14429   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
14430     return CW_Register; // an individual CR bit.
14431   else if ((StringRef(constraint) == "wa" ||
14432             StringRef(constraint) == "wd" ||
14433             StringRef(constraint) == "wf") &&
14434            type->isVectorTy())
14435     return CW_Register;
14436   else if (StringRef(constraint) == "wi" && type->isIntegerTy(64))
14437     return CW_Register; // just hold 64-bit integers data.
14438   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
14439     return CW_Register;
14440   else if (StringRef(constraint) == "ww" && type->isFloatTy())
14441     return CW_Register;
14442 
14443   switch (*constraint) {
14444   default:
14445     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
14446     break;
14447   case 'b':
14448     if (type->isIntegerTy())
14449       weight = CW_Register;
14450     break;
14451   case 'f':
14452     if (type->isFloatTy())
14453       weight = CW_Register;
14454     break;
14455   case 'd':
14456     if (type->isDoubleTy())
14457       weight = CW_Register;
14458     break;
14459   case 'v':
14460     if (type->isVectorTy())
14461       weight = CW_Register;
14462     break;
14463   case 'y':
14464     weight = CW_Register;
14465     break;
14466   case 'Z':
14467     weight = CW_Memory;
14468     break;
14469   }
14470   return weight;
14471 }
14472 
14473 std::pair<unsigned, const TargetRegisterClass *>
14474 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
14475                                                 StringRef Constraint,
14476                                                 MVT VT) const {
14477   if (Constraint.size() == 1) {
14478     // GCC RS6000 Constraint Letters
14479     switch (Constraint[0]) {
14480     case 'b':   // R1-R31
14481       if (VT == MVT::i64 && Subtarget.isPPC64())
14482         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
14483       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
14484     case 'r':   // R0-R31
14485       if (VT == MVT::i64 && Subtarget.isPPC64())
14486         return std::make_pair(0U, &PPC::G8RCRegClass);
14487       return std::make_pair(0U, &PPC::GPRCRegClass);
14488     // 'd' and 'f' constraints are both defined to be "the floating point
14489     // registers", where one is for 32-bit and the other for 64-bit. We don't
14490     // really care overly much here so just give them all the same reg classes.
14491     case 'd':
14492     case 'f':
14493       if (Subtarget.hasSPE()) {
14494         if (VT == MVT::f32 || VT == MVT::i32)
14495           return std::make_pair(0U, &PPC::GPRCRegClass);
14496         if (VT == MVT::f64 || VT == MVT::i64)
14497           return std::make_pair(0U, &PPC::SPERCRegClass);
14498       } else {
14499         if (VT == MVT::f32 || VT == MVT::i32)
14500           return std::make_pair(0U, &PPC::F4RCRegClass);
14501         if (VT == MVT::f64 || VT == MVT::i64)
14502           return std::make_pair(0U, &PPC::F8RCRegClass);
14503         if (VT == MVT::v4f64 && Subtarget.hasQPX())
14504           return std::make_pair(0U, &PPC::QFRCRegClass);
14505         if (VT == MVT::v4f32 && Subtarget.hasQPX())
14506           return std::make_pair(0U, &PPC::QSRCRegClass);
14507       }
14508       break;
14509     case 'v':
14510       if (VT == MVT::v4f64 && Subtarget.hasQPX())
14511         return std::make_pair(0U, &PPC::QFRCRegClass);
14512       if (VT == MVT::v4f32 && Subtarget.hasQPX())
14513         return std::make_pair(0U, &PPC::QSRCRegClass);
14514       if (Subtarget.hasAltivec())
14515         return std::make_pair(0U, &PPC::VRRCRegClass);
14516       break;
14517     case 'y':   // crrc
14518       return std::make_pair(0U, &PPC::CRRCRegClass);
14519     }
14520   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
14521     // An individual CR bit.
14522     return std::make_pair(0U, &PPC::CRBITRCRegClass);
14523   } else if ((Constraint == "wa" || Constraint == "wd" ||
14524              Constraint == "wf" || Constraint == "wi") &&
14525              Subtarget.hasVSX()) {
14526     return std::make_pair(0U, &PPC::VSRCRegClass);
14527   } else if ((Constraint == "ws" || Constraint == "ww") && Subtarget.hasVSX()) {
14528     if (VT == MVT::f32 && Subtarget.hasP8Vector())
14529       return std::make_pair(0U, &PPC::VSSRCRegClass);
14530     else
14531       return std::make_pair(0U, &PPC::VSFRCRegClass);
14532   }
14533 
14534   // If we name a VSX register, we can't defer to the base class because it
14535   // will not recognize the correct register (their names will be VSL{0-31}
14536   // and V{0-31} so they won't match). So we match them here.
14537   if (Constraint.size() > 3 && Constraint[1] == 'v' && Constraint[2] == 's') {
14538     int VSNum = atoi(Constraint.data() + 3);
14539     assert(VSNum >= 0 && VSNum <= 63 &&
14540            "Attempted to access a vsr out of range");
14541     if (VSNum < 32)
14542       return std::make_pair(PPC::VSL0 + VSNum, &PPC::VSRCRegClass);
14543     return std::make_pair(PPC::V0 + VSNum - 32, &PPC::VSRCRegClass);
14544   }
14545   std::pair<unsigned, const TargetRegisterClass *> R =
14546       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
14547 
14548   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
14549   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
14550   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
14551   // register.
14552   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
14553   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
14554   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
14555       PPC::GPRCRegClass.contains(R.first))
14556     return std::make_pair(TRI->getMatchingSuperReg(R.first,
14557                             PPC::sub_32, &PPC::G8RCRegClass),
14558                           &PPC::G8RCRegClass);
14559 
14560   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
14561   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
14562     R.first = PPC::CR0;
14563     R.second = &PPC::CRRCRegClass;
14564   }
14565 
14566   return R;
14567 }
14568 
14569 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
14570 /// vector.  If it is invalid, don't add anything to Ops.
14571 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
14572                                                      std::string &Constraint,
14573                                                      std::vector<SDValue>&Ops,
14574                                                      SelectionDAG &DAG) const {
14575   SDValue Result;
14576 
14577   // Only support length 1 constraints.
14578   if (Constraint.length() > 1) return;
14579 
14580   char Letter = Constraint[0];
14581   switch (Letter) {
14582   default: break;
14583   case 'I':
14584   case 'J':
14585   case 'K':
14586   case 'L':
14587   case 'M':
14588   case 'N':
14589   case 'O':
14590   case 'P': {
14591     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
14592     if (!CST) return; // Must be an immediate to match.
14593     SDLoc dl(Op);
14594     int64_t Value = CST->getSExtValue();
14595     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
14596                          // numbers are printed as such.
14597     switch (Letter) {
14598     default: llvm_unreachable("Unknown constraint letter!");
14599     case 'I':  // "I" is a signed 16-bit constant.
14600       if (isInt<16>(Value))
14601         Result = DAG.getTargetConstant(Value, dl, TCVT);
14602       break;
14603     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
14604       if (isShiftedUInt<16, 16>(Value))
14605         Result = DAG.getTargetConstant(Value, dl, TCVT);
14606       break;
14607     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
14608       if (isShiftedInt<16, 16>(Value))
14609         Result = DAG.getTargetConstant(Value, dl, TCVT);
14610       break;
14611     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
14612       if (isUInt<16>(Value))
14613         Result = DAG.getTargetConstant(Value, dl, TCVT);
14614       break;
14615     case 'M':  // "M" is a constant that is greater than 31.
14616       if (Value > 31)
14617         Result = DAG.getTargetConstant(Value, dl, TCVT);
14618       break;
14619     case 'N':  // "N" is a positive constant that is an exact power of two.
14620       if (Value > 0 && isPowerOf2_64(Value))
14621         Result = DAG.getTargetConstant(Value, dl, TCVT);
14622       break;
14623     case 'O':  // "O" is the constant zero.
14624       if (Value == 0)
14625         Result = DAG.getTargetConstant(Value, dl, TCVT);
14626       break;
14627     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
14628       if (isInt<16>(-Value))
14629         Result = DAG.getTargetConstant(Value, dl, TCVT);
14630       break;
14631     }
14632     break;
14633   }
14634   }
14635 
14636   if (Result.getNode()) {
14637     Ops.push_back(Result);
14638     return;
14639   }
14640 
14641   // Handle standard constraint letters.
14642   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14643 }
14644 
14645 // isLegalAddressingMode - Return true if the addressing mode represented
14646 // by AM is legal for this target, for a load/store of the specified type.
14647 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
14648                                               const AddrMode &AM, Type *Ty,
14649                                               unsigned AS, Instruction *I) const {
14650   // PPC does not allow r+i addressing modes for vectors!
14651   if (Ty->isVectorTy() && AM.BaseOffs != 0)
14652     return false;
14653 
14654   // PPC allows a sign-extended 16-bit immediate field.
14655   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
14656     return false;
14657 
14658   // No global is ever allowed as a base.
14659   if (AM.BaseGV)
14660     return false;
14661 
14662   // PPC only support r+r,
14663   switch (AM.Scale) {
14664   case 0:  // "r+i" or just "i", depending on HasBaseReg.
14665     break;
14666   case 1:
14667     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
14668       return false;
14669     // Otherwise we have r+r or r+i.
14670     break;
14671   case 2:
14672     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
14673       return false;
14674     // Allow 2*r as r+r.
14675     break;
14676   default:
14677     // No other scales are supported.
14678     return false;
14679   }
14680 
14681   return true;
14682 }
14683 
14684 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
14685                                            SelectionDAG &DAG) const {
14686   MachineFunction &MF = DAG.getMachineFunction();
14687   MachineFrameInfo &MFI = MF.getFrameInfo();
14688   MFI.setReturnAddressIsTaken(true);
14689 
14690   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14691     return SDValue();
14692 
14693   SDLoc dl(Op);
14694   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14695 
14696   // Make sure the function does not optimize away the store of the RA to
14697   // the stack.
14698   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
14699   FuncInfo->setLRStoreRequired();
14700   bool isPPC64 = Subtarget.isPPC64();
14701   auto PtrVT = getPointerTy(MF.getDataLayout());
14702 
14703   if (Depth > 0) {
14704     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14705     SDValue Offset =
14706         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
14707                         isPPC64 ? MVT::i64 : MVT::i32);
14708     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14709                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
14710                        MachinePointerInfo());
14711   }
14712 
14713   // Just load the return address off the stack.
14714   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
14715   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
14716                      MachinePointerInfo());
14717 }
14718 
14719 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
14720                                           SelectionDAG &DAG) const {
14721   SDLoc dl(Op);
14722   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14723 
14724   MachineFunction &MF = DAG.getMachineFunction();
14725   MachineFrameInfo &MFI = MF.getFrameInfo();
14726   MFI.setFrameAddressIsTaken(true);
14727 
14728   EVT PtrVT = getPointerTy(MF.getDataLayout());
14729   bool isPPC64 = PtrVT == MVT::i64;
14730 
14731   // Naked functions never have a frame pointer, and so we use r1. For all
14732   // other functions, this decision must be delayed until during PEI.
14733   unsigned FrameReg;
14734   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
14735     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
14736   else
14737     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
14738 
14739   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
14740                                          PtrVT);
14741   while (Depth--)
14742     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
14743                             FrameAddr, MachinePointerInfo());
14744   return FrameAddr;
14745 }
14746 
14747 // FIXME? Maybe this could be a TableGen attribute on some registers and
14748 // this table could be generated automatically from RegInfo.
14749 Register PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
14750                                               const MachineFunction &MF) const {
14751   bool isPPC64 = Subtarget.isPPC64();
14752   bool IsDarwinABI = Subtarget.isDarwinABI();
14753 
14754   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
14755       (!isPPC64 && VT != MVT::i32))
14756     report_fatal_error("Invalid register global variable type");
14757 
14758   bool is64Bit = isPPC64 && VT == MVT::i64;
14759   Register Reg = StringSwitch<Register>(RegName)
14760                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
14761                    .Case("r2", (IsDarwinABI || isPPC64) ? Register() : PPC::R2)
14762                    .Case("r13", (!isPPC64 && IsDarwinABI) ? Register() :
14763                                   (is64Bit ? PPC::X13 : PPC::R13))
14764                    .Default(Register());
14765 
14766   if (Reg)
14767     return Reg;
14768   report_fatal_error("Invalid register name global variable");
14769 }
14770 
14771 bool PPCTargetLowering::isAccessedAsGotIndirect(SDValue GA) const {
14772   // 32-bit SVR4 ABI access everything as got-indirect.
14773   if (Subtarget.is32BitELFABI())
14774     return true;
14775 
14776   // AIX accesses everything indirectly through the TOC, which is similar to
14777   // the GOT.
14778   if (Subtarget.isAIXABI())
14779     return true;
14780 
14781   CodeModel::Model CModel = getTargetMachine().getCodeModel();
14782   // If it is small or large code model, module locals are accessed
14783   // indirectly by loading their address from .toc/.got.
14784   if (CModel == CodeModel::Small || CModel == CodeModel::Large)
14785     return true;
14786 
14787   // JumpTable and BlockAddress are accessed as got-indirect.
14788   if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA))
14789     return true;
14790 
14791   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA))
14792     return Subtarget.isGVIndirectSymbol(G->getGlobal());
14793 
14794   return false;
14795 }
14796 
14797 bool
14798 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14799   // The PowerPC target isn't yet aware of offsets.
14800   return false;
14801 }
14802 
14803 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14804                                            const CallInst &I,
14805                                            MachineFunction &MF,
14806                                            unsigned Intrinsic) const {
14807   switch (Intrinsic) {
14808   case Intrinsic::ppc_qpx_qvlfd:
14809   case Intrinsic::ppc_qpx_qvlfs:
14810   case Intrinsic::ppc_qpx_qvlfcd:
14811   case Intrinsic::ppc_qpx_qvlfcs:
14812   case Intrinsic::ppc_qpx_qvlfiwa:
14813   case Intrinsic::ppc_qpx_qvlfiwz:
14814   case Intrinsic::ppc_altivec_lvx:
14815   case Intrinsic::ppc_altivec_lvxl:
14816   case Intrinsic::ppc_altivec_lvebx:
14817   case Intrinsic::ppc_altivec_lvehx:
14818   case Intrinsic::ppc_altivec_lvewx:
14819   case Intrinsic::ppc_vsx_lxvd2x:
14820   case Intrinsic::ppc_vsx_lxvw4x: {
14821     EVT VT;
14822     switch (Intrinsic) {
14823     case Intrinsic::ppc_altivec_lvebx:
14824       VT = MVT::i8;
14825       break;
14826     case Intrinsic::ppc_altivec_lvehx:
14827       VT = MVT::i16;
14828       break;
14829     case Intrinsic::ppc_altivec_lvewx:
14830       VT = MVT::i32;
14831       break;
14832     case Intrinsic::ppc_vsx_lxvd2x:
14833       VT = MVT::v2f64;
14834       break;
14835     case Intrinsic::ppc_qpx_qvlfd:
14836       VT = MVT::v4f64;
14837       break;
14838     case Intrinsic::ppc_qpx_qvlfs:
14839       VT = MVT::v4f32;
14840       break;
14841     case Intrinsic::ppc_qpx_qvlfcd:
14842       VT = MVT::v2f64;
14843       break;
14844     case Intrinsic::ppc_qpx_qvlfcs:
14845       VT = MVT::v2f32;
14846       break;
14847     default:
14848       VT = MVT::v4i32;
14849       break;
14850     }
14851 
14852     Info.opc = ISD::INTRINSIC_W_CHAIN;
14853     Info.memVT = VT;
14854     Info.ptrVal = I.getArgOperand(0);
14855     Info.offset = -VT.getStoreSize()+1;
14856     Info.size = 2*VT.getStoreSize()-1;
14857     Info.align = Align::None();
14858     Info.flags = MachineMemOperand::MOLoad;
14859     return true;
14860   }
14861   case Intrinsic::ppc_qpx_qvlfda:
14862   case Intrinsic::ppc_qpx_qvlfsa:
14863   case Intrinsic::ppc_qpx_qvlfcda:
14864   case Intrinsic::ppc_qpx_qvlfcsa:
14865   case Intrinsic::ppc_qpx_qvlfiwaa:
14866   case Intrinsic::ppc_qpx_qvlfiwza: {
14867     EVT VT;
14868     switch (Intrinsic) {
14869     case Intrinsic::ppc_qpx_qvlfda:
14870       VT = MVT::v4f64;
14871       break;
14872     case Intrinsic::ppc_qpx_qvlfsa:
14873       VT = MVT::v4f32;
14874       break;
14875     case Intrinsic::ppc_qpx_qvlfcda:
14876       VT = MVT::v2f64;
14877       break;
14878     case Intrinsic::ppc_qpx_qvlfcsa:
14879       VT = MVT::v2f32;
14880       break;
14881     default:
14882       VT = MVT::v4i32;
14883       break;
14884     }
14885 
14886     Info.opc = ISD::INTRINSIC_W_CHAIN;
14887     Info.memVT = VT;
14888     Info.ptrVal = I.getArgOperand(0);
14889     Info.offset = 0;
14890     Info.size = VT.getStoreSize();
14891     Info.align = Align::None();
14892     Info.flags = MachineMemOperand::MOLoad;
14893     return true;
14894   }
14895   case Intrinsic::ppc_qpx_qvstfd:
14896   case Intrinsic::ppc_qpx_qvstfs:
14897   case Intrinsic::ppc_qpx_qvstfcd:
14898   case Intrinsic::ppc_qpx_qvstfcs:
14899   case Intrinsic::ppc_qpx_qvstfiw:
14900   case Intrinsic::ppc_altivec_stvx:
14901   case Intrinsic::ppc_altivec_stvxl:
14902   case Intrinsic::ppc_altivec_stvebx:
14903   case Intrinsic::ppc_altivec_stvehx:
14904   case Intrinsic::ppc_altivec_stvewx:
14905   case Intrinsic::ppc_vsx_stxvd2x:
14906   case Intrinsic::ppc_vsx_stxvw4x: {
14907     EVT VT;
14908     switch (Intrinsic) {
14909     case Intrinsic::ppc_altivec_stvebx:
14910       VT = MVT::i8;
14911       break;
14912     case Intrinsic::ppc_altivec_stvehx:
14913       VT = MVT::i16;
14914       break;
14915     case Intrinsic::ppc_altivec_stvewx:
14916       VT = MVT::i32;
14917       break;
14918     case Intrinsic::ppc_vsx_stxvd2x:
14919       VT = MVT::v2f64;
14920       break;
14921     case Intrinsic::ppc_qpx_qvstfd:
14922       VT = MVT::v4f64;
14923       break;
14924     case Intrinsic::ppc_qpx_qvstfs:
14925       VT = MVT::v4f32;
14926       break;
14927     case Intrinsic::ppc_qpx_qvstfcd:
14928       VT = MVT::v2f64;
14929       break;
14930     case Intrinsic::ppc_qpx_qvstfcs:
14931       VT = MVT::v2f32;
14932       break;
14933     default:
14934       VT = MVT::v4i32;
14935       break;
14936     }
14937 
14938     Info.opc = ISD::INTRINSIC_VOID;
14939     Info.memVT = VT;
14940     Info.ptrVal = I.getArgOperand(1);
14941     Info.offset = -VT.getStoreSize()+1;
14942     Info.size = 2*VT.getStoreSize()-1;
14943     Info.align = Align::None();
14944     Info.flags = MachineMemOperand::MOStore;
14945     return true;
14946   }
14947   case Intrinsic::ppc_qpx_qvstfda:
14948   case Intrinsic::ppc_qpx_qvstfsa:
14949   case Intrinsic::ppc_qpx_qvstfcda:
14950   case Intrinsic::ppc_qpx_qvstfcsa:
14951   case Intrinsic::ppc_qpx_qvstfiwa: {
14952     EVT VT;
14953     switch (Intrinsic) {
14954     case Intrinsic::ppc_qpx_qvstfda:
14955       VT = MVT::v4f64;
14956       break;
14957     case Intrinsic::ppc_qpx_qvstfsa:
14958       VT = MVT::v4f32;
14959       break;
14960     case Intrinsic::ppc_qpx_qvstfcda:
14961       VT = MVT::v2f64;
14962       break;
14963     case Intrinsic::ppc_qpx_qvstfcsa:
14964       VT = MVT::v2f32;
14965       break;
14966     default:
14967       VT = MVT::v4i32;
14968       break;
14969     }
14970 
14971     Info.opc = ISD::INTRINSIC_VOID;
14972     Info.memVT = VT;
14973     Info.ptrVal = I.getArgOperand(1);
14974     Info.offset = 0;
14975     Info.size = VT.getStoreSize();
14976     Info.align = Align::None();
14977     Info.flags = MachineMemOperand::MOStore;
14978     return true;
14979   }
14980   default:
14981     break;
14982   }
14983 
14984   return false;
14985 }
14986 
14987 /// getOptimalMemOpType - Returns the target specific optimal type for load
14988 /// and store operations as a result of memset, memcpy, and memmove
14989 /// lowering. If DstAlign is zero that means it's safe to destination
14990 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
14991 /// means there isn't a need to check it against alignment requirement,
14992 /// probably because the source does not need to be loaded. If 'IsMemset' is
14993 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
14994 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
14995 /// source is constant so it does not need to be loaded.
14996 /// It returns EVT::Other if the type should be determined using generic
14997 /// target-independent logic.
14998 EVT PPCTargetLowering::getOptimalMemOpType(
14999     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
15000     bool ZeroMemset, bool MemcpyStrSrc,
15001     const AttributeList &FuncAttributes) const {
15002   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
15003     // When expanding a memset, require at least two QPX instructions to cover
15004     // the cost of loading the value to be stored from the constant pool.
15005     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
15006        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
15007         !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat)) {
15008       return MVT::v4f64;
15009     }
15010 
15011     // We should use Altivec/VSX loads and stores when available. For unaligned
15012     // addresses, unaligned VSX loads are only fast starting with the P8.
15013     if (Subtarget.hasAltivec() && Size >= 16 &&
15014         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
15015          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
15016       return MVT::v4i32;
15017   }
15018 
15019   if (Subtarget.isPPC64()) {
15020     return MVT::i64;
15021   }
15022 
15023   return MVT::i32;
15024 }
15025 
15026 /// Returns true if it is beneficial to convert a load of a constant
15027 /// to just the constant itself.
15028 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
15029                                                           Type *Ty) const {
15030   assert(Ty->isIntegerTy());
15031 
15032   unsigned BitSize = Ty->getPrimitiveSizeInBits();
15033   return !(BitSize == 0 || BitSize > 64);
15034 }
15035 
15036 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15037   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15038     return false;
15039   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15040   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15041   return NumBits1 == 64 && NumBits2 == 32;
15042 }
15043 
15044 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15045   if (!VT1.isInteger() || !VT2.isInteger())
15046     return false;
15047   unsigned NumBits1 = VT1.getSizeInBits();
15048   unsigned NumBits2 = VT2.getSizeInBits();
15049   return NumBits1 == 64 && NumBits2 == 32;
15050 }
15051 
15052 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15053   // Generally speaking, zexts are not free, but they are free when they can be
15054   // folded with other operations.
15055   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
15056     EVT MemVT = LD->getMemoryVT();
15057     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
15058          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
15059         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
15060          LD->getExtensionType() == ISD::ZEXTLOAD))
15061       return true;
15062   }
15063 
15064   // FIXME: Add other cases...
15065   //  - 32-bit shifts with a zext to i64
15066   //  - zext after ctlz, bswap, etc.
15067   //  - zext after and by a constant mask
15068 
15069   return TargetLowering::isZExtFree(Val, VT2);
15070 }
15071 
15072 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
15073   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
15074          "invalid fpext types");
15075   // Extending to float128 is not free.
15076   if (DestVT == MVT::f128)
15077     return false;
15078   return true;
15079 }
15080 
15081 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15082   return isInt<16>(Imm) || isUInt<16>(Imm);
15083 }
15084 
15085 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
15086   return isInt<16>(Imm) || isUInt<16>(Imm);
15087 }
15088 
15089 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
15090                                                        unsigned,
15091                                                        unsigned,
15092                                                        MachineMemOperand::Flags,
15093                                                        bool *Fast) const {
15094   if (DisablePPCUnaligned)
15095     return false;
15096 
15097   // PowerPC supports unaligned memory access for simple non-vector types.
15098   // Although accessing unaligned addresses is not as efficient as accessing
15099   // aligned addresses, it is generally more efficient than manual expansion,
15100   // and generally only traps for software emulation when crossing page
15101   // boundaries.
15102 
15103   if (!VT.isSimple())
15104     return false;
15105 
15106   if (VT.getSimpleVT().isVector()) {
15107     if (Subtarget.hasVSX()) {
15108       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
15109           VT != MVT::v4f32 && VT != MVT::v4i32)
15110         return false;
15111     } else {
15112       return false;
15113     }
15114   }
15115 
15116   if (VT == MVT::ppcf128)
15117     return false;
15118 
15119   if (Fast)
15120     *Fast = true;
15121 
15122   return true;
15123 }
15124 
15125 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
15126                                                    EVT VT) const {
15127   VT = VT.getScalarType();
15128 
15129   if (!VT.isSimple())
15130     return false;
15131 
15132   switch (VT.getSimpleVT().SimpleTy) {
15133   case MVT::f32:
15134   case MVT::f64:
15135     return true;
15136   case MVT::f128:
15137     return (EnableQuadPrecision && Subtarget.hasP9Vector());
15138   default:
15139     break;
15140   }
15141 
15142   return false;
15143 }
15144 
15145 const MCPhysReg *
15146 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
15147   // LR is a callee-save register, but we must treat it as clobbered by any call
15148   // site. Hence we include LR in the scratch registers, which are in turn added
15149   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
15150   // to CTR, which is used by any indirect call.
15151   static const MCPhysReg ScratchRegs[] = {
15152     PPC::X12, PPC::LR8, PPC::CTR8, 0
15153   };
15154 
15155   return ScratchRegs;
15156 }
15157 
15158 unsigned PPCTargetLowering::getExceptionPointerRegister(
15159     const Constant *PersonalityFn) const {
15160   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
15161 }
15162 
15163 unsigned PPCTargetLowering::getExceptionSelectorRegister(
15164     const Constant *PersonalityFn) const {
15165   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
15166 }
15167 
15168 bool
15169 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
15170                      EVT VT , unsigned DefinedValues) const {
15171   if (VT == MVT::v2i64)
15172     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
15173 
15174   if (Subtarget.hasVSX() || Subtarget.hasQPX())
15175     return true;
15176 
15177   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
15178 }
15179 
15180 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
15181   if (DisableILPPref || Subtarget.enableMachineScheduler())
15182     return TargetLowering::getSchedulingPreference(N);
15183 
15184   return Sched::ILP;
15185 }
15186 
15187 // Create a fast isel object.
15188 FastISel *
15189 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
15190                                   const TargetLibraryInfo *LibInfo) const {
15191   return PPC::createFastISel(FuncInfo, LibInfo);
15192 }
15193 
15194 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15195   if (Subtarget.isDarwinABI()) return;
15196   if (!Subtarget.isPPC64()) return;
15197 
15198   // Update IsSplitCSR in PPCFunctionInfo
15199   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
15200   PFI->setIsSplitCSR(true);
15201 }
15202 
15203 void PPCTargetLowering::insertCopiesSplitCSR(
15204   MachineBasicBlock *Entry,
15205   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15206   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
15207   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15208   if (!IStart)
15209     return;
15210 
15211   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
15212   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15213   MachineBasicBlock::iterator MBBI = Entry->begin();
15214   for (const MCPhysReg *I = IStart; *I; ++I) {
15215     const TargetRegisterClass *RC = nullptr;
15216     if (PPC::G8RCRegClass.contains(*I))
15217       RC = &PPC::G8RCRegClass;
15218     else if (PPC::F8RCRegClass.contains(*I))
15219       RC = &PPC::F8RCRegClass;
15220     else if (PPC::CRRCRegClass.contains(*I))
15221       RC = &PPC::CRRCRegClass;
15222     else if (PPC::VRRCRegClass.contains(*I))
15223       RC = &PPC::VRRCRegClass;
15224     else
15225       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15226 
15227     Register NewVR = MRI->createVirtualRegister(RC);
15228     // Create copy from CSR to a virtual register.
15229     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15230     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15231     // nounwind. If we want to generalize this later, we may need to emit
15232     // CFI pseudo-instructions.
15233     assert(Entry->getParent()->getFunction().hasFnAttribute(
15234              Attribute::NoUnwind) &&
15235            "Function should be nounwind in insertCopiesSplitCSR!");
15236     Entry->addLiveIn(*I);
15237     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15238       .addReg(*I);
15239 
15240     // Insert the copy-back instructions right before the terminator.
15241     for (auto *Exit : Exits)
15242       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15243               TII->get(TargetOpcode::COPY), *I)
15244         .addReg(NewVR);
15245   }
15246 }
15247 
15248 // Override to enable LOAD_STACK_GUARD lowering on Linux.
15249 bool PPCTargetLowering::useLoadStackGuardNode() const {
15250   if (!Subtarget.isTargetLinux())
15251     return TargetLowering::useLoadStackGuardNode();
15252   return true;
15253 }
15254 
15255 // Override to disable global variable loading on Linux.
15256 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
15257   if (!Subtarget.isTargetLinux())
15258     return TargetLowering::insertSSPDeclarations(M);
15259 }
15260 
15261 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
15262                                      bool ForCodeSize) const {
15263   if (!VT.isSimple() || !Subtarget.hasVSX())
15264     return false;
15265 
15266   switch(VT.getSimpleVT().SimpleTy) {
15267   default:
15268     // For FP types that are currently not supported by PPC backend, return
15269     // false. Examples: f16, f80.
15270     return false;
15271   case MVT::f32:
15272   case MVT::f64:
15273   case MVT::ppcf128:
15274     return Imm.isPosZero();
15275   }
15276 }
15277 
15278 // For vector shift operation op, fold
15279 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
15280 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
15281                                   SelectionDAG &DAG) {
15282   SDValue N0 = N->getOperand(0);
15283   SDValue N1 = N->getOperand(1);
15284   EVT VT = N0.getValueType();
15285   unsigned OpSizeInBits = VT.getScalarSizeInBits();
15286   unsigned Opcode = N->getOpcode();
15287   unsigned TargetOpcode;
15288 
15289   switch (Opcode) {
15290   default:
15291     llvm_unreachable("Unexpected shift operation");
15292   case ISD::SHL:
15293     TargetOpcode = PPCISD::SHL;
15294     break;
15295   case ISD::SRL:
15296     TargetOpcode = PPCISD::SRL;
15297     break;
15298   case ISD::SRA:
15299     TargetOpcode = PPCISD::SRA;
15300     break;
15301   }
15302 
15303   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
15304       N1->getOpcode() == ISD::AND)
15305     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
15306       if (Mask->getZExtValue() == OpSizeInBits - 1)
15307         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
15308 
15309   return SDValue();
15310 }
15311 
15312 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
15313   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15314     return Value;
15315 
15316   SDValue N0 = N->getOperand(0);
15317   ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1));
15318   if (!Subtarget.isISA3_0() ||
15319       N0.getOpcode() != ISD::SIGN_EXTEND ||
15320       N0.getOperand(0).getValueType() != MVT::i32 ||
15321       CN1 == nullptr || N->getValueType(0) != MVT::i64)
15322     return SDValue();
15323 
15324   // We can't save an operation here if the value is already extended, and
15325   // the existing shift is easier to combine.
15326   SDValue ExtsSrc = N0.getOperand(0);
15327   if (ExtsSrc.getOpcode() == ISD::TRUNCATE &&
15328       ExtsSrc.getOperand(0).getOpcode() == ISD::AssertSext)
15329     return SDValue();
15330 
15331   SDLoc DL(N0);
15332   SDValue ShiftBy = SDValue(CN1, 0);
15333   // We want the shift amount to be i32 on the extswli, but the shift could
15334   // have an i64.
15335   if (ShiftBy.getValueType() == MVT::i64)
15336     ShiftBy = DCI.DAG.getConstant(CN1->getZExtValue(), DL, MVT::i32);
15337 
15338   return DCI.DAG.getNode(PPCISD::EXTSWSLI, DL, MVT::i64, N0->getOperand(0),
15339                          ShiftBy);
15340 }
15341 
15342 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
15343   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15344     return Value;
15345 
15346   return SDValue();
15347 }
15348 
15349 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
15350   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
15351     return Value;
15352 
15353   return SDValue();
15354 }
15355 
15356 // Transform (add X, (zext(setne Z, C))) -> (addze X, (addic (addi Z, -C), -1))
15357 // Transform (add X, (zext(sete  Z, C))) -> (addze X, (subfic (addi Z, -C), 0))
15358 // When C is zero, the equation (addi Z, -C) can be simplified to Z
15359 // Requirement: -C in [-32768, 32767], X and Z are MVT::i64 types
15360 static SDValue combineADDToADDZE(SDNode *N, SelectionDAG &DAG,
15361                                  const PPCSubtarget &Subtarget) {
15362   if (!Subtarget.isPPC64())
15363     return SDValue();
15364 
15365   SDValue LHS = N->getOperand(0);
15366   SDValue RHS = N->getOperand(1);
15367 
15368   auto isZextOfCompareWithConstant = [](SDValue Op) {
15369     if (Op.getOpcode() != ISD::ZERO_EXTEND || !Op.hasOneUse() ||
15370         Op.getValueType() != MVT::i64)
15371       return false;
15372 
15373     SDValue Cmp = Op.getOperand(0);
15374     if (Cmp.getOpcode() != ISD::SETCC || !Cmp.hasOneUse() ||
15375         Cmp.getOperand(0).getValueType() != MVT::i64)
15376       return false;
15377 
15378     if (auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1))) {
15379       int64_t NegConstant = 0 - Constant->getSExtValue();
15380       // Due to the limitations of the addi instruction,
15381       // -C is required to be [-32768, 32767].
15382       return isInt<16>(NegConstant);
15383     }
15384 
15385     return false;
15386   };
15387 
15388   bool LHSHasPattern = isZextOfCompareWithConstant(LHS);
15389   bool RHSHasPattern = isZextOfCompareWithConstant(RHS);
15390 
15391   // If there is a pattern, canonicalize a zext operand to the RHS.
15392   if (LHSHasPattern && !RHSHasPattern)
15393     std::swap(LHS, RHS);
15394   else if (!LHSHasPattern && !RHSHasPattern)
15395     return SDValue();
15396 
15397   SDLoc DL(N);
15398   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Glue);
15399   SDValue Cmp = RHS.getOperand(0);
15400   SDValue Z = Cmp.getOperand(0);
15401   auto *Constant = dyn_cast<ConstantSDNode>(Cmp.getOperand(1));
15402 
15403   assert(Constant && "Constant Should not be a null pointer.");
15404   int64_t NegConstant = 0 - Constant->getSExtValue();
15405 
15406   switch(cast<CondCodeSDNode>(Cmp.getOperand(2))->get()) {
15407   default: break;
15408   case ISD::SETNE: {
15409     //                                 when C == 0
15410     //                             --> addze X, (addic Z, -1).carry
15411     //                            /
15412     // add X, (zext(setne Z, C))--
15413     //                            \    when -32768 <= -C <= 32767 && C != 0
15414     //                             --> addze X, (addic (addi Z, -C), -1).carry
15415     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15416                               DAG.getConstant(NegConstant, DL, MVT::i64));
15417     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15418     SDValue Addc = DAG.getNode(ISD::ADDC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15419                                AddOrZ, DAG.getConstant(-1ULL, DL, MVT::i64));
15420     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15421                        SDValue(Addc.getNode(), 1));
15422     }
15423   case ISD::SETEQ: {
15424     //                                 when C == 0
15425     //                             --> addze X, (subfic Z, 0).carry
15426     //                            /
15427     // add X, (zext(sete  Z, C))--
15428     //                            \    when -32768 <= -C <= 32767 && C != 0
15429     //                             --> addze X, (subfic (addi Z, -C), 0).carry
15430     SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Z,
15431                               DAG.getConstant(NegConstant, DL, MVT::i64));
15432     SDValue AddOrZ = NegConstant != 0 ? Add : Z;
15433     SDValue Subc = DAG.getNode(ISD::SUBC, DL, DAG.getVTList(MVT::i64, MVT::Glue),
15434                                DAG.getConstant(0, DL, MVT::i64), AddOrZ);
15435     return DAG.getNode(ISD::ADDE, DL, VTs, LHS, DAG.getConstant(0, DL, MVT::i64),
15436                        SDValue(Subc.getNode(), 1));
15437     }
15438   }
15439 
15440   return SDValue();
15441 }
15442 
15443 SDValue PPCTargetLowering::combineADD(SDNode *N, DAGCombinerInfo &DCI) const {
15444   if (auto Value = combineADDToADDZE(N, DCI.DAG, Subtarget))
15445     return Value;
15446 
15447   return SDValue();
15448 }
15449 
15450 // Detect TRUNCATE operations on bitcasts of float128 values.
15451 // What we are looking for here is the situtation where we extract a subset
15452 // of bits from a 128 bit float.
15453 // This can be of two forms:
15454 // 1) BITCAST of f128 feeding TRUNCATE
15455 // 2) BITCAST of f128 feeding SRL (a shift) feeding TRUNCATE
15456 // The reason this is required is because we do not have a legal i128 type
15457 // and so we want to prevent having to store the f128 and then reload part
15458 // of it.
15459 SDValue PPCTargetLowering::combineTRUNCATE(SDNode *N,
15460                                            DAGCombinerInfo &DCI) const {
15461   // If we are using CRBits then try that first.
15462   if (Subtarget.useCRBits()) {
15463     // Check if CRBits did anything and return that if it did.
15464     if (SDValue CRTruncValue = DAGCombineTruncBoolExt(N, DCI))
15465       return CRTruncValue;
15466   }
15467 
15468   SDLoc dl(N);
15469   SDValue Op0 = N->getOperand(0);
15470 
15471   // Looking for a truncate of i128 to i64.
15472   if (Op0.getValueType() != MVT::i128 || N->getValueType(0) != MVT::i64)
15473     return SDValue();
15474 
15475   int EltToExtract = DCI.DAG.getDataLayout().isBigEndian() ? 1 : 0;
15476 
15477   // SRL feeding TRUNCATE.
15478   if (Op0.getOpcode() == ISD::SRL) {
15479     ConstantSDNode *ConstNode = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
15480     // The right shift has to be by 64 bits.
15481     if (!ConstNode || ConstNode->getZExtValue() != 64)
15482       return SDValue();
15483 
15484     // Switch the element number to extract.
15485     EltToExtract = EltToExtract ? 0 : 1;
15486     // Update Op0 past the SRL.
15487     Op0 = Op0.getOperand(0);
15488   }
15489 
15490   // BITCAST feeding a TRUNCATE possibly via SRL.
15491   if (Op0.getOpcode() == ISD::BITCAST &&
15492       Op0.getValueType() == MVT::i128 &&
15493       Op0.getOperand(0).getValueType() == MVT::f128) {
15494     SDValue Bitcast = DCI.DAG.getBitcast(MVT::v2i64, Op0.getOperand(0));
15495     return DCI.DAG.getNode(
15496         ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Bitcast,
15497         DCI.DAG.getTargetConstant(EltToExtract, dl, MVT::i32));
15498   }
15499   return SDValue();
15500 }
15501 
15502 SDValue PPCTargetLowering::combineMUL(SDNode *N, DAGCombinerInfo &DCI) const {
15503   SelectionDAG &DAG = DCI.DAG;
15504 
15505   ConstantSDNode *ConstOpOrElement = isConstOrConstSplat(N->getOperand(1));
15506   if (!ConstOpOrElement)
15507     return SDValue();
15508 
15509   // An imul is usually smaller than the alternative sequence for legal type.
15510   if (DAG.getMachineFunction().getFunction().hasMinSize() &&
15511       isOperationLegal(ISD::MUL, N->getValueType(0)))
15512     return SDValue();
15513 
15514   auto IsProfitable = [this](bool IsNeg, bool IsAddOne, EVT VT) -> bool {
15515     switch (this->Subtarget.getCPUDirective()) {
15516     default:
15517       // TODO: enhance the condition for subtarget before pwr8
15518       return false;
15519     case PPC::DIR_PWR8:
15520       //  type        mul     add    shl
15521       // scalar        4       1      1
15522       // vector        7       2      2
15523       return true;
15524     case PPC::DIR_PWR9:
15525     case PPC::DIR_PWR_FUTURE:
15526       //  type        mul     add    shl
15527       // scalar        5       2      2
15528       // vector        7       2      2
15529 
15530       // The cycle RATIO of related operations are showed as a table above.
15531       // Because mul is 5(scalar)/7(vector), add/sub/shl are all 2 for both
15532       // scalar and vector type. For 2 instrs patterns, add/sub + shl
15533       // are 4, it is always profitable; but for 3 instrs patterns
15534       // (mul x, -(2^N + 1)) => -(add (shl x, N), x), sub + add + shl are 6.
15535       // So we should only do it for vector type.
15536       return IsAddOne && IsNeg ? VT.isVector() : true;
15537     }
15538   };
15539 
15540   EVT VT = N->getValueType(0);
15541   SDLoc DL(N);
15542 
15543   const APInt &MulAmt = ConstOpOrElement->getAPIntValue();
15544   bool IsNeg = MulAmt.isNegative();
15545   APInt MulAmtAbs = MulAmt.abs();
15546 
15547   if ((MulAmtAbs - 1).isPowerOf2()) {
15548     // (mul x, 2^N + 1) => (add (shl x, N), x)
15549     // (mul x, -(2^N + 1)) => -(add (shl x, N), x)
15550 
15551     if (!IsProfitable(IsNeg, true, VT))
15552       return SDValue();
15553 
15554     SDValue Op0 = N->getOperand(0);
15555     SDValue Op1 =
15556         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15557                     DAG.getConstant((MulAmtAbs - 1).logBase2(), DL, VT));
15558     SDValue Res = DAG.getNode(ISD::ADD, DL, VT, Op0, Op1);
15559 
15560     if (!IsNeg)
15561       return Res;
15562 
15563     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
15564   } else if ((MulAmtAbs + 1).isPowerOf2()) {
15565     // (mul x, 2^N - 1) => (sub (shl x, N), x)
15566     // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
15567 
15568     if (!IsProfitable(IsNeg, false, VT))
15569       return SDValue();
15570 
15571     SDValue Op0 = N->getOperand(0);
15572     SDValue Op1 =
15573         DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
15574                     DAG.getConstant((MulAmtAbs + 1).logBase2(), DL, VT));
15575 
15576     if (!IsNeg)
15577       return DAG.getNode(ISD::SUB, DL, VT, Op1, Op0);
15578     else
15579       return DAG.getNode(ISD::SUB, DL, VT, Op0, Op1);
15580 
15581   } else {
15582     return SDValue();
15583   }
15584 }
15585 
15586 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
15587   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
15588   if (!Subtarget.is64BitELFABI())
15589     return false;
15590 
15591   // If not a tail call then no need to proceed.
15592   if (!CI->isTailCall())
15593     return false;
15594 
15595   // If tail calls are disabled for the caller then we are done.
15596   const Function *Caller = CI->getParent()->getParent();
15597   auto Attr = Caller->getFnAttribute("disable-tail-calls");
15598   if (Attr.getValueAsString() == "true")
15599     return false;
15600 
15601   // If sibling calls have been disabled and tail-calls aren't guaranteed
15602   // there is no reason to duplicate.
15603   auto &TM = getTargetMachine();
15604   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
15605     return false;
15606 
15607   // Can't tail call a function called indirectly, or if it has variadic args.
15608   const Function *Callee = CI->getCalledFunction();
15609   if (!Callee || Callee->isVarArg())
15610     return false;
15611 
15612   // Make sure the callee and caller calling conventions are eligible for tco.
15613   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
15614                                            CI->getCallingConv()))
15615       return false;
15616 
15617   // If the function is local then we have a good chance at tail-calling it
15618   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
15619 }
15620 
15621 bool PPCTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
15622   if (!Subtarget.hasVSX())
15623     return false;
15624   if (Subtarget.hasP9Vector() && VT == MVT::f128)
15625     return true;
15626   return VT == MVT::f32 || VT == MVT::f64 ||
15627     VT == MVT::v4f32 || VT == MVT::v2f64;
15628 }
15629 
15630 bool PPCTargetLowering::
15631 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
15632   const Value *Mask = AndI.getOperand(1);
15633   // If the mask is suitable for andi. or andis. we should sink the and.
15634   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
15635     // Can't handle constants wider than 64-bits.
15636     if (CI->getBitWidth() > 64)
15637       return false;
15638     int64_t ConstVal = CI->getZExtValue();
15639     return isUInt<16>(ConstVal) ||
15640       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
15641   }
15642 
15643   // For non-constant masks, we can always use the record-form and.
15644   return true;
15645 }
15646 
15647 // Transform (abs (sub (zext a), (zext b))) to (vabsd a b 0)
15648 // Transform (abs (sub (zext a), (zext_invec b))) to (vabsd a b 0)
15649 // Transform (abs (sub (zext_invec a), (zext_invec b))) to (vabsd a b 0)
15650 // Transform (abs (sub (zext_invec a), (zext b))) to (vabsd a b 0)
15651 // Transform (abs (sub a, b) to (vabsd a b 1)) if a & b of type v4i32
15652 SDValue PPCTargetLowering::combineABS(SDNode *N, DAGCombinerInfo &DCI) const {
15653   assert((N->getOpcode() == ISD::ABS) && "Need ABS node here");
15654   assert(Subtarget.hasP9Altivec() &&
15655          "Only combine this when P9 altivec supported!");
15656   EVT VT = N->getValueType(0);
15657   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15658     return SDValue();
15659 
15660   SelectionDAG &DAG = DCI.DAG;
15661   SDLoc dl(N);
15662   if (N->getOperand(0).getOpcode() == ISD::SUB) {
15663     // Even for signed integers, if it's known to be positive (as signed
15664     // integer) due to zero-extended inputs.
15665     unsigned SubOpcd0 = N->getOperand(0)->getOperand(0).getOpcode();
15666     unsigned SubOpcd1 = N->getOperand(0)->getOperand(1).getOpcode();
15667     if ((SubOpcd0 == ISD::ZERO_EXTEND ||
15668          SubOpcd0 == ISD::ZERO_EXTEND_VECTOR_INREG) &&
15669         (SubOpcd1 == ISD::ZERO_EXTEND ||
15670          SubOpcd1 == ISD::ZERO_EXTEND_VECTOR_INREG)) {
15671       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15672                          N->getOperand(0)->getOperand(0),
15673                          N->getOperand(0)->getOperand(1),
15674                          DAG.getTargetConstant(0, dl, MVT::i32));
15675     }
15676 
15677     // For type v4i32, it can be optimized with xvnegsp + vabsduw
15678     if (N->getOperand(0).getValueType() == MVT::v4i32 &&
15679         N->getOperand(0).hasOneUse()) {
15680       return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(0).getValueType(),
15681                          N->getOperand(0)->getOperand(0),
15682                          N->getOperand(0)->getOperand(1),
15683                          DAG.getTargetConstant(1, dl, MVT::i32));
15684     }
15685   }
15686 
15687   return SDValue();
15688 }
15689 
15690 // For type v4i32/v8ii16/v16i8, transform
15691 // from (vselect (setcc a, b, setugt), (sub a, b), (sub b, a)) to (vabsd a, b)
15692 // from (vselect (setcc a, b, setuge), (sub a, b), (sub b, a)) to (vabsd a, b)
15693 // from (vselect (setcc a, b, setult), (sub b, a), (sub a, b)) to (vabsd a, b)
15694 // from (vselect (setcc a, b, setule), (sub b, a), (sub a, b)) to (vabsd a, b)
15695 SDValue PPCTargetLowering::combineVSelect(SDNode *N,
15696                                           DAGCombinerInfo &DCI) const {
15697   assert((N->getOpcode() == ISD::VSELECT) && "Need VSELECT node here");
15698   assert(Subtarget.hasP9Altivec() &&
15699          "Only combine this when P9 altivec supported!");
15700 
15701   SelectionDAG &DAG = DCI.DAG;
15702   SDLoc dl(N);
15703   SDValue Cond = N->getOperand(0);
15704   SDValue TrueOpnd = N->getOperand(1);
15705   SDValue FalseOpnd = N->getOperand(2);
15706   EVT VT = N->getOperand(1).getValueType();
15707 
15708   if (Cond.getOpcode() != ISD::SETCC || TrueOpnd.getOpcode() != ISD::SUB ||
15709       FalseOpnd.getOpcode() != ISD::SUB)
15710     return SDValue();
15711 
15712   // ABSD only available for type v4i32/v8i16/v16i8
15713   if (VT != MVT::v4i32 && VT != MVT::v8i16 && VT != MVT::v16i8)
15714     return SDValue();
15715 
15716   // At least to save one more dependent computation
15717   if (!(Cond.hasOneUse() || TrueOpnd.hasOneUse() || FalseOpnd.hasOneUse()))
15718     return SDValue();
15719 
15720   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
15721 
15722   // Can only handle unsigned comparison here
15723   switch (CC) {
15724   default:
15725     return SDValue();
15726   case ISD::SETUGT:
15727   case ISD::SETUGE:
15728     break;
15729   case ISD::SETULT:
15730   case ISD::SETULE:
15731     std::swap(TrueOpnd, FalseOpnd);
15732     break;
15733   }
15734 
15735   SDValue CmpOpnd1 = Cond.getOperand(0);
15736   SDValue CmpOpnd2 = Cond.getOperand(1);
15737 
15738   // SETCC CmpOpnd1 CmpOpnd2 cond
15739   // TrueOpnd = CmpOpnd1 - CmpOpnd2
15740   // FalseOpnd = CmpOpnd2 - CmpOpnd1
15741   if (TrueOpnd.getOperand(0) == CmpOpnd1 &&
15742       TrueOpnd.getOperand(1) == CmpOpnd2 &&
15743       FalseOpnd.getOperand(0) == CmpOpnd2 &&
15744       FalseOpnd.getOperand(1) == CmpOpnd1) {
15745     return DAG.getNode(PPCISD::VABSD, dl, N->getOperand(1).getValueType(),
15746                        CmpOpnd1, CmpOpnd2,
15747                        DAG.getTargetConstant(0, dl, MVT::i32));
15748   }
15749 
15750   return SDValue();
15751 }
15752