1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCCCState.h"
18 #include "PPCCallingConv.h"
19 #include "PPCFrameLowering.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCMachineFunctionInfo.h"
22 #include "PPCPerfectShuffle.h"
23 #include "PPCRegisterInfo.h"
24 #include "PPCSubtarget.h"
25 #include "PPCTargetMachine.h"
26 #include "llvm/ADT/APFloat.h"
27 #include "llvm/ADT/APInt.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/CodeGen/CallingConvLower.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineJumpTableInfo.h"
46 #include "llvm/CodeGen/MachineLoopInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.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/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/ValueTypes.h"
57 #include "llvm/IR/CallSite.h"
58 #include "llvm/IR/CallingConv.h"
59 #include "llvm/IR/Constant.h"
60 #include "llvm/IR/Constants.h"
61 #include "llvm/IR/DataLayout.h"
62 #include "llvm/IR/DebugLoc.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Function.h"
65 #include "llvm/IR/GlobalValue.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/Intrinsics.h"
69 #include "llvm/IR/Module.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/MC/MCExpr.h"
74 #include "llvm/MC/MCRegisterInfo.h"
75 #include "llvm/Support/AtomicOrdering.h"
76 #include "llvm/Support/BranchProbability.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CodeGen.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/Format.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MachineValueType.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Target/TargetMachine.h"
89 #include "llvm/Target/TargetOptions.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <list>
95 #include <utility>
96 #include <vector>
97 
98 using namespace llvm;
99 
100 #define DEBUG_TYPE "ppc-lowering"
101 
102 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
103 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
104 
105 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
106 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
107 
108 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
109 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
110 
111 static cl::opt<bool> DisableSCO("disable-ppc-sco",
112 cl::desc("disable sibling call optimization on ppc"), cl::Hidden);
113 
114 static cl::opt<bool> EnableQuadPrecision("enable-ppc-quad-precision",
115 cl::desc("enable quad precision float support on ppc"), cl::Hidden);
116 
117 STATISTIC(NumTailCalls, "Number of tail calls");
118 STATISTIC(NumSiblingCalls, "Number of sibling calls");
119 
120 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *, unsigned, int);
121 
122 // FIXME: Remove this once the bug has been fixed!
123 extern cl::opt<bool> ANDIGlueBug;
124 
125 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
126                                      const PPCSubtarget &STI)
127     : TargetLowering(TM), Subtarget(STI) {
128   // Use _setjmp/_longjmp instead of setjmp/longjmp.
129   setUseUnderscoreSetJmp(true);
130   setUseUnderscoreLongJmp(true);
131 
132   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
133   // arguments are at least 4/8 bytes aligned.
134   bool isPPC64 = Subtarget.isPPC64();
135   setMinStackArgumentAlignment(isPPC64 ? 8:4);
136 
137   // Set up the register classes.
138   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
139   if (!useSoftFloat()) {
140     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
141     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
142   }
143 
144   // Match BITREVERSE to customized fast code sequence in the td file.
145   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
146   setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
147 
148   // Sub-word ATOMIC_CMP_SWAP need to ensure that the input is zero-extended.
149   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
150 
151   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD.
152   for (MVT VT : MVT::integer_valuetypes()) {
153     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
154     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
155   }
156 
157   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
158 
159   // PowerPC has pre-inc load and store's.
160   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
161   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
162   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
163   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
164   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
165   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
166   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
167   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
168   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
169   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
170   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
171   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
172   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
173   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
174 
175   // PowerPC uses ADDC/ADDE/SUBC/SUBE to propagate carry.
176   const MVT ScalarIntVTs[] = { MVT::i32, MVT::i64 };
177   for (MVT VT : ScalarIntVTs) {
178     setOperationAction(ISD::ADDC, VT, Legal);
179     setOperationAction(ISD::ADDE, VT, Legal);
180     setOperationAction(ISD::SUBC, VT, Legal);
181     setOperationAction(ISD::SUBE, VT, Legal);
182   }
183 
184   if (Subtarget.useCRBits()) {
185     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
186 
187     if (isPPC64 || Subtarget.hasFPCVT()) {
188       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
189       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
190                          isPPC64 ? MVT::i64 : MVT::i32);
191       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
192       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
193                         isPPC64 ? MVT::i64 : MVT::i32);
194     } else {
195       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
196       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
197     }
198 
199     // PowerPC does not support direct load/store of condition registers.
200     setOperationAction(ISD::LOAD, MVT::i1, Custom);
201     setOperationAction(ISD::STORE, MVT::i1, Custom);
202 
203     // FIXME: Remove this once the ANDI glue bug is fixed:
204     if (ANDIGlueBug)
205       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
206 
207     for (MVT VT : MVT::integer_valuetypes()) {
208       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
209       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
210       setTruncStoreAction(VT, MVT::i1, Expand);
211     }
212 
213     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
214   }
215 
216   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
217   // PPC (the libcall is not available).
218   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
219   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
220 
221   // We do not currently implement these libm ops for PowerPC.
222   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
223   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
224   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
225   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
226   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
227   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
228 
229   // PowerPC has no SREM/UREM instructions unless we are on P9
230   // On P9 we may use a hardware instruction to compute the remainder.
231   // The instructions are not legalized directly because in the cases where the
232   // result of both the remainder and the division is required it is more
233   // efficient to compute the remainder from the result of the division rather
234   // than use the remainder instruction.
235   if (Subtarget.isISA3_0()) {
236     setOperationAction(ISD::SREM, MVT::i32, Custom);
237     setOperationAction(ISD::UREM, MVT::i32, Custom);
238     setOperationAction(ISD::SREM, MVT::i64, Custom);
239     setOperationAction(ISD::UREM, MVT::i64, Custom);
240   } else {
241     setOperationAction(ISD::SREM, MVT::i32, Expand);
242     setOperationAction(ISD::UREM, MVT::i32, Expand);
243     setOperationAction(ISD::SREM, MVT::i64, Expand);
244     setOperationAction(ISD::UREM, MVT::i64, Expand);
245   }
246 
247   if (Subtarget.hasP9Vector()) {
248     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
249     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
250     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
251   }
252 
253   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
254   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
255   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
256   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
257   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
258   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
259   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
260   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
261   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
262 
263   // We don't support sin/cos/sqrt/fmod/pow
264   setOperationAction(ISD::FSIN , MVT::f64, Expand);
265   setOperationAction(ISD::FCOS , MVT::f64, Expand);
266   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
267   setOperationAction(ISD::FREM , MVT::f64, Expand);
268   setOperationAction(ISD::FPOW , MVT::f64, Expand);
269   setOperationAction(ISD::FMA  , MVT::f64, Legal);
270   setOperationAction(ISD::FSIN , MVT::f32, Expand);
271   setOperationAction(ISD::FCOS , MVT::f32, Expand);
272   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
273   setOperationAction(ISD::FREM , MVT::f32, Expand);
274   setOperationAction(ISD::FPOW , MVT::f32, Expand);
275   setOperationAction(ISD::FMA  , MVT::f32, Legal);
276 
277   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
278 
279   // If we're enabling GP optimizations, use hardware square root
280   if (!Subtarget.hasFSQRT() &&
281       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
282         Subtarget.hasFRE()))
283     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
284 
285   if (!Subtarget.hasFSQRT() &&
286       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
287         Subtarget.hasFRES()))
288     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
289 
290   if (Subtarget.hasFCPSGN()) {
291     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
292     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
293   } else {
294     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
295     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
296   }
297 
298   if (Subtarget.hasFPRND()) {
299     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
300     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
301     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
302     setOperationAction(ISD::FROUND, MVT::f64, Legal);
303 
304     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
305     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
306     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
307     setOperationAction(ISD::FROUND, MVT::f32, Legal);
308   }
309 
310   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
311   // to speed up scalar BSWAP64.
312   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
313   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
314   if (Subtarget.isISA3_0()) {
315     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
316     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
317     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
318   } else {
319     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
320     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
321     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
322   }
323 
324   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
325     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
326     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
327   } else {
328     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
329     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
330   }
331 
332   // PowerPC does not have ROTR
333   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
334   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
335 
336   if (!Subtarget.useCRBits()) {
337     // PowerPC does not have Select
338     setOperationAction(ISD::SELECT, MVT::i32, Expand);
339     setOperationAction(ISD::SELECT, MVT::i64, Expand);
340     setOperationAction(ISD::SELECT, MVT::f32, Expand);
341     setOperationAction(ISD::SELECT, MVT::f64, Expand);
342   }
343 
344   // PowerPC wants to turn select_cc of FP into fsel when possible.
345   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
346   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
347 
348   // PowerPC wants to optimize integer setcc a bit
349   if (!Subtarget.useCRBits())
350     setOperationAction(ISD::SETCC, MVT::i32, Custom);
351 
352   // PowerPC does not have BRCOND which requires SetCC
353   if (!Subtarget.useCRBits())
354     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
355 
356   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
357 
358   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
359   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
360 
361   // PowerPC does not have [U|S]INT_TO_FP
362   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
363   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
364 
365   if (Subtarget.hasDirectMove() && isPPC64) {
366     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
367     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
368     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
369     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
370   } else {
371     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
372     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
373     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
374     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
375   }
376 
377   // We cannot sextinreg(i1).  Expand to shifts.
378   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
379 
380   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
381   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
382   // support continuation, user-level threading, and etc.. As a result, no
383   // other SjLj exception interfaces are implemented and please don't build
384   // your own exception handling based on them.
385   // LLVM/Clang supports zero-cost DWARF exception handling.
386   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
387   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
388 
389   // We want to legalize GlobalAddress and ConstantPool nodes into the
390   // appropriate instructions to materialize the address.
391   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
392   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
393   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
394   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
395   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
396   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
397   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
398   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
399   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
400   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
401 
402   // TRAP is legal.
403   setOperationAction(ISD::TRAP, MVT::Other, Legal);
404 
405   // TRAMPOLINE is custom lowered.
406   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
407   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
408 
409   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
410   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
411 
412   if (Subtarget.isSVR4ABI()) {
413     if (isPPC64) {
414       // VAARG always uses double-word chunks, so promote anything smaller.
415       setOperationAction(ISD::VAARG, MVT::i1, Promote);
416       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
417       setOperationAction(ISD::VAARG, MVT::i8, Promote);
418       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
419       setOperationAction(ISD::VAARG, MVT::i16, Promote);
420       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
421       setOperationAction(ISD::VAARG, MVT::i32, Promote);
422       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
423       setOperationAction(ISD::VAARG, MVT::Other, Expand);
424     } else {
425       // VAARG is custom lowered with the 32-bit SVR4 ABI.
426       setOperationAction(ISD::VAARG, MVT::Other, Custom);
427       setOperationAction(ISD::VAARG, MVT::i64, Custom);
428     }
429   } else
430     setOperationAction(ISD::VAARG, MVT::Other, Expand);
431 
432   if (Subtarget.isSVR4ABI() && !isPPC64)
433     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
434     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
435   else
436     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
437 
438   // Use the default implementation.
439   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
440   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
441   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
442   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
443   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
444   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
445   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
446   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
447   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
448 
449   // We want to custom lower some of our intrinsics.
450   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
451 
452   // To handle counter-based loop conditions.
453   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
454 
455   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
456   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
457   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
458   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
459 
460   // Comparisons that require checking two conditions.
461   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
462   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
463   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
464   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
465   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
466   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
467   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
468   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
469   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
470   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
471   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
472   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
473 
474   if (Subtarget.has64BitSupport()) {
475     // They also have instructions for converting between i64 and fp.
476     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
477     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
478     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
479     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
480     // This is just the low 32 bits of a (signed) fp->i64 conversion.
481     // We cannot do this with Promote because i64 is not a legal type.
482     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
483 
484     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
485       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
486   } else {
487     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
488     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
489   }
490 
491   // With the instructions enabled under FPCVT, we can do everything.
492   if (Subtarget.hasFPCVT()) {
493     if (Subtarget.has64BitSupport()) {
494       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
495       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
496       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
497       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
498     }
499 
500     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
501     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
502     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
503     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
504   }
505 
506   if (Subtarget.use64BitRegs()) {
507     // 64-bit PowerPC implementations can support i64 types directly
508     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
509     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
510     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
511     // 64-bit PowerPC wants to expand i128 shifts itself.
512     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
513     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
514     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
515   } else {
516     // 32-bit PowerPC wants to expand i64 shifts itself.
517     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
518     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
519     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
520   }
521 
522   if (Subtarget.hasAltivec()) {
523     // First set operation action for all vector types to expand. Then we
524     // will selectively turn on ones that can be effectively codegen'd.
525     for (MVT VT : MVT::vector_valuetypes()) {
526       // add/sub are legal for all supported vector VT's.
527       setOperationAction(ISD::ADD, VT, Legal);
528       setOperationAction(ISD::SUB, VT, Legal);
529 
530       // Vector instructions introduced in P8
531       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
532         setOperationAction(ISD::CTPOP, VT, Legal);
533         setOperationAction(ISD::CTLZ, VT, Legal);
534       }
535       else {
536         setOperationAction(ISD::CTPOP, VT, Expand);
537         setOperationAction(ISD::CTLZ, VT, Expand);
538       }
539 
540       // Vector instructions introduced in P9
541       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
542         setOperationAction(ISD::CTTZ, VT, Legal);
543       else
544         setOperationAction(ISD::CTTZ, VT, Expand);
545 
546       // We promote all shuffles to v16i8.
547       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
548       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
549 
550       // We promote all non-typed operations to v4i32.
551       setOperationAction(ISD::AND   , VT, Promote);
552       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
553       setOperationAction(ISD::OR    , VT, Promote);
554       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
555       setOperationAction(ISD::XOR   , VT, Promote);
556       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
557       setOperationAction(ISD::LOAD  , VT, Promote);
558       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
559       setOperationAction(ISD::SELECT, VT, Promote);
560       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
561       setOperationAction(ISD::SELECT_CC, VT, Promote);
562       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
563       setOperationAction(ISD::STORE, VT, Promote);
564       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
565 
566       // No other operations are legal.
567       setOperationAction(ISD::MUL , VT, Expand);
568       setOperationAction(ISD::SDIV, VT, Expand);
569       setOperationAction(ISD::SREM, VT, Expand);
570       setOperationAction(ISD::UDIV, VT, Expand);
571       setOperationAction(ISD::UREM, VT, Expand);
572       setOperationAction(ISD::FDIV, VT, Expand);
573       setOperationAction(ISD::FREM, VT, Expand);
574       setOperationAction(ISD::FNEG, VT, Expand);
575       setOperationAction(ISD::FSQRT, VT, Expand);
576       setOperationAction(ISD::FLOG, VT, Expand);
577       setOperationAction(ISD::FLOG10, VT, Expand);
578       setOperationAction(ISD::FLOG2, VT, Expand);
579       setOperationAction(ISD::FEXP, VT, Expand);
580       setOperationAction(ISD::FEXP2, VT, Expand);
581       setOperationAction(ISD::FSIN, VT, Expand);
582       setOperationAction(ISD::FCOS, VT, Expand);
583       setOperationAction(ISD::FABS, VT, Expand);
584       setOperationAction(ISD::FFLOOR, VT, Expand);
585       setOperationAction(ISD::FCEIL,  VT, Expand);
586       setOperationAction(ISD::FTRUNC, VT, Expand);
587       setOperationAction(ISD::FRINT,  VT, Expand);
588       setOperationAction(ISD::FNEARBYINT, VT, Expand);
589       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
590       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
591       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
592       setOperationAction(ISD::MULHU, VT, Expand);
593       setOperationAction(ISD::MULHS, VT, Expand);
594       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
595       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
596       setOperationAction(ISD::UDIVREM, VT, Expand);
597       setOperationAction(ISD::SDIVREM, VT, Expand);
598       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
599       setOperationAction(ISD::FPOW, VT, Expand);
600       setOperationAction(ISD::BSWAP, VT, Expand);
601       setOperationAction(ISD::VSELECT, VT, Expand);
602       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
603       setOperationAction(ISD::ROTL, VT, Expand);
604       setOperationAction(ISD::ROTR, VT, Expand);
605 
606       for (MVT InnerVT : MVT::vector_valuetypes()) {
607         setTruncStoreAction(VT, InnerVT, Expand);
608         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
609         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
610         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
611       }
612     }
613 
614     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
615     // with merges, splats, etc.
616     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
617 
618     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
619     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
620     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
621     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
622     setOperationAction(ISD::SELECT, MVT::v4i32,
623                        Subtarget.useCRBits() ? Legal : Expand);
624     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
625     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
626     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
627     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
628     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
629     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
630     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
631     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
632     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
633 
634     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
635     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
636     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
637     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
638 
639     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
640     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
641 
642     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
643       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
644       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
645     }
646 
647     if (Subtarget.hasP8Altivec())
648       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
649     else
650       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
651 
652     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
653     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
654 
655     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
656     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
657 
658     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
659     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
660     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
661     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
662 
663     // Altivec does not contain unordered floating-point compare instructions
664     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
665     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
666     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
667     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
668 
669     if (Subtarget.hasVSX()) {
670       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
671       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
672       if (Subtarget.hasP8Vector()) {
673         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
674         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
675       }
676       if (Subtarget.hasDirectMove() && isPPC64) {
677         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
678         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
679         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
680         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
681         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
682         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
683         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
684         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
685       }
686       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
687 
688       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
689       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
690       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
691       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
692       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
693 
694       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
695 
696       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
697       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
698 
699       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
700       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
701 
702       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
703       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
704       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
705       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
706       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
707 
708       // Share the Altivec comparison restrictions.
709       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
710       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
711       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
712       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
713 
714       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
715       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
716 
717       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
718 
719       if (Subtarget.hasP8Vector())
720         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
721 
722       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
723 
724       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
725       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
726       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
727 
728       if (Subtarget.hasP8Altivec()) {
729         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
730         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
731         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
732 
733         // 128 bit shifts can be accomplished via 3 instructions for SHL and
734         // SRL, but not for SRA because of the instructions available:
735         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
736         // doing
737         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
738         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
739         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
740 
741         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
742       }
743       else {
744         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
745         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
746         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
747 
748         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
749 
750         // VSX v2i64 only supports non-arithmetic operations.
751         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
752         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
753       }
754 
755       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
756       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
757       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
758       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
759 
760       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
761 
762       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
763       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
764       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
765       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
766 
767       // Vector operation legalization checks the result type of
768       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
769       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
770       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
771       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
772       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
773 
774       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
775       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
776       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
777       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
778 
779       if (Subtarget.hasDirectMove())
780         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
781       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
782 
783       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
784     }
785 
786     if (Subtarget.hasP8Altivec()) {
787       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
788       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
789     }
790 
791     if (Subtarget.hasP9Vector()) {
792       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
793       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
794 
795       // 128 bit shifts can be accomplished via 3 instructions for SHL and
796       // SRL, but not for SRA because of the instructions available:
797       // VS{RL} and VS{RL}O.
798       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
799       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
800       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
801 
802       if (EnableQuadPrecision) {
803         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
804         setOperationAction(ISD::FADD, MVT::f128, Legal);
805         setOperationAction(ISD::FSUB, MVT::f128, Legal);
806         setOperationAction(ISD::FDIV, MVT::f128, Legal);
807         setOperationAction(ISD::FMUL, MVT::f128, Legal);
808         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
809         setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
810         setOperationAction(ISD::FMA, MVT::f128, Legal);
811       }
812 
813     }
814 
815     if (Subtarget.hasP9Altivec()) {
816       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
817       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
818     }
819   }
820 
821   if (Subtarget.hasQPX()) {
822     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
823     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
824     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
825     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
826 
827     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
828     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
829 
830     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
831     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
832 
833     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
834     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
835 
836     if (!Subtarget.useCRBits())
837       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
838     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
839 
840     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
841     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
842     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
843     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
844     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
845     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
846     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
847 
848     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
849     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
850 
851     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
852     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
853     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
854 
855     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
856     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
857     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
858     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
859     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
860     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
861     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
862     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
863     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
864     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
865 
866     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
867     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
868 
869     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
870     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
871 
872     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
873 
874     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
875     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
876     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
877     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
878 
879     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
880     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
881 
882     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
883     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
884 
885     if (!Subtarget.useCRBits())
886       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
887     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
888 
889     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
890     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
891     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
892     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
893     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
894     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
895     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
896 
897     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
898     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
899 
900     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
901     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
902     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
903     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
904     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
905     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
906     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
907     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
908     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
909     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
910 
911     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
912     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
913 
914     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
915     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
916 
917     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
918 
919     setOperationAction(ISD::AND , MVT::v4i1, Legal);
920     setOperationAction(ISD::OR , MVT::v4i1, Legal);
921     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
922 
923     if (!Subtarget.useCRBits())
924       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
925     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
926 
927     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
928     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
929 
930     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
931     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
932     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
933     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
934     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
935     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
936     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
937 
938     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
939     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
940 
941     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
942 
943     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
944     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
945     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
946     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
947 
948     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
949     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
950     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
951     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
952 
953     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
954     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
955 
956     // These need to set FE_INEXACT, and so cannot be vectorized here.
957     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
958     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
959 
960     if (TM.Options.UnsafeFPMath) {
961       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
962       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
963 
964       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
965       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
966     } else {
967       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
968       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
969 
970       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
971       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
972     }
973   }
974 
975   if (Subtarget.has64BitSupport())
976     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
977 
978   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
979 
980   if (!isPPC64) {
981     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
982     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
983   }
984 
985   setBooleanContents(ZeroOrOneBooleanContent);
986 
987   if (Subtarget.hasAltivec()) {
988     // Altivec instructions set fields to all zeros or all ones.
989     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
990   }
991 
992   if (!isPPC64) {
993     // These libcalls are not available in 32-bit.
994     setLibcallName(RTLIB::SHL_I128, nullptr);
995     setLibcallName(RTLIB::SRL_I128, nullptr);
996     setLibcallName(RTLIB::SRA_I128, nullptr);
997   }
998 
999   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
1000 
1001   // We have target-specific dag combine patterns for the following nodes:
1002   setTargetDAGCombine(ISD::SHL);
1003   setTargetDAGCombine(ISD::SRA);
1004   setTargetDAGCombine(ISD::SRL);
1005   setTargetDAGCombine(ISD::SINT_TO_FP);
1006   setTargetDAGCombine(ISD::BUILD_VECTOR);
1007   if (Subtarget.hasFPCVT())
1008     setTargetDAGCombine(ISD::UINT_TO_FP);
1009   setTargetDAGCombine(ISD::LOAD);
1010   setTargetDAGCombine(ISD::STORE);
1011   setTargetDAGCombine(ISD::BR_CC);
1012   if (Subtarget.useCRBits())
1013     setTargetDAGCombine(ISD::BRCOND);
1014   setTargetDAGCombine(ISD::BSWAP);
1015   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1016   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1017   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1018 
1019   setTargetDAGCombine(ISD::SIGN_EXTEND);
1020   setTargetDAGCombine(ISD::ZERO_EXTEND);
1021   setTargetDAGCombine(ISD::ANY_EXTEND);
1022 
1023   if (Subtarget.useCRBits()) {
1024     setTargetDAGCombine(ISD::TRUNCATE);
1025     setTargetDAGCombine(ISD::SETCC);
1026     setTargetDAGCombine(ISD::SELECT_CC);
1027   }
1028 
1029   // Use reciprocal estimates.
1030   if (TM.Options.UnsafeFPMath) {
1031     setTargetDAGCombine(ISD::FDIV);
1032     setTargetDAGCombine(ISD::FSQRT);
1033   }
1034 
1035   // Darwin long double math library functions have $LDBL128 appended.
1036   if (Subtarget.isDarwin()) {
1037     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1038     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1039     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1040     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1041     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1042     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1043     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1044     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1045     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1046     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1047   }
1048 
1049   // With 32 condition bits, we don't need to sink (and duplicate) compares
1050   // aggressively in CodeGenPrep.
1051   if (Subtarget.useCRBits()) {
1052     setHasMultipleConditionRegisters();
1053     setJumpIsExpensive();
1054   }
1055 
1056   setMinFunctionAlignment(2);
1057   if (Subtarget.isDarwin())
1058     setPrefFunctionAlignment(4);
1059 
1060   switch (Subtarget.getDarwinDirective()) {
1061   default: break;
1062   case PPC::DIR_970:
1063   case PPC::DIR_A2:
1064   case PPC::DIR_E500mc:
1065   case PPC::DIR_E5500:
1066   case PPC::DIR_PWR4:
1067   case PPC::DIR_PWR5:
1068   case PPC::DIR_PWR5X:
1069   case PPC::DIR_PWR6:
1070   case PPC::DIR_PWR6X:
1071   case PPC::DIR_PWR7:
1072   case PPC::DIR_PWR8:
1073   case PPC::DIR_PWR9:
1074     setPrefFunctionAlignment(4);
1075     setPrefLoopAlignment(4);
1076     break;
1077   }
1078 
1079   if (Subtarget.enableMachineScheduler())
1080     setSchedulingPreference(Sched::Source);
1081   else
1082     setSchedulingPreference(Sched::Hybrid);
1083 
1084   computeRegisterProperties(STI.getRegisterInfo());
1085 
1086   // The Freescale cores do better with aggressive inlining of memcpy and
1087   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1088   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1089       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1090     MaxStoresPerMemset = 32;
1091     MaxStoresPerMemsetOptSize = 16;
1092     MaxStoresPerMemcpy = 32;
1093     MaxStoresPerMemcpyOptSize = 8;
1094     MaxStoresPerMemmove = 32;
1095     MaxStoresPerMemmoveOptSize = 8;
1096   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1097     // The A2 also benefits from (very) aggressive inlining of memcpy and
1098     // friends. The overhead of a the function call, even when warm, can be
1099     // over one hundred cycles.
1100     MaxStoresPerMemset = 128;
1101     MaxStoresPerMemcpy = 128;
1102     MaxStoresPerMemmove = 128;
1103     MaxLoadsPerMemcmp = 128;
1104   } else {
1105     MaxLoadsPerMemcmp = 8;
1106     MaxLoadsPerMemcmpOptSize = 4;
1107   }
1108 }
1109 
1110 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1111 /// the desired ByVal argument alignment.
1112 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1113                              unsigned MaxMaxAlign) {
1114   if (MaxAlign == MaxMaxAlign)
1115     return;
1116   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1117     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1118       MaxAlign = 32;
1119     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1120       MaxAlign = 16;
1121   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1122     unsigned EltAlign = 0;
1123     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1124     if (EltAlign > MaxAlign)
1125       MaxAlign = EltAlign;
1126   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1127     for (auto *EltTy : STy->elements()) {
1128       unsigned EltAlign = 0;
1129       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1130       if (EltAlign > MaxAlign)
1131         MaxAlign = EltAlign;
1132       if (MaxAlign == MaxMaxAlign)
1133         break;
1134     }
1135   }
1136 }
1137 
1138 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1139 /// function arguments in the caller parameter area.
1140 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1141                                                   const DataLayout &DL) const {
1142   // Darwin passes everything on 4 byte boundary.
1143   if (Subtarget.isDarwin())
1144     return 4;
1145 
1146   // 16byte and wider vectors are passed on 16byte boundary.
1147   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1148   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1149   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1150     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1151   return Align;
1152 }
1153 
1154 bool PPCTargetLowering::useSoftFloat() const {
1155   return Subtarget.useSoftFloat();
1156 }
1157 
1158 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1159   switch ((PPCISD::NodeType)Opcode) {
1160   case PPCISD::FIRST_NUMBER:    break;
1161   case PPCISD::FSEL:            return "PPCISD::FSEL";
1162   case PPCISD::FCFID:           return "PPCISD::FCFID";
1163   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1164   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1165   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1166   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1167   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1168   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1169   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1170   case PPCISD::FP_TO_UINT_IN_VSR:
1171                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1172   case PPCISD::FP_TO_SINT_IN_VSR:
1173                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1174   case PPCISD::FRE:             return "PPCISD::FRE";
1175   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1176   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1177   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1178   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1179   case PPCISD::VPERM:           return "PPCISD::VPERM";
1180   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1181   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1182   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1183   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1184   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1185   case PPCISD::CMPB:            return "PPCISD::CMPB";
1186   case PPCISD::Hi:              return "PPCISD::Hi";
1187   case PPCISD::Lo:              return "PPCISD::Lo";
1188   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1189   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1190   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1191   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1192   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1193   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1194   case PPCISD::SRL:             return "PPCISD::SRL";
1195   case PPCISD::SRA:             return "PPCISD::SRA";
1196   case PPCISD::SHL:             return "PPCISD::SHL";
1197   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1198   case PPCISD::CALL:            return "PPCISD::CALL";
1199   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1200   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1201   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1202   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1203   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1204   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1205   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1206   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1207   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1208   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1209   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1210   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1211   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1212   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1213   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1214   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1215   case PPCISD::VCMP:            return "PPCISD::VCMP";
1216   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1217   case PPCISD::LBRX:            return "PPCISD::LBRX";
1218   case PPCISD::STBRX:           return "PPCISD::STBRX";
1219   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1220   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1221   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1222   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1223   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1224   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1225   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1226   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1227   case PPCISD::ST_VSR_SCAL_INT:
1228                                 return "PPCISD::ST_VSR_SCAL_INT";
1229   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1230   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1231   case PPCISD::BDZ:             return "PPCISD::BDZ";
1232   case PPCISD::MFFS:            return "PPCISD::MFFS";
1233   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1234   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1235   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1236   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1237   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1238   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1239   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1240   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1241   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1242   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1243   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1244   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1245   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1246   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1247   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1248   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1249   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1250   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1251   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1252   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1253   case PPCISD::SC:              return "PPCISD::SC";
1254   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1255   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1256   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1257   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1258   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1259   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1260   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1261   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1262   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1263   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1264   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1265   }
1266   return nullptr;
1267 }
1268 
1269 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1270                                           EVT VT) const {
1271   if (!VT.isVector())
1272     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1273 
1274   if (Subtarget.hasQPX())
1275     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1276 
1277   return VT.changeVectorElementTypeToInteger();
1278 }
1279 
1280 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1281   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1282   return true;
1283 }
1284 
1285 //===----------------------------------------------------------------------===//
1286 // Node matching predicates, for use by the tblgen matching code.
1287 //===----------------------------------------------------------------------===//
1288 
1289 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1290 static bool isFloatingPointZero(SDValue Op) {
1291   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1292     return CFP->getValueAPF().isZero();
1293   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1294     // Maybe this has already been legalized into the constant pool?
1295     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1296       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1297         return CFP->getValueAPF().isZero();
1298   }
1299   return false;
1300 }
1301 
1302 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1303 /// true if Op is undef or if it matches the specified value.
1304 static bool isConstantOrUndef(int Op, int Val) {
1305   return Op < 0 || Op == Val;
1306 }
1307 
1308 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1309 /// VPKUHUM instruction.
1310 /// The ShuffleKind distinguishes between big-endian operations with
1311 /// two different inputs (0), either-endian operations with two identical
1312 /// inputs (1), and little-endian operations with two different inputs (2).
1313 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1314 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1315                                SelectionDAG &DAG) {
1316   bool IsLE = DAG.getDataLayout().isLittleEndian();
1317   if (ShuffleKind == 0) {
1318     if (IsLE)
1319       return false;
1320     for (unsigned i = 0; i != 16; ++i)
1321       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1322         return false;
1323   } else if (ShuffleKind == 2) {
1324     if (!IsLE)
1325       return false;
1326     for (unsigned i = 0; i != 16; ++i)
1327       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1328         return false;
1329   } else if (ShuffleKind == 1) {
1330     unsigned j = IsLE ? 0 : 1;
1331     for (unsigned i = 0; i != 8; ++i)
1332       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1333           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1334         return false;
1335   }
1336   return true;
1337 }
1338 
1339 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1340 /// VPKUWUM instruction.
1341 /// The ShuffleKind distinguishes between big-endian operations with
1342 /// two different inputs (0), either-endian operations with two identical
1343 /// inputs (1), and little-endian operations with two different inputs (2).
1344 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1345 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1346                                SelectionDAG &DAG) {
1347   bool IsLE = DAG.getDataLayout().isLittleEndian();
1348   if (ShuffleKind == 0) {
1349     if (IsLE)
1350       return false;
1351     for (unsigned i = 0; i != 16; i += 2)
1352       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1353           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1354         return false;
1355   } else if (ShuffleKind == 2) {
1356     if (!IsLE)
1357       return false;
1358     for (unsigned i = 0; i != 16; i += 2)
1359       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1360           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1361         return false;
1362   } else if (ShuffleKind == 1) {
1363     unsigned j = IsLE ? 0 : 2;
1364     for (unsigned i = 0; i != 8; i += 2)
1365       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1366           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1367           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1368           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1369         return false;
1370   }
1371   return true;
1372 }
1373 
1374 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1375 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1376 /// current subtarget.
1377 ///
1378 /// The ShuffleKind distinguishes between big-endian operations with
1379 /// two different inputs (0), either-endian operations with two identical
1380 /// inputs (1), and little-endian operations with two different inputs (2).
1381 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1382 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1383                                SelectionDAG &DAG) {
1384   const PPCSubtarget& Subtarget =
1385     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1386   if (!Subtarget.hasP8Vector())
1387     return false;
1388 
1389   bool IsLE = DAG.getDataLayout().isLittleEndian();
1390   if (ShuffleKind == 0) {
1391     if (IsLE)
1392       return false;
1393     for (unsigned i = 0; i != 16; i += 4)
1394       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1395           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1396           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1397           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1398         return false;
1399   } else if (ShuffleKind == 2) {
1400     if (!IsLE)
1401       return false;
1402     for (unsigned i = 0; i != 16; i += 4)
1403       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1404           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1405           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1406           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1407         return false;
1408   } else if (ShuffleKind == 1) {
1409     unsigned j = IsLE ? 0 : 4;
1410     for (unsigned i = 0; i != 8; i += 4)
1411       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1412           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1413           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1414           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1415           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1416           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1417           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1418           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1419         return false;
1420   }
1421   return true;
1422 }
1423 
1424 /// isVMerge - Common function, used to match vmrg* shuffles.
1425 ///
1426 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1427                      unsigned LHSStart, unsigned RHSStart) {
1428   if (N->getValueType(0) != MVT::v16i8)
1429     return false;
1430   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1431          "Unsupported merge size!");
1432 
1433   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1434     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1435       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1436                              LHSStart+j+i*UnitSize) ||
1437           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1438                              RHSStart+j+i*UnitSize))
1439         return false;
1440     }
1441   return true;
1442 }
1443 
1444 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1445 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1446 /// The ShuffleKind distinguishes between big-endian merges with two
1447 /// different inputs (0), either-endian merges with two identical inputs (1),
1448 /// and little-endian merges with two different inputs (2).  For the latter,
1449 /// the input operands are swapped (see PPCInstrAltivec.td).
1450 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1451                              unsigned ShuffleKind, SelectionDAG &DAG) {
1452   if (DAG.getDataLayout().isLittleEndian()) {
1453     if (ShuffleKind == 1) // unary
1454       return isVMerge(N, UnitSize, 0, 0);
1455     else if (ShuffleKind == 2) // swapped
1456       return isVMerge(N, UnitSize, 0, 16);
1457     else
1458       return false;
1459   } else {
1460     if (ShuffleKind == 1) // unary
1461       return isVMerge(N, UnitSize, 8, 8);
1462     else if (ShuffleKind == 0) // normal
1463       return isVMerge(N, UnitSize, 8, 24);
1464     else
1465       return false;
1466   }
1467 }
1468 
1469 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1470 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1471 /// The ShuffleKind distinguishes between big-endian merges with two
1472 /// different inputs (0), either-endian merges with two identical inputs (1),
1473 /// and little-endian merges with two different inputs (2).  For the latter,
1474 /// the input operands are swapped (see PPCInstrAltivec.td).
1475 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1476                              unsigned ShuffleKind, SelectionDAG &DAG) {
1477   if (DAG.getDataLayout().isLittleEndian()) {
1478     if (ShuffleKind == 1) // unary
1479       return isVMerge(N, UnitSize, 8, 8);
1480     else if (ShuffleKind == 2) // swapped
1481       return isVMerge(N, UnitSize, 8, 24);
1482     else
1483       return false;
1484   } else {
1485     if (ShuffleKind == 1) // unary
1486       return isVMerge(N, UnitSize, 0, 0);
1487     else if (ShuffleKind == 0) // normal
1488       return isVMerge(N, UnitSize, 0, 16);
1489     else
1490       return false;
1491   }
1492 }
1493 
1494 /**
1495  * Common function used to match vmrgew and vmrgow shuffles
1496  *
1497  * The indexOffset determines whether to look for even or odd words in
1498  * the shuffle mask. This is based on the of the endianness of the target
1499  * machine.
1500  *   - Little Endian:
1501  *     - Use offset of 0 to check for odd elements
1502  *     - Use offset of 4 to check for even elements
1503  *   - Big Endian:
1504  *     - Use offset of 0 to check for even elements
1505  *     - Use offset of 4 to check for odd elements
1506  * A detailed description of the vector element ordering for little endian and
1507  * big endian can be found at
1508  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1509  * Targeting your applications - what little endian and big endian IBM XL C/C++
1510  * compiler differences mean to you
1511  *
1512  * The mask to the shuffle vector instruction specifies the indices of the
1513  * elements from the two input vectors to place in the result. The elements are
1514  * numbered in array-access order, starting with the first vector. These vectors
1515  * are always of type v16i8, thus each vector will contain 16 elements of size
1516  * 8. More info on the shuffle vector can be found in the
1517  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1518  * Language Reference.
1519  *
1520  * The RHSStartValue indicates whether the same input vectors are used (unary)
1521  * or two different input vectors are used, based on the following:
1522  *   - If the instruction uses the same vector for both inputs, the range of the
1523  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1524  *     be 0.
1525  *   - If the instruction has two different vectors then the range of the
1526  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1527  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1528  *     to 31 specify elements in the second vector).
1529  *
1530  * \param[in] N The shuffle vector SD Node to analyze
1531  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1532  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1533  * vector to the shuffle_vector instruction
1534  * \return true iff this shuffle vector represents an even or odd word merge
1535  */
1536 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1537                      unsigned RHSStartValue) {
1538   if (N->getValueType(0) != MVT::v16i8)
1539     return false;
1540 
1541   for (unsigned i = 0; i < 2; ++i)
1542     for (unsigned j = 0; j < 4; ++j)
1543       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1544                              i*RHSStartValue+j+IndexOffset) ||
1545           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1546                              i*RHSStartValue+j+IndexOffset+8))
1547         return false;
1548   return true;
1549 }
1550 
1551 /**
1552  * Determine if the specified shuffle mask is suitable for the vmrgew or
1553  * vmrgow instructions.
1554  *
1555  * \param[in] N The shuffle vector SD Node to analyze
1556  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1557  * \param[in] ShuffleKind Identify the type of merge:
1558  *   - 0 = big-endian merge with two different inputs;
1559  *   - 1 = either-endian merge with two identical inputs;
1560  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1561  *     little-endian merges).
1562  * \param[in] DAG The current SelectionDAG
1563  * \return true iff this shuffle mask
1564  */
1565 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1566                               unsigned ShuffleKind, SelectionDAG &DAG) {
1567   if (DAG.getDataLayout().isLittleEndian()) {
1568     unsigned indexOffset = CheckEven ? 4 : 0;
1569     if (ShuffleKind == 1) // Unary
1570       return isVMerge(N, indexOffset, 0);
1571     else if (ShuffleKind == 2) // swapped
1572       return isVMerge(N, indexOffset, 16);
1573     else
1574       return false;
1575   }
1576   else {
1577     unsigned indexOffset = CheckEven ? 0 : 4;
1578     if (ShuffleKind == 1) // Unary
1579       return isVMerge(N, indexOffset, 0);
1580     else if (ShuffleKind == 0) // Normal
1581       return isVMerge(N, indexOffset, 16);
1582     else
1583       return false;
1584   }
1585   return false;
1586 }
1587 
1588 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1589 /// amount, otherwise return -1.
1590 /// The ShuffleKind distinguishes between big-endian operations with two
1591 /// different inputs (0), either-endian operations with two identical inputs
1592 /// (1), and little-endian operations with two different inputs (2).  For the
1593 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1594 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1595                              SelectionDAG &DAG) {
1596   if (N->getValueType(0) != MVT::v16i8)
1597     return -1;
1598 
1599   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1600 
1601   // Find the first non-undef value in the shuffle mask.
1602   unsigned i;
1603   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1604     /*search*/;
1605 
1606   if (i == 16) return -1;  // all undef.
1607 
1608   // Otherwise, check to see if the rest of the elements are consecutively
1609   // numbered from this value.
1610   unsigned ShiftAmt = SVOp->getMaskElt(i);
1611   if (ShiftAmt < i) return -1;
1612 
1613   ShiftAmt -= i;
1614   bool isLE = DAG.getDataLayout().isLittleEndian();
1615 
1616   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1617     // Check the rest of the elements to see if they are consecutive.
1618     for (++i; i != 16; ++i)
1619       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1620         return -1;
1621   } else if (ShuffleKind == 1) {
1622     // Check the rest of the elements to see if they are consecutive.
1623     for (++i; i != 16; ++i)
1624       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1625         return -1;
1626   } else
1627     return -1;
1628 
1629   if (isLE)
1630     ShiftAmt = 16 - ShiftAmt;
1631 
1632   return ShiftAmt;
1633 }
1634 
1635 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1636 /// specifies a splat of a single element that is suitable for input to
1637 /// VSPLTB/VSPLTH/VSPLTW.
1638 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1639   assert(N->getValueType(0) == MVT::v16i8 &&
1640          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1641 
1642   // The consecutive indices need to specify an element, not part of two
1643   // different elements.  So abandon ship early if this isn't the case.
1644   if (N->getMaskElt(0) % EltSize != 0)
1645     return false;
1646 
1647   // This is a splat operation if each element of the permute is the same, and
1648   // if the value doesn't reference the second vector.
1649   unsigned ElementBase = N->getMaskElt(0);
1650 
1651   // FIXME: Handle UNDEF elements too!
1652   if (ElementBase >= 16)
1653     return false;
1654 
1655   // Check that the indices are consecutive, in the case of a multi-byte element
1656   // splatted with a v16i8 mask.
1657   for (unsigned i = 1; i != EltSize; ++i)
1658     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1659       return false;
1660 
1661   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1662     if (N->getMaskElt(i) < 0) continue;
1663     for (unsigned j = 0; j != EltSize; ++j)
1664       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1665         return false;
1666   }
1667   return true;
1668 }
1669 
1670 /// Check that the mask is shuffling N byte elements. Within each N byte
1671 /// element of the mask, the indices could be either in increasing or
1672 /// decreasing order as long as they are consecutive.
1673 /// \param[in] N the shuffle vector SD Node to analyze
1674 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1675 /// Word/DoubleWord/QuadWord).
1676 /// \param[in] StepLen the delta indices number among the N byte element, if
1677 /// the mask is in increasing/decreasing order then it is 1/-1.
1678 /// \return true iff the mask is shuffling N byte elements.
1679 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1680                                    int StepLen) {
1681   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1682          "Unexpected element width.");
1683   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1684 
1685   unsigned NumOfElem = 16 / Width;
1686   unsigned MaskVal[16]; //  Width is never greater than 16
1687   for (unsigned i = 0; i < NumOfElem; ++i) {
1688     MaskVal[0] = N->getMaskElt(i * Width);
1689     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1690       return false;
1691     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1692       return false;
1693     }
1694 
1695     for (unsigned int j = 1; j < Width; ++j) {
1696       MaskVal[j] = N->getMaskElt(i * Width + j);
1697       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1698         return false;
1699       }
1700     }
1701   }
1702 
1703   return true;
1704 }
1705 
1706 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1707                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1708   if (!isNByteElemShuffleMask(N, 4, 1))
1709     return false;
1710 
1711   // Now we look at mask elements 0,4,8,12
1712   unsigned M0 = N->getMaskElt(0) / 4;
1713   unsigned M1 = N->getMaskElt(4) / 4;
1714   unsigned M2 = N->getMaskElt(8) / 4;
1715   unsigned M3 = N->getMaskElt(12) / 4;
1716   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1717   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1718 
1719   // Below, let H and L be arbitrary elements of the shuffle mask
1720   // where H is in the range [4,7] and L is in the range [0,3].
1721   // H, 1, 2, 3 or L, 5, 6, 7
1722   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1723       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1724     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1725     InsertAtByte = IsLE ? 12 : 0;
1726     Swap = M0 < 4;
1727     return true;
1728   }
1729   // 0, H, 2, 3 or 4, L, 6, 7
1730   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1731       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1732     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1733     InsertAtByte = IsLE ? 8 : 4;
1734     Swap = M1 < 4;
1735     return true;
1736   }
1737   // 0, 1, H, 3 or 4, 5, L, 7
1738   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1739       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1740     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1741     InsertAtByte = IsLE ? 4 : 8;
1742     Swap = M2 < 4;
1743     return true;
1744   }
1745   // 0, 1, 2, H or 4, 5, 6, L
1746   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1747       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1748     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1749     InsertAtByte = IsLE ? 0 : 12;
1750     Swap = M3 < 4;
1751     return true;
1752   }
1753 
1754   // If both vector operands for the shuffle are the same vector, the mask will
1755   // contain only elements from the first one and the second one will be undef.
1756   if (N->getOperand(1).isUndef()) {
1757     ShiftElts = 0;
1758     Swap = true;
1759     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1760     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1761       InsertAtByte = IsLE ? 12 : 0;
1762       return true;
1763     }
1764     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1765       InsertAtByte = IsLE ? 8 : 4;
1766       return true;
1767     }
1768     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1769       InsertAtByte = IsLE ? 4 : 8;
1770       return true;
1771     }
1772     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1773       InsertAtByte = IsLE ? 0 : 12;
1774       return true;
1775     }
1776   }
1777 
1778   return false;
1779 }
1780 
1781 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1782                                bool &Swap, bool IsLE) {
1783   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1784   // Ensure each byte index of the word is consecutive.
1785   if (!isNByteElemShuffleMask(N, 4, 1))
1786     return false;
1787 
1788   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1789   unsigned M0 = N->getMaskElt(0) / 4;
1790   unsigned M1 = N->getMaskElt(4) / 4;
1791   unsigned M2 = N->getMaskElt(8) / 4;
1792   unsigned M3 = N->getMaskElt(12) / 4;
1793 
1794   // If both vector operands for the shuffle are the same vector, the mask will
1795   // contain only elements from the first one and the second one will be undef.
1796   if (N->getOperand(1).isUndef()) {
1797     assert(M0 < 4 && "Indexing into an undef vector?");
1798     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1799       return false;
1800 
1801     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1802     Swap = false;
1803     return true;
1804   }
1805 
1806   // Ensure each word index of the ShuffleVector Mask is consecutive.
1807   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1808     return false;
1809 
1810   if (IsLE) {
1811     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1812       // Input vectors don't need to be swapped if the leading element
1813       // of the result is one of the 3 left elements of the second vector
1814       // (or if there is no shift to be done at all).
1815       Swap = false;
1816       ShiftElts = (8 - M0) % 8;
1817     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1818       // Input vectors need to be swapped if the leading element
1819       // of the result is one of the 3 left elements of the first vector
1820       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1821       Swap = true;
1822       ShiftElts = (4 - M0) % 4;
1823     }
1824 
1825     return true;
1826   } else {                                          // BE
1827     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1828       // Input vectors don't need to be swapped if the leading element
1829       // of the result is one of the 4 elements of the first vector.
1830       Swap = false;
1831       ShiftElts = M0;
1832     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1833       // Input vectors need to be swapped if the leading element
1834       // of the result is one of the 4 elements of the right vector.
1835       Swap = true;
1836       ShiftElts = M0 - 4;
1837     }
1838 
1839     return true;
1840   }
1841 }
1842 
1843 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1844   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1845 
1846   if (!isNByteElemShuffleMask(N, Width, -1))
1847     return false;
1848 
1849   for (int i = 0; i < 16; i += Width)
1850     if (N->getMaskElt(i) != i + Width - 1)
1851       return false;
1852 
1853   return true;
1854 }
1855 
1856 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1857   return isXXBRShuffleMaskHelper(N, 2);
1858 }
1859 
1860 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1861   return isXXBRShuffleMaskHelper(N, 4);
1862 }
1863 
1864 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1865   return isXXBRShuffleMaskHelper(N, 8);
1866 }
1867 
1868 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1869   return isXXBRShuffleMaskHelper(N, 16);
1870 }
1871 
1872 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1873 /// if the inputs to the instruction should be swapped and set \p DM to the
1874 /// value for the immediate.
1875 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1876 /// AND element 0 of the result comes from the first input (LE) or second input
1877 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1878 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1879 /// mask.
1880 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1881                                bool &Swap, bool IsLE) {
1882   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1883 
1884   // Ensure each byte index of the double word is consecutive.
1885   if (!isNByteElemShuffleMask(N, 8, 1))
1886     return false;
1887 
1888   unsigned M0 = N->getMaskElt(0) / 8;
1889   unsigned M1 = N->getMaskElt(8) / 8;
1890   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1891 
1892   // If both vector operands for the shuffle are the same vector, the mask will
1893   // contain only elements from the first one and the second one will be undef.
1894   if (N->getOperand(1).isUndef()) {
1895     if ((M0 | M1) < 2) {
1896       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1897       Swap = false;
1898       return true;
1899     } else
1900       return false;
1901   }
1902 
1903   if (IsLE) {
1904     if (M0 > 1 && M1 < 2) {
1905       Swap = false;
1906     } else if (M0 < 2 && M1 > 1) {
1907       M0 = (M0 + 2) % 4;
1908       M1 = (M1 + 2) % 4;
1909       Swap = true;
1910     } else
1911       return false;
1912 
1913     // Note: if control flow comes here that means Swap is already set above
1914     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
1915     return true;
1916   } else { // BE
1917     if (M0 < 2 && M1 > 1) {
1918       Swap = false;
1919     } else if (M0 > 1 && M1 < 2) {
1920       M0 = (M0 + 2) % 4;
1921       M1 = (M1 + 2) % 4;
1922       Swap = true;
1923     } else
1924       return false;
1925 
1926     // Note: if control flow comes here that means Swap is already set above
1927     DM = (M0 << 1) + (M1 & 1);
1928     return true;
1929   }
1930 }
1931 
1932 
1933 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1934 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1935 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1936                                 SelectionDAG &DAG) {
1937   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1938   assert(isSplatShuffleMask(SVOp, EltSize));
1939   if (DAG.getDataLayout().isLittleEndian())
1940     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1941   else
1942     return SVOp->getMaskElt(0) / EltSize;
1943 }
1944 
1945 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1946 /// by using a vspltis[bhw] instruction of the specified element size, return
1947 /// the constant being splatted.  The ByteSize field indicates the number of
1948 /// bytes of each element [124] -> [bhw].
1949 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1950   SDValue OpVal(nullptr, 0);
1951 
1952   // If ByteSize of the splat is bigger than the element size of the
1953   // build_vector, then we have a case where we are checking for a splat where
1954   // multiple elements of the buildvector are folded together into a single
1955   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1956   unsigned EltSize = 16/N->getNumOperands();
1957   if (EltSize < ByteSize) {
1958     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1959     SDValue UniquedVals[4];
1960     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1961 
1962     // See if all of the elements in the buildvector agree across.
1963     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1964       if (N->getOperand(i).isUndef()) continue;
1965       // If the element isn't a constant, bail fully out.
1966       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1967 
1968       if (!UniquedVals[i&(Multiple-1)].getNode())
1969         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1970       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1971         return SDValue();  // no match.
1972     }
1973 
1974     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1975     // either constant or undef values that are identical for each chunk.  See
1976     // if these chunks can form into a larger vspltis*.
1977 
1978     // Check to see if all of the leading entries are either 0 or -1.  If
1979     // neither, then this won't fit into the immediate field.
1980     bool LeadingZero = true;
1981     bool LeadingOnes = true;
1982     for (unsigned i = 0; i != Multiple-1; ++i) {
1983       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1984 
1985       LeadingZero &= isNullConstant(UniquedVals[i]);
1986       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1987     }
1988     // Finally, check the least significant entry.
1989     if (LeadingZero) {
1990       if (!UniquedVals[Multiple-1].getNode())
1991         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1992       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1993       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1994         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1995     }
1996     if (LeadingOnes) {
1997       if (!UniquedVals[Multiple-1].getNode())
1998         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1999       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
2000       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
2001         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
2002     }
2003 
2004     return SDValue();
2005   }
2006 
2007   // Check to see if this buildvec has a single non-undef value in its elements.
2008   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2009     if (N->getOperand(i).isUndef()) continue;
2010     if (!OpVal.getNode())
2011       OpVal = N->getOperand(i);
2012     else if (OpVal != N->getOperand(i))
2013       return SDValue();
2014   }
2015 
2016   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2017 
2018   unsigned ValSizeInBytes = EltSize;
2019   uint64_t Value = 0;
2020   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2021     Value = CN->getZExtValue();
2022   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2023     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2024     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2025   }
2026 
2027   // If the splat value is larger than the element value, then we can never do
2028   // this splat.  The only case that we could fit the replicated bits into our
2029   // immediate field for would be zero, and we prefer to use vxor for it.
2030   if (ValSizeInBytes < ByteSize) return SDValue();
2031 
2032   // If the element value is larger than the splat value, check if it consists
2033   // of a repeated bit pattern of size ByteSize.
2034   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2035     return SDValue();
2036 
2037   // Properly sign extend the value.
2038   int MaskVal = SignExtend32(Value, ByteSize * 8);
2039 
2040   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2041   if (MaskVal == 0) return SDValue();
2042 
2043   // Finally, if this value fits in a 5 bit sext field, return it
2044   if (SignExtend32<5>(MaskVal) == MaskVal)
2045     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2046   return SDValue();
2047 }
2048 
2049 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2050 /// amount, otherwise return -1.
2051 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2052   EVT VT = N->getValueType(0);
2053   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2054     return -1;
2055 
2056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2057 
2058   // Find the first non-undef value in the shuffle mask.
2059   unsigned i;
2060   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2061     /*search*/;
2062 
2063   if (i == 4) return -1;  // all undef.
2064 
2065   // Otherwise, check to see if the rest of the elements are consecutively
2066   // numbered from this value.
2067   unsigned ShiftAmt = SVOp->getMaskElt(i);
2068   if (ShiftAmt < i) return -1;
2069   ShiftAmt -= i;
2070 
2071   // Check the rest of the elements to see if they are consecutive.
2072   for (++i; i != 4; ++i)
2073     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2074       return -1;
2075 
2076   return ShiftAmt;
2077 }
2078 
2079 //===----------------------------------------------------------------------===//
2080 //  Addressing Mode Selection
2081 //===----------------------------------------------------------------------===//
2082 
2083 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2084 /// or 64-bit immediate, and if the value can be accurately represented as a
2085 /// sign extension from a 16-bit value.  If so, this returns true and the
2086 /// immediate.
2087 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2088   if (!isa<ConstantSDNode>(N))
2089     return false;
2090 
2091   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2092   if (N->getValueType(0) == MVT::i32)
2093     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2094   else
2095     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2096 }
2097 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2098   return isIntS16Immediate(Op.getNode(), Imm);
2099 }
2100 
2101 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2102 /// can be represented as an indexed [r+r] operation.  Returns false if it
2103 /// can be more efficiently represented with [r+imm].
2104 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2105                                             SDValue &Index,
2106                                             SelectionDAG &DAG) const {
2107   int16_t imm = 0;
2108   if (N.getOpcode() == ISD::ADD) {
2109     if (isIntS16Immediate(N.getOperand(1), imm))
2110       return false;    // r+i
2111     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2112       return false;    // r+i
2113 
2114     Base = N.getOperand(0);
2115     Index = N.getOperand(1);
2116     return true;
2117   } else if (N.getOpcode() == ISD::OR) {
2118     if (isIntS16Immediate(N.getOperand(1), imm))
2119       return false;    // r+i can fold it if we can.
2120 
2121     // If this is an or of disjoint bitfields, we can codegen this as an add
2122     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2123     // disjoint.
2124     KnownBits LHSKnown, RHSKnown;
2125     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2126 
2127     if (LHSKnown.Zero.getBoolValue()) {
2128       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2129       // If all of the bits are known zero on the LHS or RHS, the add won't
2130       // carry.
2131       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2132         Base = N.getOperand(0);
2133         Index = N.getOperand(1);
2134         return true;
2135       }
2136     }
2137   }
2138 
2139   return false;
2140 }
2141 
2142 // If we happen to be doing an i64 load or store into a stack slot that has
2143 // less than a 4-byte alignment, then the frame-index elimination may need to
2144 // use an indexed load or store instruction (because the offset may not be a
2145 // multiple of 4). The extra register needed to hold the offset comes from the
2146 // register scavenger, and it is possible that the scavenger will need to use
2147 // an emergency spill slot. As a result, we need to make sure that a spill slot
2148 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2149 // stack slot.
2150 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2151   // FIXME: This does not handle the LWA case.
2152   if (VT != MVT::i64)
2153     return;
2154 
2155   // NOTE: We'll exclude negative FIs here, which come from argument
2156   // lowering, because there are no known test cases triggering this problem
2157   // using packed structures (or similar). We can remove this exclusion if
2158   // we find such a test case. The reason why this is so test-case driven is
2159   // because this entire 'fixup' is only to prevent crashes (from the
2160   // register scavenger) on not-really-valid inputs. For example, if we have:
2161   //   %a = alloca i1
2162   //   %b = bitcast i1* %a to i64*
2163   //   store i64* a, i64 b
2164   // then the store should really be marked as 'align 1', but is not. If it
2165   // were marked as 'align 1' then the indexed form would have been
2166   // instruction-selected initially, and the problem this 'fixup' is preventing
2167   // won't happen regardless.
2168   if (FrameIdx < 0)
2169     return;
2170 
2171   MachineFunction &MF = DAG.getMachineFunction();
2172   MachineFrameInfo &MFI = MF.getFrameInfo();
2173 
2174   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2175   if (Align >= 4)
2176     return;
2177 
2178   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2179   FuncInfo->setHasNonRISpills();
2180 }
2181 
2182 /// Returns true if the address N can be represented by a base register plus
2183 /// a signed 16-bit displacement [r+imm], and if it is not better
2184 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2185 /// displacements that are multiples of that value.
2186 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2187                                             SDValue &Base,
2188                                             SelectionDAG &DAG,
2189                                             unsigned Alignment) const {
2190   // FIXME dl should come from parent load or store, not from address
2191   SDLoc dl(N);
2192   // If this can be more profitably realized as r+r, fail.
2193   if (SelectAddressRegReg(N, Disp, Base, DAG))
2194     return false;
2195 
2196   if (N.getOpcode() == ISD::ADD) {
2197     int16_t imm = 0;
2198     if (isIntS16Immediate(N.getOperand(1), imm) &&
2199         (!Alignment || (imm % Alignment) == 0)) {
2200       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2201       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2202         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2203         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2204       } else {
2205         Base = N.getOperand(0);
2206       }
2207       return true; // [r+i]
2208     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2209       // Match LOAD (ADD (X, Lo(G))).
2210       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2211              && "Cannot handle constant offsets yet!");
2212       Disp = N.getOperand(1).getOperand(0);  // The global address.
2213       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2214              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2215              Disp.getOpcode() == ISD::TargetConstantPool ||
2216              Disp.getOpcode() == ISD::TargetJumpTable);
2217       Base = N.getOperand(0);
2218       return true;  // [&g+r]
2219     }
2220   } else if (N.getOpcode() == ISD::OR) {
2221     int16_t imm = 0;
2222     if (isIntS16Immediate(N.getOperand(1), imm) &&
2223         (!Alignment || (imm % Alignment) == 0)) {
2224       // If this is an or of disjoint bitfields, we can codegen this as an add
2225       // (for better address arithmetic) if the LHS and RHS of the OR are
2226       // provably disjoint.
2227       KnownBits LHSKnown;
2228       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2229 
2230       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2231         // If all of the bits are known zero on the LHS or RHS, the add won't
2232         // carry.
2233         if (FrameIndexSDNode *FI =
2234               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2235           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2236           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2237         } else {
2238           Base = N.getOperand(0);
2239         }
2240         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2241         return true;
2242       }
2243     }
2244   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2245     // Loading from a constant address.
2246 
2247     // If this address fits entirely in a 16-bit sext immediate field, codegen
2248     // this as "d, 0"
2249     int16_t Imm;
2250     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2251       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2252       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2253                              CN->getValueType(0));
2254       return true;
2255     }
2256 
2257     // Handle 32-bit sext immediates with LIS + addr mode.
2258     if ((CN->getValueType(0) == MVT::i32 ||
2259          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2260         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2261       int Addr = (int)CN->getZExtValue();
2262 
2263       // Otherwise, break this down into an LIS + disp.
2264       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2265 
2266       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2267                                    MVT::i32);
2268       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2269       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2270       return true;
2271     }
2272   }
2273 
2274   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2275   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2276     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2277     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2278   } else
2279     Base = N;
2280   return true;      // [r+0]
2281 }
2282 
2283 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2284 /// represented as an indexed [r+r] operation.
2285 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2286                                                 SDValue &Index,
2287                                                 SelectionDAG &DAG) const {
2288   // Check to see if we can easily represent this as an [r+r] address.  This
2289   // will fail if it thinks that the address is more profitably represented as
2290   // reg+imm, e.g. where imm = 0.
2291   if (SelectAddressRegReg(N, Base, Index, DAG))
2292     return true;
2293 
2294   // If the address is the result of an add, we will utilize the fact that the
2295   // address calculation includes an implicit add.  However, we can reduce
2296   // register pressure if we do not materialize a constant just for use as the
2297   // index register.  We only get rid of the add if it is not an add of a
2298   // value and a 16-bit signed constant and both have a single use.
2299   int16_t imm = 0;
2300   if (N.getOpcode() == ISD::ADD &&
2301       (!isIntS16Immediate(N.getOperand(1), imm) ||
2302        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2303     Base = N.getOperand(0);
2304     Index = N.getOperand(1);
2305     return true;
2306   }
2307 
2308   // Otherwise, do it the hard way, using R0 as the base register.
2309   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2310                          N.getValueType());
2311   Index = N;
2312   return true;
2313 }
2314 
2315 /// getPreIndexedAddressParts - returns true by value, base pointer and
2316 /// offset pointer and addressing mode by reference if the node's address
2317 /// can be legally represented as pre-indexed load / store address.
2318 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2319                                                   SDValue &Offset,
2320                                                   ISD::MemIndexedMode &AM,
2321                                                   SelectionDAG &DAG) const {
2322   if (DisablePPCPreinc) return false;
2323 
2324   bool isLoad = true;
2325   SDValue Ptr;
2326   EVT VT;
2327   unsigned Alignment;
2328   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2329     Ptr = LD->getBasePtr();
2330     VT = LD->getMemoryVT();
2331     Alignment = LD->getAlignment();
2332   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2333     Ptr = ST->getBasePtr();
2334     VT  = ST->getMemoryVT();
2335     Alignment = ST->getAlignment();
2336     isLoad = false;
2337   } else
2338     return false;
2339 
2340   // PowerPC doesn't have preinc load/store instructions for vectors (except
2341   // for QPX, which does have preinc r+r forms).
2342   if (VT.isVector()) {
2343     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2344       return false;
2345     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2346       AM = ISD::PRE_INC;
2347       return true;
2348     }
2349   }
2350 
2351   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2352     // Common code will reject creating a pre-inc form if the base pointer
2353     // is a frame index, or if N is a store and the base pointer is either
2354     // the same as or a predecessor of the value being stored.  Check for
2355     // those situations here, and try with swapped Base/Offset instead.
2356     bool Swap = false;
2357 
2358     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2359       Swap = true;
2360     else if (!isLoad) {
2361       SDValue Val = cast<StoreSDNode>(N)->getValue();
2362       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2363         Swap = true;
2364     }
2365 
2366     if (Swap)
2367       std::swap(Base, Offset);
2368 
2369     AM = ISD::PRE_INC;
2370     return true;
2371   }
2372 
2373   // LDU/STU can only handle immediates that are a multiple of 4.
2374   if (VT != MVT::i64) {
2375     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2376       return false;
2377   } else {
2378     // LDU/STU need an address with at least 4-byte alignment.
2379     if (Alignment < 4)
2380       return false;
2381 
2382     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2383       return false;
2384   }
2385 
2386   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2387     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2388     // sext i32 to i64 when addr mode is r+i.
2389     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2390         LD->getExtensionType() == ISD::SEXTLOAD &&
2391         isa<ConstantSDNode>(Offset))
2392       return false;
2393   }
2394 
2395   AM = ISD::PRE_INC;
2396   return true;
2397 }
2398 
2399 //===----------------------------------------------------------------------===//
2400 //  LowerOperation implementation
2401 //===----------------------------------------------------------------------===//
2402 
2403 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2404 /// and LoOpFlags to the target MO flags.
2405 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2406                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2407                                const GlobalValue *GV = nullptr) {
2408   HiOpFlags = PPCII::MO_HA;
2409   LoOpFlags = PPCII::MO_LO;
2410 
2411   // Don't use the pic base if not in PIC relocation model.
2412   if (IsPIC) {
2413     HiOpFlags |= PPCII::MO_PIC_FLAG;
2414     LoOpFlags |= PPCII::MO_PIC_FLAG;
2415   }
2416 
2417   // If this is a reference to a global value that requires a non-lazy-ptr, make
2418   // sure that instruction lowering adds it.
2419   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2420     HiOpFlags |= PPCII::MO_NLP_FLAG;
2421     LoOpFlags |= PPCII::MO_NLP_FLAG;
2422 
2423     if (GV->hasHiddenVisibility()) {
2424       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2425       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2426     }
2427   }
2428 }
2429 
2430 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2431                              SelectionDAG &DAG) {
2432   SDLoc DL(HiPart);
2433   EVT PtrVT = HiPart.getValueType();
2434   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2435 
2436   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2437   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2438 
2439   // With PIC, the first instruction is actually "GR+hi(&G)".
2440   if (isPIC)
2441     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2442                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2443 
2444   // Generate non-pic code that has direct accesses to the constant pool.
2445   // The address of the global is just (hi(&g)+lo(&g)).
2446   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2447 }
2448 
2449 static void setUsesTOCBasePtr(MachineFunction &MF) {
2450   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2451   FuncInfo->setUsesTOCBasePtr();
2452 }
2453 
2454 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2455   setUsesTOCBasePtr(DAG.getMachineFunction());
2456 }
2457 
2458 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2459                            SDValue GA) {
2460   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2461   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2462                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2463 
2464   SDValue Ops[] = { GA, Reg };
2465   return DAG.getMemIntrinsicNode(
2466       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2467       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2468       MachineMemOperand::MOLoad);
2469 }
2470 
2471 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2472                                              SelectionDAG &DAG) const {
2473   EVT PtrVT = Op.getValueType();
2474   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2475   const Constant *C = CP->getConstVal();
2476 
2477   // 64-bit SVR4 ABI code is always position-independent.
2478   // The actual address of the GlobalValue is stored in the TOC.
2479   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2480     setUsesTOCBasePtr(DAG);
2481     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2482     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2483   }
2484 
2485   unsigned MOHiFlag, MOLoFlag;
2486   bool IsPIC = isPositionIndependent();
2487   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2488 
2489   if (IsPIC && Subtarget.isSVR4ABI()) {
2490     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2491                                            PPCII::MO_PIC_FLAG);
2492     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2493   }
2494 
2495   SDValue CPIHi =
2496     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2497   SDValue CPILo =
2498     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2499   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2500 }
2501 
2502 // For 64-bit PowerPC, prefer the more compact relative encodings.
2503 // This trades 32 bits per jump table entry for one or two instructions
2504 // on the jump site.
2505 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2506   if (isJumpTableRelative())
2507     return MachineJumpTableInfo::EK_LabelDifference32;
2508 
2509   return TargetLowering::getJumpTableEncoding();
2510 }
2511 
2512 bool PPCTargetLowering::isJumpTableRelative() const {
2513   if (Subtarget.isPPC64())
2514     return true;
2515   return TargetLowering::isJumpTableRelative();
2516 }
2517 
2518 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2519                                                     SelectionDAG &DAG) const {
2520   if (!Subtarget.isPPC64())
2521     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2522 
2523   switch (getTargetMachine().getCodeModel()) {
2524   case CodeModel::Small:
2525   case CodeModel::Medium:
2526     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2527   default:
2528     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2529                        getPointerTy(DAG.getDataLayout()));
2530   }
2531 }
2532 
2533 const MCExpr *
2534 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2535                                                 unsigned JTI,
2536                                                 MCContext &Ctx) const {
2537   if (!Subtarget.isPPC64())
2538     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2539 
2540   switch (getTargetMachine().getCodeModel()) {
2541   case CodeModel::Small:
2542   case CodeModel::Medium:
2543     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2544   default:
2545     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2546   }
2547 }
2548 
2549 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2550   EVT PtrVT = Op.getValueType();
2551   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2552 
2553   // 64-bit SVR4 ABI code is always position-independent.
2554   // The actual address of the GlobalValue is stored in the TOC.
2555   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2556     setUsesTOCBasePtr(DAG);
2557     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2558     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2559   }
2560 
2561   unsigned MOHiFlag, MOLoFlag;
2562   bool IsPIC = isPositionIndependent();
2563   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2564 
2565   if (IsPIC && Subtarget.isSVR4ABI()) {
2566     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2567                                         PPCII::MO_PIC_FLAG);
2568     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2569   }
2570 
2571   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2572   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2573   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2574 }
2575 
2576 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2577                                              SelectionDAG &DAG) const {
2578   EVT PtrVT = Op.getValueType();
2579   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2580   const BlockAddress *BA = BASDN->getBlockAddress();
2581 
2582   // 64-bit SVR4 ABI code is always position-independent.
2583   // The actual BlockAddress is stored in the TOC.
2584   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2585     setUsesTOCBasePtr(DAG);
2586     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2587     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2588   }
2589 
2590   unsigned MOHiFlag, MOLoFlag;
2591   bool IsPIC = isPositionIndependent();
2592   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2593   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2594   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2595   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2596 }
2597 
2598 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2599                                               SelectionDAG &DAG) const {
2600   // FIXME: TLS addresses currently use medium model code sequences,
2601   // which is the most useful form.  Eventually support for small and
2602   // large models could be added if users need it, at the cost of
2603   // additional complexity.
2604   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2605   if (DAG.getTarget().useEmulatedTLS())
2606     return LowerToTLSEmulatedModel(GA, DAG);
2607 
2608   SDLoc dl(GA);
2609   const GlobalValue *GV = GA->getGlobal();
2610   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2611   bool is64bit = Subtarget.isPPC64();
2612   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2613   PICLevel::Level picLevel = M->getPICLevel();
2614 
2615   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2616 
2617   if (Model == TLSModel::LocalExec) {
2618     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2619                                                PPCII::MO_TPREL_HA);
2620     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2621                                                PPCII::MO_TPREL_LO);
2622     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2623                              : DAG.getRegister(PPC::R2, MVT::i32);
2624 
2625     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2626     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2627   }
2628 
2629   if (Model == TLSModel::InitialExec) {
2630     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2631     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2632                                                 PPCII::MO_TLS);
2633     SDValue GOTPtr;
2634     if (is64bit) {
2635       setUsesTOCBasePtr(DAG);
2636       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2637       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2638                            PtrVT, GOTReg, TGA);
2639     } else
2640       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2641     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2642                                    PtrVT, TGA, GOTPtr);
2643     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2644   }
2645 
2646   if (Model == TLSModel::GeneralDynamic) {
2647     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2648     SDValue GOTPtr;
2649     if (is64bit) {
2650       setUsesTOCBasePtr(DAG);
2651       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2652       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2653                                    GOTReg, TGA);
2654     } else {
2655       if (picLevel == PICLevel::SmallPIC)
2656         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2657       else
2658         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2659     }
2660     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2661                        GOTPtr, TGA, TGA);
2662   }
2663 
2664   if (Model == TLSModel::LocalDynamic) {
2665     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2666     SDValue GOTPtr;
2667     if (is64bit) {
2668       setUsesTOCBasePtr(DAG);
2669       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2670       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2671                            GOTReg, TGA);
2672     } else {
2673       if (picLevel == PICLevel::SmallPIC)
2674         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2675       else
2676         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2677     }
2678     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2679                                   PtrVT, GOTPtr, TGA, TGA);
2680     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2681                                       PtrVT, TLSAddr, TGA);
2682     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2683   }
2684 
2685   llvm_unreachable("Unknown TLS model!");
2686 }
2687 
2688 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2689                                               SelectionDAG &DAG) const {
2690   EVT PtrVT = Op.getValueType();
2691   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2692   SDLoc DL(GSDN);
2693   const GlobalValue *GV = GSDN->getGlobal();
2694 
2695   // 64-bit SVR4 ABI code is always position-independent.
2696   // The actual address of the GlobalValue is stored in the TOC.
2697   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2698     setUsesTOCBasePtr(DAG);
2699     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2700     return getTOCEntry(DAG, DL, true, GA);
2701   }
2702 
2703   unsigned MOHiFlag, MOLoFlag;
2704   bool IsPIC = isPositionIndependent();
2705   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2706 
2707   if (IsPIC && Subtarget.isSVR4ABI()) {
2708     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2709                                             GSDN->getOffset(),
2710                                             PPCII::MO_PIC_FLAG);
2711     return getTOCEntry(DAG, DL, false, GA);
2712   }
2713 
2714   SDValue GAHi =
2715     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2716   SDValue GALo =
2717     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2718 
2719   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2720 
2721   // If the global reference is actually to a non-lazy-pointer, we have to do an
2722   // extra load to get the address of the global.
2723   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2724     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2725   return Ptr;
2726 }
2727 
2728 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2729   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2730   SDLoc dl(Op);
2731 
2732   if (Op.getValueType() == MVT::v2i64) {
2733     // When the operands themselves are v2i64 values, we need to do something
2734     // special because VSX has no underlying comparison operations for these.
2735     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2736       // Equality can be handled by casting to the legal type for Altivec
2737       // comparisons, everything else needs to be expanded.
2738       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2739         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2740                  DAG.getSetCC(dl, MVT::v4i32,
2741                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2742                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2743                    CC));
2744       }
2745 
2746       return SDValue();
2747     }
2748 
2749     // We handle most of these in the usual way.
2750     return Op;
2751   }
2752 
2753   // If we're comparing for equality to zero, expose the fact that this is
2754   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2755   // fold the new nodes.
2756   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2757     return V;
2758 
2759   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2760     // Leave comparisons against 0 and -1 alone for now, since they're usually
2761     // optimized.  FIXME: revisit this when we can custom lower all setcc
2762     // optimizations.
2763     if (C->isAllOnesValue() || C->isNullValue())
2764       return SDValue();
2765   }
2766 
2767   // If we have an integer seteq/setne, turn it into a compare against zero
2768   // by xor'ing the rhs with the lhs, which is faster than setting a
2769   // condition register, reading it back out, and masking the correct bit.  The
2770   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2771   // the result to other bit-twiddling opportunities.
2772   EVT LHSVT = Op.getOperand(0).getValueType();
2773   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2774     EVT VT = Op.getValueType();
2775     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2776                                 Op.getOperand(1));
2777     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2778   }
2779   return SDValue();
2780 }
2781 
2782 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2783   SDNode *Node = Op.getNode();
2784   EVT VT = Node->getValueType(0);
2785   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2786   SDValue InChain = Node->getOperand(0);
2787   SDValue VAListPtr = Node->getOperand(1);
2788   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2789   SDLoc dl(Node);
2790 
2791   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2792 
2793   // gpr_index
2794   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2795                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2796   InChain = GprIndex.getValue(1);
2797 
2798   if (VT == MVT::i64) {
2799     // Check if GprIndex is even
2800     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2801                                  DAG.getConstant(1, dl, MVT::i32));
2802     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2803                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2804     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2805                                           DAG.getConstant(1, dl, MVT::i32));
2806     // Align GprIndex to be even if it isn't
2807     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2808                            GprIndex);
2809   }
2810 
2811   // fpr index is 1 byte after gpr
2812   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2813                                DAG.getConstant(1, dl, MVT::i32));
2814 
2815   // fpr
2816   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2817                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2818   InChain = FprIndex.getValue(1);
2819 
2820   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2821                                        DAG.getConstant(8, dl, MVT::i32));
2822 
2823   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2824                                         DAG.getConstant(4, dl, MVT::i32));
2825 
2826   // areas
2827   SDValue OverflowArea =
2828       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2829   InChain = OverflowArea.getValue(1);
2830 
2831   SDValue RegSaveArea =
2832       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2833   InChain = RegSaveArea.getValue(1);
2834 
2835   // select overflow_area if index > 8
2836   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2837                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2838 
2839   // adjustment constant gpr_index * 4/8
2840   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2841                                     VT.isInteger() ? GprIndex : FprIndex,
2842                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2843                                                     MVT::i32));
2844 
2845   // OurReg = RegSaveArea + RegConstant
2846   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2847                                RegConstant);
2848 
2849   // Floating types are 32 bytes into RegSaveArea
2850   if (VT.isFloatingPoint())
2851     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2852                          DAG.getConstant(32, dl, MVT::i32));
2853 
2854   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2855   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2856                                    VT.isInteger() ? GprIndex : FprIndex,
2857                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2858                                                    MVT::i32));
2859 
2860   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2861                               VT.isInteger() ? VAListPtr : FprPtr,
2862                               MachinePointerInfo(SV), MVT::i8);
2863 
2864   // determine if we should load from reg_save_area or overflow_area
2865   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2866 
2867   // increase overflow_area by 4/8 if gpr/fpr > 8
2868   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2869                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2870                                           dl, MVT::i32));
2871 
2872   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2873                              OverflowAreaPlusN);
2874 
2875   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2876                               MachinePointerInfo(), MVT::i32);
2877 
2878   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2879 }
2880 
2881 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2882   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2883 
2884   // We have to copy the entire va_list struct:
2885   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2886   return DAG.getMemcpy(Op.getOperand(0), Op,
2887                        Op.getOperand(1), Op.getOperand(2),
2888                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2889                        false, MachinePointerInfo(), MachinePointerInfo());
2890 }
2891 
2892 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2893                                                   SelectionDAG &DAG) const {
2894   return Op.getOperand(0);
2895 }
2896 
2897 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2898                                                 SelectionDAG &DAG) const {
2899   SDValue Chain = Op.getOperand(0);
2900   SDValue Trmp = Op.getOperand(1); // trampoline
2901   SDValue FPtr = Op.getOperand(2); // nested function
2902   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2903   SDLoc dl(Op);
2904 
2905   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2906   bool isPPC64 = (PtrVT == MVT::i64);
2907   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2908 
2909   TargetLowering::ArgListTy Args;
2910   TargetLowering::ArgListEntry Entry;
2911 
2912   Entry.Ty = IntPtrTy;
2913   Entry.Node = Trmp; Args.push_back(Entry);
2914 
2915   // TrampSize == (isPPC64 ? 48 : 40);
2916   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2917                                isPPC64 ? MVT::i64 : MVT::i32);
2918   Args.push_back(Entry);
2919 
2920   Entry.Node = FPtr; Args.push_back(Entry);
2921   Entry.Node = Nest; Args.push_back(Entry);
2922 
2923   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2924   TargetLowering::CallLoweringInfo CLI(DAG);
2925   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2926       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2927       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2928 
2929   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2930   return CallResult.second;
2931 }
2932 
2933 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2934   MachineFunction &MF = DAG.getMachineFunction();
2935   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2936   EVT PtrVT = getPointerTy(MF.getDataLayout());
2937 
2938   SDLoc dl(Op);
2939 
2940   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2941     // vastart just stores the address of the VarArgsFrameIndex slot into the
2942     // memory location argument.
2943     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2944     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2945     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2946                         MachinePointerInfo(SV));
2947   }
2948 
2949   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2950   // We suppose the given va_list is already allocated.
2951   //
2952   // typedef struct {
2953   //  char gpr;     /* index into the array of 8 GPRs
2954   //                 * stored in the register save area
2955   //                 * gpr=0 corresponds to r3,
2956   //                 * gpr=1 to r4, etc.
2957   //                 */
2958   //  char fpr;     /* index into the array of 8 FPRs
2959   //                 * stored in the register save area
2960   //                 * fpr=0 corresponds to f1,
2961   //                 * fpr=1 to f2, etc.
2962   //                 */
2963   //  char *overflow_arg_area;
2964   //                /* location on stack that holds
2965   //                 * the next overflow argument
2966   //                 */
2967   //  char *reg_save_area;
2968   //               /* where r3:r10 and f1:f8 (if saved)
2969   //                * are stored
2970   //                */
2971   // } va_list[1];
2972 
2973   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2974   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2975   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2976                                             PtrVT);
2977   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2978                                  PtrVT);
2979 
2980   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2981   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2982 
2983   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2984   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2985 
2986   uint64_t FPROffset = 1;
2987   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2988 
2989   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2990 
2991   // Store first byte : number of int regs
2992   SDValue firstStore =
2993       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2994                         MachinePointerInfo(SV), MVT::i8);
2995   uint64_t nextOffset = FPROffset;
2996   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2997                                   ConstFPROffset);
2998 
2999   // Store second byte : number of float regs
3000   SDValue secondStore =
3001       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
3002                         MachinePointerInfo(SV, nextOffset), MVT::i8);
3003   nextOffset += StackOffset;
3004   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
3005 
3006   // Store second word : arguments given on stack
3007   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
3008                                     MachinePointerInfo(SV, nextOffset));
3009   nextOffset += FrameOffset;
3010   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3011 
3012   // Store third word : arguments given in registers
3013   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3014                       MachinePointerInfo(SV, nextOffset));
3015 }
3016 
3017 #include "PPCGenCallingConv.inc"
3018 
3019 // Function whose sole purpose is to kill compiler warnings
3020 // stemming from unused functions included from PPCGenCallingConv.inc.
3021 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3022   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3023 }
3024 
3025 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3026                                       CCValAssign::LocInfo &LocInfo,
3027                                       ISD::ArgFlagsTy &ArgFlags,
3028                                       CCState &State) {
3029   return true;
3030 }
3031 
3032 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3033                                              MVT &LocVT,
3034                                              CCValAssign::LocInfo &LocInfo,
3035                                              ISD::ArgFlagsTy &ArgFlags,
3036                                              CCState &State) {
3037   static const MCPhysReg ArgRegs[] = {
3038     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3039     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3040   };
3041   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3042 
3043   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3044 
3045   // Skip one register if the first unallocated register has an even register
3046   // number and there are still argument registers available which have not been
3047   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3048   // need to skip a register if RegNum is odd.
3049   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3050     State.AllocateReg(ArgRegs[RegNum]);
3051   }
3052 
3053   // Always return false here, as this function only makes sure that the first
3054   // unallocated register has an odd register number and does not actually
3055   // allocate a register for the current argument.
3056   return false;
3057 }
3058 
3059 bool
3060 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3061                                                   MVT &LocVT,
3062                                                   CCValAssign::LocInfo &LocInfo,
3063                                                   ISD::ArgFlagsTy &ArgFlags,
3064                                                   CCState &State) {
3065   static const MCPhysReg ArgRegs[] = {
3066     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3067     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3068   };
3069   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3070 
3071   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3072   int RegsLeft = NumArgRegs - RegNum;
3073 
3074   // Skip if there is not enough registers left for long double type (4 gpr regs
3075   // in soft float mode) and put long double argument on the stack.
3076   if (RegNum != NumArgRegs && RegsLeft < 4) {
3077     for (int i = 0; i < RegsLeft; i++) {
3078       State.AllocateReg(ArgRegs[RegNum + i]);
3079     }
3080   }
3081 
3082   return false;
3083 }
3084 
3085 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3086                                                MVT &LocVT,
3087                                                CCValAssign::LocInfo &LocInfo,
3088                                                ISD::ArgFlagsTy &ArgFlags,
3089                                                CCState &State) {
3090   static const MCPhysReg ArgRegs[] = {
3091     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3092     PPC::F8
3093   };
3094 
3095   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3096 
3097   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3098 
3099   // If there is only one Floating-point register left we need to put both f64
3100   // values of a split ppc_fp128 value on the stack.
3101   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3102     State.AllocateReg(ArgRegs[RegNum]);
3103   }
3104 
3105   // Always return false here, as this function only makes sure that the two f64
3106   // values a ppc_fp128 value is split into are both passed in registers or both
3107   // passed on the stack and does not actually allocate a register for the
3108   // current argument.
3109   return false;
3110 }
3111 
3112 /// FPR - The set of FP registers that should be allocated for arguments,
3113 /// on Darwin.
3114 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3115                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3116                                 PPC::F11, PPC::F12, PPC::F13};
3117 
3118 /// QFPR - The set of QPX registers that should be allocated for arguments.
3119 static const MCPhysReg QFPR[] = {
3120     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3121     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3122 
3123 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3124 /// the stack.
3125 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3126                                        unsigned PtrByteSize) {
3127   unsigned ArgSize = ArgVT.getStoreSize();
3128   if (Flags.isByVal())
3129     ArgSize = Flags.getByValSize();
3130 
3131   // Round up to multiples of the pointer size, except for array members,
3132   // which are always packed.
3133   if (!Flags.isInConsecutiveRegs())
3134     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3135 
3136   return ArgSize;
3137 }
3138 
3139 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3140 /// on the stack.
3141 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3142                                             ISD::ArgFlagsTy Flags,
3143                                             unsigned PtrByteSize) {
3144   unsigned Align = PtrByteSize;
3145 
3146   // Altivec parameters are padded to a 16 byte boundary.
3147   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3148       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3149       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3150       ArgVT == MVT::v1i128)
3151     Align = 16;
3152   // QPX vector types stored in double-precision are padded to a 32 byte
3153   // boundary.
3154   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3155     Align = 32;
3156 
3157   // ByVal parameters are aligned as requested.
3158   if (Flags.isByVal()) {
3159     unsigned BVAlign = Flags.getByValAlign();
3160     if (BVAlign > PtrByteSize) {
3161       if (BVAlign % PtrByteSize != 0)
3162           llvm_unreachable(
3163             "ByVal alignment is not a multiple of the pointer size");
3164 
3165       Align = BVAlign;
3166     }
3167   }
3168 
3169   // Array members are always packed to their original alignment.
3170   if (Flags.isInConsecutiveRegs()) {
3171     // If the array member was split into multiple registers, the first
3172     // needs to be aligned to the size of the full type.  (Except for
3173     // ppcf128, which is only aligned as its f64 components.)
3174     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3175       Align = OrigVT.getStoreSize();
3176     else
3177       Align = ArgVT.getStoreSize();
3178   }
3179 
3180   return Align;
3181 }
3182 
3183 /// CalculateStackSlotUsed - Return whether this argument will use its
3184 /// stack slot (instead of being passed in registers).  ArgOffset,
3185 /// AvailableFPRs, and AvailableVRs must hold the current argument
3186 /// position, and will be updated to account for this argument.
3187 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3188                                    ISD::ArgFlagsTy Flags,
3189                                    unsigned PtrByteSize,
3190                                    unsigned LinkageSize,
3191                                    unsigned ParamAreaSize,
3192                                    unsigned &ArgOffset,
3193                                    unsigned &AvailableFPRs,
3194                                    unsigned &AvailableVRs, bool HasQPX) {
3195   bool UseMemory = false;
3196 
3197   // Respect alignment of argument on the stack.
3198   unsigned Align =
3199     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3200   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3201   // If there's no space left in the argument save area, we must
3202   // use memory (this check also catches zero-sized arguments).
3203   if (ArgOffset >= LinkageSize + ParamAreaSize)
3204     UseMemory = true;
3205 
3206   // Allocate argument on the stack.
3207   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3208   if (Flags.isInConsecutiveRegsLast())
3209     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3210   // If we overran the argument save area, we must use memory
3211   // (this check catches arguments passed partially in memory)
3212   if (ArgOffset > LinkageSize + ParamAreaSize)
3213     UseMemory = true;
3214 
3215   // However, if the argument is actually passed in an FPR or a VR,
3216   // we don't use memory after all.
3217   if (!Flags.isByVal()) {
3218     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3219         // QPX registers overlap with the scalar FP registers.
3220         (HasQPX && (ArgVT == MVT::v4f32 ||
3221                     ArgVT == MVT::v4f64 ||
3222                     ArgVT == MVT::v4i1)))
3223       if (AvailableFPRs > 0) {
3224         --AvailableFPRs;
3225         return false;
3226       }
3227     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3228         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3229         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3230         ArgVT == MVT::v1i128)
3231       if (AvailableVRs > 0) {
3232         --AvailableVRs;
3233         return false;
3234       }
3235   }
3236 
3237   return UseMemory;
3238 }
3239 
3240 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3241 /// ensure minimum alignment required for target.
3242 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3243                                      unsigned NumBytes) {
3244   unsigned TargetAlign = Lowering->getStackAlignment();
3245   unsigned AlignMask = TargetAlign - 1;
3246   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3247   return NumBytes;
3248 }
3249 
3250 SDValue PPCTargetLowering::LowerFormalArguments(
3251     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3252     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3253     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3254   if (Subtarget.isSVR4ABI()) {
3255     if (Subtarget.isPPC64())
3256       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3257                                          dl, DAG, InVals);
3258     else
3259       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3260                                          dl, DAG, InVals);
3261   } else {
3262     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3263                                        dl, DAG, InVals);
3264   }
3265 }
3266 
3267 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3268     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3269     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3270     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3271 
3272   // 32-bit SVR4 ABI Stack Frame Layout:
3273   //              +-----------------------------------+
3274   //        +-->  |            Back chain             |
3275   //        |     +-----------------------------------+
3276   //        |     | Floating-point register save area |
3277   //        |     +-----------------------------------+
3278   //        |     |    General register save area     |
3279   //        |     +-----------------------------------+
3280   //        |     |          CR save word             |
3281   //        |     +-----------------------------------+
3282   //        |     |         VRSAVE save word          |
3283   //        |     +-----------------------------------+
3284   //        |     |         Alignment padding         |
3285   //        |     +-----------------------------------+
3286   //        |     |     Vector register save area     |
3287   //        |     +-----------------------------------+
3288   //        |     |       Local variable space        |
3289   //        |     +-----------------------------------+
3290   //        |     |        Parameter list area        |
3291   //        |     +-----------------------------------+
3292   //        |     |           LR save word            |
3293   //        |     +-----------------------------------+
3294   // SP-->  +---  |            Back chain             |
3295   //              +-----------------------------------+
3296   //
3297   // Specifications:
3298   //   System V Application Binary Interface PowerPC Processor Supplement
3299   //   AltiVec Technology Programming Interface Manual
3300 
3301   MachineFunction &MF = DAG.getMachineFunction();
3302   MachineFrameInfo &MFI = MF.getFrameInfo();
3303   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3304 
3305   EVT PtrVT = getPointerTy(MF.getDataLayout());
3306   // Potential tail calls could cause overwriting of argument stack slots.
3307   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3308                        (CallConv == CallingConv::Fast));
3309   unsigned PtrByteSize = 4;
3310 
3311   // Assign locations to all of the incoming arguments.
3312   SmallVector<CCValAssign, 16> ArgLocs;
3313   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3314                  *DAG.getContext());
3315 
3316   // Reserve space for the linkage area on the stack.
3317   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3318   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3319   if (useSoftFloat())
3320     CCInfo.PreAnalyzeFormalArguments(Ins);
3321 
3322   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3323   CCInfo.clearWasPPCF128();
3324 
3325   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3326     CCValAssign &VA = ArgLocs[i];
3327 
3328     // Arguments stored in registers.
3329     if (VA.isRegLoc()) {
3330       const TargetRegisterClass *RC;
3331       EVT ValVT = VA.getValVT();
3332 
3333       switch (ValVT.getSimpleVT().SimpleTy) {
3334         default:
3335           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3336         case MVT::i1:
3337         case MVT::i32:
3338           RC = &PPC::GPRCRegClass;
3339           break;
3340         case MVT::f32:
3341           if (Subtarget.hasP8Vector())
3342             RC = &PPC::VSSRCRegClass;
3343           else
3344             RC = &PPC::F4RCRegClass;
3345           break;
3346         case MVT::f64:
3347           if (Subtarget.hasVSX())
3348             RC = &PPC::VSFRCRegClass;
3349           else
3350             RC = &PPC::F8RCRegClass;
3351           break;
3352         case MVT::v16i8:
3353         case MVT::v8i16:
3354         case MVT::v4i32:
3355           RC = &PPC::VRRCRegClass;
3356           break;
3357         case MVT::v4f32:
3358           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3359           break;
3360         case MVT::v2f64:
3361         case MVT::v2i64:
3362           RC = &PPC::VRRCRegClass;
3363           break;
3364         case MVT::v4f64:
3365           RC = &PPC::QFRCRegClass;
3366           break;
3367         case MVT::v4i1:
3368           RC = &PPC::QBRCRegClass;
3369           break;
3370       }
3371 
3372       // Transform the arguments stored in physical registers into virtual ones.
3373       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3374       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3375                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3376 
3377       if (ValVT == MVT::i1)
3378         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3379 
3380       InVals.push_back(ArgValue);
3381     } else {
3382       // Argument stored in memory.
3383       assert(VA.isMemLoc());
3384 
3385       unsigned ArgSize = VA.getLocVT().getStoreSize();
3386       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3387                                      isImmutable);
3388 
3389       // Create load nodes to retrieve arguments from the stack.
3390       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3391       InVals.push_back(
3392           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3393     }
3394   }
3395 
3396   // Assign locations to all of the incoming aggregate by value arguments.
3397   // Aggregates passed by value are stored in the local variable space of the
3398   // caller's stack frame, right above the parameter list area.
3399   SmallVector<CCValAssign, 16> ByValArgLocs;
3400   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3401                       ByValArgLocs, *DAG.getContext());
3402 
3403   // Reserve stack space for the allocations in CCInfo.
3404   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3405 
3406   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3407 
3408   // Area that is at least reserved in the caller of this function.
3409   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3410   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3411 
3412   // Set the size that is at least reserved in caller of this function.  Tail
3413   // call optimized function's reserved stack space needs to be aligned so that
3414   // taking the difference between two stack areas will result in an aligned
3415   // stack.
3416   MinReservedArea =
3417       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3418   FuncInfo->setMinReservedArea(MinReservedArea);
3419 
3420   SmallVector<SDValue, 8> MemOps;
3421 
3422   // If the function takes variable number of arguments, make a frame index for
3423   // the start of the first vararg value... for expansion of llvm.va_start.
3424   if (isVarArg) {
3425     static const MCPhysReg GPArgRegs[] = {
3426       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3427       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3428     };
3429     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3430 
3431     static const MCPhysReg FPArgRegs[] = {
3432       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3433       PPC::F8
3434     };
3435     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3436 
3437     if (useSoftFloat())
3438        NumFPArgRegs = 0;
3439 
3440     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3441     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3442 
3443     // Make room for NumGPArgRegs and NumFPArgRegs.
3444     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3445                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3446 
3447     FuncInfo->setVarArgsStackOffset(
3448       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3449                             CCInfo.getNextStackOffset(), true));
3450 
3451     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3452     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3453 
3454     // The fixed integer arguments of a variadic function are stored to the
3455     // VarArgsFrameIndex on the stack so that they may be loaded by
3456     // dereferencing the result of va_next.
3457     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3458       // Get an existing live-in vreg, or add a new one.
3459       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3460       if (!VReg)
3461         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3462 
3463       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3464       SDValue Store =
3465           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3466       MemOps.push_back(Store);
3467       // Increment the address by four for the next argument to store
3468       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3469       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3470     }
3471 
3472     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3473     // is set.
3474     // The double arguments are stored to the VarArgsFrameIndex
3475     // on the stack.
3476     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3477       // Get an existing live-in vreg, or add a new one.
3478       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3479       if (!VReg)
3480         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3481 
3482       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3483       SDValue Store =
3484           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3485       MemOps.push_back(Store);
3486       // Increment the address by eight for the next argument to store
3487       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3488                                          PtrVT);
3489       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3490     }
3491   }
3492 
3493   if (!MemOps.empty())
3494     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3495 
3496   return Chain;
3497 }
3498 
3499 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3500 // value to MVT::i64 and then truncate to the correct register size.
3501 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3502                                              EVT ObjectVT, SelectionDAG &DAG,
3503                                              SDValue ArgVal,
3504                                              const SDLoc &dl) const {
3505   if (Flags.isSExt())
3506     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3507                          DAG.getValueType(ObjectVT));
3508   else if (Flags.isZExt())
3509     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3510                          DAG.getValueType(ObjectVT));
3511 
3512   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3513 }
3514 
3515 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3516     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3517     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3518     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3519   // TODO: add description of PPC stack frame format, or at least some docs.
3520   //
3521   bool isELFv2ABI = Subtarget.isELFv2ABI();
3522   bool isLittleEndian = Subtarget.isLittleEndian();
3523   MachineFunction &MF = DAG.getMachineFunction();
3524   MachineFrameInfo &MFI = MF.getFrameInfo();
3525   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3526 
3527   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3528          "fastcc not supported on varargs functions");
3529 
3530   EVT PtrVT = getPointerTy(MF.getDataLayout());
3531   // Potential tail calls could cause overwriting of argument stack slots.
3532   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3533                        (CallConv == CallingConv::Fast));
3534   unsigned PtrByteSize = 8;
3535   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3536 
3537   static const MCPhysReg GPR[] = {
3538     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3539     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3540   };
3541   static const MCPhysReg VR[] = {
3542     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3543     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3544   };
3545 
3546   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3547   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3548   const unsigned Num_VR_Regs  = array_lengthof(VR);
3549   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3550 
3551   // Do a first pass over the arguments to determine whether the ABI
3552   // guarantees that our caller has allocated the parameter save area
3553   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3554   // in the ELFv2 ABI, it is true if this is a vararg function or if
3555   // any parameter is located in a stack slot.
3556 
3557   bool HasParameterArea = !isELFv2ABI || isVarArg;
3558   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3559   unsigned NumBytes = LinkageSize;
3560   unsigned AvailableFPRs = Num_FPR_Regs;
3561   unsigned AvailableVRs = Num_VR_Regs;
3562   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3563     if (Ins[i].Flags.isNest())
3564       continue;
3565 
3566     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3567                                PtrByteSize, LinkageSize, ParamAreaSize,
3568                                NumBytes, AvailableFPRs, AvailableVRs,
3569                                Subtarget.hasQPX()))
3570       HasParameterArea = true;
3571   }
3572 
3573   // Add DAG nodes to load the arguments or copy them out of registers.  On
3574   // entry to a function on PPC, the arguments start after the linkage area,
3575   // although the first ones are often in registers.
3576 
3577   unsigned ArgOffset = LinkageSize;
3578   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3579   unsigned &QFPR_idx = FPR_idx;
3580   SmallVector<SDValue, 8> MemOps;
3581   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3582   unsigned CurArgIdx = 0;
3583   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3584     SDValue ArgVal;
3585     bool needsLoad = false;
3586     EVT ObjectVT = Ins[ArgNo].VT;
3587     EVT OrigVT = Ins[ArgNo].ArgVT;
3588     unsigned ObjSize = ObjectVT.getStoreSize();
3589     unsigned ArgSize = ObjSize;
3590     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3591     if (Ins[ArgNo].isOrigArg()) {
3592       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3593       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3594     }
3595     // We re-align the argument offset for each argument, except when using the
3596     // fast calling convention, when we need to make sure we do that only when
3597     // we'll actually use a stack slot.
3598     unsigned CurArgOffset, Align;
3599     auto ComputeArgOffset = [&]() {
3600       /* Respect alignment of argument on the stack.  */
3601       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3602       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3603       CurArgOffset = ArgOffset;
3604     };
3605 
3606     if (CallConv != CallingConv::Fast) {
3607       ComputeArgOffset();
3608 
3609       /* Compute GPR index associated with argument offset.  */
3610       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3611       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3612     }
3613 
3614     // FIXME the codegen can be much improved in some cases.
3615     // We do not have to keep everything in memory.
3616     if (Flags.isByVal()) {
3617       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3618 
3619       if (CallConv == CallingConv::Fast)
3620         ComputeArgOffset();
3621 
3622       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3623       ObjSize = Flags.getByValSize();
3624       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3625       // Empty aggregate parameters do not take up registers.  Examples:
3626       //   struct { } a;
3627       //   union  { } b;
3628       //   int c[0];
3629       // etc.  However, we have to provide a place-holder in InVals, so
3630       // pretend we have an 8-byte item at the current address for that
3631       // purpose.
3632       if (!ObjSize) {
3633         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3634         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3635         InVals.push_back(FIN);
3636         continue;
3637       }
3638 
3639       // Create a stack object covering all stack doublewords occupied
3640       // by the argument.  If the argument is (fully or partially) on
3641       // the stack, or if the argument is fully in registers but the
3642       // caller has allocated the parameter save anyway, we can refer
3643       // directly to the caller's stack frame.  Otherwise, create a
3644       // local copy in our own frame.
3645       int FI;
3646       if (HasParameterArea ||
3647           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3648         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3649       else
3650         FI = MFI.CreateStackObject(ArgSize, Align, false);
3651       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3652 
3653       // Handle aggregates smaller than 8 bytes.
3654       if (ObjSize < PtrByteSize) {
3655         // The value of the object is its address, which differs from the
3656         // address of the enclosing doubleword on big-endian systems.
3657         SDValue Arg = FIN;
3658         if (!isLittleEndian) {
3659           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3660           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3661         }
3662         InVals.push_back(Arg);
3663 
3664         if (GPR_idx != Num_GPR_Regs) {
3665           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3666           FuncInfo->addLiveInAttr(VReg, Flags);
3667           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3668           SDValue Store;
3669 
3670           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3671             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3672                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3673             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3674                                       MachinePointerInfo(&*FuncArg), ObjType);
3675           } else {
3676             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3677             // store the whole register as-is to the parameter save area
3678             // slot.
3679             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3680                                  MachinePointerInfo(&*FuncArg));
3681           }
3682 
3683           MemOps.push_back(Store);
3684         }
3685         // Whether we copied from a register or not, advance the offset
3686         // into the parameter save area by a full doubleword.
3687         ArgOffset += PtrByteSize;
3688         continue;
3689       }
3690 
3691       // The value of the object is its address, which is the address of
3692       // its first stack doubleword.
3693       InVals.push_back(FIN);
3694 
3695       // Store whatever pieces of the object are in registers to memory.
3696       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3697         if (GPR_idx == Num_GPR_Regs)
3698           break;
3699 
3700         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3701         FuncInfo->addLiveInAttr(VReg, Flags);
3702         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3703         SDValue Addr = FIN;
3704         if (j) {
3705           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3706           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3707         }
3708         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3709                                      MachinePointerInfo(&*FuncArg, j));
3710         MemOps.push_back(Store);
3711         ++GPR_idx;
3712       }
3713       ArgOffset += ArgSize;
3714       continue;
3715     }
3716 
3717     switch (ObjectVT.getSimpleVT().SimpleTy) {
3718     default: llvm_unreachable("Unhandled argument type!");
3719     case MVT::i1:
3720     case MVT::i32:
3721     case MVT::i64:
3722       if (Flags.isNest()) {
3723         // The 'nest' parameter, if any, is passed in R11.
3724         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3725         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3726 
3727         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3728           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3729 
3730         break;
3731       }
3732 
3733       // These can be scalar arguments or elements of an integer array type
3734       // passed directly.  Clang may use those instead of "byval" aggregate
3735       // types to avoid forcing arguments to memory unnecessarily.
3736       if (GPR_idx != Num_GPR_Regs) {
3737         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3738         FuncInfo->addLiveInAttr(VReg, Flags);
3739         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3740 
3741         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3742           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3743           // value to MVT::i64 and then truncate to the correct register size.
3744           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3745       } else {
3746         if (CallConv == CallingConv::Fast)
3747           ComputeArgOffset();
3748 
3749         needsLoad = true;
3750         ArgSize = PtrByteSize;
3751       }
3752       if (CallConv != CallingConv::Fast || needsLoad)
3753         ArgOffset += 8;
3754       break;
3755 
3756     case MVT::f32:
3757     case MVT::f64:
3758       // These can be scalar arguments or elements of a float array type
3759       // passed directly.  The latter are used to implement ELFv2 homogenous
3760       // float aggregates.
3761       if (FPR_idx != Num_FPR_Regs) {
3762         unsigned VReg;
3763 
3764         if (ObjectVT == MVT::f32)
3765           VReg = MF.addLiveIn(FPR[FPR_idx],
3766                               Subtarget.hasP8Vector()
3767                                   ? &PPC::VSSRCRegClass
3768                                   : &PPC::F4RCRegClass);
3769         else
3770           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3771                                                 ? &PPC::VSFRCRegClass
3772                                                 : &PPC::F8RCRegClass);
3773 
3774         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3775         ++FPR_idx;
3776       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3777         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3778         // once we support fp <-> gpr moves.
3779 
3780         // This can only ever happen in the presence of f32 array types,
3781         // since otherwise we never run out of FPRs before running out
3782         // of GPRs.
3783         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3784         FuncInfo->addLiveInAttr(VReg, Flags);
3785         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3786 
3787         if (ObjectVT == MVT::f32) {
3788           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3789             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3790                                  DAG.getConstant(32, dl, MVT::i32));
3791           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3792         }
3793 
3794         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3795       } else {
3796         if (CallConv == CallingConv::Fast)
3797           ComputeArgOffset();
3798 
3799         needsLoad = true;
3800       }
3801 
3802       // When passing an array of floats, the array occupies consecutive
3803       // space in the argument area; only round up to the next doubleword
3804       // at the end of the array.  Otherwise, each float takes 8 bytes.
3805       if (CallConv != CallingConv::Fast || needsLoad) {
3806         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3807         ArgOffset += ArgSize;
3808         if (Flags.isInConsecutiveRegsLast())
3809           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3810       }
3811       break;
3812     case MVT::v4f32:
3813     case MVT::v4i32:
3814     case MVT::v8i16:
3815     case MVT::v16i8:
3816     case MVT::v2f64:
3817     case MVT::v2i64:
3818     case MVT::v1i128:
3819       if (!Subtarget.hasQPX()) {
3820         // These can be scalar arguments or elements of a vector array type
3821         // passed directly.  The latter are used to implement ELFv2 homogenous
3822         // vector aggregates.
3823         if (VR_idx != Num_VR_Regs) {
3824           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3825           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3826           ++VR_idx;
3827         } else {
3828           if (CallConv == CallingConv::Fast)
3829             ComputeArgOffset();
3830           needsLoad = true;
3831         }
3832         if (CallConv != CallingConv::Fast || needsLoad)
3833           ArgOffset += 16;
3834         break;
3835       } // not QPX
3836 
3837       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3838              "Invalid QPX parameter type");
3839       /* fall through */
3840 
3841     case MVT::v4f64:
3842     case MVT::v4i1:
3843       // QPX vectors are treated like their scalar floating-point subregisters
3844       // (except that they're larger).
3845       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3846       if (QFPR_idx != Num_QFPR_Regs) {
3847         const TargetRegisterClass *RC;
3848         switch (ObjectVT.getSimpleVT().SimpleTy) {
3849         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3850         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3851         default:         RC = &PPC::QBRCRegClass; break;
3852         }
3853 
3854         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3855         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3856         ++QFPR_idx;
3857       } else {
3858         if (CallConv == CallingConv::Fast)
3859           ComputeArgOffset();
3860         needsLoad = true;
3861       }
3862       if (CallConv != CallingConv::Fast || needsLoad)
3863         ArgOffset += Sz;
3864       break;
3865     }
3866 
3867     // We need to load the argument to a virtual register if we determined
3868     // above that we ran out of physical registers of the appropriate type.
3869     if (needsLoad) {
3870       if (ObjSize < ArgSize && !isLittleEndian)
3871         CurArgOffset += ArgSize - ObjSize;
3872       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3873       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3874       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3875     }
3876 
3877     InVals.push_back(ArgVal);
3878   }
3879 
3880   // Area that is at least reserved in the caller of this function.
3881   unsigned MinReservedArea;
3882   if (HasParameterArea)
3883     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3884   else
3885     MinReservedArea = LinkageSize;
3886 
3887   // Set the size that is at least reserved in caller of this function.  Tail
3888   // call optimized functions' reserved stack space needs to be aligned so that
3889   // taking the difference between two stack areas will result in an aligned
3890   // stack.
3891   MinReservedArea =
3892       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3893   FuncInfo->setMinReservedArea(MinReservedArea);
3894 
3895   // If the function takes variable number of arguments, make a frame index for
3896   // the start of the first vararg value... for expansion of llvm.va_start.
3897   if (isVarArg) {
3898     int Depth = ArgOffset;
3899 
3900     FuncInfo->setVarArgsFrameIndex(
3901       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3902     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3903 
3904     // If this function is vararg, store any remaining integer argument regs
3905     // to their spots on the stack so that they may be loaded by dereferencing
3906     // the result of va_next.
3907     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3908          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3909       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3910       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3911       SDValue Store =
3912           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3913       MemOps.push_back(Store);
3914       // Increment the address by four for the next argument to store
3915       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3916       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3917     }
3918   }
3919 
3920   if (!MemOps.empty())
3921     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3922 
3923   return Chain;
3924 }
3925 
3926 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3927     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3928     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3929     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3930   // TODO: add description of PPC stack frame format, or at least some docs.
3931   //
3932   MachineFunction &MF = DAG.getMachineFunction();
3933   MachineFrameInfo &MFI = MF.getFrameInfo();
3934   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3935 
3936   EVT PtrVT = getPointerTy(MF.getDataLayout());
3937   bool isPPC64 = PtrVT == MVT::i64;
3938   // Potential tail calls could cause overwriting of argument stack slots.
3939   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3940                        (CallConv == CallingConv::Fast));
3941   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3942   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3943   unsigned ArgOffset = LinkageSize;
3944   // Area that is at least reserved in caller of this function.
3945   unsigned MinReservedArea = ArgOffset;
3946 
3947   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3948     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3949     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3950   };
3951   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3952     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3953     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3954   };
3955   static const MCPhysReg VR[] = {
3956     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3957     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3958   };
3959 
3960   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3961   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3962   const unsigned Num_VR_Regs  = array_lengthof( VR);
3963 
3964   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3965 
3966   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3967 
3968   // In 32-bit non-varargs functions, the stack space for vectors is after the
3969   // stack space for non-vectors.  We do not use this space unless we have
3970   // too many vectors to fit in registers, something that only occurs in
3971   // constructed examples:), but we have to walk the arglist to figure
3972   // that out...for the pathological case, compute VecArgOffset as the
3973   // start of the vector parameter area.  Computing VecArgOffset is the
3974   // entire point of the following loop.
3975   unsigned VecArgOffset = ArgOffset;
3976   if (!isVarArg && !isPPC64) {
3977     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3978          ++ArgNo) {
3979       EVT ObjectVT = Ins[ArgNo].VT;
3980       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3981 
3982       if (Flags.isByVal()) {
3983         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3984         unsigned ObjSize = Flags.getByValSize();
3985         unsigned ArgSize =
3986                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3987         VecArgOffset += ArgSize;
3988         continue;
3989       }
3990 
3991       switch(ObjectVT.getSimpleVT().SimpleTy) {
3992       default: llvm_unreachable("Unhandled argument type!");
3993       case MVT::i1:
3994       case MVT::i32:
3995       case MVT::f32:
3996         VecArgOffset += 4;
3997         break;
3998       case MVT::i64:  // PPC64
3999       case MVT::f64:
4000         // FIXME: We are guaranteed to be !isPPC64 at this point.
4001         // Does MVT::i64 apply?
4002         VecArgOffset += 8;
4003         break;
4004       case MVT::v4f32:
4005       case MVT::v4i32:
4006       case MVT::v8i16:
4007       case MVT::v16i8:
4008         // Nothing to do, we're only looking at Nonvector args here.
4009         break;
4010       }
4011     }
4012   }
4013   // We've found where the vector parameter area in memory is.  Skip the
4014   // first 12 parameters; these don't use that memory.
4015   VecArgOffset = ((VecArgOffset+15)/16)*16;
4016   VecArgOffset += 12*16;
4017 
4018   // Add DAG nodes to load the arguments or copy them out of registers.  On
4019   // entry to a function on PPC, the arguments start after the linkage area,
4020   // although the first ones are often in registers.
4021 
4022   SmallVector<SDValue, 8> MemOps;
4023   unsigned nAltivecParamsAtEnd = 0;
4024   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4025   unsigned CurArgIdx = 0;
4026   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4027     SDValue ArgVal;
4028     bool needsLoad = false;
4029     EVT ObjectVT = Ins[ArgNo].VT;
4030     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4031     unsigned ArgSize = ObjSize;
4032     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4033     if (Ins[ArgNo].isOrigArg()) {
4034       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4035       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4036     }
4037     unsigned CurArgOffset = ArgOffset;
4038 
4039     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4040     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4041         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4042       if (isVarArg || isPPC64) {
4043         MinReservedArea = ((MinReservedArea+15)/16)*16;
4044         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4045                                                   Flags,
4046                                                   PtrByteSize);
4047       } else  nAltivecParamsAtEnd++;
4048     } else
4049       // Calculate min reserved area.
4050       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4051                                                 Flags,
4052                                                 PtrByteSize);
4053 
4054     // FIXME the codegen can be much improved in some cases.
4055     // We do not have to keep everything in memory.
4056     if (Flags.isByVal()) {
4057       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4058 
4059       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4060       ObjSize = Flags.getByValSize();
4061       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4062       // Objects of size 1 and 2 are right justified, everything else is
4063       // left justified.  This means the memory address is adjusted forwards.
4064       if (ObjSize==1 || ObjSize==2) {
4065         CurArgOffset = CurArgOffset + (4 - ObjSize);
4066       }
4067       // The value of the object is its address.
4068       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4069       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4070       InVals.push_back(FIN);
4071       if (ObjSize==1 || ObjSize==2) {
4072         if (GPR_idx != Num_GPR_Regs) {
4073           unsigned VReg;
4074           if (isPPC64)
4075             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4076           else
4077             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4078           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4079           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4080           SDValue Store =
4081               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4082                                 MachinePointerInfo(&*FuncArg), ObjType);
4083           MemOps.push_back(Store);
4084           ++GPR_idx;
4085         }
4086 
4087         ArgOffset += PtrByteSize;
4088 
4089         continue;
4090       }
4091       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4092         // Store whatever pieces of the object are in registers
4093         // to memory.  ArgOffset will be the address of the beginning
4094         // of the object.
4095         if (GPR_idx != Num_GPR_Regs) {
4096           unsigned VReg;
4097           if (isPPC64)
4098             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4099           else
4100             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4101           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4102           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4103           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4104           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4105                                        MachinePointerInfo(&*FuncArg, j));
4106           MemOps.push_back(Store);
4107           ++GPR_idx;
4108           ArgOffset += PtrByteSize;
4109         } else {
4110           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4111           break;
4112         }
4113       }
4114       continue;
4115     }
4116 
4117     switch (ObjectVT.getSimpleVT().SimpleTy) {
4118     default: llvm_unreachable("Unhandled argument type!");
4119     case MVT::i1:
4120     case MVT::i32:
4121       if (!isPPC64) {
4122         if (GPR_idx != Num_GPR_Regs) {
4123           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4124           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4125 
4126           if (ObjectVT == MVT::i1)
4127             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4128 
4129           ++GPR_idx;
4130         } else {
4131           needsLoad = true;
4132           ArgSize = PtrByteSize;
4133         }
4134         // All int arguments reserve stack space in the Darwin ABI.
4135         ArgOffset += PtrByteSize;
4136         break;
4137       }
4138       LLVM_FALLTHROUGH;
4139     case MVT::i64:  // PPC64
4140       if (GPR_idx != Num_GPR_Regs) {
4141         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4142         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4143 
4144         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4145           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4146           // value to MVT::i64 and then truncate to the correct register size.
4147           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4148 
4149         ++GPR_idx;
4150       } else {
4151         needsLoad = true;
4152         ArgSize = PtrByteSize;
4153       }
4154       // All int arguments reserve stack space in the Darwin ABI.
4155       ArgOffset += 8;
4156       break;
4157 
4158     case MVT::f32:
4159     case MVT::f64:
4160       // Every 4 bytes of argument space consumes one of the GPRs available for
4161       // argument passing.
4162       if (GPR_idx != Num_GPR_Regs) {
4163         ++GPR_idx;
4164         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4165           ++GPR_idx;
4166       }
4167       if (FPR_idx != Num_FPR_Regs) {
4168         unsigned VReg;
4169 
4170         if (ObjectVT == MVT::f32)
4171           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4172         else
4173           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4174 
4175         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4176         ++FPR_idx;
4177       } else {
4178         needsLoad = true;
4179       }
4180 
4181       // All FP arguments reserve stack space in the Darwin ABI.
4182       ArgOffset += isPPC64 ? 8 : ObjSize;
4183       break;
4184     case MVT::v4f32:
4185     case MVT::v4i32:
4186     case MVT::v8i16:
4187     case MVT::v16i8:
4188       // Note that vector arguments in registers don't reserve stack space,
4189       // except in varargs functions.
4190       if (VR_idx != Num_VR_Regs) {
4191         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4192         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4193         if (isVarArg) {
4194           while ((ArgOffset % 16) != 0) {
4195             ArgOffset += PtrByteSize;
4196             if (GPR_idx != Num_GPR_Regs)
4197               GPR_idx++;
4198           }
4199           ArgOffset += 16;
4200           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4201         }
4202         ++VR_idx;
4203       } else {
4204         if (!isVarArg && !isPPC64) {
4205           // Vectors go after all the nonvectors.
4206           CurArgOffset = VecArgOffset;
4207           VecArgOffset += 16;
4208         } else {
4209           // Vectors are aligned.
4210           ArgOffset = ((ArgOffset+15)/16)*16;
4211           CurArgOffset = ArgOffset;
4212           ArgOffset += 16;
4213         }
4214         needsLoad = true;
4215       }
4216       break;
4217     }
4218 
4219     // We need to load the argument to a virtual register if we determined above
4220     // that we ran out of physical registers of the appropriate type.
4221     if (needsLoad) {
4222       int FI = MFI.CreateFixedObject(ObjSize,
4223                                      CurArgOffset + (ArgSize - ObjSize),
4224                                      isImmutable);
4225       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4226       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4227     }
4228 
4229     InVals.push_back(ArgVal);
4230   }
4231 
4232   // Allow for Altivec parameters at the end, if needed.
4233   if (nAltivecParamsAtEnd) {
4234     MinReservedArea = ((MinReservedArea+15)/16)*16;
4235     MinReservedArea += 16*nAltivecParamsAtEnd;
4236   }
4237 
4238   // Area that is at least reserved in the caller of this function.
4239   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4240 
4241   // Set the size that is at least reserved in caller of this function.  Tail
4242   // call optimized functions' reserved stack space needs to be aligned so that
4243   // taking the difference between two stack areas will result in an aligned
4244   // stack.
4245   MinReservedArea =
4246       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4247   FuncInfo->setMinReservedArea(MinReservedArea);
4248 
4249   // If the function takes variable number of arguments, make a frame index for
4250   // the start of the first vararg value... for expansion of llvm.va_start.
4251   if (isVarArg) {
4252     int Depth = ArgOffset;
4253 
4254     FuncInfo->setVarArgsFrameIndex(
4255       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4256                             Depth, true));
4257     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4258 
4259     // If this function is vararg, store any remaining integer argument regs
4260     // to their spots on the stack so that they may be loaded by dereferencing
4261     // the result of va_next.
4262     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4263       unsigned VReg;
4264 
4265       if (isPPC64)
4266         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4267       else
4268         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4269 
4270       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4271       SDValue Store =
4272           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4273       MemOps.push_back(Store);
4274       // Increment the address by four for the next argument to store
4275       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4276       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4277     }
4278   }
4279 
4280   if (!MemOps.empty())
4281     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4282 
4283   return Chain;
4284 }
4285 
4286 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4287 /// adjusted to accommodate the arguments for the tailcall.
4288 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4289                                    unsigned ParamSize) {
4290 
4291   if (!isTailCall) return 0;
4292 
4293   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4294   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4295   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4296   // Remember only if the new adjustement is bigger.
4297   if (SPDiff < FI->getTailCallSPDelta())
4298     FI->setTailCallSPDelta(SPDiff);
4299 
4300   return SPDiff;
4301 }
4302 
4303 static bool isFunctionGlobalAddress(SDValue Callee);
4304 
4305 static bool
4306 callsShareTOCBase(const Function *Caller, SDValue Callee,
4307                     const TargetMachine &TM) {
4308   // If !G, Callee can be an external symbol.
4309   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4310   if (!G)
4311     return false;
4312 
4313   // The medium and large code models are expected to provide a sufficiently
4314   // large TOC to provide all data addressing needs of a module with a
4315   // single TOC. Since each module will be addressed with a single TOC then we
4316   // only need to check that caller and callee don't cross dso boundaries.
4317   if (CodeModel::Medium == TM.getCodeModel() ||
4318       CodeModel::Large == TM.getCodeModel())
4319     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4320 
4321   // Otherwise we need to ensure callee and caller are in the same section,
4322   // since the linker may allocate multiple TOCs, and we don't know which
4323   // sections will belong to the same TOC base.
4324 
4325   const GlobalValue *GV = G->getGlobal();
4326   if (!GV->isStrongDefinitionForLinker())
4327     return false;
4328 
4329   // Any explicitly-specified sections and section prefixes must also match.
4330   // Also, if we're using -ffunction-sections, then each function is always in
4331   // a different section (the same is true for COMDAT functions).
4332   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4333       GV->getSection() != Caller->getSection())
4334     return false;
4335   if (const auto *F = dyn_cast<Function>(GV)) {
4336     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4337       return false;
4338   }
4339 
4340   // If the callee might be interposed, then we can't assume the ultimate call
4341   // target will be in the same section. Even in cases where we can assume that
4342   // interposition won't happen, in any case where the linker might insert a
4343   // stub to allow for interposition, we must generate code as though
4344   // interposition might occur. To understand why this matters, consider a
4345   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4346   // in the same section, but a is in a different module (i.e. has a different
4347   // TOC base pointer). If the linker allows for interposition between b and c,
4348   // then it will generate a stub for the call edge between b and c which will
4349   // save the TOC pointer into the designated stack slot allocated by b. If we
4350   // return true here, and therefore allow a tail call between b and c, that
4351   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4352   // pointer into the stack slot allocated by a (where the a -> b stub saved
4353   // a's TOC base pointer). If we're not considering a tail call, but rather,
4354   // whether a nop is needed after the call instruction in b, because the linker
4355   // will insert a stub, it might complain about a missing nop if we omit it
4356   // (although many don't complain in this case).
4357   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4358     return false;
4359 
4360   return true;
4361 }
4362 
4363 static bool
4364 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4365                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4366   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4367 
4368   const unsigned PtrByteSize = 8;
4369   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4370 
4371   static const MCPhysReg GPR[] = {
4372     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4373     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4374   };
4375   static const MCPhysReg VR[] = {
4376     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4377     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4378   };
4379 
4380   const unsigned NumGPRs = array_lengthof(GPR);
4381   const unsigned NumFPRs = 13;
4382   const unsigned NumVRs = array_lengthof(VR);
4383   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4384 
4385   unsigned NumBytes = LinkageSize;
4386   unsigned AvailableFPRs = NumFPRs;
4387   unsigned AvailableVRs = NumVRs;
4388 
4389   for (const ISD::OutputArg& Param : Outs) {
4390     if (Param.Flags.isNest()) continue;
4391 
4392     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4393                                PtrByteSize, LinkageSize, ParamAreaSize,
4394                                NumBytes, AvailableFPRs, AvailableVRs,
4395                                Subtarget.hasQPX()))
4396       return true;
4397   }
4398   return false;
4399 }
4400 
4401 static bool
4402 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4403   if (CS.arg_size() != CallerFn->arg_size())
4404     return false;
4405 
4406   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4407   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4408   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4409 
4410   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4411     const Value* CalleeArg = *CalleeArgIter;
4412     const Value* CallerArg = &(*CallerArgIter);
4413     if (CalleeArg == CallerArg)
4414       continue;
4415 
4416     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4417     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4418     //      }
4419     // 1st argument of callee is undef and has the same type as caller.
4420     if (CalleeArg->getType() == CallerArg->getType() &&
4421         isa<UndefValue>(CalleeArg))
4422       continue;
4423 
4424     return false;
4425   }
4426 
4427   return true;
4428 }
4429 
4430 // Returns true if TCO is possible between the callers and callees
4431 // calling conventions.
4432 static bool
4433 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4434                                     CallingConv::ID CalleeCC) {
4435   // Tail calls are possible with fastcc and ccc.
4436   auto isTailCallableCC  = [] (CallingConv::ID CC){
4437       return  CC == CallingConv::C || CC == CallingConv::Fast;
4438   };
4439   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4440     return false;
4441 
4442   // We can safely tail call both fastcc and ccc callees from a c calling
4443   // convention caller. If the caller is fastcc, we may have less stack space
4444   // than a non-fastcc caller with the same signature so disable tail-calls in
4445   // that case.
4446   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4447 }
4448 
4449 bool
4450 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4451                                     SDValue Callee,
4452                                     CallingConv::ID CalleeCC,
4453                                     ImmutableCallSite CS,
4454                                     bool isVarArg,
4455                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4456                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4457                                     SelectionDAG& DAG) const {
4458   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4459 
4460   if (DisableSCO && !TailCallOpt) return false;
4461 
4462   // Variadic argument functions are not supported.
4463   if (isVarArg) return false;
4464 
4465   auto &Caller = DAG.getMachineFunction().getFunction();
4466   // Check that the calling conventions are compatible for tco.
4467   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4468     return false;
4469 
4470   // Caller contains any byval parameter is not supported.
4471   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4472     return false;
4473 
4474   // Callee contains any byval parameter is not supported, too.
4475   // Note: This is a quick work around, because in some cases, e.g.
4476   // caller's stack size > callee's stack size, we are still able to apply
4477   // sibling call optimization. For example, gcc is able to do SCO for caller1
4478   // in the following example, but not for caller2.
4479   //   struct test {
4480   //     long int a;
4481   //     char ary[56];
4482   //   } gTest;
4483   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4484   //     b->a = v.a;
4485   //     return 0;
4486   //   }
4487   //   void caller1(struct test a, struct test c, struct test *b) {
4488   //     callee(gTest, b); }
4489   //   void caller2(struct test *b) { callee(gTest, b); }
4490   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4491     return false;
4492 
4493   // If callee and caller use different calling conventions, we cannot pass
4494   // parameters on stack since offsets for the parameter area may be different.
4495   if (Caller.getCallingConv() != CalleeCC &&
4496       needStackSlotPassParameters(Subtarget, Outs))
4497     return false;
4498 
4499   // No TCO/SCO on indirect call because Caller have to restore its TOC
4500   if (!isFunctionGlobalAddress(Callee) &&
4501       !isa<ExternalSymbolSDNode>(Callee))
4502     return false;
4503 
4504   // If the caller and callee potentially have different TOC bases then we
4505   // cannot tail call since we need to restore the TOC pointer after the call.
4506   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4507   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4508     return false;
4509 
4510   // TCO allows altering callee ABI, so we don't have to check further.
4511   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4512     return true;
4513 
4514   if (DisableSCO) return false;
4515 
4516   // If callee use the same argument list that caller is using, then we can
4517   // apply SCO on this case. If it is not, then we need to check if callee needs
4518   // stack for passing arguments.
4519   if (!hasSameArgumentList(&Caller, CS) &&
4520       needStackSlotPassParameters(Subtarget, Outs)) {
4521     return false;
4522   }
4523 
4524   return true;
4525 }
4526 
4527 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4528 /// for tail call optimization. Targets which want to do tail call
4529 /// optimization should implement this function.
4530 bool
4531 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4532                                                      CallingConv::ID CalleeCC,
4533                                                      bool isVarArg,
4534                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4535                                                      SelectionDAG& DAG) const {
4536   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4537     return false;
4538 
4539   // Variable argument functions are not supported.
4540   if (isVarArg)
4541     return false;
4542 
4543   MachineFunction &MF = DAG.getMachineFunction();
4544   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4545   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4546     // Functions containing by val parameters are not supported.
4547     for (unsigned i = 0; i != Ins.size(); i++) {
4548        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4549        if (Flags.isByVal()) return false;
4550     }
4551 
4552     // Non-PIC/GOT tail calls are supported.
4553     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4554       return true;
4555 
4556     // At the moment we can only do local tail calls (in same module, hidden
4557     // or protected) if we are generating PIC.
4558     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4559       return G->getGlobal()->hasHiddenVisibility()
4560           || G->getGlobal()->hasProtectedVisibility();
4561   }
4562 
4563   return false;
4564 }
4565 
4566 /// isCallCompatibleAddress - Return the immediate to use if the specified
4567 /// 32-bit value is representable in the immediate field of a BxA instruction.
4568 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4569   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4570   if (!C) return nullptr;
4571 
4572   int Addr = C->getZExtValue();
4573   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4574       SignExtend32<26>(Addr) != Addr)
4575     return nullptr;  // Top 6 bits have to be sext of immediate.
4576 
4577   return DAG
4578       .getConstant(
4579           (int)C->getZExtValue() >> 2, SDLoc(Op),
4580           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4581       .getNode();
4582 }
4583 
4584 namespace {
4585 
4586 struct TailCallArgumentInfo {
4587   SDValue Arg;
4588   SDValue FrameIdxOp;
4589   int FrameIdx = 0;
4590 
4591   TailCallArgumentInfo() = default;
4592 };
4593 
4594 } // end anonymous namespace
4595 
4596 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4597 static void StoreTailCallArgumentsToStackSlot(
4598     SelectionDAG &DAG, SDValue Chain,
4599     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4600     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4601   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4602     SDValue Arg = TailCallArgs[i].Arg;
4603     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4604     int FI = TailCallArgs[i].FrameIdx;
4605     // Store relative to framepointer.
4606     MemOpChains.push_back(DAG.getStore(
4607         Chain, dl, Arg, FIN,
4608         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4609   }
4610 }
4611 
4612 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4613 /// the appropriate stack slot for the tail call optimized function call.
4614 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4615                                              SDValue OldRetAddr, SDValue OldFP,
4616                                              int SPDiff, const SDLoc &dl) {
4617   if (SPDiff) {
4618     // Calculate the new stack slot for the return address.
4619     MachineFunction &MF = DAG.getMachineFunction();
4620     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4621     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4622     bool isPPC64 = Subtarget.isPPC64();
4623     int SlotSize = isPPC64 ? 8 : 4;
4624     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4625     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4626                                                          NewRetAddrLoc, true);
4627     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4628     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4629     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4630                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4631 
4632     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4633     // slot as the FP is never overwritten.
4634     if (Subtarget.isDarwinABI()) {
4635       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4636       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4637                                                          true);
4638       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4639       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4640                            MachinePointerInfo::getFixedStack(
4641                                DAG.getMachineFunction(), NewFPIdx));
4642     }
4643   }
4644   return Chain;
4645 }
4646 
4647 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4648 /// the position of the argument.
4649 static void
4650 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4651                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4652                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4653   int Offset = ArgOffset + SPDiff;
4654   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4655   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4656   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4657   SDValue FIN = DAG.getFrameIndex(FI, VT);
4658   TailCallArgumentInfo Info;
4659   Info.Arg = Arg;
4660   Info.FrameIdxOp = FIN;
4661   Info.FrameIdx = FI;
4662   TailCallArguments.push_back(Info);
4663 }
4664 
4665 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4666 /// stack slot. Returns the chain as result and the loaded frame pointers in
4667 /// LROpOut/FPOpout. Used when tail calling.
4668 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4669     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4670     SDValue &FPOpOut, const SDLoc &dl) const {
4671   if (SPDiff) {
4672     // Load the LR and FP stack slot for later adjusting.
4673     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4674     LROpOut = getReturnAddrFrameIndex(DAG);
4675     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4676     Chain = SDValue(LROpOut.getNode(), 1);
4677 
4678     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4679     // slot as the FP is never overwritten.
4680     if (Subtarget.isDarwinABI()) {
4681       FPOpOut = getFramePointerFrameIndex(DAG);
4682       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4683       Chain = SDValue(FPOpOut.getNode(), 1);
4684     }
4685   }
4686   return Chain;
4687 }
4688 
4689 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4690 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4691 /// specified by the specific parameter attribute. The copy will be passed as
4692 /// a byval function parameter.
4693 /// Sometimes what we are copying is the end of a larger object, the part that
4694 /// does not fit in registers.
4695 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4696                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4697                                          SelectionDAG &DAG, const SDLoc &dl) {
4698   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4699   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4700                        false, false, false, MachinePointerInfo(),
4701                        MachinePointerInfo());
4702 }
4703 
4704 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4705 /// tail calls.
4706 static void LowerMemOpCallTo(
4707     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4708     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4709     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4710     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4711   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4712   if (!isTailCall) {
4713     if (isVector) {
4714       SDValue StackPtr;
4715       if (isPPC64)
4716         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4717       else
4718         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4719       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4720                            DAG.getConstant(ArgOffset, dl, PtrVT));
4721     }
4722     MemOpChains.push_back(
4723         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4724     // Calculate and remember argument location.
4725   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4726                                   TailCallArguments);
4727 }
4728 
4729 static void
4730 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4731                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4732                 SDValue FPOp,
4733                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4734   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4735   // might overwrite each other in case of tail call optimization.
4736   SmallVector<SDValue, 8> MemOpChains2;
4737   // Do not flag preceding copytoreg stuff together with the following stuff.
4738   InFlag = SDValue();
4739   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4740                                     MemOpChains2, dl);
4741   if (!MemOpChains2.empty())
4742     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4743 
4744   // Store the return address to the appropriate stack slot.
4745   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4746 
4747   // Emit callseq_end just before tailcall node.
4748   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4749                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4750   InFlag = Chain.getValue(1);
4751 }
4752 
4753 // Is this global address that of a function that can be called by name? (as
4754 // opposed to something that must hold a descriptor for an indirect call).
4755 static bool isFunctionGlobalAddress(SDValue Callee) {
4756   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4757     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4758         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4759       return false;
4760 
4761     return G->getGlobal()->getValueType()->isFunctionTy();
4762   }
4763 
4764   return false;
4765 }
4766 
4767 static unsigned
4768 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4769             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4770             bool isPatchPoint, bool hasNest,
4771             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4772             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4773             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4774   bool isPPC64 = Subtarget.isPPC64();
4775   bool isSVR4ABI = Subtarget.isSVR4ABI();
4776   bool isELFv2ABI = Subtarget.isELFv2ABI();
4777 
4778   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4779   NodeTys.push_back(MVT::Other);   // Returns a chain
4780   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4781 
4782   unsigned CallOpc = PPCISD::CALL;
4783 
4784   bool needIndirectCall = true;
4785   if (!isSVR4ABI || !isPPC64)
4786     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4787       // If this is an absolute destination address, use the munged value.
4788       Callee = SDValue(Dest, 0);
4789       needIndirectCall = false;
4790     }
4791 
4792   // PC-relative references to external symbols should go through $stub, unless
4793   // we're building with the leopard linker or later, which automatically
4794   // synthesizes these stubs.
4795   const TargetMachine &TM = DAG.getTarget();
4796   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4797   const GlobalValue *GV = nullptr;
4798   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4799     GV = G->getGlobal();
4800   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4801   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4802 
4803   if (isFunctionGlobalAddress(Callee)) {
4804     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4805     // A call to a TLS address is actually an indirect call to a
4806     // thread-specific pointer.
4807     unsigned OpFlags = 0;
4808     if (UsePlt)
4809       OpFlags = PPCII::MO_PLT;
4810 
4811     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4812     // every direct call is) turn it into a TargetGlobalAddress /
4813     // TargetExternalSymbol node so that legalize doesn't hack it.
4814     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4815                                         Callee.getValueType(), 0, OpFlags);
4816     needIndirectCall = false;
4817   }
4818 
4819   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4820     unsigned char OpFlags = 0;
4821 
4822     if (UsePlt)
4823       OpFlags = PPCII::MO_PLT;
4824 
4825     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4826                                          OpFlags);
4827     needIndirectCall = false;
4828   }
4829 
4830   if (isPatchPoint) {
4831     // We'll form an invalid direct call when lowering a patchpoint; the full
4832     // sequence for an indirect call is complicated, and many of the
4833     // instructions introduced might have side effects (and, thus, can't be
4834     // removed later). The call itself will be removed as soon as the
4835     // argument/return lowering is complete, so the fact that it has the wrong
4836     // kind of operands should not really matter.
4837     needIndirectCall = false;
4838   }
4839 
4840   if (needIndirectCall) {
4841     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4842     // to do the call, we can't use PPCISD::CALL.
4843     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4844 
4845     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4846       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4847       // entry point, but to the function descriptor (the function entry point
4848       // address is part of the function descriptor though).
4849       // The function descriptor is a three doubleword structure with the
4850       // following fields: function entry point, TOC base address and
4851       // environment pointer.
4852       // Thus for a call through a function pointer, the following actions need
4853       // to be performed:
4854       //   1. Save the TOC of the caller in the TOC save area of its stack
4855       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4856       //   2. Load the address of the function entry point from the function
4857       //      descriptor.
4858       //   3. Load the TOC of the callee from the function descriptor into r2.
4859       //   4. Load the environment pointer from the function descriptor into
4860       //      r11.
4861       //   5. Branch to the function entry point address.
4862       //   6. On return of the callee, the TOC of the caller needs to be
4863       //      restored (this is done in FinishCall()).
4864       //
4865       // The loads are scheduled at the beginning of the call sequence, and the
4866       // register copies are flagged together to ensure that no other
4867       // operations can be scheduled in between. E.g. without flagging the
4868       // copies together, a TOC access in the caller could be scheduled between
4869       // the assignment of the callee TOC and the branch to the callee, which
4870       // results in the TOC access going through the TOC of the callee instead
4871       // of going through the TOC of the caller, which leads to incorrect code.
4872 
4873       // Load the address of the function entry point from the function
4874       // descriptor.
4875       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4876       if (LDChain.getValueType() == MVT::Glue)
4877         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4878 
4879       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4880                           ? (MachineMemOperand::MODereferenceable |
4881                              MachineMemOperand::MOInvariant)
4882                           : MachineMemOperand::MONone;
4883 
4884       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4885       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4886                                         /* Alignment = */ 8, MMOFlags);
4887 
4888       // Load environment pointer into r11.
4889       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4890       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4891       SDValue LoadEnvPtr =
4892           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4893                       /* Alignment = */ 8, MMOFlags);
4894 
4895       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4896       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4897       SDValue TOCPtr =
4898           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4899                       /* Alignment = */ 8, MMOFlags);
4900 
4901       setUsesTOCBasePtr(DAG);
4902       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4903                                         InFlag);
4904       Chain = TOCVal.getValue(0);
4905       InFlag = TOCVal.getValue(1);
4906 
4907       // If the function call has an explicit 'nest' parameter, it takes the
4908       // place of the environment pointer.
4909       if (!hasNest) {
4910         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4911                                           InFlag);
4912 
4913         Chain = EnvVal.getValue(0);
4914         InFlag = EnvVal.getValue(1);
4915       }
4916 
4917       MTCTROps[0] = Chain;
4918       MTCTROps[1] = LoadFuncPtr;
4919       MTCTROps[2] = InFlag;
4920     }
4921 
4922     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4923                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4924     InFlag = Chain.getValue(1);
4925 
4926     NodeTys.clear();
4927     NodeTys.push_back(MVT::Other);
4928     NodeTys.push_back(MVT::Glue);
4929     Ops.push_back(Chain);
4930     CallOpc = PPCISD::BCTRL;
4931     Callee.setNode(nullptr);
4932     // Add use of X11 (holding environment pointer)
4933     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4934       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4935     // Add CTR register as callee so a bctr can be emitted later.
4936     if (isTailCall)
4937       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4938   }
4939 
4940   // If this is a direct call, pass the chain and the callee.
4941   if (Callee.getNode()) {
4942     Ops.push_back(Chain);
4943     Ops.push_back(Callee);
4944   }
4945   // If this is a tail call add stack pointer delta.
4946   if (isTailCall)
4947     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4948 
4949   // Add argument registers to the end of the list so that they are known live
4950   // into the call.
4951   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4952     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4953                                   RegsToPass[i].second.getValueType()));
4954 
4955   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4956   // into the call.
4957   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4958     setUsesTOCBasePtr(DAG);
4959     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4960   }
4961 
4962   return CallOpc;
4963 }
4964 
4965 SDValue PPCTargetLowering::LowerCallResult(
4966     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4967     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4968     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4969   SmallVector<CCValAssign, 16> RVLocs;
4970   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4971                     *DAG.getContext());
4972 
4973   CCRetInfo.AnalyzeCallResult(
4974       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4975                ? RetCC_PPC_Cold
4976                : RetCC_PPC);
4977 
4978   // Copy all of the result registers out of their specified physreg.
4979   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4980     CCValAssign &VA = RVLocs[i];
4981     assert(VA.isRegLoc() && "Can only return in registers!");
4982 
4983     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4984                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4985     Chain = Val.getValue(1);
4986     InFlag = Val.getValue(2);
4987 
4988     switch (VA.getLocInfo()) {
4989     default: llvm_unreachable("Unknown loc info!");
4990     case CCValAssign::Full: break;
4991     case CCValAssign::AExt:
4992       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4993       break;
4994     case CCValAssign::ZExt:
4995       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4996                         DAG.getValueType(VA.getValVT()));
4997       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4998       break;
4999     case CCValAssign::SExt:
5000       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
5001                         DAG.getValueType(VA.getValVT()));
5002       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
5003       break;
5004     }
5005 
5006     InVals.push_back(Val);
5007   }
5008 
5009   return Chain;
5010 }
5011 
5012 SDValue PPCTargetLowering::FinishCall(
5013     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5014     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5015     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5016     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5017     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5018     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5019   std::vector<EVT> NodeTys;
5020   SmallVector<SDValue, 8> Ops;
5021   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5022                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5023                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5024 
5025   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5026   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5027     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5028 
5029   // When performing tail call optimization the callee pops its arguments off
5030   // the stack. Account for this here so these bytes can be pushed back on in
5031   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5032   int BytesCalleePops =
5033     (CallConv == CallingConv::Fast &&
5034      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5035 
5036   // Add a register mask operand representing the call-preserved registers.
5037   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5038   const uint32_t *Mask =
5039       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5040   assert(Mask && "Missing call preserved mask for calling convention");
5041   Ops.push_back(DAG.getRegisterMask(Mask));
5042 
5043   if (InFlag.getNode())
5044     Ops.push_back(InFlag);
5045 
5046   // Emit tail call.
5047   if (isTailCall) {
5048     assert(((Callee.getOpcode() == ISD::Register &&
5049              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5050             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5051             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5052             isa<ConstantSDNode>(Callee)) &&
5053     "Expecting an global address, external symbol, absolute value or register");
5054 
5055     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5056     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5057   }
5058 
5059   // Add a NOP immediately after the branch instruction when using the 64-bit
5060   // SVR4 ABI. At link time, if caller and callee are in a different module and
5061   // thus have a different TOC, the call will be replaced with a call to a stub
5062   // function which saves the current TOC, loads the TOC of the callee and
5063   // branches to the callee. The NOP will be replaced with a load instruction
5064   // which restores the TOC of the caller from the TOC save slot of the current
5065   // stack frame. If caller and callee belong to the same module (and have the
5066   // same TOC), the NOP will remain unchanged.
5067 
5068   MachineFunction &MF = DAG.getMachineFunction();
5069   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5070       !isPatchPoint) {
5071     if (CallOpc == PPCISD::BCTRL) {
5072       // This is a call through a function pointer.
5073       // Restore the caller TOC from the save area into R2.
5074       // See PrepareCall() for more information about calls through function
5075       // pointers in the 64-bit SVR4 ABI.
5076       // We are using a target-specific load with r2 hard coded, because the
5077       // result of a target-independent load would never go directly into r2,
5078       // since r2 is a reserved register (which prevents the register allocator
5079       // from allocating it), resulting in an additional register being
5080       // allocated and an unnecessary move instruction being generated.
5081       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5082 
5083       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5084       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5085       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5086       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5087       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5088 
5089       // The address needs to go after the chain input but before the flag (or
5090       // any other variadic arguments).
5091       Ops.insert(std::next(Ops.begin()), AddTOC);
5092     } else if (CallOpc == PPCISD::CALL &&
5093       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5094       // Otherwise insert NOP for non-local calls.
5095       CallOpc = PPCISD::CALL_NOP;
5096     }
5097   }
5098 
5099   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5100   InFlag = Chain.getValue(1);
5101 
5102   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5103                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5104                              InFlag, dl);
5105   if (!Ins.empty())
5106     InFlag = Chain.getValue(1);
5107 
5108   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5109                          Ins, dl, DAG, InVals);
5110 }
5111 
5112 SDValue
5113 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5114                              SmallVectorImpl<SDValue> &InVals) const {
5115   SelectionDAG &DAG                     = CLI.DAG;
5116   SDLoc &dl                             = CLI.DL;
5117   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5118   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5119   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5120   SDValue Chain                         = CLI.Chain;
5121   SDValue Callee                        = CLI.Callee;
5122   bool &isTailCall                      = CLI.IsTailCall;
5123   CallingConv::ID CallConv              = CLI.CallConv;
5124   bool isVarArg                         = CLI.IsVarArg;
5125   bool isPatchPoint                     = CLI.IsPatchPoint;
5126   ImmutableCallSite CS                  = CLI.CS;
5127 
5128   if (isTailCall) {
5129     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5130       isTailCall = false;
5131     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5132       isTailCall =
5133         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5134                                                  isVarArg, Outs, Ins, DAG);
5135     else
5136       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5137                                                      Ins, DAG);
5138     if (isTailCall) {
5139       ++NumTailCalls;
5140       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5141         ++NumSiblingCalls;
5142 
5143       assert(isa<GlobalAddressSDNode>(Callee) &&
5144              "Callee should be an llvm::Function object.");
5145       LLVM_DEBUG(
5146           const GlobalValue *GV =
5147               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5148           const unsigned Width =
5149               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5150           dbgs() << "TCO caller: "
5151                  << left_justify(DAG.getMachineFunction().getName(), Width)
5152                  << ", callee linkage: " << GV->getVisibility() << ", "
5153                  << GV->getLinkage() << "\n");
5154     }
5155   }
5156 
5157   if (!isTailCall && CS && CS.isMustTailCall())
5158     report_fatal_error("failed to perform tail call elimination on a call "
5159                        "site marked musttail");
5160 
5161   // When long calls (i.e. indirect calls) are always used, calls are always
5162   // made via function pointer. If we have a function name, first translate it
5163   // into a pointer.
5164   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5165       !isTailCall)
5166     Callee = LowerGlobalAddress(Callee, DAG);
5167 
5168   if (Subtarget.isSVR4ABI()) {
5169     if (Subtarget.isPPC64())
5170       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5171                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5172                               dl, DAG, InVals, CS);
5173     else
5174       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5175                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5176                               dl, DAG, InVals, CS);
5177   }
5178 
5179   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5180                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5181                           dl, DAG, InVals, CS);
5182 }
5183 
5184 SDValue PPCTargetLowering::LowerCall_32SVR4(
5185     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5186     bool isTailCall, bool isPatchPoint,
5187     const SmallVectorImpl<ISD::OutputArg> &Outs,
5188     const SmallVectorImpl<SDValue> &OutVals,
5189     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5190     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5191     ImmutableCallSite CS) const {
5192   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5193   // of the 32-bit SVR4 ABI stack frame layout.
5194 
5195   assert((CallConv == CallingConv::C ||
5196           CallConv == CallingConv::Cold ||
5197           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5198 
5199   unsigned PtrByteSize = 4;
5200 
5201   MachineFunction &MF = DAG.getMachineFunction();
5202 
5203   // Mark this function as potentially containing a function that contains a
5204   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5205   // and restoring the callers stack pointer in this functions epilog. This is
5206   // done because by tail calling the called function might overwrite the value
5207   // in this function's (MF) stack pointer stack slot 0(SP).
5208   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5209       CallConv == CallingConv::Fast)
5210     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5211 
5212   // Count how many bytes are to be pushed on the stack, including the linkage
5213   // area, parameter list area and the part of the local variable space which
5214   // contains copies of aggregates which are passed by value.
5215 
5216   // Assign locations to all of the outgoing arguments.
5217   SmallVector<CCValAssign, 16> ArgLocs;
5218   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5219 
5220   // Reserve space for the linkage area on the stack.
5221   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5222                        PtrByteSize);
5223   if (useSoftFloat())
5224     CCInfo.PreAnalyzeCallOperands(Outs);
5225 
5226   if (isVarArg) {
5227     // Handle fixed and variable vector arguments differently.
5228     // Fixed vector arguments go into registers as long as registers are
5229     // available. Variable vector arguments always go into memory.
5230     unsigned NumArgs = Outs.size();
5231 
5232     for (unsigned i = 0; i != NumArgs; ++i) {
5233       MVT ArgVT = Outs[i].VT;
5234       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5235       bool Result;
5236 
5237       if (Outs[i].IsFixed) {
5238         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5239                                CCInfo);
5240       } else {
5241         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5242                                       ArgFlags, CCInfo);
5243       }
5244 
5245       if (Result) {
5246 #ifndef NDEBUG
5247         errs() << "Call operand #" << i << " has unhandled type "
5248              << EVT(ArgVT).getEVTString() << "\n";
5249 #endif
5250         llvm_unreachable(nullptr);
5251       }
5252     }
5253   } else {
5254     // All arguments are treated the same.
5255     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5256   }
5257   CCInfo.clearWasPPCF128();
5258 
5259   // Assign locations to all of the outgoing aggregate by value arguments.
5260   SmallVector<CCValAssign, 16> ByValArgLocs;
5261   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5262 
5263   // Reserve stack space for the allocations in CCInfo.
5264   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5265 
5266   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5267 
5268   // Size of the linkage area, parameter list area and the part of the local
5269   // space variable where copies of aggregates which are passed by value are
5270   // stored.
5271   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5272 
5273   // Calculate by how many bytes the stack has to be adjusted in case of tail
5274   // call optimization.
5275   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5276 
5277   // Adjust the stack pointer for the new arguments...
5278   // These operations are automatically eliminated by the prolog/epilog pass
5279   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5280   SDValue CallSeqStart = Chain;
5281 
5282   // Load the return address and frame pointer so it can be moved somewhere else
5283   // later.
5284   SDValue LROp, FPOp;
5285   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5286 
5287   // Set up a copy of the stack pointer for use loading and storing any
5288   // arguments that may not fit in the registers available for argument
5289   // passing.
5290   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5291 
5292   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5293   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5294   SmallVector<SDValue, 8> MemOpChains;
5295 
5296   bool seenFloatArg = false;
5297   // Walk the register/memloc assignments, inserting copies/loads.
5298   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5299        i != e;
5300        ++i) {
5301     CCValAssign &VA = ArgLocs[i];
5302     SDValue Arg = OutVals[i];
5303     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5304 
5305     if (Flags.isByVal()) {
5306       // Argument is an aggregate which is passed by value, thus we need to
5307       // create a copy of it in the local variable space of the current stack
5308       // frame (which is the stack frame of the caller) and pass the address of
5309       // this copy to the callee.
5310       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5311       CCValAssign &ByValVA = ByValArgLocs[j++];
5312       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5313 
5314       // Memory reserved in the local variable space of the callers stack frame.
5315       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5316 
5317       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5318       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5319                            StackPtr, PtrOff);
5320 
5321       // Create a copy of the argument in the local area of the current
5322       // stack frame.
5323       SDValue MemcpyCall =
5324         CreateCopyOfByValArgument(Arg, PtrOff,
5325                                   CallSeqStart.getNode()->getOperand(0),
5326                                   Flags, DAG, dl);
5327 
5328       // This must go outside the CALLSEQ_START..END.
5329       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5330                                                      SDLoc(MemcpyCall));
5331       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5332                              NewCallSeqStart.getNode());
5333       Chain = CallSeqStart = NewCallSeqStart;
5334 
5335       // Pass the address of the aggregate copy on the stack either in a
5336       // physical register or in the parameter list area of the current stack
5337       // frame to the callee.
5338       Arg = PtrOff;
5339     }
5340 
5341     if (VA.isRegLoc()) {
5342       if (Arg.getValueType() == MVT::i1)
5343         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5344 
5345       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5346       // Put argument in a physical register.
5347       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5348     } else {
5349       // Put argument in the parameter list area of the current stack frame.
5350       assert(VA.isMemLoc());
5351       unsigned LocMemOffset = VA.getLocMemOffset();
5352 
5353       if (!isTailCall) {
5354         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5355         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5356                              StackPtr, PtrOff);
5357 
5358         MemOpChains.push_back(
5359             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5360       } else {
5361         // Calculate and remember argument location.
5362         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5363                                  TailCallArguments);
5364       }
5365     }
5366   }
5367 
5368   if (!MemOpChains.empty())
5369     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5370 
5371   // Build a sequence of copy-to-reg nodes chained together with token chain
5372   // and flag operands which copy the outgoing args into the appropriate regs.
5373   SDValue InFlag;
5374   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5375     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5376                              RegsToPass[i].second, InFlag);
5377     InFlag = Chain.getValue(1);
5378   }
5379 
5380   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5381   // registers.
5382   if (isVarArg) {
5383     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5384     SDValue Ops[] = { Chain, InFlag };
5385 
5386     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5387                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5388 
5389     InFlag = Chain.getValue(1);
5390   }
5391 
5392   if (isTailCall)
5393     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5394                     TailCallArguments);
5395 
5396   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5397                     /* unused except on PPC64 ELFv1 */ false, DAG,
5398                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5399                     NumBytes, Ins, InVals, CS);
5400 }
5401 
5402 // Copy an argument into memory, being careful to do this outside the
5403 // call sequence for the call to which the argument belongs.
5404 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5405     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5406     SelectionDAG &DAG, const SDLoc &dl) const {
5407   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5408                         CallSeqStart.getNode()->getOperand(0),
5409                         Flags, DAG, dl);
5410   // The MEMCPY must go outside the CALLSEQ_START..END.
5411   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5412   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5413                                                  SDLoc(MemcpyCall));
5414   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5415                          NewCallSeqStart.getNode());
5416   return NewCallSeqStart;
5417 }
5418 
5419 SDValue PPCTargetLowering::LowerCall_64SVR4(
5420     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5421     bool isTailCall, bool isPatchPoint,
5422     const SmallVectorImpl<ISD::OutputArg> &Outs,
5423     const SmallVectorImpl<SDValue> &OutVals,
5424     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5425     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5426     ImmutableCallSite CS) const {
5427   bool isELFv2ABI = Subtarget.isELFv2ABI();
5428   bool isLittleEndian = Subtarget.isLittleEndian();
5429   unsigned NumOps = Outs.size();
5430   bool hasNest = false;
5431   bool IsSibCall = false;
5432 
5433   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5434   unsigned PtrByteSize = 8;
5435 
5436   MachineFunction &MF = DAG.getMachineFunction();
5437 
5438   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5439     IsSibCall = true;
5440 
5441   // Mark this function as potentially containing a function that contains a
5442   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5443   // and restoring the callers stack pointer in this functions epilog. This is
5444   // done because by tail calling the called function might overwrite the value
5445   // in this function's (MF) stack pointer stack slot 0(SP).
5446   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5447       CallConv == CallingConv::Fast)
5448     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5449 
5450   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5451          "fastcc not supported on varargs functions");
5452 
5453   // Count how many bytes are to be pushed on the stack, including the linkage
5454   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5455   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5456   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5457   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5458   unsigned NumBytes = LinkageSize;
5459   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5460   unsigned &QFPR_idx = FPR_idx;
5461 
5462   static const MCPhysReg GPR[] = {
5463     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5464     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5465   };
5466   static const MCPhysReg VR[] = {
5467     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5468     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5469   };
5470 
5471   const unsigned NumGPRs = array_lengthof(GPR);
5472   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5473   const unsigned NumVRs  = array_lengthof(VR);
5474   const unsigned NumQFPRs = NumFPRs;
5475 
5476   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5477   // can be passed to the callee in registers.
5478   // For the fast calling convention, there is another check below.
5479   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5480   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5481   if (!HasParameterArea) {
5482     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5483     unsigned AvailableFPRs = NumFPRs;
5484     unsigned AvailableVRs = NumVRs;
5485     unsigned NumBytesTmp = NumBytes;
5486     for (unsigned i = 0; i != NumOps; ++i) {
5487       if (Outs[i].Flags.isNest()) continue;
5488       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5489                                 PtrByteSize, LinkageSize, ParamAreaSize,
5490                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5491                                 Subtarget.hasQPX()))
5492         HasParameterArea = true;
5493     }
5494   }
5495 
5496   // When using the fast calling convention, we don't provide backing for
5497   // arguments that will be in registers.
5498   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5499 
5500   // Avoid allocating parameter area for fastcc functions if all the arguments
5501   // can be passed in the registers.
5502   if (CallConv == CallingConv::Fast)
5503     HasParameterArea = false;
5504 
5505   // Add up all the space actually used.
5506   for (unsigned i = 0; i != NumOps; ++i) {
5507     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5508     EVT ArgVT = Outs[i].VT;
5509     EVT OrigVT = Outs[i].ArgVT;
5510 
5511     if (Flags.isNest())
5512       continue;
5513 
5514     if (CallConv == CallingConv::Fast) {
5515       if (Flags.isByVal()) {
5516         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5517         if (NumGPRsUsed > NumGPRs)
5518           HasParameterArea = true;
5519       } else {
5520         switch (ArgVT.getSimpleVT().SimpleTy) {
5521         default: llvm_unreachable("Unexpected ValueType for argument!");
5522         case MVT::i1:
5523         case MVT::i32:
5524         case MVT::i64:
5525           if (++NumGPRsUsed <= NumGPRs)
5526             continue;
5527           break;
5528         case MVT::v4i32:
5529         case MVT::v8i16:
5530         case MVT::v16i8:
5531         case MVT::v2f64:
5532         case MVT::v2i64:
5533         case MVT::v1i128:
5534           if (++NumVRsUsed <= NumVRs)
5535             continue;
5536           break;
5537         case MVT::v4f32:
5538           // When using QPX, this is handled like a FP register, otherwise, it
5539           // is an Altivec register.
5540           if (Subtarget.hasQPX()) {
5541             if (++NumFPRsUsed <= NumFPRs)
5542               continue;
5543           } else {
5544             if (++NumVRsUsed <= NumVRs)
5545               continue;
5546           }
5547           break;
5548         case MVT::f32:
5549         case MVT::f64:
5550         case MVT::v4f64: // QPX
5551         case MVT::v4i1:  // QPX
5552           if (++NumFPRsUsed <= NumFPRs)
5553             continue;
5554           break;
5555         }
5556         HasParameterArea = true;
5557       }
5558     }
5559 
5560     /* Respect alignment of argument on the stack.  */
5561     unsigned Align =
5562       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5563     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5564 
5565     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5566     if (Flags.isInConsecutiveRegsLast())
5567       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5568   }
5569 
5570   unsigned NumBytesActuallyUsed = NumBytes;
5571 
5572   // In the old ELFv1 ABI,
5573   // the prolog code of the callee may store up to 8 GPR argument registers to
5574   // the stack, allowing va_start to index over them in memory if its varargs.
5575   // Because we cannot tell if this is needed on the caller side, we have to
5576   // conservatively assume that it is needed.  As such, make sure we have at
5577   // least enough stack space for the caller to store the 8 GPRs.
5578   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5579   // really requires memory operands, e.g. a vararg function.
5580   if (HasParameterArea)
5581     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5582   else
5583     NumBytes = LinkageSize;
5584 
5585   // Tail call needs the stack to be aligned.
5586   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5587       CallConv == CallingConv::Fast)
5588     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5589 
5590   int SPDiff = 0;
5591 
5592   // Calculate by how many bytes the stack has to be adjusted in case of tail
5593   // call optimization.
5594   if (!IsSibCall)
5595     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5596 
5597   // To protect arguments on the stack from being clobbered in a tail call,
5598   // force all the loads to happen before doing any other lowering.
5599   if (isTailCall)
5600     Chain = DAG.getStackArgumentTokenFactor(Chain);
5601 
5602   // Adjust the stack pointer for the new arguments...
5603   // These operations are automatically eliminated by the prolog/epilog pass
5604   if (!IsSibCall)
5605     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5606   SDValue CallSeqStart = Chain;
5607 
5608   // Load the return address and frame pointer so it can be move somewhere else
5609   // later.
5610   SDValue LROp, FPOp;
5611   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5612 
5613   // Set up a copy of the stack pointer for use loading and storing any
5614   // arguments that may not fit in the registers available for argument
5615   // passing.
5616   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5617 
5618   // Figure out which arguments are going to go in registers, and which in
5619   // memory.  Also, if this is a vararg function, floating point operations
5620   // must be stored to our stack, and loaded into integer regs as well, if
5621   // any integer regs are available for argument passing.
5622   unsigned ArgOffset = LinkageSize;
5623 
5624   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5625   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5626 
5627   SmallVector<SDValue, 8> MemOpChains;
5628   for (unsigned i = 0; i != NumOps; ++i) {
5629     SDValue Arg = OutVals[i];
5630     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5631     EVT ArgVT = Outs[i].VT;
5632     EVT OrigVT = Outs[i].ArgVT;
5633 
5634     // PtrOff will be used to store the current argument to the stack if a
5635     // register cannot be found for it.
5636     SDValue PtrOff;
5637 
5638     // We re-align the argument offset for each argument, except when using the
5639     // fast calling convention, when we need to make sure we do that only when
5640     // we'll actually use a stack slot.
5641     auto ComputePtrOff = [&]() {
5642       /* Respect alignment of argument on the stack.  */
5643       unsigned Align =
5644         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5645       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5646 
5647       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5648 
5649       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5650     };
5651 
5652     if (CallConv != CallingConv::Fast) {
5653       ComputePtrOff();
5654 
5655       /* Compute GPR index associated with argument offset.  */
5656       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5657       GPR_idx = std::min(GPR_idx, NumGPRs);
5658     }
5659 
5660     // Promote integers to 64-bit values.
5661     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5662       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5663       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5664       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5665     }
5666 
5667     // FIXME memcpy is used way more than necessary.  Correctness first.
5668     // Note: "by value" is code for passing a structure by value, not
5669     // basic types.
5670     if (Flags.isByVal()) {
5671       // Note: Size includes alignment padding, so
5672       //   struct x { short a; char b; }
5673       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5674       // These are the proper values we need for right-justifying the
5675       // aggregate in a parameter register.
5676       unsigned Size = Flags.getByValSize();
5677 
5678       // An empty aggregate parameter takes up no storage and no
5679       // registers.
5680       if (Size == 0)
5681         continue;
5682 
5683       if (CallConv == CallingConv::Fast)
5684         ComputePtrOff();
5685 
5686       // All aggregates smaller than 8 bytes must be passed right-justified.
5687       if (Size==1 || Size==2 || Size==4) {
5688         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5689         if (GPR_idx != NumGPRs) {
5690           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5691                                         MachinePointerInfo(), VT);
5692           MemOpChains.push_back(Load.getValue(1));
5693           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5694 
5695           ArgOffset += PtrByteSize;
5696           continue;
5697         }
5698       }
5699 
5700       if (GPR_idx == NumGPRs && Size < 8) {
5701         SDValue AddPtr = PtrOff;
5702         if (!isLittleEndian) {
5703           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5704                                           PtrOff.getValueType());
5705           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5706         }
5707         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5708                                                           CallSeqStart,
5709                                                           Flags, DAG, dl);
5710         ArgOffset += PtrByteSize;
5711         continue;
5712       }
5713       // Copy entire object into memory.  There are cases where gcc-generated
5714       // code assumes it is there, even if it could be put entirely into
5715       // registers.  (This is not what the doc says.)
5716 
5717       // FIXME: The above statement is likely due to a misunderstanding of the
5718       // documents.  All arguments must be copied into the parameter area BY
5719       // THE CALLEE in the event that the callee takes the address of any
5720       // formal argument.  That has not yet been implemented.  However, it is
5721       // reasonable to use the stack area as a staging area for the register
5722       // load.
5723 
5724       // Skip this for small aggregates, as we will use the same slot for a
5725       // right-justified copy, below.
5726       if (Size >= 8)
5727         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5728                                                           CallSeqStart,
5729                                                           Flags, DAG, dl);
5730 
5731       // When a register is available, pass a small aggregate right-justified.
5732       if (Size < 8 && GPR_idx != NumGPRs) {
5733         // The easiest way to get this right-justified in a register
5734         // is to copy the structure into the rightmost portion of a
5735         // local variable slot, then load the whole slot into the
5736         // register.
5737         // FIXME: The memcpy seems to produce pretty awful code for
5738         // small aggregates, particularly for packed ones.
5739         // FIXME: It would be preferable to use the slot in the
5740         // parameter save area instead of a new local variable.
5741         SDValue AddPtr = PtrOff;
5742         if (!isLittleEndian) {
5743           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5744           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5745         }
5746         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5747                                                           CallSeqStart,
5748                                                           Flags, DAG, dl);
5749 
5750         // Load the slot into the register.
5751         SDValue Load =
5752             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5753         MemOpChains.push_back(Load.getValue(1));
5754         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5755 
5756         // Done with this argument.
5757         ArgOffset += PtrByteSize;
5758         continue;
5759       }
5760 
5761       // For aggregates larger than PtrByteSize, copy the pieces of the
5762       // object that fit into registers from the parameter save area.
5763       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5764         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5765         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5766         if (GPR_idx != NumGPRs) {
5767           SDValue Load =
5768               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5769           MemOpChains.push_back(Load.getValue(1));
5770           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5771           ArgOffset += PtrByteSize;
5772         } else {
5773           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5774           break;
5775         }
5776       }
5777       continue;
5778     }
5779 
5780     switch (Arg.getSimpleValueType().SimpleTy) {
5781     default: llvm_unreachable("Unexpected ValueType for argument!");
5782     case MVT::i1:
5783     case MVT::i32:
5784     case MVT::i64:
5785       if (Flags.isNest()) {
5786         // The 'nest' parameter, if any, is passed in R11.
5787         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5788         hasNest = true;
5789         break;
5790       }
5791 
5792       // These can be scalar arguments or elements of an integer array type
5793       // passed directly.  Clang may use those instead of "byval" aggregate
5794       // types to avoid forcing arguments to memory unnecessarily.
5795       if (GPR_idx != NumGPRs) {
5796         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5797       } else {
5798         if (CallConv == CallingConv::Fast)
5799           ComputePtrOff();
5800 
5801         assert(HasParameterArea &&
5802                "Parameter area must exist to pass an argument in memory.");
5803         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5804                          true, isTailCall, false, MemOpChains,
5805                          TailCallArguments, dl);
5806         if (CallConv == CallingConv::Fast)
5807           ArgOffset += PtrByteSize;
5808       }
5809       if (CallConv != CallingConv::Fast)
5810         ArgOffset += PtrByteSize;
5811       break;
5812     case MVT::f32:
5813     case MVT::f64: {
5814       // These can be scalar arguments or elements of a float array type
5815       // passed directly.  The latter are used to implement ELFv2 homogenous
5816       // float aggregates.
5817 
5818       // Named arguments go into FPRs first, and once they overflow, the
5819       // remaining arguments go into GPRs and then the parameter save area.
5820       // Unnamed arguments for vararg functions always go to GPRs and
5821       // then the parameter save area.  For now, put all arguments to vararg
5822       // routines always in both locations (FPR *and* GPR or stack slot).
5823       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5824       bool NeededLoad = false;
5825 
5826       // First load the argument into the next available FPR.
5827       if (FPR_idx != NumFPRs)
5828         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5829 
5830       // Next, load the argument into GPR or stack slot if needed.
5831       if (!NeedGPROrStack)
5832         ;
5833       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5834         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5835         // once we support fp <-> gpr moves.
5836 
5837         // In the non-vararg case, this can only ever happen in the
5838         // presence of f32 array types, since otherwise we never run
5839         // out of FPRs before running out of GPRs.
5840         SDValue ArgVal;
5841 
5842         // Double values are always passed in a single GPR.
5843         if (Arg.getValueType() != MVT::f32) {
5844           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5845 
5846         // Non-array float values are extended and passed in a GPR.
5847         } else if (!Flags.isInConsecutiveRegs()) {
5848           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5849           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5850 
5851         // If we have an array of floats, we collect every odd element
5852         // together with its predecessor into one GPR.
5853         } else if (ArgOffset % PtrByteSize != 0) {
5854           SDValue Lo, Hi;
5855           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5856           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5857           if (!isLittleEndian)
5858             std::swap(Lo, Hi);
5859           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5860 
5861         // The final element, if even, goes into the first half of a GPR.
5862         } else if (Flags.isInConsecutiveRegsLast()) {
5863           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5864           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5865           if (!isLittleEndian)
5866             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5867                                  DAG.getConstant(32, dl, MVT::i32));
5868 
5869         // Non-final even elements are skipped; they will be handled
5870         // together the with subsequent argument on the next go-around.
5871         } else
5872           ArgVal = SDValue();
5873 
5874         if (ArgVal.getNode())
5875           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5876       } else {
5877         if (CallConv == CallingConv::Fast)
5878           ComputePtrOff();
5879 
5880         // Single-precision floating-point values are mapped to the
5881         // second (rightmost) word of the stack doubleword.
5882         if (Arg.getValueType() == MVT::f32 &&
5883             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5884           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5885           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5886         }
5887 
5888         assert(HasParameterArea &&
5889                "Parameter area must exist to pass an argument in memory.");
5890         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5891                          true, isTailCall, false, MemOpChains,
5892                          TailCallArguments, dl);
5893 
5894         NeededLoad = true;
5895       }
5896       // When passing an array of floats, the array occupies consecutive
5897       // space in the argument area; only round up to the next doubleword
5898       // at the end of the array.  Otherwise, each float takes 8 bytes.
5899       if (CallConv != CallingConv::Fast || NeededLoad) {
5900         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5901                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5902         if (Flags.isInConsecutiveRegsLast())
5903           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5904       }
5905       break;
5906     }
5907     case MVT::v4f32:
5908     case MVT::v4i32:
5909     case MVT::v8i16:
5910     case MVT::v16i8:
5911     case MVT::v2f64:
5912     case MVT::v2i64:
5913     case MVT::v1i128:
5914       if (!Subtarget.hasQPX()) {
5915       // These can be scalar arguments or elements of a vector array type
5916       // passed directly.  The latter are used to implement ELFv2 homogenous
5917       // vector aggregates.
5918 
5919       // For a varargs call, named arguments go into VRs or on the stack as
5920       // usual; unnamed arguments always go to the stack or the corresponding
5921       // GPRs when within range.  For now, we always put the value in both
5922       // locations (or even all three).
5923       if (isVarArg) {
5924         assert(HasParameterArea &&
5925                "Parameter area must exist if we have a varargs call.");
5926         // We could elide this store in the case where the object fits
5927         // entirely in R registers.  Maybe later.
5928         SDValue Store =
5929             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5930         MemOpChains.push_back(Store);
5931         if (VR_idx != NumVRs) {
5932           SDValue Load =
5933               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5934           MemOpChains.push_back(Load.getValue(1));
5935           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5936         }
5937         ArgOffset += 16;
5938         for (unsigned i=0; i<16; i+=PtrByteSize) {
5939           if (GPR_idx == NumGPRs)
5940             break;
5941           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5942                                    DAG.getConstant(i, dl, PtrVT));
5943           SDValue Load =
5944               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5945           MemOpChains.push_back(Load.getValue(1));
5946           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5947         }
5948         break;
5949       }
5950 
5951       // Non-varargs Altivec params go into VRs or on the stack.
5952       if (VR_idx != NumVRs) {
5953         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5954       } else {
5955         if (CallConv == CallingConv::Fast)
5956           ComputePtrOff();
5957 
5958         assert(HasParameterArea &&
5959                "Parameter area must exist to pass an argument in memory.");
5960         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5961                          true, isTailCall, true, MemOpChains,
5962                          TailCallArguments, dl);
5963         if (CallConv == CallingConv::Fast)
5964           ArgOffset += 16;
5965       }
5966 
5967       if (CallConv != CallingConv::Fast)
5968         ArgOffset += 16;
5969       break;
5970       } // not QPX
5971 
5972       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5973              "Invalid QPX parameter type");
5974 
5975       /* fall through */
5976     case MVT::v4f64:
5977     case MVT::v4i1: {
5978       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5979       if (isVarArg) {
5980         assert(HasParameterArea &&
5981                "Parameter area must exist if we have a varargs call.");
5982         // We could elide this store in the case where the object fits
5983         // entirely in R registers.  Maybe later.
5984         SDValue Store =
5985             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5986         MemOpChains.push_back(Store);
5987         if (QFPR_idx != NumQFPRs) {
5988           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5989                                      PtrOff, MachinePointerInfo());
5990           MemOpChains.push_back(Load.getValue(1));
5991           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5992         }
5993         ArgOffset += (IsF32 ? 16 : 32);
5994         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5995           if (GPR_idx == NumGPRs)
5996             break;
5997           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5998                                    DAG.getConstant(i, dl, PtrVT));
5999           SDValue Load =
6000               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6001           MemOpChains.push_back(Load.getValue(1));
6002           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6003         }
6004         break;
6005       }
6006 
6007       // Non-varargs QPX params go into registers or on the stack.
6008       if (QFPR_idx != NumQFPRs) {
6009         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6010       } else {
6011         if (CallConv == CallingConv::Fast)
6012           ComputePtrOff();
6013 
6014         assert(HasParameterArea &&
6015                "Parameter area must exist to pass an argument in memory.");
6016         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6017                          true, isTailCall, true, MemOpChains,
6018                          TailCallArguments, dl);
6019         if (CallConv == CallingConv::Fast)
6020           ArgOffset += (IsF32 ? 16 : 32);
6021       }
6022 
6023       if (CallConv != CallingConv::Fast)
6024         ArgOffset += (IsF32 ? 16 : 32);
6025       break;
6026       }
6027     }
6028   }
6029 
6030   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6031          "mismatch in size of parameter area");
6032   (void)NumBytesActuallyUsed;
6033 
6034   if (!MemOpChains.empty())
6035     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6036 
6037   // Check if this is an indirect call (MTCTR/BCTRL).
6038   // See PrepareCall() for more information about calls through function
6039   // pointers in the 64-bit SVR4 ABI.
6040   if (!isTailCall && !isPatchPoint &&
6041       !isFunctionGlobalAddress(Callee) &&
6042       !isa<ExternalSymbolSDNode>(Callee)) {
6043     // Load r2 into a virtual register and store it to the TOC save area.
6044     setUsesTOCBasePtr(DAG);
6045     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6046     // TOC save area offset.
6047     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6048     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6049     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6050     Chain = DAG.getStore(
6051         Val.getValue(1), dl, Val, AddPtr,
6052         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6053     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6054     // This does not mean the MTCTR instruction must use R12; it's easier
6055     // to model this as an extra parameter, so do that.
6056     if (isELFv2ABI && !isPatchPoint)
6057       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6058   }
6059 
6060   // Build a sequence of copy-to-reg nodes chained together with token chain
6061   // and flag operands which copy the outgoing args into the appropriate regs.
6062   SDValue InFlag;
6063   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6064     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6065                              RegsToPass[i].second, InFlag);
6066     InFlag = Chain.getValue(1);
6067   }
6068 
6069   if (isTailCall && !IsSibCall)
6070     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6071                     TailCallArguments);
6072 
6073   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6074                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6075                     SPDiff, NumBytes, Ins, InVals, CS);
6076 }
6077 
6078 SDValue PPCTargetLowering::LowerCall_Darwin(
6079     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6080     bool isTailCall, bool isPatchPoint,
6081     const SmallVectorImpl<ISD::OutputArg> &Outs,
6082     const SmallVectorImpl<SDValue> &OutVals,
6083     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6084     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6085     ImmutableCallSite CS) const {
6086   unsigned NumOps = Outs.size();
6087 
6088   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6089   bool isPPC64 = PtrVT == MVT::i64;
6090   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6091 
6092   MachineFunction &MF = DAG.getMachineFunction();
6093 
6094   // Mark this function as potentially containing a function that contains a
6095   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6096   // and restoring the callers stack pointer in this functions epilog. This is
6097   // done because by tail calling the called function might overwrite the value
6098   // in this function's (MF) stack pointer stack slot 0(SP).
6099   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6100       CallConv == CallingConv::Fast)
6101     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6102 
6103   // Count how many bytes are to be pushed on the stack, including the linkage
6104   // area, and parameter passing area.  We start with 24/48 bytes, which is
6105   // prereserved space for [SP][CR][LR][3 x unused].
6106   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6107   unsigned NumBytes = LinkageSize;
6108 
6109   // Add up all the space actually used.
6110   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6111   // they all go in registers, but we must reserve stack space for them for
6112   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6113   // assigned stack space in order, with padding so Altivec parameters are
6114   // 16-byte aligned.
6115   unsigned nAltivecParamsAtEnd = 0;
6116   for (unsigned i = 0; i != NumOps; ++i) {
6117     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6118     EVT ArgVT = Outs[i].VT;
6119     // Varargs Altivec parameters are padded to a 16 byte boundary.
6120     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6121         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6122         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6123       if (!isVarArg && !isPPC64) {
6124         // Non-varargs Altivec parameters go after all the non-Altivec
6125         // parameters; handle those later so we know how much padding we need.
6126         nAltivecParamsAtEnd++;
6127         continue;
6128       }
6129       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6130       NumBytes = ((NumBytes+15)/16)*16;
6131     }
6132     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6133   }
6134 
6135   // Allow for Altivec parameters at the end, if needed.
6136   if (nAltivecParamsAtEnd) {
6137     NumBytes = ((NumBytes+15)/16)*16;
6138     NumBytes += 16*nAltivecParamsAtEnd;
6139   }
6140 
6141   // The prolog code of the callee may store up to 8 GPR argument registers to
6142   // the stack, allowing va_start to index over them in memory if its varargs.
6143   // Because we cannot tell if this is needed on the caller side, we have to
6144   // conservatively assume that it is needed.  As such, make sure we have at
6145   // least enough stack space for the caller to store the 8 GPRs.
6146   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6147 
6148   // Tail call needs the stack to be aligned.
6149   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6150       CallConv == CallingConv::Fast)
6151     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6152 
6153   // Calculate by how many bytes the stack has to be adjusted in case of tail
6154   // call optimization.
6155   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6156 
6157   // To protect arguments on the stack from being clobbered in a tail call,
6158   // force all the loads to happen before doing any other lowering.
6159   if (isTailCall)
6160     Chain = DAG.getStackArgumentTokenFactor(Chain);
6161 
6162   // Adjust the stack pointer for the new arguments...
6163   // These operations are automatically eliminated by the prolog/epilog pass
6164   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6165   SDValue CallSeqStart = Chain;
6166 
6167   // Load the return address and frame pointer so it can be move somewhere else
6168   // later.
6169   SDValue LROp, FPOp;
6170   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6171 
6172   // Set up a copy of the stack pointer for use loading and storing any
6173   // arguments that may not fit in the registers available for argument
6174   // passing.
6175   SDValue StackPtr;
6176   if (isPPC64)
6177     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6178   else
6179     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6180 
6181   // Figure out which arguments are going to go in registers, and which in
6182   // memory.  Also, if this is a vararg function, floating point operations
6183   // must be stored to our stack, and loaded into integer regs as well, if
6184   // any integer regs are available for argument passing.
6185   unsigned ArgOffset = LinkageSize;
6186   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6187 
6188   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6189     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6190     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6191   };
6192   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6193     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6194     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6195   };
6196   static const MCPhysReg VR[] = {
6197     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6198     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6199   };
6200   const unsigned NumGPRs = array_lengthof(GPR_32);
6201   const unsigned NumFPRs = 13;
6202   const unsigned NumVRs  = array_lengthof(VR);
6203 
6204   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6205 
6206   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6207   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6208 
6209   SmallVector<SDValue, 8> MemOpChains;
6210   for (unsigned i = 0; i != NumOps; ++i) {
6211     SDValue Arg = OutVals[i];
6212     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6213 
6214     // PtrOff will be used to store the current argument to the stack if a
6215     // register cannot be found for it.
6216     SDValue PtrOff;
6217 
6218     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6219 
6220     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6221 
6222     // On PPC64, promote integers to 64-bit values.
6223     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6224       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6225       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6226       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6227     }
6228 
6229     // FIXME memcpy is used way more than necessary.  Correctness first.
6230     // Note: "by value" is code for passing a structure by value, not
6231     // basic types.
6232     if (Flags.isByVal()) {
6233       unsigned Size = Flags.getByValSize();
6234       // Very small objects are passed right-justified.  Everything else is
6235       // passed left-justified.
6236       if (Size==1 || Size==2) {
6237         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6238         if (GPR_idx != NumGPRs) {
6239           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6240                                         MachinePointerInfo(), VT);
6241           MemOpChains.push_back(Load.getValue(1));
6242           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6243 
6244           ArgOffset += PtrByteSize;
6245         } else {
6246           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6247                                           PtrOff.getValueType());
6248           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6249           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6250                                                             CallSeqStart,
6251                                                             Flags, DAG, dl);
6252           ArgOffset += PtrByteSize;
6253         }
6254         continue;
6255       }
6256       // Copy entire object into memory.  There are cases where gcc-generated
6257       // code assumes it is there, even if it could be put entirely into
6258       // registers.  (This is not what the doc says.)
6259       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6260                                                         CallSeqStart,
6261                                                         Flags, DAG, dl);
6262 
6263       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6264       // copy the pieces of the object that fit into registers from the
6265       // parameter save area.
6266       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6267         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6268         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6269         if (GPR_idx != NumGPRs) {
6270           SDValue Load =
6271               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6272           MemOpChains.push_back(Load.getValue(1));
6273           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6274           ArgOffset += PtrByteSize;
6275         } else {
6276           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6277           break;
6278         }
6279       }
6280       continue;
6281     }
6282 
6283     switch (Arg.getSimpleValueType().SimpleTy) {
6284     default: llvm_unreachable("Unexpected ValueType for argument!");
6285     case MVT::i1:
6286     case MVT::i32:
6287     case MVT::i64:
6288       if (GPR_idx != NumGPRs) {
6289         if (Arg.getValueType() == MVT::i1)
6290           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6291 
6292         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6293       } else {
6294         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6295                          isPPC64, isTailCall, false, MemOpChains,
6296                          TailCallArguments, dl);
6297       }
6298       ArgOffset += PtrByteSize;
6299       break;
6300     case MVT::f32:
6301     case MVT::f64:
6302       if (FPR_idx != NumFPRs) {
6303         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6304 
6305         if (isVarArg) {
6306           SDValue Store =
6307               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6308           MemOpChains.push_back(Store);
6309 
6310           // Float varargs are always shadowed in available integer registers
6311           if (GPR_idx != NumGPRs) {
6312             SDValue Load =
6313                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6314             MemOpChains.push_back(Load.getValue(1));
6315             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6316           }
6317           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6318             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6319             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6320             SDValue Load =
6321                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6322             MemOpChains.push_back(Load.getValue(1));
6323             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6324           }
6325         } else {
6326           // If we have any FPRs remaining, we may also have GPRs remaining.
6327           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6328           // GPRs.
6329           if (GPR_idx != NumGPRs)
6330             ++GPR_idx;
6331           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6332               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6333             ++GPR_idx;
6334         }
6335       } else
6336         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6337                          isPPC64, isTailCall, false, MemOpChains,
6338                          TailCallArguments, dl);
6339       if (isPPC64)
6340         ArgOffset += 8;
6341       else
6342         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6343       break;
6344     case MVT::v4f32:
6345     case MVT::v4i32:
6346     case MVT::v8i16:
6347     case MVT::v16i8:
6348       if (isVarArg) {
6349         // These go aligned on the stack, or in the corresponding R registers
6350         // when within range.  The Darwin PPC ABI doc claims they also go in
6351         // V registers; in fact gcc does this only for arguments that are
6352         // prototyped, not for those that match the ...  We do it for all
6353         // arguments, seems to work.
6354         while (ArgOffset % 16 !=0) {
6355           ArgOffset += PtrByteSize;
6356           if (GPR_idx != NumGPRs)
6357             GPR_idx++;
6358         }
6359         // We could elide this store in the case where the object fits
6360         // entirely in R registers.  Maybe later.
6361         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6362                              DAG.getConstant(ArgOffset, dl, PtrVT));
6363         SDValue Store =
6364             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6365         MemOpChains.push_back(Store);
6366         if (VR_idx != NumVRs) {
6367           SDValue Load =
6368               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6369           MemOpChains.push_back(Load.getValue(1));
6370           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6371         }
6372         ArgOffset += 16;
6373         for (unsigned i=0; i<16; i+=PtrByteSize) {
6374           if (GPR_idx == NumGPRs)
6375             break;
6376           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6377                                    DAG.getConstant(i, dl, PtrVT));
6378           SDValue Load =
6379               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6380           MemOpChains.push_back(Load.getValue(1));
6381           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6382         }
6383         break;
6384       }
6385 
6386       // Non-varargs Altivec params generally go in registers, but have
6387       // stack space allocated at the end.
6388       if (VR_idx != NumVRs) {
6389         // Doesn't have GPR space allocated.
6390         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6391       } else if (nAltivecParamsAtEnd==0) {
6392         // We are emitting Altivec params in order.
6393         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6394                          isPPC64, isTailCall, true, MemOpChains,
6395                          TailCallArguments, dl);
6396         ArgOffset += 16;
6397       }
6398       break;
6399     }
6400   }
6401   // If all Altivec parameters fit in registers, as they usually do,
6402   // they get stack space following the non-Altivec parameters.  We
6403   // don't track this here because nobody below needs it.
6404   // If there are more Altivec parameters than fit in registers emit
6405   // the stores here.
6406   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6407     unsigned j = 0;
6408     // Offset is aligned; skip 1st 12 params which go in V registers.
6409     ArgOffset = ((ArgOffset+15)/16)*16;
6410     ArgOffset += 12*16;
6411     for (unsigned i = 0; i != NumOps; ++i) {
6412       SDValue Arg = OutVals[i];
6413       EVT ArgType = Outs[i].VT;
6414       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6415           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6416         if (++j > NumVRs) {
6417           SDValue PtrOff;
6418           // We are emitting Altivec params in order.
6419           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6420                            isPPC64, isTailCall, true, MemOpChains,
6421                            TailCallArguments, dl);
6422           ArgOffset += 16;
6423         }
6424       }
6425     }
6426   }
6427 
6428   if (!MemOpChains.empty())
6429     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6430 
6431   // On Darwin, R12 must contain the address of an indirect callee.  This does
6432   // not mean the MTCTR instruction must use R12; it's easier to model this as
6433   // an extra parameter, so do that.
6434   if (!isTailCall &&
6435       !isFunctionGlobalAddress(Callee) &&
6436       !isa<ExternalSymbolSDNode>(Callee) &&
6437       !isBLACompatibleAddress(Callee, DAG))
6438     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6439                                                    PPC::R12), Callee));
6440 
6441   // Build a sequence of copy-to-reg nodes chained together with token chain
6442   // and flag operands which copy the outgoing args into the appropriate regs.
6443   SDValue InFlag;
6444   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6445     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6446                              RegsToPass[i].second, InFlag);
6447     InFlag = Chain.getValue(1);
6448   }
6449 
6450   if (isTailCall)
6451     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6452                     TailCallArguments);
6453 
6454   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6455                     /* unused except on PPC64 ELFv1 */ false, DAG,
6456                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6457                     NumBytes, Ins, InVals, CS);
6458 }
6459 
6460 bool
6461 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6462                                   MachineFunction &MF, bool isVarArg,
6463                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6464                                   LLVMContext &Context) const {
6465   SmallVector<CCValAssign, 16> RVLocs;
6466   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6467   return CCInfo.CheckReturn(
6468       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6469                 ? RetCC_PPC_Cold
6470                 : RetCC_PPC);
6471 }
6472 
6473 SDValue
6474 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6475                                bool isVarArg,
6476                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6477                                const SmallVectorImpl<SDValue> &OutVals,
6478                                const SDLoc &dl, SelectionDAG &DAG) const {
6479   SmallVector<CCValAssign, 16> RVLocs;
6480   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6481                  *DAG.getContext());
6482   CCInfo.AnalyzeReturn(Outs,
6483                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6484                            ? RetCC_PPC_Cold
6485                            : RetCC_PPC);
6486 
6487   SDValue Flag;
6488   SmallVector<SDValue, 4> RetOps(1, Chain);
6489 
6490   // Copy the result values into the output registers.
6491   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6492     CCValAssign &VA = RVLocs[i];
6493     assert(VA.isRegLoc() && "Can only return in registers!");
6494 
6495     SDValue Arg = OutVals[i];
6496 
6497     switch (VA.getLocInfo()) {
6498     default: llvm_unreachable("Unknown loc info!");
6499     case CCValAssign::Full: break;
6500     case CCValAssign::AExt:
6501       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6502       break;
6503     case CCValAssign::ZExt:
6504       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6505       break;
6506     case CCValAssign::SExt:
6507       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6508       break;
6509     }
6510 
6511     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6512     Flag = Chain.getValue(1);
6513     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6514   }
6515 
6516   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6517   const MCPhysReg *I =
6518     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6519   if (I) {
6520     for (; *I; ++I) {
6521 
6522       if (PPC::G8RCRegClass.contains(*I))
6523         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6524       else if (PPC::F8RCRegClass.contains(*I))
6525         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6526       else if (PPC::CRRCRegClass.contains(*I))
6527         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6528       else if (PPC::VRRCRegClass.contains(*I))
6529         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6530       else
6531         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6532     }
6533   }
6534 
6535   RetOps[0] = Chain;  // Update chain.
6536 
6537   // Add the flag if we have it.
6538   if (Flag.getNode())
6539     RetOps.push_back(Flag);
6540 
6541   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6542 }
6543 
6544 SDValue
6545 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6546                                                 SelectionDAG &DAG) const {
6547   SDLoc dl(Op);
6548 
6549   // Get the correct type for integers.
6550   EVT IntVT = Op.getValueType();
6551 
6552   // Get the inputs.
6553   SDValue Chain = Op.getOperand(0);
6554   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6555   // Build a DYNAREAOFFSET node.
6556   SDValue Ops[2] = {Chain, FPSIdx};
6557   SDVTList VTs = DAG.getVTList(IntVT);
6558   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6559 }
6560 
6561 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6562                                              SelectionDAG &DAG) const {
6563   // When we pop the dynamic allocation we need to restore the SP link.
6564   SDLoc dl(Op);
6565 
6566   // Get the correct type for pointers.
6567   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6568 
6569   // Construct the stack pointer operand.
6570   bool isPPC64 = Subtarget.isPPC64();
6571   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6572   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6573 
6574   // Get the operands for the STACKRESTORE.
6575   SDValue Chain = Op.getOperand(0);
6576   SDValue SaveSP = Op.getOperand(1);
6577 
6578   // Load the old link SP.
6579   SDValue LoadLinkSP =
6580       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6581 
6582   // Restore the stack pointer.
6583   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6584 
6585   // Store the old link SP.
6586   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6587 }
6588 
6589 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6590   MachineFunction &MF = DAG.getMachineFunction();
6591   bool isPPC64 = Subtarget.isPPC64();
6592   EVT PtrVT = getPointerTy(MF.getDataLayout());
6593 
6594   // Get current frame pointer save index.  The users of this index will be
6595   // primarily DYNALLOC instructions.
6596   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6597   int RASI = FI->getReturnAddrSaveIndex();
6598 
6599   // If the frame pointer save index hasn't been defined yet.
6600   if (!RASI) {
6601     // Find out what the fix offset of the frame pointer save area.
6602     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6603     // Allocate the frame index for frame pointer save area.
6604     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6605     // Save the result.
6606     FI->setReturnAddrSaveIndex(RASI);
6607   }
6608   return DAG.getFrameIndex(RASI, PtrVT);
6609 }
6610 
6611 SDValue
6612 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6613   MachineFunction &MF = DAG.getMachineFunction();
6614   bool isPPC64 = Subtarget.isPPC64();
6615   EVT PtrVT = getPointerTy(MF.getDataLayout());
6616 
6617   // Get current frame pointer save index.  The users of this index will be
6618   // primarily DYNALLOC instructions.
6619   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6620   int FPSI = FI->getFramePointerSaveIndex();
6621 
6622   // If the frame pointer save index hasn't been defined yet.
6623   if (!FPSI) {
6624     // Find out what the fix offset of the frame pointer save area.
6625     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6626     // Allocate the frame index for frame pointer save area.
6627     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6628     // Save the result.
6629     FI->setFramePointerSaveIndex(FPSI);
6630   }
6631   return DAG.getFrameIndex(FPSI, PtrVT);
6632 }
6633 
6634 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6635                                                    SelectionDAG &DAG) const {
6636   // Get the inputs.
6637   SDValue Chain = Op.getOperand(0);
6638   SDValue Size  = Op.getOperand(1);
6639   SDLoc dl(Op);
6640 
6641   // Get the correct type for pointers.
6642   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6643   // Negate the size.
6644   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6645                                 DAG.getConstant(0, dl, PtrVT), Size);
6646   // Construct a node for the frame pointer save index.
6647   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6648   // Build a DYNALLOC node.
6649   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6650   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6651   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6652 }
6653 
6654 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6655                                                      SelectionDAG &DAG) const {
6656   MachineFunction &MF = DAG.getMachineFunction();
6657 
6658   bool isPPC64 = Subtarget.isPPC64();
6659   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6660 
6661   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6662   return DAG.getFrameIndex(FI, PtrVT);
6663 }
6664 
6665 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6666                                                SelectionDAG &DAG) const {
6667   SDLoc DL(Op);
6668   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6669                      DAG.getVTList(MVT::i32, MVT::Other),
6670                      Op.getOperand(0), Op.getOperand(1));
6671 }
6672 
6673 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6674                                                 SelectionDAG &DAG) const {
6675   SDLoc DL(Op);
6676   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6677                      Op.getOperand(0), Op.getOperand(1));
6678 }
6679 
6680 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6681   if (Op.getValueType().isVector())
6682     return LowerVectorLoad(Op, DAG);
6683 
6684   assert(Op.getValueType() == MVT::i1 &&
6685          "Custom lowering only for i1 loads");
6686 
6687   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6688 
6689   SDLoc dl(Op);
6690   LoadSDNode *LD = cast<LoadSDNode>(Op);
6691 
6692   SDValue Chain = LD->getChain();
6693   SDValue BasePtr = LD->getBasePtr();
6694   MachineMemOperand *MMO = LD->getMemOperand();
6695 
6696   SDValue NewLD =
6697       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6698                      BasePtr, MVT::i8, MMO);
6699   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6700 
6701   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6702   return DAG.getMergeValues(Ops, dl);
6703 }
6704 
6705 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6706   if (Op.getOperand(1).getValueType().isVector())
6707     return LowerVectorStore(Op, DAG);
6708 
6709   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6710          "Custom lowering only for i1 stores");
6711 
6712   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6713 
6714   SDLoc dl(Op);
6715   StoreSDNode *ST = cast<StoreSDNode>(Op);
6716 
6717   SDValue Chain = ST->getChain();
6718   SDValue BasePtr = ST->getBasePtr();
6719   SDValue Value = ST->getValue();
6720   MachineMemOperand *MMO = ST->getMemOperand();
6721 
6722   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6723                       Value);
6724   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6725 }
6726 
6727 // FIXME: Remove this once the ANDI glue bug is fixed:
6728 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6729   assert(Op.getValueType() == MVT::i1 &&
6730          "Custom lowering only for i1 results");
6731 
6732   SDLoc DL(Op);
6733   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6734                      Op.getOperand(0));
6735 }
6736 
6737 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6738 /// possible.
6739 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6740   // Not FP? Not a fsel.
6741   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6742       !Op.getOperand(2).getValueType().isFloatingPoint())
6743     return Op;
6744 
6745   // We might be able to do better than this under some circumstances, but in
6746   // general, fsel-based lowering of select is a finite-math-only optimization.
6747   // For more information, see section F.3 of the 2.06 ISA specification.
6748   if (!DAG.getTarget().Options.NoInfsFPMath ||
6749       !DAG.getTarget().Options.NoNaNsFPMath)
6750     return Op;
6751   // TODO: Propagate flags from the select rather than global settings.
6752   SDNodeFlags Flags;
6753   Flags.setNoInfs(true);
6754   Flags.setNoNaNs(true);
6755 
6756   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6757 
6758   EVT ResVT = Op.getValueType();
6759   EVT CmpVT = Op.getOperand(0).getValueType();
6760   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6761   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6762   SDLoc dl(Op);
6763 
6764   // If the RHS of the comparison is a 0.0, we don't need to do the
6765   // subtraction at all.
6766   SDValue Sel1;
6767   if (isFloatingPointZero(RHS))
6768     switch (CC) {
6769     default: break;       // SETUO etc aren't handled by fsel.
6770     case ISD::SETNE:
6771       std::swap(TV, FV);
6772       LLVM_FALLTHROUGH;
6773     case ISD::SETEQ:
6774       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6775         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6776       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6777       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6778         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6779       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6780                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6781     case ISD::SETULT:
6782     case ISD::SETLT:
6783       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6784       LLVM_FALLTHROUGH;
6785     case ISD::SETOGE:
6786     case ISD::SETGE:
6787       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6788         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6789       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6790     case ISD::SETUGT:
6791     case ISD::SETGT:
6792       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6793       LLVM_FALLTHROUGH;
6794     case ISD::SETOLE:
6795     case ISD::SETLE:
6796       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6797         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6798       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6799                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6800     }
6801 
6802   SDValue Cmp;
6803   switch (CC) {
6804   default: break;       // SETUO etc aren't handled by fsel.
6805   case ISD::SETNE:
6806     std::swap(TV, FV);
6807     LLVM_FALLTHROUGH;
6808   case ISD::SETEQ:
6809     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6810     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6811       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6812     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6813     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6814       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6815     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6816                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6817   case ISD::SETULT:
6818   case ISD::SETLT:
6819     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6820     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6821       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6822     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6823   case ISD::SETOGE:
6824   case ISD::SETGE:
6825     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6826     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6827       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6828     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6829   case ISD::SETUGT:
6830   case ISD::SETGT:
6831     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6832     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6833       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6834     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6835   case ISD::SETOLE:
6836   case ISD::SETLE:
6837     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6838     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6839       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6840     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6841   }
6842   return Op;
6843 }
6844 
6845 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6846                                                SelectionDAG &DAG,
6847                                                const SDLoc &dl) const {
6848   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6849   SDValue Src = Op.getOperand(0);
6850   if (Src.getValueType() == MVT::f32)
6851     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6852 
6853   SDValue Tmp;
6854   switch (Op.getSimpleValueType().SimpleTy) {
6855   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6856   case MVT::i32:
6857     Tmp = DAG.getNode(
6858         Op.getOpcode() == ISD::FP_TO_SINT
6859             ? PPCISD::FCTIWZ
6860             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6861         dl, MVT::f64, Src);
6862     break;
6863   case MVT::i64:
6864     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6865            "i64 FP_TO_UINT is supported only with FPCVT");
6866     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6867                                                         PPCISD::FCTIDUZ,
6868                       dl, MVT::f64, Src);
6869     break;
6870   }
6871 
6872   // Convert the FP value to an int value through memory.
6873   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6874     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6875   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6876   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6877   MachinePointerInfo MPI =
6878       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6879 
6880   // Emit a store to the stack slot.
6881   SDValue Chain;
6882   if (i32Stack) {
6883     MachineFunction &MF = DAG.getMachineFunction();
6884     MachineMemOperand *MMO =
6885       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6886     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6887     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6888               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6889   } else
6890     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6891 
6892   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6893   // add in a bias on big endian.
6894   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6895     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6896                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6897     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6898   }
6899 
6900   RLI.Chain = Chain;
6901   RLI.Ptr = FIPtr;
6902   RLI.MPI = MPI;
6903 }
6904 
6905 /// Custom lowers floating point to integer conversions to use
6906 /// the direct move instructions available in ISA 2.07 to avoid the
6907 /// need for load/store combinations.
6908 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6909                                                     SelectionDAG &DAG,
6910                                                     const SDLoc &dl) const {
6911   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6912   SDValue Src = Op.getOperand(0);
6913 
6914   if (Src.getValueType() == MVT::f32)
6915     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6916 
6917   SDValue Tmp;
6918   switch (Op.getSimpleValueType().SimpleTy) {
6919   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6920   case MVT::i32:
6921     Tmp = DAG.getNode(
6922         Op.getOpcode() == ISD::FP_TO_SINT
6923             ? PPCISD::FCTIWZ
6924             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6925         dl, MVT::f64, Src);
6926     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6927     break;
6928   case MVT::i64:
6929     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6930            "i64 FP_TO_UINT is supported only with FPCVT");
6931     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6932                                                         PPCISD::FCTIDUZ,
6933                       dl, MVT::f64, Src);
6934     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6935     break;
6936   }
6937   return Tmp;
6938 }
6939 
6940 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6941                                           const SDLoc &dl) const {
6942 
6943   // FP to INT conversions are legal for f128.
6944   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
6945     return Op;
6946 
6947   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
6948   // PPC (the libcall is not available).
6949   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
6950     if (Op.getValueType() == MVT::i32) {
6951       if (Op.getOpcode() == ISD::FP_TO_SINT) {
6952         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6953                                  MVT::f64, Op.getOperand(0),
6954                                  DAG.getIntPtrConstant(0, dl));
6955         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6956                                  MVT::f64, Op.getOperand(0),
6957                                  DAG.getIntPtrConstant(1, dl));
6958 
6959         // Add the two halves of the long double in round-to-zero mode.
6960         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6961 
6962         // Now use a smaller FP_TO_SINT.
6963         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
6964       }
6965       if (Op.getOpcode() == ISD::FP_TO_UINT) {
6966         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
6967         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
6968         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
6969         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
6970         // FIXME: generated code sucks.
6971         // TODO: Are there fast-math-flags to propagate to this FSUB?
6972         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
6973                                    Op.getOperand(0), Tmp);
6974         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
6975         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
6976                            DAG.getConstant(0x80000000, dl, MVT::i32));
6977         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
6978                                     Op.getOperand(0));
6979         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
6980                                ISD::SETGE);
6981       }
6982     }
6983 
6984     return SDValue();
6985   }
6986 
6987   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6988     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6989 
6990   ReuseLoadInfo RLI;
6991   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6992 
6993   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6994                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6995 }
6996 
6997 // We're trying to insert a regular store, S, and then a load, L. If the
6998 // incoming value, O, is a load, we might just be able to have our load use the
6999 // address used by O. However, we don't know if anything else will store to
7000 // that address before we can load from it. To prevent this situation, we need
7001 // to insert our load, L, into the chain as a peer of O. To do this, we give L
7002 // the same chain operand as O, we create a token factor from the chain results
7003 // of O and L, and we replace all uses of O's chain result with that token
7004 // factor (see spliceIntoChain below for this last part).
7005 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
7006                                             ReuseLoadInfo &RLI,
7007                                             SelectionDAG &DAG,
7008                                             ISD::LoadExtType ET) const {
7009   SDLoc dl(Op);
7010   if (ET == ISD::NON_EXTLOAD &&
7011       (Op.getOpcode() == ISD::FP_TO_UINT ||
7012        Op.getOpcode() == ISD::FP_TO_SINT) &&
7013       isOperationLegalOrCustom(Op.getOpcode(),
7014                                Op.getOperand(0).getValueType())) {
7015 
7016     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7017     return true;
7018   }
7019 
7020   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7021   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7022       LD->isNonTemporal())
7023     return false;
7024   if (LD->getMemoryVT() != MemVT)
7025     return false;
7026 
7027   RLI.Ptr = LD->getBasePtr();
7028   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7029     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7030            "Non-pre-inc AM on PPC?");
7031     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7032                           LD->getOffset());
7033   }
7034 
7035   RLI.Chain = LD->getChain();
7036   RLI.MPI = LD->getPointerInfo();
7037   RLI.IsDereferenceable = LD->isDereferenceable();
7038   RLI.IsInvariant = LD->isInvariant();
7039   RLI.Alignment = LD->getAlignment();
7040   RLI.AAInfo = LD->getAAInfo();
7041   RLI.Ranges = LD->getRanges();
7042 
7043   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7044   return true;
7045 }
7046 
7047 // Given the head of the old chain, ResChain, insert a token factor containing
7048 // it and NewResChain, and make users of ResChain now be users of that token
7049 // factor.
7050 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7051 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7052                                         SDValue NewResChain,
7053                                         SelectionDAG &DAG) const {
7054   if (!ResChain)
7055     return;
7056 
7057   SDLoc dl(NewResChain);
7058 
7059   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7060                            NewResChain, DAG.getUNDEF(MVT::Other));
7061   assert(TF.getNode() != NewResChain.getNode() &&
7062          "A new TF really is required here");
7063 
7064   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7065   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7066 }
7067 
7068 /// Analyze profitability of direct move
7069 /// prefer float load to int load plus direct move
7070 /// when there is no integer use of int load
7071 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7072   SDNode *Origin = Op.getOperand(0).getNode();
7073   if (Origin->getOpcode() != ISD::LOAD)
7074     return true;
7075 
7076   // If there is no LXSIBZX/LXSIHZX, like Power8,
7077   // prefer direct move if the memory size is 1 or 2 bytes.
7078   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7079   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7080     return true;
7081 
7082   for (SDNode::use_iterator UI = Origin->use_begin(),
7083                             UE = Origin->use_end();
7084        UI != UE; ++UI) {
7085 
7086     // Only look at the users of the loaded value.
7087     if (UI.getUse().get().getResNo() != 0)
7088       continue;
7089 
7090     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7091         UI->getOpcode() != ISD::UINT_TO_FP)
7092       return true;
7093   }
7094 
7095   return false;
7096 }
7097 
7098 /// Custom lowers integer to floating point conversions to use
7099 /// the direct move instructions available in ISA 2.07 to avoid the
7100 /// need for load/store combinations.
7101 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7102                                                     SelectionDAG &DAG,
7103                                                     const SDLoc &dl) const {
7104   assert((Op.getValueType() == MVT::f32 ||
7105           Op.getValueType() == MVT::f64) &&
7106          "Invalid floating point type as target of conversion");
7107   assert(Subtarget.hasFPCVT() &&
7108          "Int to FP conversions with direct moves require FPCVT");
7109   SDValue FP;
7110   SDValue Src = Op.getOperand(0);
7111   bool SinglePrec = Op.getValueType() == MVT::f32;
7112   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7113   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7114   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7115                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7116 
7117   if (WordInt) {
7118     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7119                      dl, MVT::f64, Src);
7120     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7121   }
7122   else {
7123     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7124     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7125   }
7126 
7127   return FP;
7128 }
7129 
7130 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7131                                           SelectionDAG &DAG) const {
7132   SDLoc dl(Op);
7133 
7134   // Conversions to f128 are legal.
7135   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7136     return Op;
7137 
7138   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7139     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7140       return SDValue();
7141 
7142     SDValue Value = Op.getOperand(0);
7143     // The values are now known to be -1 (false) or 1 (true). To convert this
7144     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7145     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7146     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7147 
7148     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7149 
7150     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7151 
7152     if (Op.getValueType() != MVT::v4f64)
7153       Value = DAG.getNode(ISD::FP_ROUND, dl,
7154                           Op.getValueType(), Value,
7155                           DAG.getIntPtrConstant(1, dl));
7156     return Value;
7157   }
7158 
7159   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7160   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7161     return SDValue();
7162 
7163   if (Op.getOperand(0).getValueType() == MVT::i1)
7164     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7165                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7166                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7167 
7168   // If we have direct moves, we can do all the conversion, skip the store/load
7169   // however, without FPCVT we can't do most conversions.
7170   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7171       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7172     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7173 
7174   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7175          "UINT_TO_FP is supported only with FPCVT");
7176 
7177   // If we have FCFIDS, then use it when converting to single-precision.
7178   // Otherwise, convert to double-precision and then round.
7179   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7180                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7181                                                             : PPCISD::FCFIDS)
7182                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7183                                                             : PPCISD::FCFID);
7184   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7185                   ? MVT::f32
7186                   : MVT::f64;
7187 
7188   if (Op.getOperand(0).getValueType() == MVT::i64) {
7189     SDValue SINT = Op.getOperand(0);
7190     // When converting to single-precision, we actually need to convert
7191     // to double-precision first and then round to single-precision.
7192     // To avoid double-rounding effects during that operation, we have
7193     // to prepare the input operand.  Bits that might be truncated when
7194     // converting to double-precision are replaced by a bit that won't
7195     // be lost at this stage, but is below the single-precision rounding
7196     // position.
7197     //
7198     // However, if -enable-unsafe-fp-math is in effect, accept double
7199     // rounding to avoid the extra overhead.
7200     if (Op.getValueType() == MVT::f32 &&
7201         !Subtarget.hasFPCVT() &&
7202         !DAG.getTarget().Options.UnsafeFPMath) {
7203 
7204       // Twiddle input to make sure the low 11 bits are zero.  (If this
7205       // is the case, we are guaranteed the value will fit into the 53 bit
7206       // mantissa of an IEEE double-precision value without rounding.)
7207       // If any of those low 11 bits were not zero originally, make sure
7208       // bit 12 (value 2048) is set instead, so that the final rounding
7209       // to single-precision gets the correct result.
7210       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7211                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7212       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7213                           Round, DAG.getConstant(2047, dl, MVT::i64));
7214       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7215       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7216                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7217 
7218       // However, we cannot use that value unconditionally: if the magnitude
7219       // of the input value is small, the bit-twiddling we did above might
7220       // end up visibly changing the output.  Fortunately, in that case, we
7221       // don't need to twiddle bits since the original input will convert
7222       // exactly to double-precision floating-point already.  Therefore,
7223       // construct a conditional to use the original value if the top 11
7224       // bits are all sign-bit copies, and use the rounded value computed
7225       // above otherwise.
7226       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7227                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7228       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7229                          Cond, DAG.getConstant(1, dl, MVT::i64));
7230       Cond = DAG.getSetCC(dl, MVT::i32,
7231                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7232 
7233       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7234     }
7235 
7236     ReuseLoadInfo RLI;
7237     SDValue Bits;
7238 
7239     MachineFunction &MF = DAG.getMachineFunction();
7240     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7241       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7242                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7243       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7244     } else if (Subtarget.hasLFIWAX() &&
7245                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7246       MachineMemOperand *MMO =
7247         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7248                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7249       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7250       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7251                                      DAG.getVTList(MVT::f64, MVT::Other),
7252                                      Ops, MVT::i32, MMO);
7253       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7254     } else if (Subtarget.hasFPCVT() &&
7255                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7256       MachineMemOperand *MMO =
7257         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7258                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7259       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7260       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7261                                      DAG.getVTList(MVT::f64, MVT::Other),
7262                                      Ops, MVT::i32, MMO);
7263       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7264     } else if (((Subtarget.hasLFIWAX() &&
7265                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7266                 (Subtarget.hasFPCVT() &&
7267                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7268                SINT.getOperand(0).getValueType() == MVT::i32) {
7269       MachineFrameInfo &MFI = MF.getFrameInfo();
7270       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7271 
7272       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7273       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7274 
7275       SDValue Store =
7276           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7277                        MachinePointerInfo::getFixedStack(
7278                            DAG.getMachineFunction(), FrameIdx));
7279 
7280       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7281              "Expected an i32 store");
7282 
7283       RLI.Ptr = FIdx;
7284       RLI.Chain = Store;
7285       RLI.MPI =
7286           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7287       RLI.Alignment = 4;
7288 
7289       MachineMemOperand *MMO =
7290         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7291                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7292       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7293       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7294                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7295                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7296                                      Ops, MVT::i32, MMO);
7297     } else
7298       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7299 
7300     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7301 
7302     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7303       FP = DAG.getNode(ISD::FP_ROUND, dl,
7304                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7305     return FP;
7306   }
7307 
7308   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7309          "Unhandled INT_TO_FP type in custom expander!");
7310   // Since we only generate this in 64-bit mode, we can take advantage of
7311   // 64-bit registers.  In particular, sign extend the input value into the
7312   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7313   // then lfd it and fcfid it.
7314   MachineFunction &MF = DAG.getMachineFunction();
7315   MachineFrameInfo &MFI = MF.getFrameInfo();
7316   EVT PtrVT = getPointerTy(MF.getDataLayout());
7317 
7318   SDValue Ld;
7319   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7320     ReuseLoadInfo RLI;
7321     bool ReusingLoad;
7322     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7323                                             DAG))) {
7324       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7325       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7326 
7327       SDValue Store =
7328           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7329                        MachinePointerInfo::getFixedStack(
7330                            DAG.getMachineFunction(), FrameIdx));
7331 
7332       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7333              "Expected an i32 store");
7334 
7335       RLI.Ptr = FIdx;
7336       RLI.Chain = Store;
7337       RLI.MPI =
7338           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7339       RLI.Alignment = 4;
7340     }
7341 
7342     MachineMemOperand *MMO =
7343       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7344                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7345     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7346     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7347                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7348                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7349                                  Ops, MVT::i32, MMO);
7350     if (ReusingLoad)
7351       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7352   } else {
7353     assert(Subtarget.isPPC64() &&
7354            "i32->FP without LFIWAX supported only on PPC64");
7355 
7356     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7357     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7358 
7359     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7360                                 Op.getOperand(0));
7361 
7362     // STD the extended value into the stack slot.
7363     SDValue Store = DAG.getStore(
7364         DAG.getEntryNode(), dl, Ext64, FIdx,
7365         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7366 
7367     // Load the value as a double.
7368     Ld = DAG.getLoad(
7369         MVT::f64, dl, Store, FIdx,
7370         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7371   }
7372 
7373   // FCFID it and return it.
7374   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7375   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7376     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7377                      DAG.getIntPtrConstant(0, dl));
7378   return FP;
7379 }
7380 
7381 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7382                                             SelectionDAG &DAG) const {
7383   SDLoc dl(Op);
7384   /*
7385    The rounding mode is in bits 30:31 of FPSR, and has the following
7386    settings:
7387      00 Round to nearest
7388      01 Round to 0
7389      10 Round to +inf
7390      11 Round to -inf
7391 
7392   FLT_ROUNDS, on the other hand, expects the following:
7393     -1 Undefined
7394      0 Round to 0
7395      1 Round to nearest
7396      2 Round to +inf
7397      3 Round to -inf
7398 
7399   To perform the conversion, we do:
7400     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7401   */
7402 
7403   MachineFunction &MF = DAG.getMachineFunction();
7404   EVT VT = Op.getValueType();
7405   EVT PtrVT = getPointerTy(MF.getDataLayout());
7406 
7407   // Save FP Control Word to register
7408   EVT NodeTys[] = {
7409     MVT::f64,    // return register
7410     MVT::Glue    // unused in this context
7411   };
7412   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7413 
7414   // Save FP register to stack slot
7415   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7416   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7417   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7418                                MachinePointerInfo());
7419 
7420   // Load FP Control Word from low 32 bits of stack slot.
7421   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7422   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7423   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7424 
7425   // Transform as necessary
7426   SDValue CWD1 =
7427     DAG.getNode(ISD::AND, dl, MVT::i32,
7428                 CWD, DAG.getConstant(3, dl, MVT::i32));
7429   SDValue CWD2 =
7430     DAG.getNode(ISD::SRL, dl, MVT::i32,
7431                 DAG.getNode(ISD::AND, dl, MVT::i32,
7432                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7433                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7434                             DAG.getConstant(3, dl, MVT::i32)),
7435                 DAG.getConstant(1, dl, MVT::i32));
7436 
7437   SDValue RetVal =
7438     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7439 
7440   return DAG.getNode((VT.getSizeInBits() < 16 ?
7441                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7442 }
7443 
7444 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7445   EVT VT = Op.getValueType();
7446   unsigned BitWidth = VT.getSizeInBits();
7447   SDLoc dl(Op);
7448   assert(Op.getNumOperands() == 3 &&
7449          VT == Op.getOperand(1).getValueType() &&
7450          "Unexpected SHL!");
7451 
7452   // Expand into a bunch of logical ops.  Note that these ops
7453   // depend on the PPC behavior for oversized shift amounts.
7454   SDValue Lo = Op.getOperand(0);
7455   SDValue Hi = Op.getOperand(1);
7456   SDValue Amt = Op.getOperand(2);
7457   EVT AmtVT = Amt.getValueType();
7458 
7459   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7460                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7461   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7462   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7463   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7464   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7465                              DAG.getConstant(-BitWidth, dl, AmtVT));
7466   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7467   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7468   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7469   SDValue OutOps[] = { OutLo, OutHi };
7470   return DAG.getMergeValues(OutOps, dl);
7471 }
7472 
7473 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7474   EVT VT = Op.getValueType();
7475   SDLoc dl(Op);
7476   unsigned BitWidth = VT.getSizeInBits();
7477   assert(Op.getNumOperands() == 3 &&
7478          VT == Op.getOperand(1).getValueType() &&
7479          "Unexpected SRL!");
7480 
7481   // Expand into a bunch of logical ops.  Note that these ops
7482   // depend on the PPC behavior for oversized shift amounts.
7483   SDValue Lo = Op.getOperand(0);
7484   SDValue Hi = Op.getOperand(1);
7485   SDValue Amt = Op.getOperand(2);
7486   EVT AmtVT = Amt.getValueType();
7487 
7488   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7489                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7490   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7491   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7492   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7493   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7494                              DAG.getConstant(-BitWidth, dl, AmtVT));
7495   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7496   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7497   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7498   SDValue OutOps[] = { OutLo, OutHi };
7499   return DAG.getMergeValues(OutOps, dl);
7500 }
7501 
7502 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7503   SDLoc dl(Op);
7504   EVT VT = Op.getValueType();
7505   unsigned BitWidth = VT.getSizeInBits();
7506   assert(Op.getNumOperands() == 3 &&
7507          VT == Op.getOperand(1).getValueType() &&
7508          "Unexpected SRA!");
7509 
7510   // Expand into a bunch of logical ops, followed by a select_cc.
7511   SDValue Lo = Op.getOperand(0);
7512   SDValue Hi = Op.getOperand(1);
7513   SDValue Amt = Op.getOperand(2);
7514   EVT AmtVT = Amt.getValueType();
7515 
7516   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7517                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7518   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7519   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7520   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7521   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7522                              DAG.getConstant(-BitWidth, dl, AmtVT));
7523   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7524   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7525   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7526                                   Tmp4, Tmp6, ISD::SETLE);
7527   SDValue OutOps[] = { OutLo, OutHi };
7528   return DAG.getMergeValues(OutOps, dl);
7529 }
7530 
7531 //===----------------------------------------------------------------------===//
7532 // Vector related lowering.
7533 //
7534 
7535 /// BuildSplatI - Build a canonical splati of Val with an element size of
7536 /// SplatSize.  Cast the result to VT.
7537 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7538                            SelectionDAG &DAG, const SDLoc &dl) {
7539   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7540 
7541   static const MVT VTys[] = { // canonical VT to use for each size.
7542     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7543   };
7544 
7545   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7546 
7547   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7548   if (Val == -1)
7549     SplatSize = 1;
7550 
7551   EVT CanonicalVT = VTys[SplatSize-1];
7552 
7553   // Build a canonical splat for this value.
7554   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7555 }
7556 
7557 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7558 /// specified intrinsic ID.
7559 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7560                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7561   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7562   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7563                      DAG.getConstant(IID, dl, MVT::i32), Op);
7564 }
7565 
7566 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7567 /// specified intrinsic ID.
7568 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7569                                 SelectionDAG &DAG, const SDLoc &dl,
7570                                 EVT DestVT = MVT::Other) {
7571   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7572   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7573                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7574 }
7575 
7576 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7577 /// specified intrinsic ID.
7578 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7579                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7580                                 EVT DestVT = MVT::Other) {
7581   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7582   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7583                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7584 }
7585 
7586 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7587 /// amount.  The result has the specified value type.
7588 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7589                            SelectionDAG &DAG, const SDLoc &dl) {
7590   // Force LHS/RHS to be the right type.
7591   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7592   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7593 
7594   int Ops[16];
7595   for (unsigned i = 0; i != 16; ++i)
7596     Ops[i] = i + Amt;
7597   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7598   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7599 }
7600 
7601 /// Do we have an efficient pattern in a .td file for this node?
7602 ///
7603 /// \param V - pointer to the BuildVectorSDNode being matched
7604 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7605 ///
7606 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7607 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7608 /// the opposite is true (expansion is beneficial) are:
7609 /// - The node builds a vector out of integers that are not 32 or 64-bits
7610 /// - The node builds a vector out of constants
7611 /// - The node is a "load-and-splat"
7612 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7613 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7614                                             bool HasDirectMove,
7615                                             bool HasP8Vector) {
7616   EVT VecVT = V->getValueType(0);
7617   bool RightType = VecVT == MVT::v2f64 ||
7618     (HasP8Vector && VecVT == MVT::v4f32) ||
7619     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7620   if (!RightType)
7621     return false;
7622 
7623   bool IsSplat = true;
7624   bool IsLoad = false;
7625   SDValue Op0 = V->getOperand(0);
7626 
7627   // This function is called in a block that confirms the node is not a constant
7628   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7629   // different constants.
7630   if (V->isConstant())
7631     return false;
7632   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7633     if (V->getOperand(i).isUndef())
7634       return false;
7635     // We want to expand nodes that represent load-and-splat even if the
7636     // loaded value is a floating point truncation or conversion to int.
7637     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7638         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7639          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7640         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7641          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7642         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7643          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7644       IsLoad = true;
7645     // If the operands are different or the input is not a load and has more
7646     // uses than just this BV node, then it isn't a splat.
7647     if (V->getOperand(i) != Op0 ||
7648         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7649       IsSplat = false;
7650   }
7651   return !(IsSplat && IsLoad);
7652 }
7653 
7654 // If this is a case we can't handle, return null and let the default
7655 // expansion code take care of it.  If we CAN select this case, and if it
7656 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7657 // this case more efficiently than a constant pool load, lower it to the
7658 // sequence of ops that should be used.
7659 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7660                                              SelectionDAG &DAG) const {
7661   SDLoc dl(Op);
7662   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7663   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7664 
7665   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7666     // We first build an i32 vector, load it into a QPX register,
7667     // then convert it to a floating-point vector and compare it
7668     // to a zero vector to get the boolean result.
7669     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7670     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7671     MachinePointerInfo PtrInfo =
7672         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7673     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7674     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7675 
7676     assert(BVN->getNumOperands() == 4 &&
7677       "BUILD_VECTOR for v4i1 does not have 4 operands");
7678 
7679     bool IsConst = true;
7680     for (unsigned i = 0; i < 4; ++i) {
7681       if (BVN->getOperand(i).isUndef()) continue;
7682       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7683         IsConst = false;
7684         break;
7685       }
7686     }
7687 
7688     if (IsConst) {
7689       Constant *One =
7690         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7691       Constant *NegOne =
7692         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7693 
7694       Constant *CV[4];
7695       for (unsigned i = 0; i < 4; ++i) {
7696         if (BVN->getOperand(i).isUndef())
7697           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7698         else if (isNullConstant(BVN->getOperand(i)))
7699           CV[i] = NegOne;
7700         else
7701           CV[i] = One;
7702       }
7703 
7704       Constant *CP = ConstantVector::get(CV);
7705       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7706                                           16 /* alignment */);
7707 
7708       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7709       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7710       return DAG.getMemIntrinsicNode(
7711           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7712           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7713     }
7714 
7715     SmallVector<SDValue, 4> Stores;
7716     for (unsigned i = 0; i < 4; ++i) {
7717       if (BVN->getOperand(i).isUndef()) continue;
7718 
7719       unsigned Offset = 4*i;
7720       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7721       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7722 
7723       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7724       if (StoreSize > 4) {
7725         Stores.push_back(
7726             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7727                               PtrInfo.getWithOffset(Offset), MVT::i32));
7728       } else {
7729         SDValue StoreValue = BVN->getOperand(i);
7730         if (StoreSize < 4)
7731           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7732 
7733         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7734                                       PtrInfo.getWithOffset(Offset)));
7735       }
7736     }
7737 
7738     SDValue StoreChain;
7739     if (!Stores.empty())
7740       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7741     else
7742       StoreChain = DAG.getEntryNode();
7743 
7744     // Now load from v4i32 into the QPX register; this will extend it to
7745     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7746     // is typed as v4f64 because the QPX register integer states are not
7747     // explicitly represented.
7748 
7749     SDValue Ops[] = {StoreChain,
7750                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7751                      FIdx};
7752     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7753 
7754     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7755       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7756     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7757       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7758       LoadedVect);
7759 
7760     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7761 
7762     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7763   }
7764 
7765   // All other QPX vectors are handled by generic code.
7766   if (Subtarget.hasQPX())
7767     return SDValue();
7768 
7769   // Check if this is a splat of a constant value.
7770   APInt APSplatBits, APSplatUndef;
7771   unsigned SplatBitSize;
7772   bool HasAnyUndefs;
7773   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7774                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7775       SplatBitSize > 32) {
7776     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7777     // lowered to VSX instructions under certain conditions.
7778     // Without VSX, there is no pattern more efficient than expanding the node.
7779     if (Subtarget.hasVSX() &&
7780         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7781                                         Subtarget.hasP8Vector()))
7782       return Op;
7783     return SDValue();
7784   }
7785 
7786   unsigned SplatBits = APSplatBits.getZExtValue();
7787   unsigned SplatUndef = APSplatUndef.getZExtValue();
7788   unsigned SplatSize = SplatBitSize / 8;
7789 
7790   // First, handle single instruction cases.
7791 
7792   // All zeros?
7793   if (SplatBits == 0) {
7794     // Canonicalize all zero vectors to be v4i32.
7795     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7796       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7797       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7798     }
7799     return Op;
7800   }
7801 
7802   // We have XXSPLTIB for constant splats one byte wide
7803   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7804     // This is a splat of 1-byte elements with some elements potentially undef.
7805     // Rather than trying to match undef in the SDAG patterns, ensure that all
7806     // elements are the same constant.
7807     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7808       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7809                                                        dl, MVT::i32));
7810       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7811       if (Op.getValueType() != MVT::v16i8)
7812         return DAG.getBitcast(Op.getValueType(), NewBV);
7813       return NewBV;
7814     }
7815 
7816     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7817     // detect that constant splats like v8i16: 0xABAB are really just splats
7818     // of a 1-byte constant. In this case, we need to convert the node to a
7819     // splat of v16i8 and a bitcast.
7820     if (Op.getValueType() != MVT::v16i8)
7821       return DAG.getBitcast(Op.getValueType(),
7822                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7823 
7824     return Op;
7825   }
7826 
7827   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7828   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7829                     (32-SplatBitSize));
7830   if (SextVal >= -16 && SextVal <= 15)
7831     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7832 
7833   // Two instruction sequences.
7834 
7835   // If this value is in the range [-32,30] and is even, use:
7836   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7837   // If this value is in the range [17,31] and is odd, use:
7838   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7839   // If this value is in the range [-31,-17] and is odd, use:
7840   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7841   // Note the last two are three-instruction sequences.
7842   if (SextVal >= -32 && SextVal <= 31) {
7843     // To avoid having these optimizations undone by constant folding,
7844     // we convert to a pseudo that will be expanded later into one of
7845     // the above forms.
7846     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7847     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7848               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7849     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7850     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7851     if (VT == Op.getValueType())
7852       return RetVal;
7853     else
7854       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7855   }
7856 
7857   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7858   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7859   // for fneg/fabs.
7860   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7861     // Make -1 and vspltisw -1:
7862     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7863 
7864     // Make the VSLW intrinsic, computing 0x8000_0000.
7865     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7866                                    OnesV, DAG, dl);
7867 
7868     // xor by OnesV to invert it.
7869     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7870     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7871   }
7872 
7873   // Check to see if this is a wide variety of vsplti*, binop self cases.
7874   static const signed char SplatCsts[] = {
7875     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7876     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7877   };
7878 
7879   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7880     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7881     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7882     int i = SplatCsts[idx];
7883 
7884     // Figure out what shift amount will be used by altivec if shifted by i in
7885     // this splat size.
7886     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7887 
7888     // vsplti + shl self.
7889     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7890       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7891       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7892         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7893         Intrinsic::ppc_altivec_vslw
7894       };
7895       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7896       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7897     }
7898 
7899     // vsplti + srl self.
7900     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7901       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7902       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7903         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7904         Intrinsic::ppc_altivec_vsrw
7905       };
7906       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7907       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7908     }
7909 
7910     // vsplti + sra self.
7911     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7912       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7913       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7914         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7915         Intrinsic::ppc_altivec_vsraw
7916       };
7917       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7918       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7919     }
7920 
7921     // vsplti + rol self.
7922     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7923                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7924       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7925       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7926         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7927         Intrinsic::ppc_altivec_vrlw
7928       };
7929       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7930       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7931     }
7932 
7933     // t = vsplti c, result = vsldoi t, t, 1
7934     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7935       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7936       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7937       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7938     }
7939     // t = vsplti c, result = vsldoi t, t, 2
7940     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7941       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7942       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7943       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7944     }
7945     // t = vsplti c, result = vsldoi t, t, 3
7946     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7947       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7948       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7949       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7950     }
7951   }
7952 
7953   return SDValue();
7954 }
7955 
7956 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7957 /// the specified operations to build the shuffle.
7958 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7959                                       SDValue RHS, SelectionDAG &DAG,
7960                                       const SDLoc &dl) {
7961   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7962   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7963   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7964 
7965   enum {
7966     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7967     OP_VMRGHW,
7968     OP_VMRGLW,
7969     OP_VSPLTISW0,
7970     OP_VSPLTISW1,
7971     OP_VSPLTISW2,
7972     OP_VSPLTISW3,
7973     OP_VSLDOI4,
7974     OP_VSLDOI8,
7975     OP_VSLDOI12
7976   };
7977 
7978   if (OpNum == OP_COPY) {
7979     if (LHSID == (1*9+2)*9+3) return LHS;
7980     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7981     return RHS;
7982   }
7983 
7984   SDValue OpLHS, OpRHS;
7985   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7986   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7987 
7988   int ShufIdxs[16];
7989   switch (OpNum) {
7990   default: llvm_unreachable("Unknown i32 permute!");
7991   case OP_VMRGHW:
7992     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7993     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7994     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7995     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7996     break;
7997   case OP_VMRGLW:
7998     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7999     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
8000     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
8001     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
8002     break;
8003   case OP_VSPLTISW0:
8004     for (unsigned i = 0; i != 16; ++i)
8005       ShufIdxs[i] = (i&3)+0;
8006     break;
8007   case OP_VSPLTISW1:
8008     for (unsigned i = 0; i != 16; ++i)
8009       ShufIdxs[i] = (i&3)+4;
8010     break;
8011   case OP_VSPLTISW2:
8012     for (unsigned i = 0; i != 16; ++i)
8013       ShufIdxs[i] = (i&3)+8;
8014     break;
8015   case OP_VSPLTISW3:
8016     for (unsigned i = 0; i != 16; ++i)
8017       ShufIdxs[i] = (i&3)+12;
8018     break;
8019   case OP_VSLDOI4:
8020     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8021   case OP_VSLDOI8:
8022     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8023   case OP_VSLDOI12:
8024     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8025   }
8026   EVT VT = OpLHS.getValueType();
8027   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8028   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8029   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8030   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8031 }
8032 
8033 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8034 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8035 /// SDValue.
8036 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8037                                            SelectionDAG &DAG) const {
8038   const unsigned BytesInVector = 16;
8039   bool IsLE = Subtarget.isLittleEndian();
8040   SDLoc dl(N);
8041   SDValue V1 = N->getOperand(0);
8042   SDValue V2 = N->getOperand(1);
8043   unsigned ShiftElts = 0, InsertAtByte = 0;
8044   bool Swap = false;
8045 
8046   // Shifts required to get the byte we want at element 7.
8047   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8048                                    0, 15, 14, 13, 12, 11, 10, 9};
8049   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8050                                 1, 2,  3,  4,  5,  6,  7,  8};
8051 
8052   ArrayRef<int> Mask = N->getMask();
8053   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8054 
8055   // For each mask element, find out if we're just inserting something
8056   // from V2 into V1 or vice versa.
8057   // Possible permutations inserting an element from V2 into V1:
8058   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8059   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8060   //   ...
8061   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8062   // Inserting from V1 into V2 will be similar, except mask range will be
8063   // [16,31].
8064 
8065   bool FoundCandidate = false;
8066   // If both vector operands for the shuffle are the same vector, the mask
8067   // will contain only elements from the first one and the second one will be
8068   // undef.
8069   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8070   // Go through the mask of half-words to find an element that's being moved
8071   // from one vector to the other.
8072   for (unsigned i = 0; i < BytesInVector; ++i) {
8073     unsigned CurrentElement = Mask[i];
8074     // If 2nd operand is undefined, we should only look for element 7 in the
8075     // Mask.
8076     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8077       continue;
8078 
8079     bool OtherElementsInOrder = true;
8080     // Examine the other elements in the Mask to see if they're in original
8081     // order.
8082     for (unsigned j = 0; j < BytesInVector; ++j) {
8083       if (j == i)
8084         continue;
8085       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8086       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8087       // in which we always assume we're always picking from the 1st operand.
8088       int MaskOffset =
8089           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8090       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8091         OtherElementsInOrder = false;
8092         break;
8093       }
8094     }
8095     // If other elements are in original order, we record the number of shifts
8096     // we need to get the element we want into element 7. Also record which byte
8097     // in the vector we should insert into.
8098     if (OtherElementsInOrder) {
8099       // If 2nd operand is undefined, we assume no shifts and no swapping.
8100       if (V2.isUndef()) {
8101         ShiftElts = 0;
8102         Swap = false;
8103       } else {
8104         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8105         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8106                          : BigEndianShifts[CurrentElement & 0xF];
8107         Swap = CurrentElement < BytesInVector;
8108       }
8109       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8110       FoundCandidate = true;
8111       break;
8112     }
8113   }
8114 
8115   if (!FoundCandidate)
8116     return SDValue();
8117 
8118   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8119   // optionally with VECSHL if shift is required.
8120   if (Swap)
8121     std::swap(V1, V2);
8122   if (V2.isUndef())
8123     V2 = V1;
8124   if (ShiftElts) {
8125     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8126                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8127     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8128                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8129   }
8130   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8131                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8132 }
8133 
8134 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8135 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8136 /// SDValue.
8137 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8138                                            SelectionDAG &DAG) const {
8139   const unsigned NumHalfWords = 8;
8140   const unsigned BytesInVector = NumHalfWords * 2;
8141   // Check that the shuffle is on half-words.
8142   if (!isNByteElemShuffleMask(N, 2, 1))
8143     return SDValue();
8144 
8145   bool IsLE = Subtarget.isLittleEndian();
8146   SDLoc dl(N);
8147   SDValue V1 = N->getOperand(0);
8148   SDValue V2 = N->getOperand(1);
8149   unsigned ShiftElts = 0, InsertAtByte = 0;
8150   bool Swap = false;
8151 
8152   // Shifts required to get the half-word we want at element 3.
8153   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8154   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8155 
8156   uint32_t Mask = 0;
8157   uint32_t OriginalOrderLow = 0x1234567;
8158   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8159   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8160   // 32-bit space, only need 4-bit nibbles per element.
8161   for (unsigned i = 0; i < NumHalfWords; ++i) {
8162     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8163     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8164   }
8165 
8166   // For each mask element, find out if we're just inserting something
8167   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8168   // from V2 into V1:
8169   //   X, 1, 2, 3, 4, 5, 6, 7
8170   //   0, X, 2, 3, 4, 5, 6, 7
8171   //   0, 1, X, 3, 4, 5, 6, 7
8172   //   0, 1, 2, X, 4, 5, 6, 7
8173   //   0, 1, 2, 3, X, 5, 6, 7
8174   //   0, 1, 2, 3, 4, X, 6, 7
8175   //   0, 1, 2, 3, 4, 5, X, 7
8176   //   0, 1, 2, 3, 4, 5, 6, X
8177   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8178 
8179   bool FoundCandidate = false;
8180   // Go through the mask of half-words to find an element that's being moved
8181   // from one vector to the other.
8182   for (unsigned i = 0; i < NumHalfWords; ++i) {
8183     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8184     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8185     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8186     uint32_t TargetOrder = 0x0;
8187 
8188     // If both vector operands for the shuffle are the same vector, the mask
8189     // will contain only elements from the first one and the second one will be
8190     // undef.
8191     if (V2.isUndef()) {
8192       ShiftElts = 0;
8193       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8194       TargetOrder = OriginalOrderLow;
8195       Swap = false;
8196       // Skip if not the correct element or mask of other elements don't equal
8197       // to our expected order.
8198       if (MaskOneElt == VINSERTHSrcElem &&
8199           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8200         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8201         FoundCandidate = true;
8202         break;
8203       }
8204     } else { // If both operands are defined.
8205       // Target order is [8,15] if the current mask is between [0,7].
8206       TargetOrder =
8207           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8208       // Skip if mask of other elements don't equal our expected order.
8209       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8210         // We only need the last 3 bits for the number of shifts.
8211         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8212                          : BigEndianShifts[MaskOneElt & 0x7];
8213         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8214         Swap = MaskOneElt < NumHalfWords;
8215         FoundCandidate = true;
8216         break;
8217       }
8218     }
8219   }
8220 
8221   if (!FoundCandidate)
8222     return SDValue();
8223 
8224   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8225   // optionally with VECSHL if shift is required.
8226   if (Swap)
8227     std::swap(V1, V2);
8228   if (V2.isUndef())
8229     V2 = V1;
8230   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8231   if (ShiftElts) {
8232     // Double ShiftElts because we're left shifting on v16i8 type.
8233     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8234                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8235     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8236     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8237                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8238     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8239   }
8240   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8241   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8242                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8243   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8244 }
8245 
8246 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8247 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8248 /// return the code it can be lowered into.  Worst case, it can always be
8249 /// lowered into a vperm.
8250 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8251                                                SelectionDAG &DAG) const {
8252   SDLoc dl(Op);
8253   SDValue V1 = Op.getOperand(0);
8254   SDValue V2 = Op.getOperand(1);
8255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8256   EVT VT = Op.getValueType();
8257   bool isLittleEndian = Subtarget.isLittleEndian();
8258 
8259   unsigned ShiftElts, InsertAtByte;
8260   bool Swap = false;
8261   if (Subtarget.hasP9Vector() &&
8262       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8263                            isLittleEndian)) {
8264     if (Swap)
8265       std::swap(V1, V2);
8266     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8267     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8268     if (ShiftElts) {
8269       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8270                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8271       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8272                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8273       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8274     }
8275     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8276                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8277     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8278   }
8279 
8280   if (Subtarget.hasP9Altivec()) {
8281     SDValue NewISDNode;
8282     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8283       return NewISDNode;
8284 
8285     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8286       return NewISDNode;
8287   }
8288 
8289   if (Subtarget.hasVSX() &&
8290       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8291     if (Swap)
8292       std::swap(V1, V2);
8293     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8294     SDValue Conv2 =
8295         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8296 
8297     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8298                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8299     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8300   }
8301 
8302   if (Subtarget.hasVSX() &&
8303     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8304     if (Swap)
8305       std::swap(V1, V2);
8306     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8307     SDValue Conv2 =
8308         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8309 
8310     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8311                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8312     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8313   }
8314 
8315   if (Subtarget.hasP9Vector()) {
8316      if (PPC::isXXBRHShuffleMask(SVOp)) {
8317       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8318       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8319       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8320     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8321       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8322       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8323       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8324     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8325       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8326       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8327       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8328     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8329       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8330       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8331       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8332     }
8333   }
8334 
8335   if (Subtarget.hasVSX()) {
8336     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8337       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8338 
8339       // If the source for the shuffle is a scalar_to_vector that came from a
8340       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8341       if (Subtarget.hasP9Vector() &&
8342           ((isLittleEndian && SplatIdx == 3) ||
8343            (!isLittleEndian && SplatIdx == 0))) {
8344         SDValue Src = V1.getOperand(0);
8345         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8346             Src.getOperand(0).getOpcode() == ISD::LOAD &&
8347             Src.getOperand(0).hasOneUse())
8348           return V1;
8349       }
8350       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8351       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8352                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8353       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8354     }
8355 
8356     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8357     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8358       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8359       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8360       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8361     }
8362   }
8363 
8364   if (Subtarget.hasQPX()) {
8365     if (VT.getVectorNumElements() != 4)
8366       return SDValue();
8367 
8368     if (V2.isUndef()) V2 = V1;
8369 
8370     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8371     if (AlignIdx != -1) {
8372       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8373                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8374     } else if (SVOp->isSplat()) {
8375       int SplatIdx = SVOp->getSplatIndex();
8376       if (SplatIdx >= 4) {
8377         std::swap(V1, V2);
8378         SplatIdx -= 4;
8379       }
8380 
8381       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8382                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8383     }
8384 
8385     // Lower this into a qvgpci/qvfperm pair.
8386 
8387     // Compute the qvgpci literal
8388     unsigned idx = 0;
8389     for (unsigned i = 0; i < 4; ++i) {
8390       int m = SVOp->getMaskElt(i);
8391       unsigned mm = m >= 0 ? (unsigned) m : i;
8392       idx |= mm << (3-i)*3;
8393     }
8394 
8395     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8396                              DAG.getConstant(idx, dl, MVT::i32));
8397     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8398   }
8399 
8400   // Cases that are handled by instructions that take permute immediates
8401   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8402   // selected by the instruction selector.
8403   if (V2.isUndef()) {
8404     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8405         PPC::isSplatShuffleMask(SVOp, 2) ||
8406         PPC::isSplatShuffleMask(SVOp, 4) ||
8407         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8408         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8409         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8410         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8411         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8412         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8413         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8414         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8415         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8416         (Subtarget.hasP8Altivec() && (
8417          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8418          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8419          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8420       return Op;
8421     }
8422   }
8423 
8424   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8425   // and produce a fixed permutation.  If any of these match, do not lower to
8426   // VPERM.
8427   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8428   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8429       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8430       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8431       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8432       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8433       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8434       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8435       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8436       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8437       (Subtarget.hasP8Altivec() && (
8438        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8439        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8440        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8441     return Op;
8442 
8443   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8444   // perfect shuffle table to emit an optimal matching sequence.
8445   ArrayRef<int> PermMask = SVOp->getMask();
8446 
8447   unsigned PFIndexes[4];
8448   bool isFourElementShuffle = true;
8449   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8450     unsigned EltNo = 8;   // Start out undef.
8451     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8452       if (PermMask[i*4+j] < 0)
8453         continue;   // Undef, ignore it.
8454 
8455       unsigned ByteSource = PermMask[i*4+j];
8456       if ((ByteSource & 3) != j) {
8457         isFourElementShuffle = false;
8458         break;
8459       }
8460 
8461       if (EltNo == 8) {
8462         EltNo = ByteSource/4;
8463       } else if (EltNo != ByteSource/4) {
8464         isFourElementShuffle = false;
8465         break;
8466       }
8467     }
8468     PFIndexes[i] = EltNo;
8469   }
8470 
8471   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8472   // perfect shuffle vector to determine if it is cost effective to do this as
8473   // discrete instructions, or whether we should use a vperm.
8474   // For now, we skip this for little endian until such time as we have a
8475   // little-endian perfect shuffle table.
8476   if (isFourElementShuffle && !isLittleEndian) {
8477     // Compute the index in the perfect shuffle table.
8478     unsigned PFTableIndex =
8479       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8480 
8481     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8482     unsigned Cost  = (PFEntry >> 30);
8483 
8484     // Determining when to avoid vperm is tricky.  Many things affect the cost
8485     // of vperm, particularly how many times the perm mask needs to be computed.
8486     // For example, if the perm mask can be hoisted out of a loop or is already
8487     // used (perhaps because there are multiple permutes with the same shuffle
8488     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8489     // the loop requires an extra register.
8490     //
8491     // As a compromise, we only emit discrete instructions if the shuffle can be
8492     // generated in 3 or fewer operations.  When we have loop information
8493     // available, if this block is within a loop, we should avoid using vperm
8494     // for 3-operation perms and use a constant pool load instead.
8495     if (Cost < 3)
8496       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8497   }
8498 
8499   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8500   // vector that will get spilled to the constant pool.
8501   if (V2.isUndef()) V2 = V1;
8502 
8503   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8504   // that it is in input element units, not in bytes.  Convert now.
8505 
8506   // For little endian, the order of the input vectors is reversed, and
8507   // the permutation mask is complemented with respect to 31.  This is
8508   // necessary to produce proper semantics with the big-endian-biased vperm
8509   // instruction.
8510   EVT EltVT = V1.getValueType().getVectorElementType();
8511   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8512 
8513   SmallVector<SDValue, 16> ResultMask;
8514   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8515     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8516 
8517     for (unsigned j = 0; j != BytesPerElement; ++j)
8518       if (isLittleEndian)
8519         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8520                                              dl, MVT::i32));
8521       else
8522         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8523                                              MVT::i32));
8524   }
8525 
8526   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8527   if (isLittleEndian)
8528     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8529                        V2, V1, VPermMask);
8530   else
8531     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8532                        V1, V2, VPermMask);
8533 }
8534 
8535 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8536 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8537 /// information about the intrinsic.
8538 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8539                                  bool &isDot, const PPCSubtarget &Subtarget) {
8540   unsigned IntrinsicID =
8541       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8542   CompareOpc = -1;
8543   isDot = false;
8544   switch (IntrinsicID) {
8545   default:
8546     return false;
8547   // Comparison predicates.
8548   case Intrinsic::ppc_altivec_vcmpbfp_p:
8549     CompareOpc = 966;
8550     isDot = true;
8551     break;
8552   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8553     CompareOpc = 198;
8554     isDot = true;
8555     break;
8556   case Intrinsic::ppc_altivec_vcmpequb_p:
8557     CompareOpc = 6;
8558     isDot = true;
8559     break;
8560   case Intrinsic::ppc_altivec_vcmpequh_p:
8561     CompareOpc = 70;
8562     isDot = true;
8563     break;
8564   case Intrinsic::ppc_altivec_vcmpequw_p:
8565     CompareOpc = 134;
8566     isDot = true;
8567     break;
8568   case Intrinsic::ppc_altivec_vcmpequd_p:
8569     if (Subtarget.hasP8Altivec()) {
8570       CompareOpc = 199;
8571       isDot = true;
8572     } else
8573       return false;
8574     break;
8575   case Intrinsic::ppc_altivec_vcmpneb_p:
8576   case Intrinsic::ppc_altivec_vcmpneh_p:
8577   case Intrinsic::ppc_altivec_vcmpnew_p:
8578   case Intrinsic::ppc_altivec_vcmpnezb_p:
8579   case Intrinsic::ppc_altivec_vcmpnezh_p:
8580   case Intrinsic::ppc_altivec_vcmpnezw_p:
8581     if (Subtarget.hasP9Altivec()) {
8582       switch (IntrinsicID) {
8583       default:
8584         llvm_unreachable("Unknown comparison intrinsic.");
8585       case Intrinsic::ppc_altivec_vcmpneb_p:
8586         CompareOpc = 7;
8587         break;
8588       case Intrinsic::ppc_altivec_vcmpneh_p:
8589         CompareOpc = 71;
8590         break;
8591       case Intrinsic::ppc_altivec_vcmpnew_p:
8592         CompareOpc = 135;
8593         break;
8594       case Intrinsic::ppc_altivec_vcmpnezb_p:
8595         CompareOpc = 263;
8596         break;
8597       case Intrinsic::ppc_altivec_vcmpnezh_p:
8598         CompareOpc = 327;
8599         break;
8600       case Intrinsic::ppc_altivec_vcmpnezw_p:
8601         CompareOpc = 391;
8602         break;
8603       }
8604       isDot = true;
8605     } else
8606       return false;
8607     break;
8608   case Intrinsic::ppc_altivec_vcmpgefp_p:
8609     CompareOpc = 454;
8610     isDot = true;
8611     break;
8612   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8613     CompareOpc = 710;
8614     isDot = true;
8615     break;
8616   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8617     CompareOpc = 774;
8618     isDot = true;
8619     break;
8620   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8621     CompareOpc = 838;
8622     isDot = true;
8623     break;
8624   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8625     CompareOpc = 902;
8626     isDot = true;
8627     break;
8628   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8629     if (Subtarget.hasP8Altivec()) {
8630       CompareOpc = 967;
8631       isDot = true;
8632     } else
8633       return false;
8634     break;
8635   case Intrinsic::ppc_altivec_vcmpgtub_p:
8636     CompareOpc = 518;
8637     isDot = true;
8638     break;
8639   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8640     CompareOpc = 582;
8641     isDot = true;
8642     break;
8643   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8644     CompareOpc = 646;
8645     isDot = true;
8646     break;
8647   case Intrinsic::ppc_altivec_vcmpgtud_p:
8648     if (Subtarget.hasP8Altivec()) {
8649       CompareOpc = 711;
8650       isDot = true;
8651     } else
8652       return false;
8653     break;
8654 
8655   // VSX predicate comparisons use the same infrastructure
8656   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8657   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8658   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8659   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8660   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8661   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8662     if (Subtarget.hasVSX()) {
8663       switch (IntrinsicID) {
8664       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8665         CompareOpc = 99;
8666         break;
8667       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8668         CompareOpc = 115;
8669         break;
8670       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8671         CompareOpc = 107;
8672         break;
8673       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8674         CompareOpc = 67;
8675         break;
8676       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8677         CompareOpc = 83;
8678         break;
8679       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8680         CompareOpc = 75;
8681         break;
8682       }
8683       isDot = true;
8684     } else
8685       return false;
8686     break;
8687 
8688   // Normal Comparisons.
8689   case Intrinsic::ppc_altivec_vcmpbfp:
8690     CompareOpc = 966;
8691     break;
8692   case Intrinsic::ppc_altivec_vcmpeqfp:
8693     CompareOpc = 198;
8694     break;
8695   case Intrinsic::ppc_altivec_vcmpequb:
8696     CompareOpc = 6;
8697     break;
8698   case Intrinsic::ppc_altivec_vcmpequh:
8699     CompareOpc = 70;
8700     break;
8701   case Intrinsic::ppc_altivec_vcmpequw:
8702     CompareOpc = 134;
8703     break;
8704   case Intrinsic::ppc_altivec_vcmpequd:
8705     if (Subtarget.hasP8Altivec())
8706       CompareOpc = 199;
8707     else
8708       return false;
8709     break;
8710   case Intrinsic::ppc_altivec_vcmpneb:
8711   case Intrinsic::ppc_altivec_vcmpneh:
8712   case Intrinsic::ppc_altivec_vcmpnew:
8713   case Intrinsic::ppc_altivec_vcmpnezb:
8714   case Intrinsic::ppc_altivec_vcmpnezh:
8715   case Intrinsic::ppc_altivec_vcmpnezw:
8716     if (Subtarget.hasP9Altivec())
8717       switch (IntrinsicID) {
8718       default:
8719         llvm_unreachable("Unknown comparison intrinsic.");
8720       case Intrinsic::ppc_altivec_vcmpneb:
8721         CompareOpc = 7;
8722         break;
8723       case Intrinsic::ppc_altivec_vcmpneh:
8724         CompareOpc = 71;
8725         break;
8726       case Intrinsic::ppc_altivec_vcmpnew:
8727         CompareOpc = 135;
8728         break;
8729       case Intrinsic::ppc_altivec_vcmpnezb:
8730         CompareOpc = 263;
8731         break;
8732       case Intrinsic::ppc_altivec_vcmpnezh:
8733         CompareOpc = 327;
8734         break;
8735       case Intrinsic::ppc_altivec_vcmpnezw:
8736         CompareOpc = 391;
8737         break;
8738       }
8739     else
8740       return false;
8741     break;
8742   case Intrinsic::ppc_altivec_vcmpgefp:
8743     CompareOpc = 454;
8744     break;
8745   case Intrinsic::ppc_altivec_vcmpgtfp:
8746     CompareOpc = 710;
8747     break;
8748   case Intrinsic::ppc_altivec_vcmpgtsb:
8749     CompareOpc = 774;
8750     break;
8751   case Intrinsic::ppc_altivec_vcmpgtsh:
8752     CompareOpc = 838;
8753     break;
8754   case Intrinsic::ppc_altivec_vcmpgtsw:
8755     CompareOpc = 902;
8756     break;
8757   case Intrinsic::ppc_altivec_vcmpgtsd:
8758     if (Subtarget.hasP8Altivec())
8759       CompareOpc = 967;
8760     else
8761       return false;
8762     break;
8763   case Intrinsic::ppc_altivec_vcmpgtub:
8764     CompareOpc = 518;
8765     break;
8766   case Intrinsic::ppc_altivec_vcmpgtuh:
8767     CompareOpc = 582;
8768     break;
8769   case Intrinsic::ppc_altivec_vcmpgtuw:
8770     CompareOpc = 646;
8771     break;
8772   case Intrinsic::ppc_altivec_vcmpgtud:
8773     if (Subtarget.hasP8Altivec())
8774       CompareOpc = 711;
8775     else
8776       return false;
8777     break;
8778   }
8779   return true;
8780 }
8781 
8782 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8783 /// lower, do it, otherwise return null.
8784 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8785                                                    SelectionDAG &DAG) const {
8786   unsigned IntrinsicID =
8787     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8788 
8789   SDLoc dl(Op);
8790 
8791   if (IntrinsicID == Intrinsic::thread_pointer) {
8792     // Reads the thread pointer register, used for __builtin_thread_pointer.
8793     if (Subtarget.isPPC64())
8794       return DAG.getRegister(PPC::X13, MVT::i64);
8795     return DAG.getRegister(PPC::R2, MVT::i32);
8796   }
8797 
8798   // We are looking for absolute values here.
8799   // The idea is to try to fit one of two patterns:
8800   //  max (a, (0-a))  OR  max ((0-a), a)
8801   if (Subtarget.hasP9Vector() &&
8802       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8803        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8804        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8805     SDValue V1 = Op.getOperand(1);
8806     SDValue V2 = Op.getOperand(2);
8807     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8808         (V1.getSimpleValueType() == MVT::v4i32 ||
8809          V1.getSimpleValueType() == MVT::v8i16 ||
8810          V1.getSimpleValueType() == MVT::v16i8)) {
8811       if ( V1.getOpcode() == ISD::SUB &&
8812            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8813            V1.getOperand(1) == V2 ) {
8814         // Generate the abs instruction with the operands
8815         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8816       }
8817 
8818       if ( V2.getOpcode() == ISD::SUB &&
8819            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8820            V2.getOperand(1) == V1 ) {
8821         // Generate the abs instruction with the operands
8822         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8823       }
8824     }
8825   }
8826 
8827   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8828   // opcode number of the comparison.
8829   int CompareOpc;
8830   bool isDot;
8831   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8832     return SDValue();    // Don't custom lower most intrinsics.
8833 
8834   // If this is a non-dot comparison, make the VCMP node and we are done.
8835   if (!isDot) {
8836     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8837                               Op.getOperand(1), Op.getOperand(2),
8838                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8839     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8840   }
8841 
8842   // Create the PPCISD altivec 'dot' comparison node.
8843   SDValue Ops[] = {
8844     Op.getOperand(2),  // LHS
8845     Op.getOperand(3),  // RHS
8846     DAG.getConstant(CompareOpc, dl, MVT::i32)
8847   };
8848   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8849   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8850 
8851   // Now that we have the comparison, emit a copy from the CR to a GPR.
8852   // This is flagged to the above dot comparison.
8853   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8854                                 DAG.getRegister(PPC::CR6, MVT::i32),
8855                                 CompNode.getValue(1));
8856 
8857   // Unpack the result based on how the target uses it.
8858   unsigned BitNo;   // Bit # of CR6.
8859   bool InvertBit;   // Invert result?
8860   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8861   default:  // Can't happen, don't crash on invalid number though.
8862   case 0:   // Return the value of the EQ bit of CR6.
8863     BitNo = 0; InvertBit = false;
8864     break;
8865   case 1:   // Return the inverted value of the EQ bit of CR6.
8866     BitNo = 0; InvertBit = true;
8867     break;
8868   case 2:   // Return the value of the LT bit of CR6.
8869     BitNo = 2; InvertBit = false;
8870     break;
8871   case 3:   // Return the inverted value of the LT bit of CR6.
8872     BitNo = 2; InvertBit = true;
8873     break;
8874   }
8875 
8876   // Shift the bit into the low position.
8877   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8878                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8879   // Isolate the bit.
8880   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8881                       DAG.getConstant(1, dl, MVT::i32));
8882 
8883   // If we are supposed to, toggle the bit.
8884   if (InvertBit)
8885     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8886                         DAG.getConstant(1, dl, MVT::i32));
8887   return Flags;
8888 }
8889 
8890 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8891                                                SelectionDAG &DAG) const {
8892   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8893   // the beginning of the argument list.
8894   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8895   SDLoc DL(Op);
8896   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8897   case Intrinsic::ppc_cfence: {
8898     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8899     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8900     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8901                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8902                                                   Op.getOperand(ArgStart + 1)),
8903                                       Op.getOperand(0)),
8904                    0);
8905   }
8906   default:
8907     break;
8908   }
8909   return SDValue();
8910 }
8911 
8912 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
8913   // Check for a DIV with the same operands as this REM.
8914   for (auto UI : Op.getOperand(1)->uses()) {
8915     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
8916         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
8917       if (UI->getOperand(0) == Op.getOperand(0) &&
8918           UI->getOperand(1) == Op.getOperand(1))
8919         return SDValue();
8920   }
8921   return Op;
8922 }
8923 
8924 // Lower scalar BSWAP64 to xxbrd.
8925 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
8926   SDLoc dl(Op);
8927   // MTVSRDD
8928   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
8929                    Op.getOperand(0));
8930   // XXBRD
8931   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
8932   // MFVSRD
8933   int VectorIndex = 0;
8934   if (Subtarget.isLittleEndian())
8935     VectorIndex = 1;
8936   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
8937                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
8938   return Op;
8939 }
8940 
8941 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
8942 // compared to a value that is atomically loaded (atomic loads zero-extend).
8943 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
8944                                                 SelectionDAG &DAG) const {
8945   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
8946          "Expecting an atomic compare-and-swap here.");
8947   SDLoc dl(Op);
8948   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
8949   EVT MemVT = AtomicNode->getMemoryVT();
8950   if (MemVT.getSizeInBits() >= 32)
8951     return Op;
8952 
8953   SDValue CmpOp = Op.getOperand(2);
8954   // If this is already correctly zero-extended, leave it alone.
8955   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
8956   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
8957     return Op;
8958 
8959   // Clear the high bits of the compare operand.
8960   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
8961   SDValue NewCmpOp =
8962     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
8963                 DAG.getConstant(MaskVal, dl, MVT::i32));
8964 
8965   // Replace the existing compare operand with the properly zero-extended one.
8966   SmallVector<SDValue, 4> Ops;
8967   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
8968     Ops.push_back(AtomicNode->getOperand(i));
8969   Ops[2] = NewCmpOp;
8970   MachineMemOperand *MMO = AtomicNode->getMemOperand();
8971   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
8972   auto NodeTy =
8973     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
8974   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
8975 }
8976 
8977 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8978                                                   SelectionDAG &DAG) const {
8979   SDLoc dl(Op);
8980   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8981   // instructions), but for smaller types, we need to first extend up to v2i32
8982   // before doing going farther.
8983   if (Op.getValueType() == MVT::v2i64) {
8984     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8985     if (ExtVT != MVT::v2i32) {
8986       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8987       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8988                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8989                                         ExtVT.getVectorElementType(), 4)));
8990       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8991       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8992                        DAG.getValueType(MVT::v2i32));
8993     }
8994 
8995     return Op;
8996   }
8997 
8998   return SDValue();
8999 }
9000 
9001 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
9002                                                  SelectionDAG &DAG) const {
9003   SDLoc dl(Op);
9004   // Create a stack slot that is 16-byte aligned.
9005   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9006   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9007   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9008   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9009 
9010   // Store the input value into Value#0 of the stack slot.
9011   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9012                                MachinePointerInfo());
9013   // Load it out.
9014   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9015 }
9016 
9017 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9018                                                   SelectionDAG &DAG) const {
9019   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9020          "Should only be called for ISD::INSERT_VECTOR_ELT");
9021 
9022   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9023   // We have legal lowering for constant indices but not for variable ones.
9024   if (!C)
9025     return SDValue();
9026 
9027   EVT VT = Op.getValueType();
9028   SDLoc dl(Op);
9029   SDValue V1 = Op.getOperand(0);
9030   SDValue V2 = Op.getOperand(1);
9031   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9032   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9033     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9034     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9035     unsigned InsertAtElement = C->getZExtValue();
9036     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9037     if (Subtarget.isLittleEndian()) {
9038       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9039     }
9040     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9041                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9042   }
9043   return Op;
9044 }
9045 
9046 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9047                                                    SelectionDAG &DAG) const {
9048   SDLoc dl(Op);
9049   SDNode *N = Op.getNode();
9050 
9051   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9052          "Unknown extract_vector_elt type");
9053 
9054   SDValue Value = N->getOperand(0);
9055 
9056   // The first part of this is like the store lowering except that we don't
9057   // need to track the chain.
9058 
9059   // The values are now known to be -1 (false) or 1 (true). To convert this
9060   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9061   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9062   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9063 
9064   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9065   // understand how to form the extending load.
9066   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9067 
9068   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9069 
9070   // Now convert to an integer and store.
9071   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9072     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9073     Value);
9074 
9075   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9076   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9077   MachinePointerInfo PtrInfo =
9078       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9079   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9080   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9081 
9082   SDValue StoreChain = DAG.getEntryNode();
9083   SDValue Ops[] = {StoreChain,
9084                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9085                    Value, FIdx};
9086   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9087 
9088   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9089     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9090 
9091   // Extract the value requested.
9092   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9093   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9094   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9095 
9096   SDValue IntVal =
9097       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9098 
9099   if (!Subtarget.useCRBits())
9100     return IntVal;
9101 
9102   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9103 }
9104 
9105 /// Lowering for QPX v4i1 loads
9106 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9107                                            SelectionDAG &DAG) const {
9108   SDLoc dl(Op);
9109   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9110   SDValue LoadChain = LN->getChain();
9111   SDValue BasePtr = LN->getBasePtr();
9112 
9113   if (Op.getValueType() == MVT::v4f64 ||
9114       Op.getValueType() == MVT::v4f32) {
9115     EVT MemVT = LN->getMemoryVT();
9116     unsigned Alignment = LN->getAlignment();
9117 
9118     // If this load is properly aligned, then it is legal.
9119     if (Alignment >= MemVT.getStoreSize())
9120       return Op;
9121 
9122     EVT ScalarVT = Op.getValueType().getScalarType(),
9123         ScalarMemVT = MemVT.getScalarType();
9124     unsigned Stride = ScalarMemVT.getStoreSize();
9125 
9126     SDValue Vals[4], LoadChains[4];
9127     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9128       SDValue Load;
9129       if (ScalarVT != ScalarMemVT)
9130         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9131                               BasePtr,
9132                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9133                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9134                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9135       else
9136         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9137                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9138                            MinAlign(Alignment, Idx * Stride),
9139                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9140 
9141       if (Idx == 0 && LN->isIndexed()) {
9142         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9143                "Unknown addressing mode on vector load");
9144         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9145                                   LN->getAddressingMode());
9146       }
9147 
9148       Vals[Idx] = Load;
9149       LoadChains[Idx] = Load.getValue(1);
9150 
9151       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9152                             DAG.getConstant(Stride, dl,
9153                                             BasePtr.getValueType()));
9154     }
9155 
9156     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9157     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9158 
9159     if (LN->isIndexed()) {
9160       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9161       return DAG.getMergeValues(RetOps, dl);
9162     }
9163 
9164     SDValue RetOps[] = { Value, TF };
9165     return DAG.getMergeValues(RetOps, dl);
9166   }
9167 
9168   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9169   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9170 
9171   // To lower v4i1 from a byte array, we load the byte elements of the
9172   // vector and then reuse the BUILD_VECTOR logic.
9173 
9174   SDValue VectElmts[4], VectElmtChains[4];
9175   for (unsigned i = 0; i < 4; ++i) {
9176     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9177     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9178 
9179     VectElmts[i] = DAG.getExtLoad(
9180         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9181         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9182         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9183     VectElmtChains[i] = VectElmts[i].getValue(1);
9184   }
9185 
9186   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9187   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9188 
9189   SDValue RVals[] = { Value, LoadChain };
9190   return DAG.getMergeValues(RVals, dl);
9191 }
9192 
9193 /// Lowering for QPX v4i1 stores
9194 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9195                                             SelectionDAG &DAG) const {
9196   SDLoc dl(Op);
9197   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9198   SDValue StoreChain = SN->getChain();
9199   SDValue BasePtr = SN->getBasePtr();
9200   SDValue Value = SN->getValue();
9201 
9202   if (Value.getValueType() == MVT::v4f64 ||
9203       Value.getValueType() == MVT::v4f32) {
9204     EVT MemVT = SN->getMemoryVT();
9205     unsigned Alignment = SN->getAlignment();
9206 
9207     // If this store is properly aligned, then it is legal.
9208     if (Alignment >= MemVT.getStoreSize())
9209       return Op;
9210 
9211     EVT ScalarVT = Value.getValueType().getScalarType(),
9212         ScalarMemVT = MemVT.getScalarType();
9213     unsigned Stride = ScalarMemVT.getStoreSize();
9214 
9215     SDValue Stores[4];
9216     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9217       SDValue Ex = DAG.getNode(
9218           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9219           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9220       SDValue Store;
9221       if (ScalarVT != ScalarMemVT)
9222         Store =
9223             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9224                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9225                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9226                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9227       else
9228         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9229                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9230                              MinAlign(Alignment, Idx * Stride),
9231                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9232 
9233       if (Idx == 0 && SN->isIndexed()) {
9234         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9235                "Unknown addressing mode on vector store");
9236         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9237                                     SN->getAddressingMode());
9238       }
9239 
9240       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9241                             DAG.getConstant(Stride, dl,
9242                                             BasePtr.getValueType()));
9243       Stores[Idx] = Store;
9244     }
9245 
9246     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9247 
9248     if (SN->isIndexed()) {
9249       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9250       return DAG.getMergeValues(RetOps, dl);
9251     }
9252 
9253     return TF;
9254   }
9255 
9256   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9257   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9258 
9259   // The values are now known to be -1 (false) or 1 (true). To convert this
9260   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9261   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9262   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9263 
9264   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9265   // understand how to form the extending load.
9266   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9267 
9268   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9269 
9270   // Now convert to an integer and store.
9271   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9272     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9273     Value);
9274 
9275   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9276   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9277   MachinePointerInfo PtrInfo =
9278       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9279   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9280   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9281 
9282   SDValue Ops[] = {StoreChain,
9283                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9284                    Value, FIdx};
9285   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9286 
9287   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9288     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9289 
9290   // Move data into the byte array.
9291   SDValue Loads[4], LoadChains[4];
9292   for (unsigned i = 0; i < 4; ++i) {
9293     unsigned Offset = 4*i;
9294     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9295     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9296 
9297     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9298                            PtrInfo.getWithOffset(Offset));
9299     LoadChains[i] = Loads[i].getValue(1);
9300   }
9301 
9302   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9303 
9304   SDValue Stores[4];
9305   for (unsigned i = 0; i < 4; ++i) {
9306     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9307     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9308 
9309     Stores[i] = DAG.getTruncStore(
9310         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9311         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9312         SN->getAAInfo());
9313   }
9314 
9315   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9316 
9317   return StoreChain;
9318 }
9319 
9320 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9321   SDLoc dl(Op);
9322   if (Op.getValueType() == MVT::v4i32) {
9323     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9324 
9325     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9326     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9327 
9328     SDValue RHSSwap =   // = vrlw RHS, 16
9329       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9330 
9331     // Shrinkify inputs to v8i16.
9332     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9333     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9334     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9335 
9336     // Low parts multiplied together, generating 32-bit results (we ignore the
9337     // top parts).
9338     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9339                                         LHS, RHS, DAG, dl, MVT::v4i32);
9340 
9341     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9342                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9343     // Shift the high parts up 16 bits.
9344     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9345                               Neg16, DAG, dl);
9346     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9347   } else if (Op.getValueType() == MVT::v8i16) {
9348     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9349 
9350     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9351 
9352     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9353                             LHS, RHS, Zero, DAG, dl);
9354   } else if (Op.getValueType() == MVT::v16i8) {
9355     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9356     bool isLittleEndian = Subtarget.isLittleEndian();
9357 
9358     // Multiply the even 8-bit parts, producing 16-bit sums.
9359     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9360                                            LHS, RHS, DAG, dl, MVT::v8i16);
9361     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9362 
9363     // Multiply the odd 8-bit parts, producing 16-bit sums.
9364     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9365                                           LHS, RHS, DAG, dl, MVT::v8i16);
9366     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9367 
9368     // Merge the results together.  Because vmuleub and vmuloub are
9369     // instructions with a big-endian bias, we must reverse the
9370     // element numbering and reverse the meaning of "odd" and "even"
9371     // when generating little endian code.
9372     int Ops[16];
9373     for (unsigned i = 0; i != 8; ++i) {
9374       if (isLittleEndian) {
9375         Ops[i*2  ] = 2*i;
9376         Ops[i*2+1] = 2*i+16;
9377       } else {
9378         Ops[i*2  ] = 2*i+1;
9379         Ops[i*2+1] = 2*i+1+16;
9380       }
9381     }
9382     if (isLittleEndian)
9383       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9384     else
9385       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9386   } else {
9387     llvm_unreachable("Unknown mul to lower!");
9388   }
9389 }
9390 
9391 /// LowerOperation - Provide custom lowering hooks for some operations.
9392 ///
9393 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9394   switch (Op.getOpcode()) {
9395   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9396   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9397   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9398   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9399   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9400   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9401   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9402   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9403   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9404 
9405   // Variable argument lowering.
9406   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9407   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9408   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9409 
9410   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9411   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9412   case ISD::GET_DYNAMIC_AREA_OFFSET:
9413     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9414 
9415   // Exception handling lowering.
9416   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9417   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9418   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9419 
9420   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9421   case ISD::STORE:              return LowerSTORE(Op, DAG);
9422   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9423   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9424   case ISD::FP_TO_UINT:
9425   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9426   case ISD::UINT_TO_FP:
9427   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9428   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9429 
9430   // Lower 64-bit shifts.
9431   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9432   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9433   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9434 
9435   // Vector-related lowering.
9436   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9437   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9438   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9439   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9440   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9441   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9442   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9443   case ISD::MUL:                return LowerMUL(Op, DAG);
9444 
9445   // For counter-based loop handling.
9446   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9447 
9448   // Frame & Return address.
9449   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9450   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9451 
9452   case ISD::INTRINSIC_VOID:
9453     return LowerINTRINSIC_VOID(Op, DAG);
9454   case ISD::SREM:
9455   case ISD::UREM:
9456     return LowerREM(Op, DAG);
9457   case ISD::BSWAP:
9458     return LowerBSWAP(Op, DAG);
9459   case ISD::ATOMIC_CMP_SWAP:
9460     return LowerATOMIC_CMP_SWAP(Op, DAG);
9461   }
9462 }
9463 
9464 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9465                                            SmallVectorImpl<SDValue>&Results,
9466                                            SelectionDAG &DAG) const {
9467   SDLoc dl(N);
9468   switch (N->getOpcode()) {
9469   default:
9470     llvm_unreachable("Do not know how to custom type legalize this operation!");
9471   case ISD::READCYCLECOUNTER: {
9472     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9473     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9474 
9475     Results.push_back(RTB);
9476     Results.push_back(RTB.getValue(1));
9477     Results.push_back(RTB.getValue(2));
9478     break;
9479   }
9480   case ISD::INTRINSIC_W_CHAIN: {
9481     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9482         Intrinsic::ppc_is_decremented_ctr_nonzero)
9483       break;
9484 
9485     assert(N->getValueType(0) == MVT::i1 &&
9486            "Unexpected result type for CTR decrement intrinsic");
9487     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9488                                  N->getValueType(0));
9489     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9490     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9491                                  N->getOperand(1));
9492 
9493     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9494     Results.push_back(NewInt.getValue(1));
9495     break;
9496   }
9497   case ISD::VAARG: {
9498     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9499       return;
9500 
9501     EVT VT = N->getValueType(0);
9502 
9503     if (VT == MVT::i64) {
9504       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9505 
9506       Results.push_back(NewNode);
9507       Results.push_back(NewNode.getValue(1));
9508     }
9509     return;
9510   }
9511   case ISD::FP_TO_SINT:
9512   case ISD::FP_TO_UINT:
9513     // LowerFP_TO_INT() can only handle f32 and f64.
9514     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9515       return;
9516     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9517     return;
9518   }
9519 }
9520 
9521 //===----------------------------------------------------------------------===//
9522 //  Other Lowering Code
9523 //===----------------------------------------------------------------------===//
9524 
9525 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9526   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9527   Function *Func = Intrinsic::getDeclaration(M, Id);
9528   return Builder.CreateCall(Func, {});
9529 }
9530 
9531 // The mappings for emitLeading/TrailingFence is taken from
9532 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9533 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9534                                                  Instruction *Inst,
9535                                                  AtomicOrdering Ord) const {
9536   if (Ord == AtomicOrdering::SequentiallyConsistent)
9537     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9538   if (isReleaseOrStronger(Ord))
9539     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9540   return nullptr;
9541 }
9542 
9543 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9544                                                   Instruction *Inst,
9545                                                   AtomicOrdering Ord) const {
9546   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9547     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9548     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9549     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9550     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9551       return Builder.CreateCall(
9552           Intrinsic::getDeclaration(
9553               Builder.GetInsertBlock()->getParent()->getParent(),
9554               Intrinsic::ppc_cfence, {Inst->getType()}),
9555           {Inst});
9556     // FIXME: Can use isync for rmw operation.
9557     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9558   }
9559   return nullptr;
9560 }
9561 
9562 MachineBasicBlock *
9563 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9564                                     unsigned AtomicSize,
9565                                     unsigned BinOpcode,
9566                                     unsigned CmpOpcode,
9567                                     unsigned CmpPred) const {
9568   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9569   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9570 
9571   auto LoadMnemonic = PPC::LDARX;
9572   auto StoreMnemonic = PPC::STDCX;
9573   switch (AtomicSize) {
9574   default:
9575     llvm_unreachable("Unexpected size of atomic entity");
9576   case 1:
9577     LoadMnemonic = PPC::LBARX;
9578     StoreMnemonic = PPC::STBCX;
9579     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9580     break;
9581   case 2:
9582     LoadMnemonic = PPC::LHARX;
9583     StoreMnemonic = PPC::STHCX;
9584     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9585     break;
9586   case 4:
9587     LoadMnemonic = PPC::LWARX;
9588     StoreMnemonic = PPC::STWCX;
9589     break;
9590   case 8:
9591     LoadMnemonic = PPC::LDARX;
9592     StoreMnemonic = PPC::STDCX;
9593     break;
9594   }
9595 
9596   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9597   MachineFunction *F = BB->getParent();
9598   MachineFunction::iterator It = ++BB->getIterator();
9599 
9600   unsigned dest = MI.getOperand(0).getReg();
9601   unsigned ptrA = MI.getOperand(1).getReg();
9602   unsigned ptrB = MI.getOperand(2).getReg();
9603   unsigned incr = MI.getOperand(3).getReg();
9604   DebugLoc dl = MI.getDebugLoc();
9605 
9606   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9607   MachineBasicBlock *loop2MBB =
9608     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9609   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9610   F->insert(It, loopMBB);
9611   if (CmpOpcode)
9612     F->insert(It, loop2MBB);
9613   F->insert(It, exitMBB);
9614   exitMBB->splice(exitMBB->begin(), BB,
9615                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9616   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9617 
9618   MachineRegisterInfo &RegInfo = F->getRegInfo();
9619   unsigned TmpReg = (!BinOpcode) ? incr :
9620     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9621                                            : &PPC::GPRCRegClass);
9622 
9623   //  thisMBB:
9624   //   ...
9625   //   fallthrough --> loopMBB
9626   BB->addSuccessor(loopMBB);
9627 
9628   //  loopMBB:
9629   //   l[wd]arx dest, ptr
9630   //   add r0, dest, incr
9631   //   st[wd]cx. r0, ptr
9632   //   bne- loopMBB
9633   //   fallthrough --> exitMBB
9634 
9635   // For max/min...
9636   //  loopMBB:
9637   //   l[wd]arx dest, ptr
9638   //   cmpl?[wd] incr, dest
9639   //   bgt exitMBB
9640   //  loop2MBB:
9641   //   st[wd]cx. dest, ptr
9642   //   bne- loopMBB
9643   //   fallthrough --> exitMBB
9644 
9645   BB = loopMBB;
9646   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9647     .addReg(ptrA).addReg(ptrB);
9648   if (BinOpcode)
9649     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9650   if (CmpOpcode) {
9651     // Signed comparisons of byte or halfword values must be sign-extended.
9652     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9653       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9654       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9655               ExtReg).addReg(dest);
9656       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9657         .addReg(incr).addReg(ExtReg);
9658     } else
9659       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9660         .addReg(incr).addReg(dest);
9661 
9662     BuildMI(BB, dl, TII->get(PPC::BCC))
9663       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9664     BB->addSuccessor(loop2MBB);
9665     BB->addSuccessor(exitMBB);
9666     BB = loop2MBB;
9667   }
9668   BuildMI(BB, dl, TII->get(StoreMnemonic))
9669     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9670   BuildMI(BB, dl, TII->get(PPC::BCC))
9671     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9672   BB->addSuccessor(loopMBB);
9673   BB->addSuccessor(exitMBB);
9674 
9675   //  exitMBB:
9676   //   ...
9677   BB = exitMBB;
9678   return BB;
9679 }
9680 
9681 MachineBasicBlock *
9682 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9683                                             MachineBasicBlock *BB,
9684                                             bool is8bit, // operation
9685                                             unsigned BinOpcode,
9686                                             unsigned CmpOpcode,
9687                                             unsigned CmpPred) const {
9688   // If we support part-word atomic mnemonics, just use them
9689   if (Subtarget.hasPartwordAtomics())
9690     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9691                             CmpOpcode, CmpPred);
9692 
9693   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9694   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9695   // In 64 bit mode we have to use 64 bits for addresses, even though the
9696   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9697   // registers without caring whether they're 32 or 64, but here we're
9698   // doing actual arithmetic on the addresses.
9699   bool is64bit = Subtarget.isPPC64();
9700   bool isLittleEndian = Subtarget.isLittleEndian();
9701   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9702 
9703   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9704   MachineFunction *F = BB->getParent();
9705   MachineFunction::iterator It = ++BB->getIterator();
9706 
9707   unsigned dest = MI.getOperand(0).getReg();
9708   unsigned ptrA = MI.getOperand(1).getReg();
9709   unsigned ptrB = MI.getOperand(2).getReg();
9710   unsigned incr = MI.getOperand(3).getReg();
9711   DebugLoc dl = MI.getDebugLoc();
9712 
9713   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9714   MachineBasicBlock *loop2MBB =
9715     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9716   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9717   F->insert(It, loopMBB);
9718   if (CmpOpcode)
9719     F->insert(It, loop2MBB);
9720   F->insert(It, exitMBB);
9721   exitMBB->splice(exitMBB->begin(), BB,
9722                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9723   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9724 
9725   MachineRegisterInfo &RegInfo = F->getRegInfo();
9726   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9727                                           : &PPC::GPRCRegClass;
9728   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9729   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9730   unsigned ShiftReg =
9731     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9732   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9733   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9734   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9735   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9736   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9737   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9738   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9739   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9740   unsigned Ptr1Reg;
9741   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9742 
9743   //  thisMBB:
9744   //   ...
9745   //   fallthrough --> loopMBB
9746   BB->addSuccessor(loopMBB);
9747 
9748   // The 4-byte load must be aligned, while a char or short may be
9749   // anywhere in the word.  Hence all this nasty bookkeeping code.
9750   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9751   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9752   //   xori shift, shift1, 24 [16]
9753   //   rlwinm ptr, ptr1, 0, 0, 29
9754   //   slw incr2, incr, shift
9755   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9756   //   slw mask, mask2, shift
9757   //  loopMBB:
9758   //   lwarx tmpDest, ptr
9759   //   add tmp, tmpDest, incr2
9760   //   andc tmp2, tmpDest, mask
9761   //   and tmp3, tmp, mask
9762   //   or tmp4, tmp3, tmp2
9763   //   stwcx. tmp4, ptr
9764   //   bne- loopMBB
9765   //   fallthrough --> exitMBB
9766   //   srw dest, tmpDest, shift
9767   if (ptrA != ZeroReg) {
9768     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9769     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9770       .addReg(ptrA).addReg(ptrB);
9771   } else {
9772     Ptr1Reg = ptrB;
9773   }
9774   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9775       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9776   if (!isLittleEndian)
9777     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9778         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9779   if (is64bit)
9780     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9781       .addReg(Ptr1Reg).addImm(0).addImm(61);
9782   else
9783     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9784       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9785   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9786       .addReg(incr).addReg(ShiftReg);
9787   if (is8bit)
9788     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9789   else {
9790     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9791     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9792   }
9793   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9794       .addReg(Mask2Reg).addReg(ShiftReg);
9795 
9796   BB = loopMBB;
9797   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9798     .addReg(ZeroReg).addReg(PtrReg);
9799   if (BinOpcode)
9800     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9801       .addReg(Incr2Reg).addReg(TmpDestReg);
9802   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9803     .addReg(TmpDestReg).addReg(MaskReg);
9804   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9805     .addReg(TmpReg).addReg(MaskReg);
9806   if (CmpOpcode) {
9807     // For unsigned comparisons, we can directly compare the shifted values.
9808     // For signed comparisons we shift and sign extend.
9809     unsigned SReg = RegInfo.createVirtualRegister(RC);
9810     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9811       .addReg(TmpDestReg).addReg(MaskReg);
9812     unsigned ValueReg = SReg;
9813     unsigned CmpReg = Incr2Reg;
9814     if (CmpOpcode == PPC::CMPW) {
9815       ValueReg = RegInfo.createVirtualRegister(RC);
9816       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9817         .addReg(SReg).addReg(ShiftReg);
9818       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9819       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9820         .addReg(ValueReg);
9821       ValueReg = ValueSReg;
9822       CmpReg = incr;
9823     }
9824     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9825       .addReg(CmpReg).addReg(ValueReg);
9826     BuildMI(BB, dl, TII->get(PPC::BCC))
9827       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9828     BB->addSuccessor(loop2MBB);
9829     BB->addSuccessor(exitMBB);
9830     BB = loop2MBB;
9831   }
9832   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9833     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9834   BuildMI(BB, dl, TII->get(PPC::STWCX))
9835     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9836   BuildMI(BB, dl, TII->get(PPC::BCC))
9837     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9838   BB->addSuccessor(loopMBB);
9839   BB->addSuccessor(exitMBB);
9840 
9841   //  exitMBB:
9842   //   ...
9843   BB = exitMBB;
9844   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9845     .addReg(ShiftReg);
9846   return BB;
9847 }
9848 
9849 llvm::MachineBasicBlock *
9850 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9851                                     MachineBasicBlock *MBB) const {
9852   DebugLoc DL = MI.getDebugLoc();
9853   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9854   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9855 
9856   MachineFunction *MF = MBB->getParent();
9857   MachineRegisterInfo &MRI = MF->getRegInfo();
9858 
9859   const BasicBlock *BB = MBB->getBasicBlock();
9860   MachineFunction::iterator I = ++MBB->getIterator();
9861 
9862   // Memory Reference
9863   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9864   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9865 
9866   unsigned DstReg = MI.getOperand(0).getReg();
9867   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9868   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9869   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9870   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9871 
9872   MVT PVT = getPointerTy(MF->getDataLayout());
9873   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9874          "Invalid Pointer Size!");
9875   // For v = setjmp(buf), we generate
9876   //
9877   // thisMBB:
9878   //  SjLjSetup mainMBB
9879   //  bl mainMBB
9880   //  v_restore = 1
9881   //  b sinkMBB
9882   //
9883   // mainMBB:
9884   //  buf[LabelOffset] = LR
9885   //  v_main = 0
9886   //
9887   // sinkMBB:
9888   //  v = phi(main, restore)
9889   //
9890 
9891   MachineBasicBlock *thisMBB = MBB;
9892   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9893   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9894   MF->insert(I, mainMBB);
9895   MF->insert(I, sinkMBB);
9896 
9897   MachineInstrBuilder MIB;
9898 
9899   // Transfer the remainder of BB and its successor edges to sinkMBB.
9900   sinkMBB->splice(sinkMBB->begin(), MBB,
9901                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9902   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9903 
9904   // Note that the structure of the jmp_buf used here is not compatible
9905   // with that used by libc, and is not designed to be. Specifically, it
9906   // stores only those 'reserved' registers that LLVM does not otherwise
9907   // understand how to spill. Also, by convention, by the time this
9908   // intrinsic is called, Clang has already stored the frame address in the
9909   // first slot of the buffer and stack address in the third. Following the
9910   // X86 target code, we'll store the jump address in the second slot. We also
9911   // need to save the TOC pointer (R2) to handle jumps between shared
9912   // libraries, and that will be stored in the fourth slot. The thread
9913   // identifier (R13) is not affected.
9914 
9915   // thisMBB:
9916   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9917   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9918   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9919 
9920   // Prepare IP either in reg.
9921   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9922   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9923   unsigned BufReg = MI.getOperand(1).getReg();
9924 
9925   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9926     setUsesTOCBasePtr(*MBB->getParent());
9927     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9928             .addReg(PPC::X2)
9929             .addImm(TOCOffset)
9930             .addReg(BufReg);
9931     MIB.setMemRefs(MMOBegin, MMOEnd);
9932   }
9933 
9934   // Naked functions never have a base pointer, and so we use r1. For all
9935   // other functions, this decision must be delayed until during PEI.
9936   unsigned BaseReg;
9937   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
9938     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9939   else
9940     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9941 
9942   MIB = BuildMI(*thisMBB, MI, DL,
9943                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9944             .addReg(BaseReg)
9945             .addImm(BPOffset)
9946             .addReg(BufReg);
9947   MIB.setMemRefs(MMOBegin, MMOEnd);
9948 
9949   // Setup
9950   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9951   MIB.addRegMask(TRI->getNoPreservedMask());
9952 
9953   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9954 
9955   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9956           .addMBB(mainMBB);
9957   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9958 
9959   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9960   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9961 
9962   // mainMBB:
9963   //  mainDstReg = 0
9964   MIB =
9965       BuildMI(mainMBB, DL,
9966               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9967 
9968   // Store IP
9969   if (Subtarget.isPPC64()) {
9970     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9971             .addReg(LabelReg)
9972             .addImm(LabelOffset)
9973             .addReg(BufReg);
9974   } else {
9975     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9976             .addReg(LabelReg)
9977             .addImm(LabelOffset)
9978             .addReg(BufReg);
9979   }
9980 
9981   MIB.setMemRefs(MMOBegin, MMOEnd);
9982 
9983   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9984   mainMBB->addSuccessor(sinkMBB);
9985 
9986   // sinkMBB:
9987   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9988           TII->get(PPC::PHI), DstReg)
9989     .addReg(mainDstReg).addMBB(mainMBB)
9990     .addReg(restoreDstReg).addMBB(thisMBB);
9991 
9992   MI.eraseFromParent();
9993   return sinkMBB;
9994 }
9995 
9996 MachineBasicBlock *
9997 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9998                                      MachineBasicBlock *MBB) const {
9999   DebugLoc DL = MI.getDebugLoc();
10000   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10001 
10002   MachineFunction *MF = MBB->getParent();
10003   MachineRegisterInfo &MRI = MF->getRegInfo();
10004 
10005   // Memory Reference
10006   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
10007   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
10008 
10009   MVT PVT = getPointerTy(MF->getDataLayout());
10010   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10011          "Invalid Pointer Size!");
10012 
10013   const TargetRegisterClass *RC =
10014     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10015   unsigned Tmp = MRI.createVirtualRegister(RC);
10016   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10017   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10018   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10019   unsigned BP =
10020       (PVT == MVT::i64)
10021           ? PPC::X30
10022           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10023                                                               : PPC::R30);
10024 
10025   MachineInstrBuilder MIB;
10026 
10027   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10028   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10029   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10030   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10031 
10032   unsigned BufReg = MI.getOperand(0).getReg();
10033 
10034   // Reload FP (the jumped-to function may not have had a
10035   // frame pointer, and if so, then its r31 will be restored
10036   // as necessary).
10037   if (PVT == MVT::i64) {
10038     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10039             .addImm(0)
10040             .addReg(BufReg);
10041   } else {
10042     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10043             .addImm(0)
10044             .addReg(BufReg);
10045   }
10046   MIB.setMemRefs(MMOBegin, MMOEnd);
10047 
10048   // Reload IP
10049   if (PVT == MVT::i64) {
10050     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10051             .addImm(LabelOffset)
10052             .addReg(BufReg);
10053   } else {
10054     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10055             .addImm(LabelOffset)
10056             .addReg(BufReg);
10057   }
10058   MIB.setMemRefs(MMOBegin, MMOEnd);
10059 
10060   // Reload SP
10061   if (PVT == MVT::i64) {
10062     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10063             .addImm(SPOffset)
10064             .addReg(BufReg);
10065   } else {
10066     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10067             .addImm(SPOffset)
10068             .addReg(BufReg);
10069   }
10070   MIB.setMemRefs(MMOBegin, MMOEnd);
10071 
10072   // Reload BP
10073   if (PVT == MVT::i64) {
10074     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10075             .addImm(BPOffset)
10076             .addReg(BufReg);
10077   } else {
10078     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10079             .addImm(BPOffset)
10080             .addReg(BufReg);
10081   }
10082   MIB.setMemRefs(MMOBegin, MMOEnd);
10083 
10084   // Reload TOC
10085   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10086     setUsesTOCBasePtr(*MBB->getParent());
10087     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10088             .addImm(TOCOffset)
10089             .addReg(BufReg);
10090 
10091     MIB.setMemRefs(MMOBegin, MMOEnd);
10092   }
10093 
10094   // Jump
10095   BuildMI(*MBB, MI, DL,
10096           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10097   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10098 
10099   MI.eraseFromParent();
10100   return MBB;
10101 }
10102 
10103 MachineBasicBlock *
10104 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10105                                                MachineBasicBlock *BB) const {
10106   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10107       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10108     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10109         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10110       // Call lowering should have added an r2 operand to indicate a dependence
10111       // on the TOC base pointer value. It can't however, because there is no
10112       // way to mark the dependence as implicit there, and so the stackmap code
10113       // will confuse it with a regular operand. Instead, add the dependence
10114       // here.
10115       setUsesTOCBasePtr(*BB->getParent());
10116       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10117     }
10118 
10119     return emitPatchPoint(MI, BB);
10120   }
10121 
10122   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10123       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10124     return emitEHSjLjSetJmp(MI, BB);
10125   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10126              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10127     return emitEHSjLjLongJmp(MI, BB);
10128   }
10129 
10130   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10131 
10132   // To "insert" these instructions we actually have to insert their
10133   // control-flow patterns.
10134   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10135   MachineFunction::iterator It = ++BB->getIterator();
10136 
10137   MachineFunction *F = BB->getParent();
10138 
10139   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10140        MI.getOpcode() == PPC::SELECT_CC_I8 ||
10141        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
10142     SmallVector<MachineOperand, 2> Cond;
10143     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10144         MI.getOpcode() == PPC::SELECT_CC_I8)
10145       Cond.push_back(MI.getOperand(4));
10146     else
10147       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10148     Cond.push_back(MI.getOperand(1));
10149 
10150     DebugLoc dl = MI.getDebugLoc();
10151     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10152                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10153   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10154              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10155              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10156              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10157              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10158              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10159              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10160              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10161              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10162              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10163              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10164              MI.getOpcode() == PPC::SELECT_I4 ||
10165              MI.getOpcode() == PPC::SELECT_I8 ||
10166              MI.getOpcode() == PPC::SELECT_F4 ||
10167              MI.getOpcode() == PPC::SELECT_F8 ||
10168              MI.getOpcode() == PPC::SELECT_QFRC ||
10169              MI.getOpcode() == PPC::SELECT_QSRC ||
10170              MI.getOpcode() == PPC::SELECT_QBRC ||
10171              MI.getOpcode() == PPC::SELECT_VRRC ||
10172              MI.getOpcode() == PPC::SELECT_VSFRC ||
10173              MI.getOpcode() == PPC::SELECT_VSSRC ||
10174              MI.getOpcode() == PPC::SELECT_VSRC) {
10175     // The incoming instruction knows the destination vreg to set, the
10176     // condition code register to branch on, the true/false values to
10177     // select between, and a branch opcode to use.
10178 
10179     //  thisMBB:
10180     //  ...
10181     //   TrueVal = ...
10182     //   cmpTY ccX, r1, r2
10183     //   bCC copy1MBB
10184     //   fallthrough --> copy0MBB
10185     MachineBasicBlock *thisMBB = BB;
10186     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10187     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10188     DebugLoc dl = MI.getDebugLoc();
10189     F->insert(It, copy0MBB);
10190     F->insert(It, sinkMBB);
10191 
10192     // Transfer the remainder of BB and its successor edges to sinkMBB.
10193     sinkMBB->splice(sinkMBB->begin(), BB,
10194                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10195     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10196 
10197     // Next, add the true and fallthrough blocks as its successors.
10198     BB->addSuccessor(copy0MBB);
10199     BB->addSuccessor(sinkMBB);
10200 
10201     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10202         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10203         MI.getOpcode() == PPC::SELECT_QFRC ||
10204         MI.getOpcode() == PPC::SELECT_QSRC ||
10205         MI.getOpcode() == PPC::SELECT_QBRC ||
10206         MI.getOpcode() == PPC::SELECT_VRRC ||
10207         MI.getOpcode() == PPC::SELECT_VSFRC ||
10208         MI.getOpcode() == PPC::SELECT_VSSRC ||
10209         MI.getOpcode() == PPC::SELECT_VSRC) {
10210       BuildMI(BB, dl, TII->get(PPC::BC))
10211           .addReg(MI.getOperand(1).getReg())
10212           .addMBB(sinkMBB);
10213     } else {
10214       unsigned SelectPred = MI.getOperand(4).getImm();
10215       BuildMI(BB, dl, TII->get(PPC::BCC))
10216           .addImm(SelectPred)
10217           .addReg(MI.getOperand(1).getReg())
10218           .addMBB(sinkMBB);
10219     }
10220 
10221     //  copy0MBB:
10222     //   %FalseValue = ...
10223     //   # fallthrough to sinkMBB
10224     BB = copy0MBB;
10225 
10226     // Update machine-CFG edges
10227     BB->addSuccessor(sinkMBB);
10228 
10229     //  sinkMBB:
10230     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10231     //  ...
10232     BB = sinkMBB;
10233     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10234         .addReg(MI.getOperand(3).getReg())
10235         .addMBB(copy0MBB)
10236         .addReg(MI.getOperand(2).getReg())
10237         .addMBB(thisMBB);
10238   } else if (MI.getOpcode() == PPC::ReadTB) {
10239     // To read the 64-bit time-base register on a 32-bit target, we read the
10240     // two halves. Should the counter have wrapped while it was being read, we
10241     // need to try again.
10242     // ...
10243     // readLoop:
10244     // mfspr Rx,TBU # load from TBU
10245     // mfspr Ry,TB  # load from TB
10246     // mfspr Rz,TBU # load from TBU
10247     // cmpw crX,Rx,Rz # check if 'old'='new'
10248     // bne readLoop   # branch if they're not equal
10249     // ...
10250 
10251     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10252     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10253     DebugLoc dl = MI.getDebugLoc();
10254     F->insert(It, readMBB);
10255     F->insert(It, sinkMBB);
10256 
10257     // Transfer the remainder of BB and its successor edges to sinkMBB.
10258     sinkMBB->splice(sinkMBB->begin(), BB,
10259                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10260     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10261 
10262     BB->addSuccessor(readMBB);
10263     BB = readMBB;
10264 
10265     MachineRegisterInfo &RegInfo = F->getRegInfo();
10266     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10267     unsigned LoReg = MI.getOperand(0).getReg();
10268     unsigned HiReg = MI.getOperand(1).getReg();
10269 
10270     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10271     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10272     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10273 
10274     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10275 
10276     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10277       .addReg(HiReg).addReg(ReadAgainReg);
10278     BuildMI(BB, dl, TII->get(PPC::BCC))
10279       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10280 
10281     BB->addSuccessor(readMBB);
10282     BB->addSuccessor(sinkMBB);
10283   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10284     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10286     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10287   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10288     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10290     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10291 
10292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10293     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10295     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10296   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10297     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10299     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10300 
10301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10302     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10304     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10305   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10306     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10308     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10309 
10310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10311     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10313     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10314   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10315     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10317     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10318 
10319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10320     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10322     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10323   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10324     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10326     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10327 
10328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10329     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10331     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10332   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10333     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10334   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10335     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10336 
10337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10338     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10339   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10340     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10341   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10342     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10343   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10344     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10345 
10346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10347     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10348   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10349     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10350   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10351     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10352   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10353     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10354 
10355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10356     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10357   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10358     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10359   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10360     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10361   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10362     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10363 
10364   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10365     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10366   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10367     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10368   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10369     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10370   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10371     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10372 
10373   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10374     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10375   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10376     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10377   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10378     BB = EmitAtomicBinary(MI, BB, 4, 0);
10379   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10380     BB = EmitAtomicBinary(MI, BB, 8, 0);
10381   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10382            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10383            (Subtarget.hasPartwordAtomics() &&
10384             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10385            (Subtarget.hasPartwordAtomics() &&
10386             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10387     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10388 
10389     auto LoadMnemonic = PPC::LDARX;
10390     auto StoreMnemonic = PPC::STDCX;
10391     switch (MI.getOpcode()) {
10392     default:
10393       llvm_unreachable("Compare and swap of unknown size");
10394     case PPC::ATOMIC_CMP_SWAP_I8:
10395       LoadMnemonic = PPC::LBARX;
10396       StoreMnemonic = PPC::STBCX;
10397       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10398       break;
10399     case PPC::ATOMIC_CMP_SWAP_I16:
10400       LoadMnemonic = PPC::LHARX;
10401       StoreMnemonic = PPC::STHCX;
10402       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10403       break;
10404     case PPC::ATOMIC_CMP_SWAP_I32:
10405       LoadMnemonic = PPC::LWARX;
10406       StoreMnemonic = PPC::STWCX;
10407       break;
10408     case PPC::ATOMIC_CMP_SWAP_I64:
10409       LoadMnemonic = PPC::LDARX;
10410       StoreMnemonic = PPC::STDCX;
10411       break;
10412     }
10413     unsigned dest = MI.getOperand(0).getReg();
10414     unsigned ptrA = MI.getOperand(1).getReg();
10415     unsigned ptrB = MI.getOperand(2).getReg();
10416     unsigned oldval = MI.getOperand(3).getReg();
10417     unsigned newval = MI.getOperand(4).getReg();
10418     DebugLoc dl = MI.getDebugLoc();
10419 
10420     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10421     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10422     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10423     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10424     F->insert(It, loop1MBB);
10425     F->insert(It, loop2MBB);
10426     F->insert(It, midMBB);
10427     F->insert(It, exitMBB);
10428     exitMBB->splice(exitMBB->begin(), BB,
10429                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10430     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10431 
10432     //  thisMBB:
10433     //   ...
10434     //   fallthrough --> loopMBB
10435     BB->addSuccessor(loop1MBB);
10436 
10437     // loop1MBB:
10438     //   l[bhwd]arx dest, ptr
10439     //   cmp[wd] dest, oldval
10440     //   bne- midMBB
10441     // loop2MBB:
10442     //   st[bhwd]cx. newval, ptr
10443     //   bne- loopMBB
10444     //   b exitBB
10445     // midMBB:
10446     //   st[bhwd]cx. dest, ptr
10447     // exitBB:
10448     BB = loop1MBB;
10449     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10450       .addReg(ptrA).addReg(ptrB);
10451     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10452       .addReg(oldval).addReg(dest);
10453     BuildMI(BB, dl, TII->get(PPC::BCC))
10454       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10455     BB->addSuccessor(loop2MBB);
10456     BB->addSuccessor(midMBB);
10457 
10458     BB = loop2MBB;
10459     BuildMI(BB, dl, TII->get(StoreMnemonic))
10460       .addReg(newval).addReg(ptrA).addReg(ptrB);
10461     BuildMI(BB, dl, TII->get(PPC::BCC))
10462       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10463     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10464     BB->addSuccessor(loop1MBB);
10465     BB->addSuccessor(exitMBB);
10466 
10467     BB = midMBB;
10468     BuildMI(BB, dl, TII->get(StoreMnemonic))
10469       .addReg(dest).addReg(ptrA).addReg(ptrB);
10470     BB->addSuccessor(exitMBB);
10471 
10472     //  exitMBB:
10473     //   ...
10474     BB = exitMBB;
10475   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10476              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10477     // We must use 64-bit registers for addresses when targeting 64-bit,
10478     // since we're actually doing arithmetic on them.  Other registers
10479     // can be 32-bit.
10480     bool is64bit = Subtarget.isPPC64();
10481     bool isLittleEndian = Subtarget.isLittleEndian();
10482     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10483 
10484     unsigned dest = MI.getOperand(0).getReg();
10485     unsigned ptrA = MI.getOperand(1).getReg();
10486     unsigned ptrB = MI.getOperand(2).getReg();
10487     unsigned oldval = MI.getOperand(3).getReg();
10488     unsigned newval = MI.getOperand(4).getReg();
10489     DebugLoc dl = MI.getDebugLoc();
10490 
10491     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10492     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10493     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10494     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10495     F->insert(It, loop1MBB);
10496     F->insert(It, loop2MBB);
10497     F->insert(It, midMBB);
10498     F->insert(It, exitMBB);
10499     exitMBB->splice(exitMBB->begin(), BB,
10500                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10501     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10502 
10503     MachineRegisterInfo &RegInfo = F->getRegInfo();
10504     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10505                                             : &PPC::GPRCRegClass;
10506     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10507     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10508     unsigned ShiftReg =
10509       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10510     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10511     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10512     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10513     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10514     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10515     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10516     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10517     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10518     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10519     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10520     unsigned Ptr1Reg;
10521     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10522     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10523     //  thisMBB:
10524     //   ...
10525     //   fallthrough --> loopMBB
10526     BB->addSuccessor(loop1MBB);
10527 
10528     // The 4-byte load must be aligned, while a char or short may be
10529     // anywhere in the word.  Hence all this nasty bookkeeping code.
10530     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10531     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10532     //   xori shift, shift1, 24 [16]
10533     //   rlwinm ptr, ptr1, 0, 0, 29
10534     //   slw newval2, newval, shift
10535     //   slw oldval2, oldval,shift
10536     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10537     //   slw mask, mask2, shift
10538     //   and newval3, newval2, mask
10539     //   and oldval3, oldval2, mask
10540     // loop1MBB:
10541     //   lwarx tmpDest, ptr
10542     //   and tmp, tmpDest, mask
10543     //   cmpw tmp, oldval3
10544     //   bne- midMBB
10545     // loop2MBB:
10546     //   andc tmp2, tmpDest, mask
10547     //   or tmp4, tmp2, newval3
10548     //   stwcx. tmp4, ptr
10549     //   bne- loop1MBB
10550     //   b exitBB
10551     // midMBB:
10552     //   stwcx. tmpDest, ptr
10553     // exitBB:
10554     //   srw dest, tmpDest, shift
10555     if (ptrA != ZeroReg) {
10556       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10557       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10558         .addReg(ptrA).addReg(ptrB);
10559     } else {
10560       Ptr1Reg = ptrB;
10561     }
10562     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10563         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10564     if (!isLittleEndian)
10565       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10566           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10567     if (is64bit)
10568       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10569         .addReg(Ptr1Reg).addImm(0).addImm(61);
10570     else
10571       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10572         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10573     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10574         .addReg(newval).addReg(ShiftReg);
10575     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10576         .addReg(oldval).addReg(ShiftReg);
10577     if (is8bit)
10578       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10579     else {
10580       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10581       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10582         .addReg(Mask3Reg).addImm(65535);
10583     }
10584     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10585         .addReg(Mask2Reg).addReg(ShiftReg);
10586     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10587         .addReg(NewVal2Reg).addReg(MaskReg);
10588     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10589         .addReg(OldVal2Reg).addReg(MaskReg);
10590 
10591     BB = loop1MBB;
10592     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10593         .addReg(ZeroReg).addReg(PtrReg);
10594     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10595         .addReg(TmpDestReg).addReg(MaskReg);
10596     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10597         .addReg(TmpReg).addReg(OldVal3Reg);
10598     BuildMI(BB, dl, TII->get(PPC::BCC))
10599         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10600     BB->addSuccessor(loop2MBB);
10601     BB->addSuccessor(midMBB);
10602 
10603     BB = loop2MBB;
10604     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10605         .addReg(TmpDestReg).addReg(MaskReg);
10606     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10607         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10608     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10609         .addReg(ZeroReg).addReg(PtrReg);
10610     BuildMI(BB, dl, TII->get(PPC::BCC))
10611       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10612     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10613     BB->addSuccessor(loop1MBB);
10614     BB->addSuccessor(exitMBB);
10615 
10616     BB = midMBB;
10617     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10618       .addReg(ZeroReg).addReg(PtrReg);
10619     BB->addSuccessor(exitMBB);
10620 
10621     //  exitMBB:
10622     //   ...
10623     BB = exitMBB;
10624     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10625       .addReg(ShiftReg);
10626   } else if (MI.getOpcode() == PPC::FADDrtz) {
10627     // This pseudo performs an FADD with rounding mode temporarily forced
10628     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10629     // is not modeled at the SelectionDAG level.
10630     unsigned Dest = MI.getOperand(0).getReg();
10631     unsigned Src1 = MI.getOperand(1).getReg();
10632     unsigned Src2 = MI.getOperand(2).getReg();
10633     DebugLoc dl = MI.getDebugLoc();
10634 
10635     MachineRegisterInfo &RegInfo = F->getRegInfo();
10636     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10637 
10638     // Save FPSCR value.
10639     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10640 
10641     // Set rounding mode to round-to-zero.
10642     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10643     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10644 
10645     // Perform addition.
10646     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10647 
10648     // Restore FPSCR value.
10649     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10650   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10651              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10652              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10653              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10654     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10655                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10656                           ? PPC::ANDIo8
10657                           : PPC::ANDIo;
10658     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10659                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10660 
10661     MachineRegisterInfo &RegInfo = F->getRegInfo();
10662     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10663                                                   &PPC::GPRCRegClass :
10664                                                   &PPC::G8RCRegClass);
10665 
10666     DebugLoc dl = MI.getDebugLoc();
10667     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10668         .addReg(MI.getOperand(1).getReg())
10669         .addImm(1);
10670     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10671             MI.getOperand(0).getReg())
10672         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10673   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10674     DebugLoc Dl = MI.getDebugLoc();
10675     MachineRegisterInfo &RegInfo = F->getRegInfo();
10676     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10677     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10678     return BB;
10679   } else {
10680     llvm_unreachable("Unexpected instr type to insert");
10681   }
10682 
10683   MI.eraseFromParent(); // The pseudo instruction is gone now.
10684   return BB;
10685 }
10686 
10687 //===----------------------------------------------------------------------===//
10688 // Target Optimization Hooks
10689 //===----------------------------------------------------------------------===//
10690 
10691 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10692   // For the estimates, convergence is quadratic, so we essentially double the
10693   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10694   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10695   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10696   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10697   if (VT.getScalarType() == MVT::f64)
10698     RefinementSteps++;
10699   return RefinementSteps;
10700 }
10701 
10702 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10703                                            int Enabled, int &RefinementSteps,
10704                                            bool &UseOneConstNR,
10705                                            bool Reciprocal) const {
10706   EVT VT = Operand.getValueType();
10707   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10708       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10709       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10710       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10711       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10712       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10713     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10714       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10715 
10716     UseOneConstNR = true;
10717     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10718   }
10719   return SDValue();
10720 }
10721 
10722 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10723                                             int Enabled,
10724                                             int &RefinementSteps) const {
10725   EVT VT = Operand.getValueType();
10726   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10727       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10728       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10729       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10730       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10731       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10732     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10733       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10734     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10735   }
10736   return SDValue();
10737 }
10738 
10739 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10740   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10741   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10742   // enabled for division), this functionality is redundant with the default
10743   // combiner logic (once the division -> reciprocal/multiply transformation
10744   // has taken place). As a result, this matters more for older cores than for
10745   // newer ones.
10746 
10747   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10748   // reciprocal if there are two or more FDIVs (for embedded cores with only
10749   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10750   switch (Subtarget.getDarwinDirective()) {
10751   default:
10752     return 3;
10753   case PPC::DIR_440:
10754   case PPC::DIR_A2:
10755   case PPC::DIR_E500mc:
10756   case PPC::DIR_E5500:
10757     return 2;
10758   }
10759 }
10760 
10761 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10762 // collapsed, and so we need to look through chains of them.
10763 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10764                                      int64_t& Offset, SelectionDAG &DAG) {
10765   if (DAG.isBaseWithConstantOffset(Loc)) {
10766     Base = Loc.getOperand(0);
10767     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10768 
10769     // The base might itself be a base plus an offset, and if so, accumulate
10770     // that as well.
10771     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10772   }
10773 }
10774 
10775 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10776                             unsigned Bytes, int Dist,
10777                             SelectionDAG &DAG) {
10778   if (VT.getSizeInBits() / 8 != Bytes)
10779     return false;
10780 
10781   SDValue BaseLoc = Base->getBasePtr();
10782   if (Loc.getOpcode() == ISD::FrameIndex) {
10783     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10784       return false;
10785     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10786     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10787     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10788     int FS  = MFI.getObjectSize(FI);
10789     int BFS = MFI.getObjectSize(BFI);
10790     if (FS != BFS || FS != (int)Bytes) return false;
10791     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10792   }
10793 
10794   SDValue Base1 = Loc, Base2 = BaseLoc;
10795   int64_t Offset1 = 0, Offset2 = 0;
10796   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10797   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10798   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10799     return true;
10800 
10801   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10802   const GlobalValue *GV1 = nullptr;
10803   const GlobalValue *GV2 = nullptr;
10804   Offset1 = 0;
10805   Offset2 = 0;
10806   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10807   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10808   if (isGA1 && isGA2 && GV1 == GV2)
10809     return Offset1 == (Offset2 + Dist*Bytes);
10810   return false;
10811 }
10812 
10813 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10814 // not enforce equality of the chain operands.
10815 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10816                             unsigned Bytes, int Dist,
10817                             SelectionDAG &DAG) {
10818   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10819     EVT VT = LS->getMemoryVT();
10820     SDValue Loc = LS->getBasePtr();
10821     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10822   }
10823 
10824   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10825     EVT VT;
10826     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10827     default: return false;
10828     case Intrinsic::ppc_qpx_qvlfd:
10829     case Intrinsic::ppc_qpx_qvlfda:
10830       VT = MVT::v4f64;
10831       break;
10832     case Intrinsic::ppc_qpx_qvlfs:
10833     case Intrinsic::ppc_qpx_qvlfsa:
10834       VT = MVT::v4f32;
10835       break;
10836     case Intrinsic::ppc_qpx_qvlfcd:
10837     case Intrinsic::ppc_qpx_qvlfcda:
10838       VT = MVT::v2f64;
10839       break;
10840     case Intrinsic::ppc_qpx_qvlfcs:
10841     case Intrinsic::ppc_qpx_qvlfcsa:
10842       VT = MVT::v2f32;
10843       break;
10844     case Intrinsic::ppc_qpx_qvlfiwa:
10845     case Intrinsic::ppc_qpx_qvlfiwz:
10846     case Intrinsic::ppc_altivec_lvx:
10847     case Intrinsic::ppc_altivec_lvxl:
10848     case Intrinsic::ppc_vsx_lxvw4x:
10849     case Intrinsic::ppc_vsx_lxvw4x_be:
10850       VT = MVT::v4i32;
10851       break;
10852     case Intrinsic::ppc_vsx_lxvd2x:
10853     case Intrinsic::ppc_vsx_lxvd2x_be:
10854       VT = MVT::v2f64;
10855       break;
10856     case Intrinsic::ppc_altivec_lvebx:
10857       VT = MVT::i8;
10858       break;
10859     case Intrinsic::ppc_altivec_lvehx:
10860       VT = MVT::i16;
10861       break;
10862     case Intrinsic::ppc_altivec_lvewx:
10863       VT = MVT::i32;
10864       break;
10865     }
10866 
10867     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10868   }
10869 
10870   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10871     EVT VT;
10872     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10873     default: return false;
10874     case Intrinsic::ppc_qpx_qvstfd:
10875     case Intrinsic::ppc_qpx_qvstfda:
10876       VT = MVT::v4f64;
10877       break;
10878     case Intrinsic::ppc_qpx_qvstfs:
10879     case Intrinsic::ppc_qpx_qvstfsa:
10880       VT = MVT::v4f32;
10881       break;
10882     case Intrinsic::ppc_qpx_qvstfcd:
10883     case Intrinsic::ppc_qpx_qvstfcda:
10884       VT = MVT::v2f64;
10885       break;
10886     case Intrinsic::ppc_qpx_qvstfcs:
10887     case Intrinsic::ppc_qpx_qvstfcsa:
10888       VT = MVT::v2f32;
10889       break;
10890     case Intrinsic::ppc_qpx_qvstfiw:
10891     case Intrinsic::ppc_qpx_qvstfiwa:
10892     case Intrinsic::ppc_altivec_stvx:
10893     case Intrinsic::ppc_altivec_stvxl:
10894     case Intrinsic::ppc_vsx_stxvw4x:
10895       VT = MVT::v4i32;
10896       break;
10897     case Intrinsic::ppc_vsx_stxvd2x:
10898       VT = MVT::v2f64;
10899       break;
10900     case Intrinsic::ppc_vsx_stxvw4x_be:
10901       VT = MVT::v4i32;
10902       break;
10903     case Intrinsic::ppc_vsx_stxvd2x_be:
10904       VT = MVT::v2f64;
10905       break;
10906     case Intrinsic::ppc_altivec_stvebx:
10907       VT = MVT::i8;
10908       break;
10909     case Intrinsic::ppc_altivec_stvehx:
10910       VT = MVT::i16;
10911       break;
10912     case Intrinsic::ppc_altivec_stvewx:
10913       VT = MVT::i32;
10914       break;
10915     }
10916 
10917     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10918   }
10919 
10920   return false;
10921 }
10922 
10923 // Return true is there is a nearyby consecutive load to the one provided
10924 // (regardless of alignment). We search up and down the chain, looking though
10925 // token factors and other loads (but nothing else). As a result, a true result
10926 // indicates that it is safe to create a new consecutive load adjacent to the
10927 // load provided.
10928 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10929   SDValue Chain = LD->getChain();
10930   EVT VT = LD->getMemoryVT();
10931 
10932   SmallSet<SDNode *, 16> LoadRoots;
10933   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10934   SmallSet<SDNode *, 16> Visited;
10935 
10936   // First, search up the chain, branching to follow all token-factor operands.
10937   // If we find a consecutive load, then we're done, otherwise, record all
10938   // nodes just above the top-level loads and token factors.
10939   while (!Queue.empty()) {
10940     SDNode *ChainNext = Queue.pop_back_val();
10941     if (!Visited.insert(ChainNext).second)
10942       continue;
10943 
10944     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10945       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10946         return true;
10947 
10948       if (!Visited.count(ChainLD->getChain().getNode()))
10949         Queue.push_back(ChainLD->getChain().getNode());
10950     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10951       for (const SDUse &O : ChainNext->ops())
10952         if (!Visited.count(O.getNode()))
10953           Queue.push_back(O.getNode());
10954     } else
10955       LoadRoots.insert(ChainNext);
10956   }
10957 
10958   // Second, search down the chain, starting from the top-level nodes recorded
10959   // in the first phase. These top-level nodes are the nodes just above all
10960   // loads and token factors. Starting with their uses, recursively look though
10961   // all loads (just the chain uses) and token factors to find a consecutive
10962   // load.
10963   Visited.clear();
10964   Queue.clear();
10965 
10966   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10967        IE = LoadRoots.end(); I != IE; ++I) {
10968     Queue.push_back(*I);
10969 
10970     while (!Queue.empty()) {
10971       SDNode *LoadRoot = Queue.pop_back_val();
10972       if (!Visited.insert(LoadRoot).second)
10973         continue;
10974 
10975       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10976         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10977           return true;
10978 
10979       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10980            UE = LoadRoot->use_end(); UI != UE; ++UI)
10981         if (((isa<MemSDNode>(*UI) &&
10982             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10983             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10984           Queue.push_back(*UI);
10985     }
10986   }
10987 
10988   return false;
10989 }
10990 
10991 /// This function is called when we have proved that a SETCC node can be replaced
10992 /// by subtraction (and other supporting instructions) so that the result of
10993 /// comparison is kept in a GPR instead of CR. This function is purely for
10994 /// codegen purposes and has some flags to guide the codegen process.
10995 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10996                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10997   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10998 
10999   // Zero extend the operands to the largest legal integer. Originally, they
11000   // must be of a strictly smaller size.
11001   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
11002                          DAG.getConstant(Size, DL, MVT::i32));
11003   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
11004                          DAG.getConstant(Size, DL, MVT::i32));
11005 
11006   // Swap if needed. Depends on the condition code.
11007   if (Swap)
11008     std::swap(Op0, Op1);
11009 
11010   // Subtract extended integers.
11011   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11012 
11013   // Move the sign bit to the least significant position and zero out the rest.
11014   // Now the least significant bit carries the result of original comparison.
11015   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11016                              DAG.getConstant(Size - 1, DL, MVT::i32));
11017   auto Final = Shifted;
11018 
11019   // Complement the result if needed. Based on the condition code.
11020   if (Complement)
11021     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11022                         DAG.getConstant(1, DL, MVT::i64));
11023 
11024   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11025 }
11026 
11027 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11028                                                   DAGCombinerInfo &DCI) const {
11029   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11030 
11031   SelectionDAG &DAG = DCI.DAG;
11032   SDLoc DL(N);
11033 
11034   // Size of integers being compared has a critical role in the following
11035   // analysis, so we prefer to do this when all types are legal.
11036   if (!DCI.isAfterLegalizeDAG())
11037     return SDValue();
11038 
11039   // If all users of SETCC extend its value to a legal integer type
11040   // then we replace SETCC with a subtraction
11041   for (SDNode::use_iterator UI = N->use_begin(),
11042        UE = N->use_end(); UI != UE; ++UI) {
11043     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11044       return SDValue();
11045   }
11046 
11047   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11048   auto OpSize = N->getOperand(0).getValueSizeInBits();
11049 
11050   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11051 
11052   if (OpSize < Size) {
11053     switch (CC) {
11054     default: break;
11055     case ISD::SETULT:
11056       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11057     case ISD::SETULE:
11058       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11059     case ISD::SETUGT:
11060       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11061     case ISD::SETUGE:
11062       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11063     }
11064   }
11065 
11066   return SDValue();
11067 }
11068 
11069 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11070                                                   DAGCombinerInfo &DCI) const {
11071   SelectionDAG &DAG = DCI.DAG;
11072   SDLoc dl(N);
11073 
11074   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11075   // If we're tracking CR bits, we need to be careful that we don't have:
11076   //   trunc(binary-ops(zext(x), zext(y)))
11077   // or
11078   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11079   // such that we're unnecessarily moving things into GPRs when it would be
11080   // better to keep them in CR bits.
11081 
11082   // Note that trunc here can be an actual i1 trunc, or can be the effective
11083   // truncation that comes from a setcc or select_cc.
11084   if (N->getOpcode() == ISD::TRUNCATE &&
11085       N->getValueType(0) != MVT::i1)
11086     return SDValue();
11087 
11088   if (N->getOperand(0).getValueType() != MVT::i32 &&
11089       N->getOperand(0).getValueType() != MVT::i64)
11090     return SDValue();
11091 
11092   if (N->getOpcode() == ISD::SETCC ||
11093       N->getOpcode() == ISD::SELECT_CC) {
11094     // If we're looking at a comparison, then we need to make sure that the
11095     // high bits (all except for the first) don't matter the result.
11096     ISD::CondCode CC =
11097       cast<CondCodeSDNode>(N->getOperand(
11098         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11099     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11100 
11101     if (ISD::isSignedIntSetCC(CC)) {
11102       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11103           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11104         return SDValue();
11105     } else if (ISD::isUnsignedIntSetCC(CC)) {
11106       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11107                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11108           !DAG.MaskedValueIsZero(N->getOperand(1),
11109                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11110         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11111                                              : SDValue());
11112     } else {
11113       // This is neither a signed nor an unsigned comparison, just make sure
11114       // that the high bits are equal.
11115       KnownBits Op1Known, Op2Known;
11116       DAG.computeKnownBits(N->getOperand(0), Op1Known);
11117       DAG.computeKnownBits(N->getOperand(1), Op2Known);
11118 
11119       // We don't really care about what is known about the first bit (if
11120       // anything), so clear it in all masks prior to comparing them.
11121       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11122       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11123 
11124       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11125         return SDValue();
11126     }
11127   }
11128 
11129   // We now know that the higher-order bits are irrelevant, we just need to
11130   // make sure that all of the intermediate operations are bit operations, and
11131   // all inputs are extensions.
11132   if (N->getOperand(0).getOpcode() != ISD::AND &&
11133       N->getOperand(0).getOpcode() != ISD::OR  &&
11134       N->getOperand(0).getOpcode() != ISD::XOR &&
11135       N->getOperand(0).getOpcode() != ISD::SELECT &&
11136       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11137       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11138       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11139       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11140       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11141     return SDValue();
11142 
11143   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11144       N->getOperand(1).getOpcode() != ISD::AND &&
11145       N->getOperand(1).getOpcode() != ISD::OR  &&
11146       N->getOperand(1).getOpcode() != ISD::XOR &&
11147       N->getOperand(1).getOpcode() != ISD::SELECT &&
11148       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11149       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11150       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11151       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11152       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11153     return SDValue();
11154 
11155   SmallVector<SDValue, 4> Inputs;
11156   SmallVector<SDValue, 8> BinOps, PromOps;
11157   SmallPtrSet<SDNode *, 16> Visited;
11158 
11159   for (unsigned i = 0; i < 2; ++i) {
11160     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11161           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11162           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11163           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11164         isa<ConstantSDNode>(N->getOperand(i)))
11165       Inputs.push_back(N->getOperand(i));
11166     else
11167       BinOps.push_back(N->getOperand(i));
11168 
11169     if (N->getOpcode() == ISD::TRUNCATE)
11170       break;
11171   }
11172 
11173   // Visit all inputs, collect all binary operations (and, or, xor and
11174   // select) that are all fed by extensions.
11175   while (!BinOps.empty()) {
11176     SDValue BinOp = BinOps.back();
11177     BinOps.pop_back();
11178 
11179     if (!Visited.insert(BinOp.getNode()).second)
11180       continue;
11181 
11182     PromOps.push_back(BinOp);
11183 
11184     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11185       // The condition of the select is not promoted.
11186       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11187         continue;
11188       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11189         continue;
11190 
11191       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11192             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11193             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11194            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11195           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11196         Inputs.push_back(BinOp.getOperand(i));
11197       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11198                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11199                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11200                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11201                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11202                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11203                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11204                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11205                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11206         BinOps.push_back(BinOp.getOperand(i));
11207       } else {
11208         // We have an input that is not an extension or another binary
11209         // operation; we'll abort this transformation.
11210         return SDValue();
11211       }
11212     }
11213   }
11214 
11215   // Make sure that this is a self-contained cluster of operations (which
11216   // is not quite the same thing as saying that everything has only one
11217   // use).
11218   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11219     if (isa<ConstantSDNode>(Inputs[i]))
11220       continue;
11221 
11222     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11223                               UE = Inputs[i].getNode()->use_end();
11224          UI != UE; ++UI) {
11225       SDNode *User = *UI;
11226       if (User != N && !Visited.count(User))
11227         return SDValue();
11228 
11229       // Make sure that we're not going to promote the non-output-value
11230       // operand(s) or SELECT or SELECT_CC.
11231       // FIXME: Although we could sometimes handle this, and it does occur in
11232       // practice that one of the condition inputs to the select is also one of
11233       // the outputs, we currently can't deal with this.
11234       if (User->getOpcode() == ISD::SELECT) {
11235         if (User->getOperand(0) == Inputs[i])
11236           return SDValue();
11237       } else if (User->getOpcode() == ISD::SELECT_CC) {
11238         if (User->getOperand(0) == Inputs[i] ||
11239             User->getOperand(1) == Inputs[i])
11240           return SDValue();
11241       }
11242     }
11243   }
11244 
11245   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11246     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11247                               UE = PromOps[i].getNode()->use_end();
11248          UI != UE; ++UI) {
11249       SDNode *User = *UI;
11250       if (User != N && !Visited.count(User))
11251         return SDValue();
11252 
11253       // Make sure that we're not going to promote the non-output-value
11254       // operand(s) or SELECT or SELECT_CC.
11255       // FIXME: Although we could sometimes handle this, and it does occur in
11256       // practice that one of the condition inputs to the select is also one of
11257       // the outputs, we currently can't deal with this.
11258       if (User->getOpcode() == ISD::SELECT) {
11259         if (User->getOperand(0) == PromOps[i])
11260           return SDValue();
11261       } else if (User->getOpcode() == ISD::SELECT_CC) {
11262         if (User->getOperand(0) == PromOps[i] ||
11263             User->getOperand(1) == PromOps[i])
11264           return SDValue();
11265       }
11266     }
11267   }
11268 
11269   // Replace all inputs with the extension operand.
11270   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11271     // Constants may have users outside the cluster of to-be-promoted nodes,
11272     // and so we need to replace those as we do the promotions.
11273     if (isa<ConstantSDNode>(Inputs[i]))
11274       continue;
11275     else
11276       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11277   }
11278 
11279   std::list<HandleSDNode> PromOpHandles;
11280   for (auto &PromOp : PromOps)
11281     PromOpHandles.emplace_back(PromOp);
11282 
11283   // Replace all operations (these are all the same, but have a different
11284   // (i1) return type). DAG.getNode will validate that the types of
11285   // a binary operator match, so go through the list in reverse so that
11286   // we've likely promoted both operands first. Any intermediate truncations or
11287   // extensions disappear.
11288   while (!PromOpHandles.empty()) {
11289     SDValue PromOp = PromOpHandles.back().getValue();
11290     PromOpHandles.pop_back();
11291 
11292     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11293         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11294         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11295         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11296       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11297           PromOp.getOperand(0).getValueType() != MVT::i1) {
11298         // The operand is not yet ready (see comment below).
11299         PromOpHandles.emplace_front(PromOp);
11300         continue;
11301       }
11302 
11303       SDValue RepValue = PromOp.getOperand(0);
11304       if (isa<ConstantSDNode>(RepValue))
11305         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11306 
11307       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11308       continue;
11309     }
11310 
11311     unsigned C;
11312     switch (PromOp.getOpcode()) {
11313     default:             C = 0; break;
11314     case ISD::SELECT:    C = 1; break;
11315     case ISD::SELECT_CC: C = 2; break;
11316     }
11317 
11318     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11319          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11320         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11321          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11322       // The to-be-promoted operands of this node have not yet been
11323       // promoted (this should be rare because we're going through the
11324       // list backward, but if one of the operands has several users in
11325       // this cluster of to-be-promoted nodes, it is possible).
11326       PromOpHandles.emplace_front(PromOp);
11327       continue;
11328     }
11329 
11330     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11331                                 PromOp.getNode()->op_end());
11332 
11333     // If there are any constant inputs, make sure they're replaced now.
11334     for (unsigned i = 0; i < 2; ++i)
11335       if (isa<ConstantSDNode>(Ops[C+i]))
11336         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11337 
11338     DAG.ReplaceAllUsesOfValueWith(PromOp,
11339       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11340   }
11341 
11342   // Now we're left with the initial truncation itself.
11343   if (N->getOpcode() == ISD::TRUNCATE)
11344     return N->getOperand(0);
11345 
11346   // Otherwise, this is a comparison. The operands to be compared have just
11347   // changed type (to i1), but everything else is the same.
11348   return SDValue(N, 0);
11349 }
11350 
11351 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11352                                                   DAGCombinerInfo &DCI) const {
11353   SelectionDAG &DAG = DCI.DAG;
11354   SDLoc dl(N);
11355 
11356   // If we're tracking CR bits, we need to be careful that we don't have:
11357   //   zext(binary-ops(trunc(x), trunc(y)))
11358   // or
11359   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11360   // such that we're unnecessarily moving things into CR bits that can more
11361   // efficiently stay in GPRs. Note that if we're not certain that the high
11362   // bits are set as required by the final extension, we still may need to do
11363   // some masking to get the proper behavior.
11364 
11365   // This same functionality is important on PPC64 when dealing with
11366   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11367   // the return values of functions. Because it is so similar, it is handled
11368   // here as well.
11369 
11370   if (N->getValueType(0) != MVT::i32 &&
11371       N->getValueType(0) != MVT::i64)
11372     return SDValue();
11373 
11374   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11375         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11376     return SDValue();
11377 
11378   if (N->getOperand(0).getOpcode() != ISD::AND &&
11379       N->getOperand(0).getOpcode() != ISD::OR  &&
11380       N->getOperand(0).getOpcode() != ISD::XOR &&
11381       N->getOperand(0).getOpcode() != ISD::SELECT &&
11382       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11383     return SDValue();
11384 
11385   SmallVector<SDValue, 4> Inputs;
11386   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11387   SmallPtrSet<SDNode *, 16> Visited;
11388 
11389   // Visit all inputs, collect all binary operations (and, or, xor and
11390   // select) that are all fed by truncations.
11391   while (!BinOps.empty()) {
11392     SDValue BinOp = BinOps.back();
11393     BinOps.pop_back();
11394 
11395     if (!Visited.insert(BinOp.getNode()).second)
11396       continue;
11397 
11398     PromOps.push_back(BinOp);
11399 
11400     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11401       // The condition of the select is not promoted.
11402       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11403         continue;
11404       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11405         continue;
11406 
11407       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11408           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11409         Inputs.push_back(BinOp.getOperand(i));
11410       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11411                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11412                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11413                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11414                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11415         BinOps.push_back(BinOp.getOperand(i));
11416       } else {
11417         // We have an input that is not a truncation or another binary
11418         // operation; we'll abort this transformation.
11419         return SDValue();
11420       }
11421     }
11422   }
11423 
11424   // The operands of a select that must be truncated when the select is
11425   // promoted because the operand is actually part of the to-be-promoted set.
11426   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11427 
11428   // Make sure that this is a self-contained cluster of operations (which
11429   // is not quite the same thing as saying that everything has only one
11430   // use).
11431   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11432     if (isa<ConstantSDNode>(Inputs[i]))
11433       continue;
11434 
11435     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11436                               UE = Inputs[i].getNode()->use_end();
11437          UI != UE; ++UI) {
11438       SDNode *User = *UI;
11439       if (User != N && !Visited.count(User))
11440         return SDValue();
11441 
11442       // If we're going to promote the non-output-value operand(s) or SELECT or
11443       // SELECT_CC, record them for truncation.
11444       if (User->getOpcode() == ISD::SELECT) {
11445         if (User->getOperand(0) == Inputs[i])
11446           SelectTruncOp[0].insert(std::make_pair(User,
11447                                     User->getOperand(0).getValueType()));
11448       } else if (User->getOpcode() == ISD::SELECT_CC) {
11449         if (User->getOperand(0) == Inputs[i])
11450           SelectTruncOp[0].insert(std::make_pair(User,
11451                                     User->getOperand(0).getValueType()));
11452         if (User->getOperand(1) == Inputs[i])
11453           SelectTruncOp[1].insert(std::make_pair(User,
11454                                     User->getOperand(1).getValueType()));
11455       }
11456     }
11457   }
11458 
11459   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11460     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11461                               UE = PromOps[i].getNode()->use_end();
11462          UI != UE; ++UI) {
11463       SDNode *User = *UI;
11464       if (User != N && !Visited.count(User))
11465         return SDValue();
11466 
11467       // If we're going to promote the non-output-value operand(s) or SELECT or
11468       // SELECT_CC, record them for truncation.
11469       if (User->getOpcode() == ISD::SELECT) {
11470         if (User->getOperand(0) == PromOps[i])
11471           SelectTruncOp[0].insert(std::make_pair(User,
11472                                     User->getOperand(0).getValueType()));
11473       } else if (User->getOpcode() == ISD::SELECT_CC) {
11474         if (User->getOperand(0) == PromOps[i])
11475           SelectTruncOp[0].insert(std::make_pair(User,
11476                                     User->getOperand(0).getValueType()));
11477         if (User->getOperand(1) == PromOps[i])
11478           SelectTruncOp[1].insert(std::make_pair(User,
11479                                     User->getOperand(1).getValueType()));
11480       }
11481     }
11482   }
11483 
11484   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11485   bool ReallyNeedsExt = false;
11486   if (N->getOpcode() != ISD::ANY_EXTEND) {
11487     // If all of the inputs are not already sign/zero extended, then
11488     // we'll still need to do that at the end.
11489     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11490       if (isa<ConstantSDNode>(Inputs[i]))
11491         continue;
11492 
11493       unsigned OpBits =
11494         Inputs[i].getOperand(0).getValueSizeInBits();
11495       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11496 
11497       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11498            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11499                                   APInt::getHighBitsSet(OpBits,
11500                                                         OpBits-PromBits))) ||
11501           (N->getOpcode() == ISD::SIGN_EXTEND &&
11502            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11503              (OpBits-(PromBits-1)))) {
11504         ReallyNeedsExt = true;
11505         break;
11506       }
11507     }
11508   }
11509 
11510   // Replace all inputs, either with the truncation operand, or a
11511   // truncation or extension to the final output type.
11512   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11513     // Constant inputs need to be replaced with the to-be-promoted nodes that
11514     // use them because they might have users outside of the cluster of
11515     // promoted nodes.
11516     if (isa<ConstantSDNode>(Inputs[i]))
11517       continue;
11518 
11519     SDValue InSrc = Inputs[i].getOperand(0);
11520     if (Inputs[i].getValueType() == N->getValueType(0))
11521       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11522     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11523       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11524         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11525     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11526       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11527         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11528     else
11529       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11530         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11531   }
11532 
11533   std::list<HandleSDNode> PromOpHandles;
11534   for (auto &PromOp : PromOps)
11535     PromOpHandles.emplace_back(PromOp);
11536 
11537   // Replace all operations (these are all the same, but have a different
11538   // (promoted) return type). DAG.getNode will validate that the types of
11539   // a binary operator match, so go through the list in reverse so that
11540   // we've likely promoted both operands first.
11541   while (!PromOpHandles.empty()) {
11542     SDValue PromOp = PromOpHandles.back().getValue();
11543     PromOpHandles.pop_back();
11544 
11545     unsigned C;
11546     switch (PromOp.getOpcode()) {
11547     default:             C = 0; break;
11548     case ISD::SELECT:    C = 1; break;
11549     case ISD::SELECT_CC: C = 2; break;
11550     }
11551 
11552     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11553          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11554         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11555          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11556       // The to-be-promoted operands of this node have not yet been
11557       // promoted (this should be rare because we're going through the
11558       // list backward, but if one of the operands has several users in
11559       // this cluster of to-be-promoted nodes, it is possible).
11560       PromOpHandles.emplace_front(PromOp);
11561       continue;
11562     }
11563 
11564     // For SELECT and SELECT_CC nodes, we do a similar check for any
11565     // to-be-promoted comparison inputs.
11566     if (PromOp.getOpcode() == ISD::SELECT ||
11567         PromOp.getOpcode() == ISD::SELECT_CC) {
11568       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11569            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11570           (SelectTruncOp[1].count(PromOp.getNode()) &&
11571            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11572         PromOpHandles.emplace_front(PromOp);
11573         continue;
11574       }
11575     }
11576 
11577     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11578                                 PromOp.getNode()->op_end());
11579 
11580     // If this node has constant inputs, then they'll need to be promoted here.
11581     for (unsigned i = 0; i < 2; ++i) {
11582       if (!isa<ConstantSDNode>(Ops[C+i]))
11583         continue;
11584       if (Ops[C+i].getValueType() == N->getValueType(0))
11585         continue;
11586 
11587       if (N->getOpcode() == ISD::SIGN_EXTEND)
11588         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11589       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11590         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11591       else
11592         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11593     }
11594 
11595     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11596     // truncate them again to the original value type.
11597     if (PromOp.getOpcode() == ISD::SELECT ||
11598         PromOp.getOpcode() == ISD::SELECT_CC) {
11599       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11600       if (SI0 != SelectTruncOp[0].end())
11601         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11602       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11603       if (SI1 != SelectTruncOp[1].end())
11604         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11605     }
11606 
11607     DAG.ReplaceAllUsesOfValueWith(PromOp,
11608       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11609   }
11610 
11611   // Now we're left with the initial extension itself.
11612   if (!ReallyNeedsExt)
11613     return N->getOperand(0);
11614 
11615   // To zero extend, just mask off everything except for the first bit (in the
11616   // i1 case).
11617   if (N->getOpcode() == ISD::ZERO_EXTEND)
11618     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11619                        DAG.getConstant(APInt::getLowBitsSet(
11620                                          N->getValueSizeInBits(0), PromBits),
11621                                        dl, N->getValueType(0)));
11622 
11623   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11624          "Invalid extension type");
11625   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11626   SDValue ShiftCst =
11627       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11628   return DAG.getNode(
11629       ISD::SRA, dl, N->getValueType(0),
11630       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11631       ShiftCst);
11632 }
11633 
11634 /// Reduces the number of fp-to-int conversion when building a vector.
11635 ///
11636 /// If this vector is built out of floating to integer conversions,
11637 /// transform it to a vector built out of floating point values followed by a
11638 /// single floating to integer conversion of the vector.
11639 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11640 /// becomes (fptosi (build_vector ($A, $B, ...)))
11641 SDValue PPCTargetLowering::
11642 combineElementTruncationToVectorTruncation(SDNode *N,
11643                                            DAGCombinerInfo &DCI) const {
11644   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11645          "Should be called with a BUILD_VECTOR node");
11646 
11647   SelectionDAG &DAG = DCI.DAG;
11648   SDLoc dl(N);
11649 
11650   SDValue FirstInput = N->getOperand(0);
11651   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11652          "The input operand must be an fp-to-int conversion.");
11653 
11654   // This combine happens after legalization so the fp_to_[su]i nodes are
11655   // already converted to PPCSISD nodes.
11656   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11657   if (FirstConversion == PPCISD::FCTIDZ ||
11658       FirstConversion == PPCISD::FCTIDUZ ||
11659       FirstConversion == PPCISD::FCTIWZ ||
11660       FirstConversion == PPCISD::FCTIWUZ) {
11661     bool IsSplat = true;
11662     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11663       FirstConversion == PPCISD::FCTIWUZ;
11664     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11665     SmallVector<SDValue, 4> Ops;
11666     EVT TargetVT = N->getValueType(0);
11667     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11668       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11669         return SDValue();
11670       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11671       if (NextConversion != FirstConversion)
11672         return SDValue();
11673       if (N->getOperand(i) != FirstInput)
11674         IsSplat = false;
11675     }
11676 
11677     // If this is a splat, we leave it as-is since there will be only a single
11678     // fp-to-int conversion followed by a splat of the integer. This is better
11679     // for 32-bit and smaller ints and neutral for 64-bit ints.
11680     if (IsSplat)
11681       return SDValue();
11682 
11683     // Now that we know we have the right type of node, get its operands
11684     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11685       SDValue In = N->getOperand(i).getOperand(0);
11686       // For 32-bit values, we need to add an FP_ROUND node.
11687       if (Is32Bit) {
11688         if (In.isUndef())
11689           Ops.push_back(DAG.getUNDEF(SrcVT));
11690         else {
11691           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11692                                       MVT::f32, In.getOperand(0),
11693                                       DAG.getIntPtrConstant(1, dl));
11694           Ops.push_back(Trunc);
11695         }
11696       } else
11697         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11698     }
11699 
11700     unsigned Opcode;
11701     if (FirstConversion == PPCISD::FCTIDZ ||
11702         FirstConversion == PPCISD::FCTIWZ)
11703       Opcode = ISD::FP_TO_SINT;
11704     else
11705       Opcode = ISD::FP_TO_UINT;
11706 
11707     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11708     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11709     return DAG.getNode(Opcode, dl, TargetVT, BV);
11710   }
11711   return SDValue();
11712 }
11713 
11714 /// Reduce the number of loads when building a vector.
11715 ///
11716 /// Building a vector out of multiple loads can be converted to a load
11717 /// of the vector type if the loads are consecutive. If the loads are
11718 /// consecutive but in descending order, a shuffle is added at the end
11719 /// to reorder the vector.
11720 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11721   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11722          "Should be called with a BUILD_VECTOR node");
11723 
11724   SDLoc dl(N);
11725   bool InputsAreConsecutiveLoads = true;
11726   bool InputsAreReverseConsecutive = true;
11727   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11728   SDValue FirstInput = N->getOperand(0);
11729   bool IsRoundOfExtLoad = false;
11730 
11731   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11732       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11733     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11734     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11735   }
11736   // Not a build vector of (possibly fp_rounded) loads.
11737   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11738     return SDValue();
11739 
11740   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11741     // If any inputs are fp_round(extload), they all must be.
11742     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11743       return SDValue();
11744 
11745     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11746       N->getOperand(i);
11747     if (NextInput.getOpcode() != ISD::LOAD)
11748       return SDValue();
11749 
11750     SDValue PreviousInput =
11751       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11752     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11753     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11754 
11755     // If any inputs are fp_round(extload), they all must be.
11756     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11757       return SDValue();
11758 
11759     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11760       InputsAreConsecutiveLoads = false;
11761     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11762       InputsAreReverseConsecutive = false;
11763 
11764     // Exit early if the loads are neither consecutive nor reverse consecutive.
11765     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11766       return SDValue();
11767   }
11768 
11769   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11770          "The loads cannot be both consecutive and reverse consecutive.");
11771 
11772   SDValue FirstLoadOp =
11773     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11774   SDValue LastLoadOp =
11775     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11776                        N->getOperand(N->getNumOperands()-1);
11777 
11778   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11779   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11780   if (InputsAreConsecutiveLoads) {
11781     assert(LD1 && "Input needs to be a LoadSDNode.");
11782     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11783                        LD1->getBasePtr(), LD1->getPointerInfo(),
11784                        LD1->getAlignment());
11785   }
11786   if (InputsAreReverseConsecutive) {
11787     assert(LDL && "Input needs to be a LoadSDNode.");
11788     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11789                                LDL->getBasePtr(), LDL->getPointerInfo(),
11790                                LDL->getAlignment());
11791     SmallVector<int, 16> Ops;
11792     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11793       Ops.push_back(i);
11794 
11795     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11796                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11797   }
11798   return SDValue();
11799 }
11800 
11801 // This function adds the required vector_shuffle needed to get
11802 // the elements of the vector extract in the correct position
11803 // as specified by the CorrectElems encoding.
11804 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11805                                       SDValue Input, uint64_t Elems,
11806                                       uint64_t CorrectElems) {
11807   SDLoc dl(N);
11808 
11809   unsigned NumElems = Input.getValueType().getVectorNumElements();
11810   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11811 
11812   // Knowing the element indices being extracted from the original
11813   // vector and the order in which they're being inserted, just put
11814   // them at element indices required for the instruction.
11815   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11816     if (DAG.getDataLayout().isLittleEndian())
11817       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11818     else
11819       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11820     CorrectElems = CorrectElems >> 8;
11821     Elems = Elems >> 8;
11822   }
11823 
11824   SDValue Shuffle =
11825       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11826                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11827 
11828   EVT Ty = N->getValueType(0);
11829   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11830   return BV;
11831 }
11832 
11833 // Look for build vector patterns where input operands come from sign
11834 // extended vector_extract elements of specific indices. If the correct indices
11835 // aren't used, add a vector shuffle to fix up the indices and create a new
11836 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11837 // during instruction selection.
11838 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11839   // This array encodes the indices that the vector sign extend instructions
11840   // extract from when extending from one type to another for both BE and LE.
11841   // The right nibble of each byte corresponds to the LE incides.
11842   // and the left nibble of each byte corresponds to the BE incides.
11843   // For example: 0x3074B8FC  byte->word
11844   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11845   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11846   // For example: 0x000070F8  byte->double word
11847   // For LE: the allowed indices are: 0x0,0x8
11848   // For BE: the allowed indices are: 0x7,0xF
11849   uint64_t TargetElems[] = {
11850       0x3074B8FC, // b->w
11851       0x000070F8, // b->d
11852       0x10325476, // h->w
11853       0x00003074, // h->d
11854       0x00001032, // w->d
11855   };
11856 
11857   uint64_t Elems = 0;
11858   int Index;
11859   SDValue Input;
11860 
11861   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11862     if (!Op)
11863       return false;
11864     if (Op.getOpcode() != ISD::SIGN_EXTEND)
11865       return false;
11866 
11867     SDValue Extract = Op.getOperand(0);
11868     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11869       return false;
11870 
11871     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
11872     if (!ExtOp)
11873       return false;
11874 
11875     Index = ExtOp->getZExtValue();
11876     if (Input && Input != Extract.getOperand(0))
11877       return false;
11878 
11879     if (!Input)
11880       Input = Extract.getOperand(0);
11881 
11882     Elems = Elems << 8;
11883     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
11884     Elems |= Index;
11885 
11886     return true;
11887   };
11888 
11889   // If the build vector operands aren't sign extended vector extracts,
11890   // of the same input vector, then return.
11891   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11892     if (!isSExtOfVecExtract(N->getOperand(i))) {
11893       return SDValue();
11894     }
11895   }
11896 
11897   // If the vector extract indicies are not correct, add the appropriate
11898   // vector_shuffle.
11899   int TgtElemArrayIdx;
11900   int InputSize = Input.getValueType().getScalarSizeInBits();
11901   int OutputSize = N->getValueType(0).getScalarSizeInBits();
11902   if (InputSize + OutputSize == 40)
11903     TgtElemArrayIdx = 0;
11904   else if (InputSize + OutputSize == 72)
11905     TgtElemArrayIdx = 1;
11906   else if (InputSize + OutputSize == 48)
11907     TgtElemArrayIdx = 2;
11908   else if (InputSize + OutputSize == 80)
11909     TgtElemArrayIdx = 3;
11910   else if (InputSize + OutputSize == 96)
11911     TgtElemArrayIdx = 4;
11912   else
11913     return SDValue();
11914 
11915   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
11916   CorrectElems = DAG.getDataLayout().isLittleEndian()
11917                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
11918                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
11919   if (Elems != CorrectElems) {
11920     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
11921   }
11922 
11923   // Regular lowering will catch cases where a shuffle is not needed.
11924   return SDValue();
11925 }
11926 
11927 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11928                                                  DAGCombinerInfo &DCI) const {
11929   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11930          "Should be called with a BUILD_VECTOR node");
11931 
11932   SelectionDAG &DAG = DCI.DAG;
11933   SDLoc dl(N);
11934 
11935   if (!Subtarget.hasVSX())
11936     return SDValue();
11937 
11938   // The target independent DAG combiner will leave a build_vector of
11939   // float-to-int conversions intact. We can generate MUCH better code for
11940   // a float-to-int conversion of a vector of floats.
11941   SDValue FirstInput = N->getOperand(0);
11942   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11943     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11944     if (Reduced)
11945       return Reduced;
11946   }
11947 
11948   // If we're building a vector out of consecutive loads, just load that
11949   // vector type.
11950   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11951   if (Reduced)
11952     return Reduced;
11953 
11954   // If we're building a vector out of extended elements from another vector
11955   // we have P9 vector integer extend instructions.
11956   if (Subtarget.hasP9Altivec()) {
11957     Reduced = combineBVOfVecSExt(N, DAG);
11958     if (Reduced)
11959       return Reduced;
11960   }
11961 
11962 
11963   if (N->getValueType(0) != MVT::v2f64)
11964     return SDValue();
11965 
11966   // Looking for:
11967   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11968   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11969       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11970     return SDValue();
11971   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11972       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11973     return SDValue();
11974   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11975     return SDValue();
11976 
11977   SDValue Ext1 = FirstInput.getOperand(0);
11978   SDValue Ext2 = N->getOperand(1).getOperand(0);
11979   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11980      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11981     return SDValue();
11982 
11983   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11984   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11985   if (!Ext1Op || !Ext2Op)
11986     return SDValue();
11987   if (Ext1.getValueType() != MVT::i32 ||
11988       Ext2.getValueType() != MVT::i32)
11989   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11990     return SDValue();
11991 
11992   int FirstElem = Ext1Op->getZExtValue();
11993   int SecondElem = Ext2Op->getZExtValue();
11994   int SubvecIdx;
11995   if (FirstElem == 0 && SecondElem == 1)
11996     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11997   else if (FirstElem == 2 && SecondElem == 3)
11998     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11999   else
12000     return SDValue();
12001 
12002   SDValue SrcVec = Ext1.getOperand(0);
12003   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
12004     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
12005   return DAG.getNode(NodeType, dl, MVT::v2f64,
12006                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
12007 }
12008 
12009 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12010                                               DAGCombinerInfo &DCI) const {
12011   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12012           N->getOpcode() == ISD::UINT_TO_FP) &&
12013          "Need an int -> FP conversion node here");
12014 
12015   if (useSoftFloat() || !Subtarget.has64BitSupport())
12016     return SDValue();
12017 
12018   SelectionDAG &DAG = DCI.DAG;
12019   SDLoc dl(N);
12020   SDValue Op(N, 0);
12021 
12022   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12023   // from the hardware.
12024   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12025     return SDValue();
12026   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12027       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12028     return SDValue();
12029 
12030   SDValue FirstOperand(Op.getOperand(0));
12031   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12032     (FirstOperand.getValueType() == MVT::i8 ||
12033      FirstOperand.getValueType() == MVT::i16);
12034   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12035     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12036     bool DstDouble = Op.getValueType() == MVT::f64;
12037     unsigned ConvOp = Signed ?
12038       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12039       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12040     SDValue WidthConst =
12041       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12042                             dl, false);
12043     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12044     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12045     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12046                                          DAG.getVTList(MVT::f64, MVT::Other),
12047                                          Ops, MVT::i8, LDN->getMemOperand());
12048 
12049     // For signed conversion, we need to sign-extend the value in the VSR
12050     if (Signed) {
12051       SDValue ExtOps[] = { Ld, WidthConst };
12052       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12053       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12054     } else
12055       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12056   }
12057 
12058 
12059   // For i32 intermediate values, unfortunately, the conversion functions
12060   // leave the upper 32 bits of the value are undefined. Within the set of
12061   // scalar instructions, we have no method for zero- or sign-extending the
12062   // value. Thus, we cannot handle i32 intermediate values here.
12063   if (Op.getOperand(0).getValueType() == MVT::i32)
12064     return SDValue();
12065 
12066   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12067          "UINT_TO_FP is supported only with FPCVT");
12068 
12069   // If we have FCFIDS, then use it when converting to single-precision.
12070   // Otherwise, convert to double-precision and then round.
12071   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12072                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12073                                                             : PPCISD::FCFIDS)
12074                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12075                                                             : PPCISD::FCFID);
12076   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12077                   ? MVT::f32
12078                   : MVT::f64;
12079 
12080   // If we're converting from a float, to an int, and back to a float again,
12081   // then we don't need the store/load pair at all.
12082   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12083        Subtarget.hasFPCVT()) ||
12084       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12085     SDValue Src = Op.getOperand(0).getOperand(0);
12086     if (Src.getValueType() == MVT::f32) {
12087       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12088       DCI.AddToWorklist(Src.getNode());
12089     } else if (Src.getValueType() != MVT::f64) {
12090       // Make sure that we don't pick up a ppc_fp128 source value.
12091       return SDValue();
12092     }
12093 
12094     unsigned FCTOp =
12095       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12096                                                         PPCISD::FCTIDUZ;
12097 
12098     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12099     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12100 
12101     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12102       FP = DAG.getNode(ISD::FP_ROUND, dl,
12103                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12104       DCI.AddToWorklist(FP.getNode());
12105     }
12106 
12107     return FP;
12108   }
12109 
12110   return SDValue();
12111 }
12112 
12113 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12114 // builtins) into loads with swaps.
12115 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12116                                               DAGCombinerInfo &DCI) const {
12117   SelectionDAG &DAG = DCI.DAG;
12118   SDLoc dl(N);
12119   SDValue Chain;
12120   SDValue Base;
12121   MachineMemOperand *MMO;
12122 
12123   switch (N->getOpcode()) {
12124   default:
12125     llvm_unreachable("Unexpected opcode for little endian VSX load");
12126   case ISD::LOAD: {
12127     LoadSDNode *LD = cast<LoadSDNode>(N);
12128     Chain = LD->getChain();
12129     Base = LD->getBasePtr();
12130     MMO = LD->getMemOperand();
12131     // If the MMO suggests this isn't a load of a full vector, leave
12132     // things alone.  For a built-in, we have to make the change for
12133     // correctness, so if there is a size problem that will be a bug.
12134     if (MMO->getSize() < 16)
12135       return SDValue();
12136     break;
12137   }
12138   case ISD::INTRINSIC_W_CHAIN: {
12139     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12140     Chain = Intrin->getChain();
12141     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12142     // us what we want. Get operand 2 instead.
12143     Base = Intrin->getOperand(2);
12144     MMO = Intrin->getMemOperand();
12145     break;
12146   }
12147   }
12148 
12149   MVT VecTy = N->getValueType(0).getSimpleVT();
12150 
12151   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12152   // aligned and the type is a vector with elements up to 4 bytes
12153   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12154       && VecTy.getScalarSizeInBits() <= 32 ) {
12155     return SDValue();
12156   }
12157 
12158   SDValue LoadOps[] = { Chain, Base };
12159   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12160                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12161                                          LoadOps, MVT::v2f64, MMO);
12162 
12163   DCI.AddToWorklist(Load.getNode());
12164   Chain = Load.getValue(1);
12165   SDValue Swap = DAG.getNode(
12166       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12167   DCI.AddToWorklist(Swap.getNode());
12168 
12169   // Add a bitcast if the resulting load type doesn't match v2f64.
12170   if (VecTy != MVT::v2f64) {
12171     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12172     DCI.AddToWorklist(N.getNode());
12173     // Package {bitcast value, swap's chain} to match Load's shape.
12174     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12175                        N, Swap.getValue(1));
12176   }
12177 
12178   return Swap;
12179 }
12180 
12181 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12182 // builtins) into stores with swaps.
12183 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12184                                                DAGCombinerInfo &DCI) const {
12185   SelectionDAG &DAG = DCI.DAG;
12186   SDLoc dl(N);
12187   SDValue Chain;
12188   SDValue Base;
12189   unsigned SrcOpnd;
12190   MachineMemOperand *MMO;
12191 
12192   switch (N->getOpcode()) {
12193   default:
12194     llvm_unreachable("Unexpected opcode for little endian VSX store");
12195   case ISD::STORE: {
12196     StoreSDNode *ST = cast<StoreSDNode>(N);
12197     Chain = ST->getChain();
12198     Base = ST->getBasePtr();
12199     MMO = ST->getMemOperand();
12200     SrcOpnd = 1;
12201     // If the MMO suggests this isn't a store of a full vector, leave
12202     // things alone.  For a built-in, we have to make the change for
12203     // correctness, so if there is a size problem that will be a bug.
12204     if (MMO->getSize() < 16)
12205       return SDValue();
12206     break;
12207   }
12208   case ISD::INTRINSIC_VOID: {
12209     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12210     Chain = Intrin->getChain();
12211     // Intrin->getBasePtr() oddly does not get what we want.
12212     Base = Intrin->getOperand(3);
12213     MMO = Intrin->getMemOperand();
12214     SrcOpnd = 2;
12215     break;
12216   }
12217   }
12218 
12219   SDValue Src = N->getOperand(SrcOpnd);
12220   MVT VecTy = Src.getValueType().getSimpleVT();
12221 
12222   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12223   // aligned and the type is a vector with elements up to 4 bytes
12224   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12225       && VecTy.getScalarSizeInBits() <= 32 ) {
12226     return SDValue();
12227   }
12228 
12229   // All stores are done as v2f64 and possible bit cast.
12230   if (VecTy != MVT::v2f64) {
12231     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12232     DCI.AddToWorklist(Src.getNode());
12233   }
12234 
12235   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12236                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12237   DCI.AddToWorklist(Swap.getNode());
12238   Chain = Swap.getValue(1);
12239   SDValue StoreOps[] = { Chain, Swap, Base };
12240   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12241                                           DAG.getVTList(MVT::Other),
12242                                           StoreOps, VecTy, MMO);
12243   DCI.AddToWorklist(Store.getNode());
12244   return Store;
12245 }
12246 
12247 // Handle DAG combine for STORE (FP_TO_INT F).
12248 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12249                                                DAGCombinerInfo &DCI) const {
12250 
12251   SelectionDAG &DAG = DCI.DAG;
12252   SDLoc dl(N);
12253   unsigned Opcode = N->getOperand(1).getOpcode();
12254 
12255   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12256          && "Not a FP_TO_INT Instruction!");
12257 
12258   SDValue Val = N->getOperand(1).getOperand(0);
12259   EVT Op1VT = N->getOperand(1).getValueType();
12260   EVT ResVT = Val.getValueType();
12261 
12262   // Floating point types smaller than 32 bits are not legal on Power.
12263   if (ResVT.getScalarSizeInBits() < 32)
12264     return SDValue();
12265 
12266   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12267   bool ValidTypeForStoreFltAsInt =
12268         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12269          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12270 
12271   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12272       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12273     return SDValue();
12274 
12275   // Extend f32 values to f64
12276   if (ResVT.getScalarSizeInBits() == 32) {
12277     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12278     DCI.AddToWorklist(Val.getNode());
12279   }
12280 
12281   // Set signed or unsigned conversion opcode.
12282   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12283                           PPCISD::FP_TO_SINT_IN_VSR :
12284                           PPCISD::FP_TO_UINT_IN_VSR;
12285 
12286   Val = DAG.getNode(ConvOpcode,
12287                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12288   DCI.AddToWorklist(Val.getNode());
12289 
12290   // Set number of bytes being converted.
12291   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12292   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12293                     DAG.getIntPtrConstant(ByteSize, dl, false),
12294                     DAG.getValueType(Op1VT) };
12295 
12296   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12297           DAG.getVTList(MVT::Other), Ops,
12298           cast<StoreSDNode>(N)->getMemoryVT(),
12299           cast<StoreSDNode>(N)->getMemOperand());
12300 
12301   DCI.AddToWorklist(Val.getNode());
12302   return Val;
12303 }
12304 
12305 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12306                                              DAGCombinerInfo &DCI) const {
12307   SelectionDAG &DAG = DCI.DAG;
12308   SDLoc dl(N);
12309   switch (N->getOpcode()) {
12310   default: break;
12311   case ISD::SHL:
12312     return combineSHL(N, DCI);
12313   case ISD::SRA:
12314     return combineSRA(N, DCI);
12315   case ISD::SRL:
12316     return combineSRL(N, DCI);
12317   case PPCISD::SHL:
12318     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12319         return N->getOperand(0);
12320     break;
12321   case PPCISD::SRL:
12322     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12323         return N->getOperand(0);
12324     break;
12325   case PPCISD::SRA:
12326     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12327       if (C->isNullValue() ||   //  0 >>s V -> 0.
12328           C->isAllOnesValue())    // -1 >>s V -> -1.
12329         return N->getOperand(0);
12330     }
12331     break;
12332   case ISD::SIGN_EXTEND:
12333   case ISD::ZERO_EXTEND:
12334   case ISD::ANY_EXTEND:
12335     return DAGCombineExtBoolTrunc(N, DCI);
12336   case ISD::TRUNCATE:
12337   case ISD::SETCC:
12338   case ISD::SELECT_CC:
12339     return DAGCombineTruncBoolExt(N, DCI);
12340   case ISD::SINT_TO_FP:
12341   case ISD::UINT_TO_FP:
12342     return combineFPToIntToFP(N, DCI);
12343   case ISD::STORE: {
12344 
12345     EVT Op1VT = N->getOperand(1).getValueType();
12346     unsigned Opcode = N->getOperand(1).getOpcode();
12347 
12348     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12349       SDValue Val= combineStoreFPToInt(N, DCI);
12350       if (Val)
12351         return Val;
12352     }
12353 
12354     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12355     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12356         N->getOperand(1).getNode()->hasOneUse() &&
12357         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12358          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12359 
12360       // STBRX can only handle simple types.
12361       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12362       if (mVT.isExtended())
12363         break;
12364 
12365       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12366       // Do an any-extend to 32-bits if this is a half-word input.
12367       if (BSwapOp.getValueType() == MVT::i16)
12368         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12369 
12370       // If the type of BSWAP operand is wider than stored memory width
12371       // it need to be shifted to the right side before STBRX.
12372       if (Op1VT.bitsGT(mVT)) {
12373         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12374         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12375                               DAG.getConstant(Shift, dl, MVT::i32));
12376         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12377         if (Op1VT == MVT::i64)
12378           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12379       }
12380 
12381       SDValue Ops[] = {
12382         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12383       };
12384       return
12385         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12386                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12387                                 cast<StoreSDNode>(N)->getMemOperand());
12388     }
12389 
12390     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
12391     // So it can increase the chance of CSE constant construction.
12392     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12393         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
12394       // Need to sign-extended to 64-bits to handle negative values.
12395       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12396       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12397                                     MemVT.getSizeInBits());
12398       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12399 
12400       // DAG.getTruncStore() can't be used here because it doesn't accept
12401       // the general (base + offset) addressing mode.
12402       // So we use UpdateNodeOperands and setTruncatingStore instead.
12403       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12404                              N->getOperand(3));
12405       cast<StoreSDNode>(N)->setTruncatingStore(true);
12406       return SDValue(N, 0);
12407     }
12408 
12409     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12410     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12411     if (Op1VT.isSimple()) {
12412       MVT StoreVT = Op1VT.getSimpleVT();
12413       if (Subtarget.needsSwapsForVSXMemOps() &&
12414           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12415            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12416         return expandVSXStoreForLE(N, DCI);
12417     }
12418     break;
12419   }
12420   case ISD::LOAD: {
12421     LoadSDNode *LD = cast<LoadSDNode>(N);
12422     EVT VT = LD->getValueType(0);
12423 
12424     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12425     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12426     if (VT.isSimple()) {
12427       MVT LoadVT = VT.getSimpleVT();
12428       if (Subtarget.needsSwapsForVSXMemOps() &&
12429           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12430            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12431         return expandVSXLoadForLE(N, DCI);
12432     }
12433 
12434     // We sometimes end up with a 64-bit integer load, from which we extract
12435     // two single-precision floating-point numbers. This happens with
12436     // std::complex<float>, and other similar structures, because of the way we
12437     // canonicalize structure copies. However, if we lack direct moves,
12438     // then the final bitcasts from the extracted integer values to the
12439     // floating-point numbers turn into store/load pairs. Even with direct moves,
12440     // just loading the two floating-point numbers is likely better.
12441     auto ReplaceTwoFloatLoad = [&]() {
12442       if (VT != MVT::i64)
12443         return false;
12444 
12445       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12446           LD->isVolatile())
12447         return false;
12448 
12449       //  We're looking for a sequence like this:
12450       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12451       //      t16: i64 = srl t13, Constant:i32<32>
12452       //    t17: i32 = truncate t16
12453       //  t18: f32 = bitcast t17
12454       //    t19: i32 = truncate t13
12455       //  t20: f32 = bitcast t19
12456 
12457       if (!LD->hasNUsesOfValue(2, 0))
12458         return false;
12459 
12460       auto UI = LD->use_begin();
12461       while (UI.getUse().getResNo() != 0) ++UI;
12462       SDNode *Trunc = *UI++;
12463       while (UI.getUse().getResNo() != 0) ++UI;
12464       SDNode *RightShift = *UI;
12465       if (Trunc->getOpcode() != ISD::TRUNCATE)
12466         std::swap(Trunc, RightShift);
12467 
12468       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12469           Trunc->getValueType(0) != MVT::i32 ||
12470           !Trunc->hasOneUse())
12471         return false;
12472       if (RightShift->getOpcode() != ISD::SRL ||
12473           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12474           RightShift->getConstantOperandVal(1) != 32 ||
12475           !RightShift->hasOneUse())
12476         return false;
12477 
12478       SDNode *Trunc2 = *RightShift->use_begin();
12479       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12480           Trunc2->getValueType(0) != MVT::i32 ||
12481           !Trunc2->hasOneUse())
12482         return false;
12483 
12484       SDNode *Bitcast = *Trunc->use_begin();
12485       SDNode *Bitcast2 = *Trunc2->use_begin();
12486 
12487       if (Bitcast->getOpcode() != ISD::BITCAST ||
12488           Bitcast->getValueType(0) != MVT::f32)
12489         return false;
12490       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12491           Bitcast2->getValueType(0) != MVT::f32)
12492         return false;
12493 
12494       if (Subtarget.isLittleEndian())
12495         std::swap(Bitcast, Bitcast2);
12496 
12497       // Bitcast has the second float (in memory-layout order) and Bitcast2
12498       // has the first one.
12499 
12500       SDValue BasePtr = LD->getBasePtr();
12501       if (LD->isIndexed()) {
12502         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12503                "Non-pre-inc AM on PPC?");
12504         BasePtr =
12505           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12506                       LD->getOffset());
12507       }
12508 
12509       auto MMOFlags =
12510           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12511       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12512                                       LD->getPointerInfo(), LD->getAlignment(),
12513                                       MMOFlags, LD->getAAInfo());
12514       SDValue AddPtr =
12515         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12516                     BasePtr, DAG.getIntPtrConstant(4, dl));
12517       SDValue FloatLoad2 = DAG.getLoad(
12518           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12519           LD->getPointerInfo().getWithOffset(4),
12520           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12521 
12522       if (LD->isIndexed()) {
12523         // Note that DAGCombine should re-form any pre-increment load(s) from
12524         // what is produced here if that makes sense.
12525         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12526       }
12527 
12528       DCI.CombineTo(Bitcast2, FloatLoad);
12529       DCI.CombineTo(Bitcast, FloatLoad2);
12530 
12531       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12532                                     SDValue(FloatLoad2.getNode(), 1));
12533       return true;
12534     };
12535 
12536     if (ReplaceTwoFloatLoad())
12537       return SDValue(N, 0);
12538 
12539     EVT MemVT = LD->getMemoryVT();
12540     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12541     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12542     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12543     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12544     if (LD->isUnindexed() && VT.isVector() &&
12545         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12546           // P8 and later hardware should just use LOAD.
12547           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12548                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12549          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12550           LD->getAlignment() >= ScalarABIAlignment)) &&
12551         LD->getAlignment() < ABIAlignment) {
12552       // This is a type-legal unaligned Altivec or QPX load.
12553       SDValue Chain = LD->getChain();
12554       SDValue Ptr = LD->getBasePtr();
12555       bool isLittleEndian = Subtarget.isLittleEndian();
12556 
12557       // This implements the loading of unaligned vectors as described in
12558       // the venerable Apple Velocity Engine overview. Specifically:
12559       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12560       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12561       //
12562       // The general idea is to expand a sequence of one or more unaligned
12563       // loads into an alignment-based permutation-control instruction (lvsl
12564       // or lvsr), a series of regular vector loads (which always truncate
12565       // their input address to an aligned address), and a series of
12566       // permutations.  The results of these permutations are the requested
12567       // loaded values.  The trick is that the last "extra" load is not taken
12568       // from the address you might suspect (sizeof(vector) bytes after the
12569       // last requested load), but rather sizeof(vector) - 1 bytes after the
12570       // last requested vector. The point of this is to avoid a page fault if
12571       // the base address happened to be aligned. This works because if the
12572       // base address is aligned, then adding less than a full vector length
12573       // will cause the last vector in the sequence to be (re)loaded.
12574       // Otherwise, the next vector will be fetched as you might suspect was
12575       // necessary.
12576 
12577       // We might be able to reuse the permutation generation from
12578       // a different base address offset from this one by an aligned amount.
12579       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12580       // optimization later.
12581       Intrinsic::ID Intr, IntrLD, IntrPerm;
12582       MVT PermCntlTy, PermTy, LDTy;
12583       if (Subtarget.hasAltivec()) {
12584         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12585                                  Intrinsic::ppc_altivec_lvsl;
12586         IntrLD = Intrinsic::ppc_altivec_lvx;
12587         IntrPerm = Intrinsic::ppc_altivec_vperm;
12588         PermCntlTy = MVT::v16i8;
12589         PermTy = MVT::v4i32;
12590         LDTy = MVT::v4i32;
12591       } else {
12592         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12593                                        Intrinsic::ppc_qpx_qvlpcls;
12594         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12595                                        Intrinsic::ppc_qpx_qvlfs;
12596         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12597         PermCntlTy = MVT::v4f64;
12598         PermTy = MVT::v4f64;
12599         LDTy = MemVT.getSimpleVT();
12600       }
12601 
12602       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12603 
12604       // Create the new MMO for the new base load. It is like the original MMO,
12605       // but represents an area in memory almost twice the vector size centered
12606       // on the original address. If the address is unaligned, we might start
12607       // reading up to (sizeof(vector)-1) bytes below the address of the
12608       // original unaligned load.
12609       MachineFunction &MF = DAG.getMachineFunction();
12610       MachineMemOperand *BaseMMO =
12611         MF.getMachineMemOperand(LD->getMemOperand(),
12612                                 -(long)MemVT.getStoreSize()+1,
12613                                 2*MemVT.getStoreSize()-1);
12614 
12615       // Create the new base load.
12616       SDValue LDXIntID =
12617           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12618       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12619       SDValue BaseLoad =
12620         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12621                                 DAG.getVTList(PermTy, MVT::Other),
12622                                 BaseLoadOps, LDTy, BaseMMO);
12623 
12624       // Note that the value of IncOffset (which is provided to the next
12625       // load's pointer info offset value, and thus used to calculate the
12626       // alignment), and the value of IncValue (which is actually used to
12627       // increment the pointer value) are different! This is because we
12628       // require the next load to appear to be aligned, even though it
12629       // is actually offset from the base pointer by a lesser amount.
12630       int IncOffset = VT.getSizeInBits() / 8;
12631       int IncValue = IncOffset;
12632 
12633       // Walk (both up and down) the chain looking for another load at the real
12634       // (aligned) offset (the alignment of the other load does not matter in
12635       // this case). If found, then do not use the offset reduction trick, as
12636       // that will prevent the loads from being later combined (as they would
12637       // otherwise be duplicates).
12638       if (!findConsecutiveLoad(LD, DAG))
12639         --IncValue;
12640 
12641       SDValue Increment =
12642           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12643       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12644 
12645       MachineMemOperand *ExtraMMO =
12646         MF.getMachineMemOperand(LD->getMemOperand(),
12647                                 1, 2*MemVT.getStoreSize()-1);
12648       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12649       SDValue ExtraLoad =
12650         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12651                                 DAG.getVTList(PermTy, MVT::Other),
12652                                 ExtraLoadOps, LDTy, ExtraMMO);
12653 
12654       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12655         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12656 
12657       // Because vperm has a big-endian bias, we must reverse the order
12658       // of the input vectors and complement the permute control vector
12659       // when generating little endian code.  We have already handled the
12660       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12661       // and ExtraLoad here.
12662       SDValue Perm;
12663       if (isLittleEndian)
12664         Perm = BuildIntrinsicOp(IntrPerm,
12665                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12666       else
12667         Perm = BuildIntrinsicOp(IntrPerm,
12668                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12669 
12670       if (VT != PermTy)
12671         Perm = Subtarget.hasAltivec() ?
12672                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12673                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12674                                DAG.getTargetConstant(1, dl, MVT::i64));
12675                                // second argument is 1 because this rounding
12676                                // is always exact.
12677 
12678       // The output of the permutation is our loaded result, the TokenFactor is
12679       // our new chain.
12680       DCI.CombineTo(N, Perm, TF);
12681       return SDValue(N, 0);
12682     }
12683     }
12684     break;
12685     case ISD::INTRINSIC_WO_CHAIN: {
12686       bool isLittleEndian = Subtarget.isLittleEndian();
12687       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12688       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12689                                            : Intrinsic::ppc_altivec_lvsl);
12690       if ((IID == Intr ||
12691            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12692            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12693         N->getOperand(1)->getOpcode() == ISD::ADD) {
12694         SDValue Add = N->getOperand(1);
12695 
12696         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12697                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12698 
12699         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12700                                   APInt::getAllOnesValue(Bits /* alignment */)
12701                                       .zext(Add.getScalarValueSizeInBits()))) {
12702           SDNode *BasePtr = Add->getOperand(0).getNode();
12703           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12704                                     UE = BasePtr->use_end();
12705                UI != UE; ++UI) {
12706             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12707                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12708               // We've found another LVSL/LVSR, and this address is an aligned
12709               // multiple of that one. The results will be the same, so use the
12710               // one we've just found instead.
12711 
12712               return SDValue(*UI, 0);
12713             }
12714           }
12715         }
12716 
12717         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12718           SDNode *BasePtr = Add->getOperand(0).getNode();
12719           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12720                UE = BasePtr->use_end(); UI != UE; ++UI) {
12721             if (UI->getOpcode() == ISD::ADD &&
12722                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12723                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12724                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12725                 (1ULL << Bits) == 0) {
12726               SDNode *OtherAdd = *UI;
12727               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12728                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12729                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12730                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12731                   return SDValue(*VI, 0);
12732                 }
12733               }
12734             }
12735           }
12736         }
12737       }
12738     }
12739 
12740     break;
12741   case ISD::INTRINSIC_W_CHAIN:
12742     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12743     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12744     if (Subtarget.needsSwapsForVSXMemOps()) {
12745       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12746       default:
12747         break;
12748       case Intrinsic::ppc_vsx_lxvw4x:
12749       case Intrinsic::ppc_vsx_lxvd2x:
12750         return expandVSXLoadForLE(N, DCI);
12751       }
12752     }
12753     break;
12754   case ISD::INTRINSIC_VOID:
12755     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12756     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12757     if (Subtarget.needsSwapsForVSXMemOps()) {
12758       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12759       default:
12760         break;
12761       case Intrinsic::ppc_vsx_stxvw4x:
12762       case Intrinsic::ppc_vsx_stxvd2x:
12763         return expandVSXStoreForLE(N, DCI);
12764       }
12765     }
12766     break;
12767   case ISD::BSWAP:
12768     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12769     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12770         N->getOperand(0).hasOneUse() &&
12771         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12772          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12773           N->getValueType(0) == MVT::i64))) {
12774       SDValue Load = N->getOperand(0);
12775       LoadSDNode *LD = cast<LoadSDNode>(Load);
12776       // Create the byte-swapping load.
12777       SDValue Ops[] = {
12778         LD->getChain(),    // Chain
12779         LD->getBasePtr(),  // Ptr
12780         DAG.getValueType(N->getValueType(0)) // VT
12781       };
12782       SDValue BSLoad =
12783         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12784                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12785                                               MVT::i64 : MVT::i32, MVT::Other),
12786                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12787 
12788       // If this is an i16 load, insert the truncate.
12789       SDValue ResVal = BSLoad;
12790       if (N->getValueType(0) == MVT::i16)
12791         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12792 
12793       // First, combine the bswap away.  This makes the value produced by the
12794       // load dead.
12795       DCI.CombineTo(N, ResVal);
12796 
12797       // Next, combine the load away, we give it a bogus result value but a real
12798       // chain result.  The result value is dead because the bswap is dead.
12799       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12800 
12801       // Return N so it doesn't get rechecked!
12802       return SDValue(N, 0);
12803     }
12804     break;
12805   case PPCISD::VCMP:
12806     // If a VCMPo node already exists with exactly the same operands as this
12807     // node, use its result instead of this node (VCMPo computes both a CR6 and
12808     // a normal output).
12809     //
12810     if (!N->getOperand(0).hasOneUse() &&
12811         !N->getOperand(1).hasOneUse() &&
12812         !N->getOperand(2).hasOneUse()) {
12813 
12814       // Scan all of the users of the LHS, looking for VCMPo's that match.
12815       SDNode *VCMPoNode = nullptr;
12816 
12817       SDNode *LHSN = N->getOperand(0).getNode();
12818       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12819            UI != E; ++UI)
12820         if (UI->getOpcode() == PPCISD::VCMPo &&
12821             UI->getOperand(1) == N->getOperand(1) &&
12822             UI->getOperand(2) == N->getOperand(2) &&
12823             UI->getOperand(0) == N->getOperand(0)) {
12824           VCMPoNode = *UI;
12825           break;
12826         }
12827 
12828       // If there is no VCMPo node, or if the flag value has a single use, don't
12829       // transform this.
12830       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12831         break;
12832 
12833       // Look at the (necessarily single) use of the flag value.  If it has a
12834       // chain, this transformation is more complex.  Note that multiple things
12835       // could use the value result, which we should ignore.
12836       SDNode *FlagUser = nullptr;
12837       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12838            FlagUser == nullptr; ++UI) {
12839         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12840         SDNode *User = *UI;
12841         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12842           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12843             FlagUser = User;
12844             break;
12845           }
12846         }
12847       }
12848 
12849       // If the user is a MFOCRF instruction, we know this is safe.
12850       // Otherwise we give up for right now.
12851       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12852         return SDValue(VCMPoNode, 0);
12853     }
12854     break;
12855   case ISD::BRCOND: {
12856     SDValue Cond = N->getOperand(1);
12857     SDValue Target = N->getOperand(2);
12858 
12859     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12860         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12861           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12862 
12863       // We now need to make the intrinsic dead (it cannot be instruction
12864       // selected).
12865       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12866       assert(Cond.getNode()->hasOneUse() &&
12867              "Counter decrement has more than one use");
12868 
12869       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12870                          N->getOperand(0), Target);
12871     }
12872   }
12873   break;
12874   case ISD::BR_CC: {
12875     // If this is a branch on an altivec predicate comparison, lower this so
12876     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
12877     // lowering is done pre-legalize, because the legalizer lowers the predicate
12878     // compare down to code that is difficult to reassemble.
12879     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12880     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12881 
12882     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12883     // value. If so, pass-through the AND to get to the intrinsic.
12884     if (LHS.getOpcode() == ISD::AND &&
12885         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12886         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12887           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12888         isa<ConstantSDNode>(LHS.getOperand(1)) &&
12889         !isNullConstant(LHS.getOperand(1)))
12890       LHS = LHS.getOperand(0);
12891 
12892     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12893         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12894           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12895         isa<ConstantSDNode>(RHS)) {
12896       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12897              "Counter decrement comparison is not EQ or NE");
12898 
12899       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12900       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12901                     (CC == ISD::SETNE && !Val);
12902 
12903       // We now need to make the intrinsic dead (it cannot be instruction
12904       // selected).
12905       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12906       assert(LHS.getNode()->hasOneUse() &&
12907              "Counter decrement has more than one use");
12908 
12909       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12910                          N->getOperand(0), N->getOperand(4));
12911     }
12912 
12913     int CompareOpc;
12914     bool isDot;
12915 
12916     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12917         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12918         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12919       assert(isDot && "Can't compare against a vector result!");
12920 
12921       // If this is a comparison against something other than 0/1, then we know
12922       // that the condition is never/always true.
12923       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12924       if (Val != 0 && Val != 1) {
12925         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
12926           return N->getOperand(0);
12927         // Always !=, turn it into an unconditional branch.
12928         return DAG.getNode(ISD::BR, dl, MVT::Other,
12929                            N->getOperand(0), N->getOperand(4));
12930       }
12931 
12932       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12933 
12934       // Create the PPCISD altivec 'dot' comparison node.
12935       SDValue Ops[] = {
12936         LHS.getOperand(2),  // LHS of compare
12937         LHS.getOperand(3),  // RHS of compare
12938         DAG.getConstant(CompareOpc, dl, MVT::i32)
12939       };
12940       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12941       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12942 
12943       // Unpack the result based on how the target uses it.
12944       PPC::Predicate CompOpc;
12945       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12946       default:  // Can't happen, don't crash on invalid number though.
12947       case 0:   // Branch on the value of the EQ bit of CR6.
12948         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12949         break;
12950       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12951         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12952         break;
12953       case 2:   // Branch on the value of the LT bit of CR6.
12954         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12955         break;
12956       case 3:   // Branch on the inverted value of the LT bit of CR6.
12957         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12958         break;
12959       }
12960 
12961       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12962                          DAG.getConstant(CompOpc, dl, MVT::i32),
12963                          DAG.getRegister(PPC::CR6, MVT::i32),
12964                          N->getOperand(4), CompNode.getValue(1));
12965     }
12966     break;
12967   }
12968   case ISD::BUILD_VECTOR:
12969     return DAGCombineBuildVector(N, DCI);
12970   }
12971 
12972   return SDValue();
12973 }
12974 
12975 SDValue
12976 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12977                                   SelectionDAG &DAG,
12978                                   std::vector<SDNode *> *Created) const {
12979   // fold (sdiv X, pow2)
12980   EVT VT = N->getValueType(0);
12981   if (VT == MVT::i64 && !Subtarget.isPPC64())
12982     return SDValue();
12983   if ((VT != MVT::i32 && VT != MVT::i64) ||
12984       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12985     return SDValue();
12986 
12987   SDLoc DL(N);
12988   SDValue N0 = N->getOperand(0);
12989 
12990   bool IsNegPow2 = (-Divisor).isPowerOf2();
12991   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12992   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12993 
12994   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12995   if (Created)
12996     Created->push_back(Op.getNode());
12997 
12998   if (IsNegPow2) {
12999     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
13000     if (Created)
13001       Created->push_back(Op.getNode());
13002   }
13003 
13004   return Op;
13005 }
13006 
13007 //===----------------------------------------------------------------------===//
13008 // Inline Assembly Support
13009 //===----------------------------------------------------------------------===//
13010 
13011 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13012                                                       KnownBits &Known,
13013                                                       const APInt &DemandedElts,
13014                                                       const SelectionDAG &DAG,
13015                                                       unsigned Depth) const {
13016   Known.resetAll();
13017   switch (Op.getOpcode()) {
13018   default: break;
13019   case PPCISD::LBRX: {
13020     // lhbrx is known to have the top bits cleared out.
13021     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13022       Known.Zero = 0xFFFF0000;
13023     break;
13024   }
13025   case ISD::INTRINSIC_WO_CHAIN: {
13026     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13027     default: break;
13028     case Intrinsic::ppc_altivec_vcmpbfp_p:
13029     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13030     case Intrinsic::ppc_altivec_vcmpequb_p:
13031     case Intrinsic::ppc_altivec_vcmpequh_p:
13032     case Intrinsic::ppc_altivec_vcmpequw_p:
13033     case Intrinsic::ppc_altivec_vcmpequd_p:
13034     case Intrinsic::ppc_altivec_vcmpgefp_p:
13035     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13036     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13037     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13038     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13039     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13040     case Intrinsic::ppc_altivec_vcmpgtub_p:
13041     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13042     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13043     case Intrinsic::ppc_altivec_vcmpgtud_p:
13044       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13045       break;
13046     }
13047   }
13048   }
13049 }
13050 
13051 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13052   switch (Subtarget.getDarwinDirective()) {
13053   default: break;
13054   case PPC::DIR_970:
13055   case PPC::DIR_PWR4:
13056   case PPC::DIR_PWR5:
13057   case PPC::DIR_PWR5X:
13058   case PPC::DIR_PWR6:
13059   case PPC::DIR_PWR6X:
13060   case PPC::DIR_PWR7:
13061   case PPC::DIR_PWR8:
13062   case PPC::DIR_PWR9: {
13063     if (!ML)
13064       break;
13065 
13066     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13067 
13068     // For small loops (between 5 and 8 instructions), align to a 32-byte
13069     // boundary so that the entire loop fits in one instruction-cache line.
13070     uint64_t LoopSize = 0;
13071     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13072       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13073         LoopSize += TII->getInstSizeInBytes(*J);
13074         if (LoopSize > 32)
13075           break;
13076       }
13077 
13078     if (LoopSize > 16 && LoopSize <= 32)
13079       return 5;
13080 
13081     break;
13082   }
13083   }
13084 
13085   return TargetLowering::getPrefLoopAlignment(ML);
13086 }
13087 
13088 /// getConstraintType - Given a constraint, return the type of
13089 /// constraint it is for this target.
13090 PPCTargetLowering::ConstraintType
13091 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13092   if (Constraint.size() == 1) {
13093     switch (Constraint[0]) {
13094     default: break;
13095     case 'b':
13096     case 'r':
13097     case 'f':
13098     case 'd':
13099     case 'v':
13100     case 'y':
13101       return C_RegisterClass;
13102     case 'Z':
13103       // FIXME: While Z does indicate a memory constraint, it specifically
13104       // indicates an r+r address (used in conjunction with the 'y' modifier
13105       // in the replacement string). Currently, we're forcing the base
13106       // register to be r0 in the asm printer (which is interpreted as zero)
13107       // and forming the complete address in the second register. This is
13108       // suboptimal.
13109       return C_Memory;
13110     }
13111   } else if (Constraint == "wc") { // individual CR bits.
13112     return C_RegisterClass;
13113   } else if (Constraint == "wa" || Constraint == "wd" ||
13114              Constraint == "wf" || Constraint == "ws") {
13115     return C_RegisterClass; // VSX registers.
13116   }
13117   return TargetLowering::getConstraintType(Constraint);
13118 }
13119 
13120 /// Examine constraint type and operand type and determine a weight value.
13121 /// This object must already have been set up with the operand type
13122 /// and the current alternative constraint selected.
13123 TargetLowering::ConstraintWeight
13124 PPCTargetLowering::getSingleConstraintMatchWeight(
13125     AsmOperandInfo &info, const char *constraint) const {
13126   ConstraintWeight weight = CW_Invalid;
13127   Value *CallOperandVal = info.CallOperandVal;
13128     // If we don't have a value, we can't do a match,
13129     // but allow it at the lowest weight.
13130   if (!CallOperandVal)
13131     return CW_Default;
13132   Type *type = CallOperandVal->getType();
13133 
13134   // Look at the constraint type.
13135   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13136     return CW_Register; // an individual CR bit.
13137   else if ((StringRef(constraint) == "wa" ||
13138             StringRef(constraint) == "wd" ||
13139             StringRef(constraint) == "wf") &&
13140            type->isVectorTy())
13141     return CW_Register;
13142   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13143     return CW_Register;
13144 
13145   switch (*constraint) {
13146   default:
13147     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13148     break;
13149   case 'b':
13150     if (type->isIntegerTy())
13151       weight = CW_Register;
13152     break;
13153   case 'f':
13154     if (type->isFloatTy())
13155       weight = CW_Register;
13156     break;
13157   case 'd':
13158     if (type->isDoubleTy())
13159       weight = CW_Register;
13160     break;
13161   case 'v':
13162     if (type->isVectorTy())
13163       weight = CW_Register;
13164     break;
13165   case 'y':
13166     weight = CW_Register;
13167     break;
13168   case 'Z':
13169     weight = CW_Memory;
13170     break;
13171   }
13172   return weight;
13173 }
13174 
13175 std::pair<unsigned, const TargetRegisterClass *>
13176 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13177                                                 StringRef Constraint,
13178                                                 MVT VT) const {
13179   if (Constraint.size() == 1) {
13180     // GCC RS6000 Constraint Letters
13181     switch (Constraint[0]) {
13182     case 'b':   // R1-R31
13183       if (VT == MVT::i64 && Subtarget.isPPC64())
13184         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13185       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13186     case 'r':   // R0-R31
13187       if (VT == MVT::i64 && Subtarget.isPPC64())
13188         return std::make_pair(0U, &PPC::G8RCRegClass);
13189       return std::make_pair(0U, &PPC::GPRCRegClass);
13190     // 'd' and 'f' constraints are both defined to be "the floating point
13191     // registers", where one is for 32-bit and the other for 64-bit. We don't
13192     // really care overly much here so just give them all the same reg classes.
13193     case 'd':
13194     case 'f':
13195       if (VT == MVT::f32 || VT == MVT::i32)
13196         return std::make_pair(0U, &PPC::F4RCRegClass);
13197       if (VT == MVT::f64 || VT == MVT::i64)
13198         return std::make_pair(0U, &PPC::F8RCRegClass);
13199       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13200         return std::make_pair(0U, &PPC::QFRCRegClass);
13201       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13202         return std::make_pair(0U, &PPC::QSRCRegClass);
13203       break;
13204     case 'v':
13205       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13206         return std::make_pair(0U, &PPC::QFRCRegClass);
13207       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13208         return std::make_pair(0U, &PPC::QSRCRegClass);
13209       if (Subtarget.hasAltivec())
13210         return std::make_pair(0U, &PPC::VRRCRegClass);
13211       break;
13212     case 'y':   // crrc
13213       return std::make_pair(0U, &PPC::CRRCRegClass);
13214     }
13215   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13216     // An individual CR bit.
13217     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13218   } else if ((Constraint == "wa" || Constraint == "wd" ||
13219              Constraint == "wf") && Subtarget.hasVSX()) {
13220     return std::make_pair(0U, &PPC::VSRCRegClass);
13221   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13222     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13223       return std::make_pair(0U, &PPC::VSSRCRegClass);
13224     else
13225       return std::make_pair(0U, &PPC::VSFRCRegClass);
13226   }
13227 
13228   std::pair<unsigned, const TargetRegisterClass *> R =
13229       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13230 
13231   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13232   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13233   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13234   // register.
13235   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13236   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13237   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13238       PPC::GPRCRegClass.contains(R.first))
13239     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13240                             PPC::sub_32, &PPC::G8RCRegClass),
13241                           &PPC::G8RCRegClass);
13242 
13243   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13244   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13245     R.first = PPC::CR0;
13246     R.second = &PPC::CRRCRegClass;
13247   }
13248 
13249   return R;
13250 }
13251 
13252 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13253 /// vector.  If it is invalid, don't add anything to Ops.
13254 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13255                                                      std::string &Constraint,
13256                                                      std::vector<SDValue>&Ops,
13257                                                      SelectionDAG &DAG) const {
13258   SDValue Result;
13259 
13260   // Only support length 1 constraints.
13261   if (Constraint.length() > 1) return;
13262 
13263   char Letter = Constraint[0];
13264   switch (Letter) {
13265   default: break;
13266   case 'I':
13267   case 'J':
13268   case 'K':
13269   case 'L':
13270   case 'M':
13271   case 'N':
13272   case 'O':
13273   case 'P': {
13274     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13275     if (!CST) return; // Must be an immediate to match.
13276     SDLoc dl(Op);
13277     int64_t Value = CST->getSExtValue();
13278     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13279                          // numbers are printed as such.
13280     switch (Letter) {
13281     default: llvm_unreachable("Unknown constraint letter!");
13282     case 'I':  // "I" is a signed 16-bit constant.
13283       if (isInt<16>(Value))
13284         Result = DAG.getTargetConstant(Value, dl, TCVT);
13285       break;
13286     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13287       if (isShiftedUInt<16, 16>(Value))
13288         Result = DAG.getTargetConstant(Value, dl, TCVT);
13289       break;
13290     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13291       if (isShiftedInt<16, 16>(Value))
13292         Result = DAG.getTargetConstant(Value, dl, TCVT);
13293       break;
13294     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13295       if (isUInt<16>(Value))
13296         Result = DAG.getTargetConstant(Value, dl, TCVT);
13297       break;
13298     case 'M':  // "M" is a constant that is greater than 31.
13299       if (Value > 31)
13300         Result = DAG.getTargetConstant(Value, dl, TCVT);
13301       break;
13302     case 'N':  // "N" is a positive constant that is an exact power of two.
13303       if (Value > 0 && isPowerOf2_64(Value))
13304         Result = DAG.getTargetConstant(Value, dl, TCVT);
13305       break;
13306     case 'O':  // "O" is the constant zero.
13307       if (Value == 0)
13308         Result = DAG.getTargetConstant(Value, dl, TCVT);
13309       break;
13310     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13311       if (isInt<16>(-Value))
13312         Result = DAG.getTargetConstant(Value, dl, TCVT);
13313       break;
13314     }
13315     break;
13316   }
13317   }
13318 
13319   if (Result.getNode()) {
13320     Ops.push_back(Result);
13321     return;
13322   }
13323 
13324   // Handle standard constraint letters.
13325   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13326 }
13327 
13328 // isLegalAddressingMode - Return true if the addressing mode represented
13329 // by AM is legal for this target, for a load/store of the specified type.
13330 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13331                                               const AddrMode &AM, Type *Ty,
13332                                               unsigned AS, Instruction *I) const {
13333   // PPC does not allow r+i addressing modes for vectors!
13334   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13335     return false;
13336 
13337   // PPC allows a sign-extended 16-bit immediate field.
13338   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13339     return false;
13340 
13341   // No global is ever allowed as a base.
13342   if (AM.BaseGV)
13343     return false;
13344 
13345   // PPC only support r+r,
13346   switch (AM.Scale) {
13347   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13348     break;
13349   case 1:
13350     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13351       return false;
13352     // Otherwise we have r+r or r+i.
13353     break;
13354   case 2:
13355     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13356       return false;
13357     // Allow 2*r as r+r.
13358     break;
13359   default:
13360     // No other scales are supported.
13361     return false;
13362   }
13363 
13364   return true;
13365 }
13366 
13367 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13368                                            SelectionDAG &DAG) const {
13369   MachineFunction &MF = DAG.getMachineFunction();
13370   MachineFrameInfo &MFI = MF.getFrameInfo();
13371   MFI.setReturnAddressIsTaken(true);
13372 
13373   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13374     return SDValue();
13375 
13376   SDLoc dl(Op);
13377   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13378 
13379   // Make sure the function does not optimize away the store of the RA to
13380   // the stack.
13381   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13382   FuncInfo->setLRStoreRequired();
13383   bool isPPC64 = Subtarget.isPPC64();
13384   auto PtrVT = getPointerTy(MF.getDataLayout());
13385 
13386   if (Depth > 0) {
13387     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13388     SDValue Offset =
13389         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13390                         isPPC64 ? MVT::i64 : MVT::i32);
13391     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13392                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13393                        MachinePointerInfo());
13394   }
13395 
13396   // Just load the return address off the stack.
13397   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13398   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13399                      MachinePointerInfo());
13400 }
13401 
13402 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13403                                           SelectionDAG &DAG) const {
13404   SDLoc dl(Op);
13405   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13406 
13407   MachineFunction &MF = DAG.getMachineFunction();
13408   MachineFrameInfo &MFI = MF.getFrameInfo();
13409   MFI.setFrameAddressIsTaken(true);
13410 
13411   EVT PtrVT = getPointerTy(MF.getDataLayout());
13412   bool isPPC64 = PtrVT == MVT::i64;
13413 
13414   // Naked functions never have a frame pointer, and so we use r1. For all
13415   // other functions, this decision must be delayed until during PEI.
13416   unsigned FrameReg;
13417   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
13418     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13419   else
13420     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13421 
13422   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13423                                          PtrVT);
13424   while (Depth--)
13425     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13426                             FrameAddr, MachinePointerInfo());
13427   return FrameAddr;
13428 }
13429 
13430 // FIXME? Maybe this could be a TableGen attribute on some registers and
13431 // this table could be generated automatically from RegInfo.
13432 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13433                                               SelectionDAG &DAG) const {
13434   bool isPPC64 = Subtarget.isPPC64();
13435   bool isDarwinABI = Subtarget.isDarwinABI();
13436 
13437   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13438       (!isPPC64 && VT != MVT::i32))
13439     report_fatal_error("Invalid register global variable type");
13440 
13441   bool is64Bit = isPPC64 && VT == MVT::i64;
13442   unsigned Reg = StringSwitch<unsigned>(RegName)
13443                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13444                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13445                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13446                                   (is64Bit ? PPC::X13 : PPC::R13))
13447                    .Default(0);
13448 
13449   if (Reg)
13450     return Reg;
13451   report_fatal_error("Invalid register name global variable");
13452 }
13453 
13454 bool
13455 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13456   // The PowerPC target isn't yet aware of offsets.
13457   return false;
13458 }
13459 
13460 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13461                                            const CallInst &I,
13462                                            MachineFunction &MF,
13463                                            unsigned Intrinsic) const {
13464   switch (Intrinsic) {
13465   case Intrinsic::ppc_qpx_qvlfd:
13466   case Intrinsic::ppc_qpx_qvlfs:
13467   case Intrinsic::ppc_qpx_qvlfcd:
13468   case Intrinsic::ppc_qpx_qvlfcs:
13469   case Intrinsic::ppc_qpx_qvlfiwa:
13470   case Intrinsic::ppc_qpx_qvlfiwz:
13471   case Intrinsic::ppc_altivec_lvx:
13472   case Intrinsic::ppc_altivec_lvxl:
13473   case Intrinsic::ppc_altivec_lvebx:
13474   case Intrinsic::ppc_altivec_lvehx:
13475   case Intrinsic::ppc_altivec_lvewx:
13476   case Intrinsic::ppc_vsx_lxvd2x:
13477   case Intrinsic::ppc_vsx_lxvw4x: {
13478     EVT VT;
13479     switch (Intrinsic) {
13480     case Intrinsic::ppc_altivec_lvebx:
13481       VT = MVT::i8;
13482       break;
13483     case Intrinsic::ppc_altivec_lvehx:
13484       VT = MVT::i16;
13485       break;
13486     case Intrinsic::ppc_altivec_lvewx:
13487       VT = MVT::i32;
13488       break;
13489     case Intrinsic::ppc_vsx_lxvd2x:
13490       VT = MVT::v2f64;
13491       break;
13492     case Intrinsic::ppc_qpx_qvlfd:
13493       VT = MVT::v4f64;
13494       break;
13495     case Intrinsic::ppc_qpx_qvlfs:
13496       VT = MVT::v4f32;
13497       break;
13498     case Intrinsic::ppc_qpx_qvlfcd:
13499       VT = MVT::v2f64;
13500       break;
13501     case Intrinsic::ppc_qpx_qvlfcs:
13502       VT = MVT::v2f32;
13503       break;
13504     default:
13505       VT = MVT::v4i32;
13506       break;
13507     }
13508 
13509     Info.opc = ISD::INTRINSIC_W_CHAIN;
13510     Info.memVT = VT;
13511     Info.ptrVal = I.getArgOperand(0);
13512     Info.offset = -VT.getStoreSize()+1;
13513     Info.size = 2*VT.getStoreSize()-1;
13514     Info.align = 1;
13515     Info.flags = MachineMemOperand::MOLoad;
13516     return true;
13517   }
13518   case Intrinsic::ppc_qpx_qvlfda:
13519   case Intrinsic::ppc_qpx_qvlfsa:
13520   case Intrinsic::ppc_qpx_qvlfcda:
13521   case Intrinsic::ppc_qpx_qvlfcsa:
13522   case Intrinsic::ppc_qpx_qvlfiwaa:
13523   case Intrinsic::ppc_qpx_qvlfiwza: {
13524     EVT VT;
13525     switch (Intrinsic) {
13526     case Intrinsic::ppc_qpx_qvlfda:
13527       VT = MVT::v4f64;
13528       break;
13529     case Intrinsic::ppc_qpx_qvlfsa:
13530       VT = MVT::v4f32;
13531       break;
13532     case Intrinsic::ppc_qpx_qvlfcda:
13533       VT = MVT::v2f64;
13534       break;
13535     case Intrinsic::ppc_qpx_qvlfcsa:
13536       VT = MVT::v2f32;
13537       break;
13538     default:
13539       VT = MVT::v4i32;
13540       break;
13541     }
13542 
13543     Info.opc = ISD::INTRINSIC_W_CHAIN;
13544     Info.memVT = VT;
13545     Info.ptrVal = I.getArgOperand(0);
13546     Info.offset = 0;
13547     Info.size = VT.getStoreSize();
13548     Info.align = 1;
13549     Info.flags = MachineMemOperand::MOLoad;
13550     return true;
13551   }
13552   case Intrinsic::ppc_qpx_qvstfd:
13553   case Intrinsic::ppc_qpx_qvstfs:
13554   case Intrinsic::ppc_qpx_qvstfcd:
13555   case Intrinsic::ppc_qpx_qvstfcs:
13556   case Intrinsic::ppc_qpx_qvstfiw:
13557   case Intrinsic::ppc_altivec_stvx:
13558   case Intrinsic::ppc_altivec_stvxl:
13559   case Intrinsic::ppc_altivec_stvebx:
13560   case Intrinsic::ppc_altivec_stvehx:
13561   case Intrinsic::ppc_altivec_stvewx:
13562   case Intrinsic::ppc_vsx_stxvd2x:
13563   case Intrinsic::ppc_vsx_stxvw4x: {
13564     EVT VT;
13565     switch (Intrinsic) {
13566     case Intrinsic::ppc_altivec_stvebx:
13567       VT = MVT::i8;
13568       break;
13569     case Intrinsic::ppc_altivec_stvehx:
13570       VT = MVT::i16;
13571       break;
13572     case Intrinsic::ppc_altivec_stvewx:
13573       VT = MVT::i32;
13574       break;
13575     case Intrinsic::ppc_vsx_stxvd2x:
13576       VT = MVT::v2f64;
13577       break;
13578     case Intrinsic::ppc_qpx_qvstfd:
13579       VT = MVT::v4f64;
13580       break;
13581     case Intrinsic::ppc_qpx_qvstfs:
13582       VT = MVT::v4f32;
13583       break;
13584     case Intrinsic::ppc_qpx_qvstfcd:
13585       VT = MVT::v2f64;
13586       break;
13587     case Intrinsic::ppc_qpx_qvstfcs:
13588       VT = MVT::v2f32;
13589       break;
13590     default:
13591       VT = MVT::v4i32;
13592       break;
13593     }
13594 
13595     Info.opc = ISD::INTRINSIC_VOID;
13596     Info.memVT = VT;
13597     Info.ptrVal = I.getArgOperand(1);
13598     Info.offset = -VT.getStoreSize()+1;
13599     Info.size = 2*VT.getStoreSize()-1;
13600     Info.align = 1;
13601     Info.flags = MachineMemOperand::MOStore;
13602     return true;
13603   }
13604   case Intrinsic::ppc_qpx_qvstfda:
13605   case Intrinsic::ppc_qpx_qvstfsa:
13606   case Intrinsic::ppc_qpx_qvstfcda:
13607   case Intrinsic::ppc_qpx_qvstfcsa:
13608   case Intrinsic::ppc_qpx_qvstfiwa: {
13609     EVT VT;
13610     switch (Intrinsic) {
13611     case Intrinsic::ppc_qpx_qvstfda:
13612       VT = MVT::v4f64;
13613       break;
13614     case Intrinsic::ppc_qpx_qvstfsa:
13615       VT = MVT::v4f32;
13616       break;
13617     case Intrinsic::ppc_qpx_qvstfcda:
13618       VT = MVT::v2f64;
13619       break;
13620     case Intrinsic::ppc_qpx_qvstfcsa:
13621       VT = MVT::v2f32;
13622       break;
13623     default:
13624       VT = MVT::v4i32;
13625       break;
13626     }
13627 
13628     Info.opc = ISD::INTRINSIC_VOID;
13629     Info.memVT = VT;
13630     Info.ptrVal = I.getArgOperand(1);
13631     Info.offset = 0;
13632     Info.size = VT.getStoreSize();
13633     Info.align = 1;
13634     Info.flags = MachineMemOperand::MOStore;
13635     return true;
13636   }
13637   default:
13638     break;
13639   }
13640 
13641   return false;
13642 }
13643 
13644 /// getOptimalMemOpType - Returns the target specific optimal type for load
13645 /// and store operations as a result of memset, memcpy, and memmove
13646 /// lowering. If DstAlign is zero that means it's safe to destination
13647 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13648 /// means there isn't a need to check it against alignment requirement,
13649 /// probably because the source does not need to be loaded. If 'IsMemset' is
13650 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13651 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13652 /// source is constant so it does not need to be loaded.
13653 /// It returns EVT::Other if the type should be determined using generic
13654 /// target-independent logic.
13655 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13656                                            unsigned DstAlign, unsigned SrcAlign,
13657                                            bool IsMemset, bool ZeroMemset,
13658                                            bool MemcpyStrSrc,
13659                                            MachineFunction &MF) const {
13660   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13661     const Function &F = MF.getFunction();
13662     // When expanding a memset, require at least two QPX instructions to cover
13663     // the cost of loading the value to be stored from the constant pool.
13664     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13665        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13666         !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13667       return MVT::v4f64;
13668     }
13669 
13670     // We should use Altivec/VSX loads and stores when available. For unaligned
13671     // addresses, unaligned VSX loads are only fast starting with the P8.
13672     if (Subtarget.hasAltivec() && Size >= 16 &&
13673         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13674          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13675       return MVT::v4i32;
13676   }
13677 
13678   if (Subtarget.isPPC64()) {
13679     return MVT::i64;
13680   }
13681 
13682   return MVT::i32;
13683 }
13684 
13685 /// Returns true if it is beneficial to convert a load of a constant
13686 /// to just the constant itself.
13687 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13688                                                           Type *Ty) const {
13689   assert(Ty->isIntegerTy());
13690 
13691   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13692   return !(BitSize == 0 || BitSize > 64);
13693 }
13694 
13695 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13696   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13697     return false;
13698   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13699   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13700   return NumBits1 == 64 && NumBits2 == 32;
13701 }
13702 
13703 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13704   if (!VT1.isInteger() || !VT2.isInteger())
13705     return false;
13706   unsigned NumBits1 = VT1.getSizeInBits();
13707   unsigned NumBits2 = VT2.getSizeInBits();
13708   return NumBits1 == 64 && NumBits2 == 32;
13709 }
13710 
13711 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13712   // Generally speaking, zexts are not free, but they are free when they can be
13713   // folded with other operations.
13714   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13715     EVT MemVT = LD->getMemoryVT();
13716     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13717          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13718         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13719          LD->getExtensionType() == ISD::ZEXTLOAD))
13720       return true;
13721   }
13722 
13723   // FIXME: Add other cases...
13724   //  - 32-bit shifts with a zext to i64
13725   //  - zext after ctlz, bswap, etc.
13726   //  - zext after and by a constant mask
13727 
13728   return TargetLowering::isZExtFree(Val, VT2);
13729 }
13730 
13731 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13732   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13733          "invalid fpext types");
13734   return true;
13735 }
13736 
13737 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13738   return isInt<16>(Imm) || isUInt<16>(Imm);
13739 }
13740 
13741 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13742   return isInt<16>(Imm) || isUInt<16>(Imm);
13743 }
13744 
13745 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13746                                                        unsigned,
13747                                                        unsigned,
13748                                                        bool *Fast) const {
13749   if (DisablePPCUnaligned)
13750     return false;
13751 
13752   // PowerPC supports unaligned memory access for simple non-vector types.
13753   // Although accessing unaligned addresses is not as efficient as accessing
13754   // aligned addresses, it is generally more efficient than manual expansion,
13755   // and generally only traps for software emulation when crossing page
13756   // boundaries.
13757 
13758   if (!VT.isSimple())
13759     return false;
13760 
13761   if (VT.getSimpleVT().isVector()) {
13762     if (Subtarget.hasVSX()) {
13763       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13764           VT != MVT::v4f32 && VT != MVT::v4i32)
13765         return false;
13766     } else {
13767       return false;
13768     }
13769   }
13770 
13771   if (VT == MVT::ppcf128)
13772     return false;
13773 
13774   if (Fast)
13775     *Fast = true;
13776 
13777   return true;
13778 }
13779 
13780 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13781   VT = VT.getScalarType();
13782 
13783   if (!VT.isSimple())
13784     return false;
13785 
13786   switch (VT.getSimpleVT().SimpleTy) {
13787   case MVT::f32:
13788   case MVT::f64:
13789     return true;
13790   case MVT::f128:
13791     return (EnableQuadPrecision && Subtarget.hasP9Vector());
13792   default:
13793     break;
13794   }
13795 
13796   return false;
13797 }
13798 
13799 const MCPhysReg *
13800 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13801   // LR is a callee-save register, but we must treat it as clobbered by any call
13802   // site. Hence we include LR in the scratch registers, which are in turn added
13803   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13804   // to CTR, which is used by any indirect call.
13805   static const MCPhysReg ScratchRegs[] = {
13806     PPC::X12, PPC::LR8, PPC::CTR8, 0
13807   };
13808 
13809   return ScratchRegs;
13810 }
13811 
13812 unsigned PPCTargetLowering::getExceptionPointerRegister(
13813     const Constant *PersonalityFn) const {
13814   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13815 }
13816 
13817 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13818     const Constant *PersonalityFn) const {
13819   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13820 }
13821 
13822 bool
13823 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13824                      EVT VT , unsigned DefinedValues) const {
13825   if (VT == MVT::v2i64)
13826     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13827 
13828   if (Subtarget.hasVSX() || Subtarget.hasQPX())
13829     return true;
13830 
13831   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13832 }
13833 
13834 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13835   if (DisableILPPref || Subtarget.enableMachineScheduler())
13836     return TargetLowering::getSchedulingPreference(N);
13837 
13838   return Sched::ILP;
13839 }
13840 
13841 // Create a fast isel object.
13842 FastISel *
13843 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13844                                   const TargetLibraryInfo *LibInfo) const {
13845   return PPC::createFastISel(FuncInfo, LibInfo);
13846 }
13847 
13848 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13849   if (Subtarget.isDarwinABI()) return;
13850   if (!Subtarget.isPPC64()) return;
13851 
13852   // Update IsSplitCSR in PPCFunctionInfo
13853   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13854   PFI->setIsSplitCSR(true);
13855 }
13856 
13857 void PPCTargetLowering::insertCopiesSplitCSR(
13858   MachineBasicBlock *Entry,
13859   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13860   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13861   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13862   if (!IStart)
13863     return;
13864 
13865   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13866   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13867   MachineBasicBlock::iterator MBBI = Entry->begin();
13868   for (const MCPhysReg *I = IStart; *I; ++I) {
13869     const TargetRegisterClass *RC = nullptr;
13870     if (PPC::G8RCRegClass.contains(*I))
13871       RC = &PPC::G8RCRegClass;
13872     else if (PPC::F8RCRegClass.contains(*I))
13873       RC = &PPC::F8RCRegClass;
13874     else if (PPC::CRRCRegClass.contains(*I))
13875       RC = &PPC::CRRCRegClass;
13876     else if (PPC::VRRCRegClass.contains(*I))
13877       RC = &PPC::VRRCRegClass;
13878     else
13879       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13880 
13881     unsigned NewVR = MRI->createVirtualRegister(RC);
13882     // Create copy from CSR to a virtual register.
13883     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13884     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13885     // nounwind. If we want to generalize this later, we may need to emit
13886     // CFI pseudo-instructions.
13887     assert(Entry->getParent()->getFunction().hasFnAttribute(
13888              Attribute::NoUnwind) &&
13889            "Function should be nounwind in insertCopiesSplitCSR!");
13890     Entry->addLiveIn(*I);
13891     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13892       .addReg(*I);
13893 
13894     // Insert the copy-back instructions right before the terminator
13895     for (auto *Exit : Exits)
13896       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13897               TII->get(TargetOpcode::COPY), *I)
13898         .addReg(NewVR);
13899   }
13900 }
13901 
13902 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13903 bool PPCTargetLowering::useLoadStackGuardNode() const {
13904   if (!Subtarget.isTargetLinux())
13905     return TargetLowering::useLoadStackGuardNode();
13906   return true;
13907 }
13908 
13909 // Override to disable global variable loading on Linux.
13910 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13911   if (!Subtarget.isTargetLinux())
13912     return TargetLowering::insertSSPDeclarations(M);
13913 }
13914 
13915 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13916   if (!VT.isSimple() || !Subtarget.hasVSX())
13917     return false;
13918 
13919   switch(VT.getSimpleVT().SimpleTy) {
13920   default:
13921     // For FP types that are currently not supported by PPC backend, return
13922     // false. Examples: f16, f80.
13923     return false;
13924   case MVT::f32:
13925   case MVT::f64:
13926   case MVT::ppcf128:
13927     return Imm.isPosZero();
13928   }
13929 }
13930 
13931 // For vector shift operation op, fold
13932 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13933 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13934                                   SelectionDAG &DAG) {
13935   SDValue N0 = N->getOperand(0);
13936   SDValue N1 = N->getOperand(1);
13937   EVT VT = N0.getValueType();
13938   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13939   unsigned Opcode = N->getOpcode();
13940   unsigned TargetOpcode;
13941 
13942   switch (Opcode) {
13943   default:
13944     llvm_unreachable("Unexpected shift operation");
13945   case ISD::SHL:
13946     TargetOpcode = PPCISD::SHL;
13947     break;
13948   case ISD::SRL:
13949     TargetOpcode = PPCISD::SRL;
13950     break;
13951   case ISD::SRA:
13952     TargetOpcode = PPCISD::SRA;
13953     break;
13954   }
13955 
13956   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13957       N1->getOpcode() == ISD::AND)
13958     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13959       if (Mask->getZExtValue() == OpSizeInBits - 1)
13960         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13961 
13962   return SDValue();
13963 }
13964 
13965 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13966   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13967     return Value;
13968 
13969   return SDValue();
13970 }
13971 
13972 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13973   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13974     return Value;
13975 
13976   return SDValue();
13977 }
13978 
13979 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13980   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13981     return Value;
13982 
13983   return SDValue();
13984 }
13985 
13986 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
13987   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
13988   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
13989     return false;
13990 
13991   // If not a tail call then no need to proceed.
13992   if (!CI->isTailCall())
13993     return false;
13994 
13995   // If tail calls are disabled for the caller then we are done.
13996   const Function *Caller = CI->getParent()->getParent();
13997   auto Attr = Caller->getFnAttribute("disable-tail-calls");
13998   if (Attr.getValueAsString() == "true")
13999     return false;
14000 
14001   // If sibling calls have been disabled and tail-calls aren't guaranteed
14002   // there is no reason to duplicate.
14003   auto &TM = getTargetMachine();
14004   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
14005     return false;
14006 
14007   // Can't tail call a function called indirectly, or if it has variadic args.
14008   const Function *Callee = CI->getCalledFunction();
14009   if (!Callee || Callee->isVarArg())
14010     return false;
14011 
14012   // Make sure the callee and caller calling conventions are eligible for tco.
14013   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14014                                            CI->getCallingConv()))
14015       return false;
14016 
14017   // If the function is local then we have a good chance at tail-calling it
14018   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14019 }
14020 
14021 bool PPCTargetLowering::
14022 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14023   const Value *Mask = AndI.getOperand(1);
14024   // If the mask is suitable for andi. or andis. we should sink the and.
14025   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14026     // Can't handle constants wider than 64-bits.
14027     if (CI->getBitWidth() > 64)
14028       return false;
14029     int64_t ConstVal = CI->getZExtValue();
14030     return isUInt<16>(ConstVal) ||
14031       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
14032   }
14033 
14034   // For non-constant masks, we can always use the record-form and.
14035   return true;
14036 }
14037