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   if (Subtarget.useCRBits()) {
176     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
177 
178     if (isPPC64 || Subtarget.hasFPCVT()) {
179       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
180       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
181                          isPPC64 ? MVT::i64 : MVT::i32);
182       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
183       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
184                         isPPC64 ? MVT::i64 : MVT::i32);
185     } else {
186       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
187       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
188     }
189 
190     // PowerPC does not support direct load/store of condition registers.
191     setOperationAction(ISD::LOAD, MVT::i1, Custom);
192     setOperationAction(ISD::STORE, MVT::i1, Custom);
193 
194     // FIXME: Remove this once the ANDI glue bug is fixed:
195     if (ANDIGlueBug)
196       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
197 
198     for (MVT VT : MVT::integer_valuetypes()) {
199       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
200       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
201       setTruncStoreAction(VT, MVT::i1, Expand);
202     }
203 
204     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
205   }
206 
207   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
208   // PPC (the libcall is not available).
209   setOperationAction(ISD::FP_TO_SINT, MVT::ppcf128, Custom);
210   setOperationAction(ISD::FP_TO_UINT, MVT::ppcf128, Custom);
211 
212   // We do not currently implement these libm ops for PowerPC.
213   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
214   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
215   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
216   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
217   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
218   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
219 
220   // PowerPC has no SREM/UREM instructions unless we are on P9
221   // On P9 we may use a hardware instruction to compute the remainder.
222   // The instructions are not legalized directly because in the cases where the
223   // result of both the remainder and the division is required it is more
224   // efficient to compute the remainder from the result of the division rather
225   // than use the remainder instruction.
226   if (Subtarget.isISA3_0()) {
227     setOperationAction(ISD::SREM, MVT::i32, Custom);
228     setOperationAction(ISD::UREM, MVT::i32, Custom);
229     setOperationAction(ISD::SREM, MVT::i64, Custom);
230     setOperationAction(ISD::UREM, MVT::i64, Custom);
231   } else {
232     setOperationAction(ISD::SREM, MVT::i32, Expand);
233     setOperationAction(ISD::UREM, MVT::i32, Expand);
234     setOperationAction(ISD::SREM, MVT::i64, Expand);
235     setOperationAction(ISD::UREM, MVT::i64, Expand);
236   }
237 
238   if (Subtarget.hasP9Vector()) {
239     setOperationAction(ISD::ABS, MVT::v4i32, Legal);
240     setOperationAction(ISD::ABS, MVT::v8i16, Legal);
241     setOperationAction(ISD::ABS, MVT::v16i8, Legal);
242   }
243 
244   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
245   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
246   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
247   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
248   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
249   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
250   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
251   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
252   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
253 
254   // We don't support sin/cos/sqrt/fmod/pow
255   setOperationAction(ISD::FSIN , MVT::f64, Expand);
256   setOperationAction(ISD::FCOS , MVT::f64, Expand);
257   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
258   setOperationAction(ISD::FREM , MVT::f64, Expand);
259   setOperationAction(ISD::FPOW , MVT::f64, Expand);
260   setOperationAction(ISD::FMA  , MVT::f64, Legal);
261   setOperationAction(ISD::FSIN , MVT::f32, Expand);
262   setOperationAction(ISD::FCOS , MVT::f32, Expand);
263   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
264   setOperationAction(ISD::FREM , MVT::f32, Expand);
265   setOperationAction(ISD::FPOW , MVT::f32, Expand);
266   setOperationAction(ISD::FMA  , MVT::f32, Legal);
267 
268   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
269 
270   // If we're enabling GP optimizations, use hardware square root
271   if (!Subtarget.hasFSQRT() &&
272       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
273         Subtarget.hasFRE()))
274     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
275 
276   if (!Subtarget.hasFSQRT() &&
277       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
278         Subtarget.hasFRES()))
279     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
280 
281   if (Subtarget.hasFCPSGN()) {
282     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
283     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
284   } else {
285     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
286     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
287   }
288 
289   if (Subtarget.hasFPRND()) {
290     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
291     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
292     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
293     setOperationAction(ISD::FROUND, MVT::f64, Legal);
294 
295     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
296     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
297     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
298     setOperationAction(ISD::FROUND, MVT::f32, Legal);
299   }
300 
301   // PowerPC does not have BSWAP, but we can use vector BSWAP instruction xxbrd
302   // to speed up scalar BSWAP64.
303   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
304   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
305   if (Subtarget.isISA3_0()) {
306     setOperationAction(ISD::BSWAP, MVT::i64  , Custom);
307     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
308     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
309   } else {
310     setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
311     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
312     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
313   }
314 
315   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
316     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
317     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
318   } else {
319     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
320     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
321   }
322 
323   // PowerPC does not have ROTR
324   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
325   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
326 
327   if (!Subtarget.useCRBits()) {
328     // PowerPC does not have Select
329     setOperationAction(ISD::SELECT, MVT::i32, Expand);
330     setOperationAction(ISD::SELECT, MVT::i64, Expand);
331     setOperationAction(ISD::SELECT, MVT::f32, Expand);
332     setOperationAction(ISD::SELECT, MVT::f64, Expand);
333   }
334 
335   // PowerPC wants to turn select_cc of FP into fsel when possible.
336   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
337   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
338 
339   // PowerPC wants to optimize integer setcc a bit
340   if (!Subtarget.useCRBits())
341     setOperationAction(ISD::SETCC, MVT::i32, Custom);
342 
343   // PowerPC does not have BRCOND which requires SetCC
344   if (!Subtarget.useCRBits())
345     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
346 
347   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
348 
349   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
350   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
351 
352   // PowerPC does not have [U|S]INT_TO_FP
353   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
354   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
355 
356   if (Subtarget.hasDirectMove() && isPPC64) {
357     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
358     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
359     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
360     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
361   } else {
362     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
363     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
364     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
365     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
366   }
367 
368   // We cannot sextinreg(i1).  Expand to shifts.
369   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
370 
371   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
372   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
373   // support continuation, user-level threading, and etc.. As a result, no
374   // other SjLj exception interfaces are implemented and please don't build
375   // your own exception handling based on them.
376   // LLVM/Clang supports zero-cost DWARF exception handling.
377   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
378   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
379 
380   // We want to legalize GlobalAddress and ConstantPool nodes into the
381   // appropriate instructions to materialize the address.
382   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
383   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
384   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
385   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
386   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
387   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
388   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
389   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
390   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
391   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
392 
393   // TRAP is legal.
394   setOperationAction(ISD::TRAP, MVT::Other, Legal);
395 
396   // TRAMPOLINE is custom lowered.
397   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
398   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
399 
400   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
401   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
402 
403   if (Subtarget.isSVR4ABI()) {
404     if (isPPC64) {
405       // VAARG always uses double-word chunks, so promote anything smaller.
406       setOperationAction(ISD::VAARG, MVT::i1, Promote);
407       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
408       setOperationAction(ISD::VAARG, MVT::i8, Promote);
409       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
410       setOperationAction(ISD::VAARG, MVT::i16, Promote);
411       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
412       setOperationAction(ISD::VAARG, MVT::i32, Promote);
413       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
414       setOperationAction(ISD::VAARG, MVT::Other, Expand);
415     } else {
416       // VAARG is custom lowered with the 32-bit SVR4 ABI.
417       setOperationAction(ISD::VAARG, MVT::Other, Custom);
418       setOperationAction(ISD::VAARG, MVT::i64, Custom);
419     }
420   } else
421     setOperationAction(ISD::VAARG, MVT::Other, Expand);
422 
423   if (Subtarget.isSVR4ABI() && !isPPC64)
424     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
425     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
426   else
427     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
428 
429   // Use the default implementation.
430   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
431   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
432   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
433   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
434   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
435   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
436   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
437   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
438   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
439 
440   // We want to custom lower some of our intrinsics.
441   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
442 
443   // To handle counter-based loop conditions.
444   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
445 
446   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
447   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
448   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
449   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
450 
451   // Comparisons that require checking two conditions.
452   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
453   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
454   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
455   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
456   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
457   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
458   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
459   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
460   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
461   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
462   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
463   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
464 
465   if (Subtarget.has64BitSupport()) {
466     // They also have instructions for converting between i64 and fp.
467     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
468     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
469     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
470     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
471     // This is just the low 32 bits of a (signed) fp->i64 conversion.
472     // We cannot do this with Promote because i64 is not a legal type.
473     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
474 
475     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
476       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
477   } else {
478     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
479     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
480   }
481 
482   // With the instructions enabled under FPCVT, we can do everything.
483   if (Subtarget.hasFPCVT()) {
484     if (Subtarget.has64BitSupport()) {
485       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
486       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
487       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
488       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
489     }
490 
491     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
492     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
493     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
494     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
495   }
496 
497   if (Subtarget.use64BitRegs()) {
498     // 64-bit PowerPC implementations can support i64 types directly
499     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
500     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
501     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
502     // 64-bit PowerPC wants to expand i128 shifts itself.
503     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
504     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
505     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
506   } else {
507     // 32-bit PowerPC wants to expand i64 shifts itself.
508     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
509     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
510     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
511   }
512 
513   if (Subtarget.hasAltivec()) {
514     // First set operation action for all vector types to expand. Then we
515     // will selectively turn on ones that can be effectively codegen'd.
516     for (MVT VT : MVT::vector_valuetypes()) {
517       // add/sub are legal for all supported vector VT's.
518       setOperationAction(ISD::ADD, VT, Legal);
519       setOperationAction(ISD::SUB, VT, Legal);
520 
521       // Vector instructions introduced in P8
522       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
523         setOperationAction(ISD::CTPOP, VT, Legal);
524         setOperationAction(ISD::CTLZ, VT, Legal);
525       }
526       else {
527         setOperationAction(ISD::CTPOP, VT, Expand);
528         setOperationAction(ISD::CTLZ, VT, Expand);
529       }
530 
531       // Vector instructions introduced in P9
532       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
533         setOperationAction(ISD::CTTZ, VT, Legal);
534       else
535         setOperationAction(ISD::CTTZ, VT, Expand);
536 
537       // We promote all shuffles to v16i8.
538       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
539       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
540 
541       // We promote all non-typed operations to v4i32.
542       setOperationAction(ISD::AND   , VT, Promote);
543       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
544       setOperationAction(ISD::OR    , VT, Promote);
545       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
546       setOperationAction(ISD::XOR   , VT, Promote);
547       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
548       setOperationAction(ISD::LOAD  , VT, Promote);
549       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
550       setOperationAction(ISD::SELECT, VT, Promote);
551       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
552       setOperationAction(ISD::SELECT_CC, VT, Promote);
553       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
554       setOperationAction(ISD::STORE, VT, Promote);
555       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
556 
557       // No other operations are legal.
558       setOperationAction(ISD::MUL , VT, Expand);
559       setOperationAction(ISD::SDIV, VT, Expand);
560       setOperationAction(ISD::SREM, VT, Expand);
561       setOperationAction(ISD::UDIV, VT, Expand);
562       setOperationAction(ISD::UREM, VT, Expand);
563       setOperationAction(ISD::FDIV, VT, Expand);
564       setOperationAction(ISD::FREM, VT, Expand);
565       setOperationAction(ISD::FNEG, VT, Expand);
566       setOperationAction(ISD::FSQRT, VT, Expand);
567       setOperationAction(ISD::FLOG, VT, Expand);
568       setOperationAction(ISD::FLOG10, VT, Expand);
569       setOperationAction(ISD::FLOG2, VT, Expand);
570       setOperationAction(ISD::FEXP, VT, Expand);
571       setOperationAction(ISD::FEXP2, VT, Expand);
572       setOperationAction(ISD::FSIN, VT, Expand);
573       setOperationAction(ISD::FCOS, VT, Expand);
574       setOperationAction(ISD::FABS, VT, Expand);
575       setOperationAction(ISD::FFLOOR, VT, Expand);
576       setOperationAction(ISD::FCEIL,  VT, Expand);
577       setOperationAction(ISD::FTRUNC, VT, Expand);
578       setOperationAction(ISD::FRINT,  VT, Expand);
579       setOperationAction(ISD::FNEARBYINT, VT, Expand);
580       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
581       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
582       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
583       setOperationAction(ISD::MULHU, VT, Expand);
584       setOperationAction(ISD::MULHS, VT, Expand);
585       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
586       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
587       setOperationAction(ISD::UDIVREM, VT, Expand);
588       setOperationAction(ISD::SDIVREM, VT, Expand);
589       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
590       setOperationAction(ISD::FPOW, VT, Expand);
591       setOperationAction(ISD::BSWAP, VT, Expand);
592       setOperationAction(ISD::VSELECT, VT, Expand);
593       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
594       setOperationAction(ISD::ROTL, VT, Expand);
595       setOperationAction(ISD::ROTR, VT, Expand);
596 
597       for (MVT InnerVT : MVT::vector_valuetypes()) {
598         setTruncStoreAction(VT, InnerVT, Expand);
599         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
600         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
601         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
602       }
603     }
604 
605     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
606     // with merges, splats, etc.
607     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
608 
609     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
610     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
611     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
612     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
613     setOperationAction(ISD::SELECT, MVT::v4i32,
614                        Subtarget.useCRBits() ? Legal : Expand);
615     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
616     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
617     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
618     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
619     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
620     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
621     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
622     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
623     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
624 
625     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
626     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
627     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
628     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
629 
630     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
631     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
632 
633     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
634       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
635       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
636     }
637 
638     if (Subtarget.hasP8Altivec())
639       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
640     else
641       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
642 
643     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
644     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
645 
646     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
647     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
648 
649     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
650     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
651     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
652     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
653 
654     // Altivec does not contain unordered floating-point compare instructions
655     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
656     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
657     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
658     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
659 
660     if (Subtarget.hasVSX()) {
661       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
662       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
663       if (Subtarget.hasP8Vector()) {
664         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
665         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
666       }
667       if (Subtarget.hasDirectMove() && isPPC64) {
668         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
669         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
670         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
671         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
672         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
673         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
674         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
675         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
676       }
677       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
678 
679       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
680       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
681       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
682       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
683       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
684 
685       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
686 
687       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
688       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
689 
690       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
691       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
692 
693       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
694       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
695       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
696       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
697       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
698 
699       // Share the Altivec comparison restrictions.
700       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
701       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
702       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
703       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
704 
705       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
706       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
707 
708       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
709 
710       if (Subtarget.hasP8Vector())
711         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
712 
713       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
714 
715       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
716       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
717       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
718 
719       if (Subtarget.hasP8Altivec()) {
720         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
721         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
722         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
723 
724         // 128 bit shifts can be accomplished via 3 instructions for SHL and
725         // SRL, but not for SRA because of the instructions available:
726         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
727         // doing
728         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
729         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
730         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
731 
732         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
733       }
734       else {
735         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
736         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
737         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
738 
739         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
740 
741         // VSX v2i64 only supports non-arithmetic operations.
742         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
743         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
744       }
745 
746       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
747       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
748       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
749       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
750 
751       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
752 
753       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
754       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
755       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
756       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
757 
758       // Vector operation legalization checks the result type of
759       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
760       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
761       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
762       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
763       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
764 
765       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
766       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
767       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
768       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
769 
770       if (Subtarget.hasDirectMove())
771         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
772       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
773 
774       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
775     }
776 
777     if (Subtarget.hasP8Altivec()) {
778       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
779       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
780     }
781 
782     if (Subtarget.hasP9Vector()) {
783       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
784       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
785 
786       // 128 bit shifts can be accomplished via 3 instructions for SHL and
787       // SRL, but not for SRA because of the instructions available:
788       // VS{RL} and VS{RL}O.
789       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
790       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
791       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
792 
793       if (EnableQuadPrecision) {
794         addRegisterClass(MVT::f128, &PPC::VRRCRegClass);
795         setOperationAction(ISD::FADD, MVT::f128, Legal);
796         setOperationAction(ISD::FSUB, MVT::f128, Legal);
797         setOperationAction(ISD::FDIV, MVT::f128, Legal);
798         setOperationAction(ISD::FMUL, MVT::f128, Legal);
799         setOperationAction(ISD::FP_EXTEND, MVT::f128, Legal);
800         setLoadExtAction(ISD::EXTLOAD, MVT::f128, MVT::f64, Expand);
801         setOperationAction(ISD::FMA, MVT::f128, Legal);
802       }
803 
804     }
805 
806     if (Subtarget.hasP9Altivec()) {
807       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
808       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
809     }
810   }
811 
812   if (Subtarget.hasQPX()) {
813     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
814     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
815     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
816     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
817 
818     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
819     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
820 
821     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
822     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
823 
824     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
825     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
826 
827     if (!Subtarget.useCRBits())
828       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
829     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
830 
831     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
832     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
833     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
835     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
836     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
837     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
838 
839     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
840     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
841 
842     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
843     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
844     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
845 
846     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
847     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
848     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
849     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
850     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
851     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
852     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
853     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
854     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
855     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
856 
857     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
858     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
859 
860     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
861     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
862 
863     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
864 
865     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
866     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
867     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
868     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
869 
870     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
871     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
872 
873     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
874     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
875 
876     if (!Subtarget.useCRBits())
877       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
878     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
879 
880     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
881     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
882     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
883     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
884     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
885     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
886     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
887 
888     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
889     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
890 
891     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
892     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
893     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
894     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
895     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
896     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
897     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
898     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
899     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
900     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
901 
902     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
903     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
904 
905     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
906     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
907 
908     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
909 
910     setOperationAction(ISD::AND , MVT::v4i1, Legal);
911     setOperationAction(ISD::OR , MVT::v4i1, Legal);
912     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
913 
914     if (!Subtarget.useCRBits())
915       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
916     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
917 
918     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
919     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
920 
921     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
922     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
923     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
924     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
925     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
926     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
927     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
928 
929     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
930     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
931 
932     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
933 
934     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
935     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
936     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
937     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
938 
939     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
940     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
941     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
942     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
943 
944     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
945     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
946 
947     // These need to set FE_INEXACT, and so cannot be vectorized here.
948     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
949     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
950 
951     if (TM.Options.UnsafeFPMath) {
952       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
953       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
954 
955       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
956       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
957     } else {
958       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
959       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
960 
961       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
962       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
963     }
964   }
965 
966   if (Subtarget.has64BitSupport())
967     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
968 
969   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
970 
971   if (!isPPC64) {
972     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
973     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
974   }
975 
976   setBooleanContents(ZeroOrOneBooleanContent);
977 
978   if (Subtarget.hasAltivec()) {
979     // Altivec instructions set fields to all zeros or all ones.
980     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
981   }
982 
983   if (!isPPC64) {
984     // These libcalls are not available in 32-bit.
985     setLibcallName(RTLIB::SHL_I128, nullptr);
986     setLibcallName(RTLIB::SRL_I128, nullptr);
987     setLibcallName(RTLIB::SRA_I128, nullptr);
988   }
989 
990   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
991 
992   // We have target-specific dag combine patterns for the following nodes:
993   setTargetDAGCombine(ISD::SHL);
994   setTargetDAGCombine(ISD::SRA);
995   setTargetDAGCombine(ISD::SRL);
996   setTargetDAGCombine(ISD::SINT_TO_FP);
997   setTargetDAGCombine(ISD::BUILD_VECTOR);
998   if (Subtarget.hasFPCVT())
999     setTargetDAGCombine(ISD::UINT_TO_FP);
1000   setTargetDAGCombine(ISD::LOAD);
1001   setTargetDAGCombine(ISD::STORE);
1002   setTargetDAGCombine(ISD::BR_CC);
1003   if (Subtarget.useCRBits())
1004     setTargetDAGCombine(ISD::BRCOND);
1005   setTargetDAGCombine(ISD::BSWAP);
1006   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1007   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
1008   setTargetDAGCombine(ISD::INTRINSIC_VOID);
1009 
1010   setTargetDAGCombine(ISD::SIGN_EXTEND);
1011   setTargetDAGCombine(ISD::ZERO_EXTEND);
1012   setTargetDAGCombine(ISD::ANY_EXTEND);
1013 
1014   if (Subtarget.useCRBits()) {
1015     setTargetDAGCombine(ISD::TRUNCATE);
1016     setTargetDAGCombine(ISD::SETCC);
1017     setTargetDAGCombine(ISD::SELECT_CC);
1018   }
1019 
1020   // Use reciprocal estimates.
1021   if (TM.Options.UnsafeFPMath) {
1022     setTargetDAGCombine(ISD::FDIV);
1023     setTargetDAGCombine(ISD::FSQRT);
1024   }
1025 
1026   // Darwin long double math library functions have $LDBL128 appended.
1027   if (Subtarget.isDarwin()) {
1028     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
1029     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
1030     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
1031     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
1032     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
1033     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
1034     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
1035     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
1036     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
1037     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
1038   }
1039 
1040   // With 32 condition bits, we don't need to sink (and duplicate) compares
1041   // aggressively in CodeGenPrep.
1042   if (Subtarget.useCRBits()) {
1043     setHasMultipleConditionRegisters();
1044     setJumpIsExpensive();
1045   }
1046 
1047   setMinFunctionAlignment(2);
1048   if (Subtarget.isDarwin())
1049     setPrefFunctionAlignment(4);
1050 
1051   switch (Subtarget.getDarwinDirective()) {
1052   default: break;
1053   case PPC::DIR_970:
1054   case PPC::DIR_A2:
1055   case PPC::DIR_E500mc:
1056   case PPC::DIR_E5500:
1057   case PPC::DIR_PWR4:
1058   case PPC::DIR_PWR5:
1059   case PPC::DIR_PWR5X:
1060   case PPC::DIR_PWR6:
1061   case PPC::DIR_PWR6X:
1062   case PPC::DIR_PWR7:
1063   case PPC::DIR_PWR8:
1064   case PPC::DIR_PWR9:
1065     setPrefFunctionAlignment(4);
1066     setPrefLoopAlignment(4);
1067     break;
1068   }
1069 
1070   if (Subtarget.enableMachineScheduler())
1071     setSchedulingPreference(Sched::Source);
1072   else
1073     setSchedulingPreference(Sched::Hybrid);
1074 
1075   computeRegisterProperties(STI.getRegisterInfo());
1076 
1077   // The Freescale cores do better with aggressive inlining of memcpy and
1078   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1079   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1080       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1081     MaxStoresPerMemset = 32;
1082     MaxStoresPerMemsetOptSize = 16;
1083     MaxStoresPerMemcpy = 32;
1084     MaxStoresPerMemcpyOptSize = 8;
1085     MaxStoresPerMemmove = 32;
1086     MaxStoresPerMemmoveOptSize = 8;
1087   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1088     // The A2 also benefits from (very) aggressive inlining of memcpy and
1089     // friends. The overhead of a the function call, even when warm, can be
1090     // over one hundred cycles.
1091     MaxStoresPerMemset = 128;
1092     MaxStoresPerMemcpy = 128;
1093     MaxStoresPerMemmove = 128;
1094     MaxLoadsPerMemcmp = 128;
1095   } else {
1096     MaxLoadsPerMemcmp = 8;
1097     MaxLoadsPerMemcmpOptSize = 4;
1098   }
1099 }
1100 
1101 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1102 /// the desired ByVal argument alignment.
1103 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1104                              unsigned MaxMaxAlign) {
1105   if (MaxAlign == MaxMaxAlign)
1106     return;
1107   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1108     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1109       MaxAlign = 32;
1110     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1111       MaxAlign = 16;
1112   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1113     unsigned EltAlign = 0;
1114     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1115     if (EltAlign > MaxAlign)
1116       MaxAlign = EltAlign;
1117   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1118     for (auto *EltTy : STy->elements()) {
1119       unsigned EltAlign = 0;
1120       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1121       if (EltAlign > MaxAlign)
1122         MaxAlign = EltAlign;
1123       if (MaxAlign == MaxMaxAlign)
1124         break;
1125     }
1126   }
1127 }
1128 
1129 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1130 /// function arguments in the caller parameter area.
1131 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1132                                                   const DataLayout &DL) const {
1133   // Darwin passes everything on 4 byte boundary.
1134   if (Subtarget.isDarwin())
1135     return 4;
1136 
1137   // 16byte and wider vectors are passed on 16byte boundary.
1138   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1139   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1140   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1141     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1142   return Align;
1143 }
1144 
1145 bool PPCTargetLowering::useSoftFloat() const {
1146   return Subtarget.useSoftFloat();
1147 }
1148 
1149 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1150   switch ((PPCISD::NodeType)Opcode) {
1151   case PPCISD::FIRST_NUMBER:    break;
1152   case PPCISD::FSEL:            return "PPCISD::FSEL";
1153   case PPCISD::FCFID:           return "PPCISD::FCFID";
1154   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1155   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1156   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1157   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1158   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1159   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1160   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1161   case PPCISD::FP_TO_UINT_IN_VSR:
1162                                 return "PPCISD::FP_TO_UINT_IN_VSR,";
1163   case PPCISD::FP_TO_SINT_IN_VSR:
1164                                 return "PPCISD::FP_TO_SINT_IN_VSR";
1165   case PPCISD::FRE:             return "PPCISD::FRE";
1166   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1167   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1168   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1169   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1170   case PPCISD::VPERM:           return "PPCISD::VPERM";
1171   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1172   case PPCISD::VECINSERT:       return "PPCISD::VECINSERT";
1173   case PPCISD::XXREVERSE:       return "PPCISD::XXREVERSE";
1174   case PPCISD::XXPERMDI:        return "PPCISD::XXPERMDI";
1175   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1176   case PPCISD::CMPB:            return "PPCISD::CMPB";
1177   case PPCISD::Hi:              return "PPCISD::Hi";
1178   case PPCISD::Lo:              return "PPCISD::Lo";
1179   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1180   case PPCISD::ATOMIC_CMP_SWAP_8: return "PPCISD::ATOMIC_CMP_SWAP_8";
1181   case PPCISD::ATOMIC_CMP_SWAP_16: return "PPCISD::ATOMIC_CMP_SWAP_16";
1182   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1183   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1184   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1185   case PPCISD::SRL:             return "PPCISD::SRL";
1186   case PPCISD::SRA:             return "PPCISD::SRA";
1187   case PPCISD::SHL:             return "PPCISD::SHL";
1188   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1189   case PPCISD::CALL:            return "PPCISD::CALL";
1190   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1191   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1192   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1193   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1194   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1195   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1196   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1197   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1198   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1199   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1200   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1201   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1202   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1203   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1204   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1205   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1206   case PPCISD::VCMP:            return "PPCISD::VCMP";
1207   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1208   case PPCISD::LBRX:            return "PPCISD::LBRX";
1209   case PPCISD::STBRX:           return "PPCISD::STBRX";
1210   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1211   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1212   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1213   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1214   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1215   case PPCISD::SExtVElems:      return "PPCISD::SExtVElems";
1216   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1217   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1218   case PPCISD::ST_VSR_SCAL_INT:
1219                                 return "PPCISD::ST_VSR_SCAL_INT";
1220   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1221   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1222   case PPCISD::BDZ:             return "PPCISD::BDZ";
1223   case PPCISD::MFFS:            return "PPCISD::MFFS";
1224   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1225   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1226   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1227   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1228   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1229   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1230   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1231   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1232   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1233   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1234   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1235   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1236   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1237   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1238   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1239   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1240   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1241   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1242   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1243   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1244   case PPCISD::SC:              return "PPCISD::SC";
1245   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1246   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1247   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1248   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1249   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1250   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1251   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1252   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1253   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1254   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1255   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1256   }
1257   return nullptr;
1258 }
1259 
1260 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1261                                           EVT VT) const {
1262   if (!VT.isVector())
1263     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1264 
1265   if (Subtarget.hasQPX())
1266     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1267 
1268   return VT.changeVectorElementTypeToInteger();
1269 }
1270 
1271 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1272   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1273   return true;
1274 }
1275 
1276 //===----------------------------------------------------------------------===//
1277 // Node matching predicates, for use by the tblgen matching code.
1278 //===----------------------------------------------------------------------===//
1279 
1280 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1281 static bool isFloatingPointZero(SDValue Op) {
1282   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1283     return CFP->getValueAPF().isZero();
1284   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1285     // Maybe this has already been legalized into the constant pool?
1286     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1287       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1288         return CFP->getValueAPF().isZero();
1289   }
1290   return false;
1291 }
1292 
1293 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1294 /// true if Op is undef or if it matches the specified value.
1295 static bool isConstantOrUndef(int Op, int Val) {
1296   return Op < 0 || Op == Val;
1297 }
1298 
1299 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1300 /// VPKUHUM instruction.
1301 /// The ShuffleKind distinguishes between big-endian operations with
1302 /// two different inputs (0), either-endian operations with two identical
1303 /// inputs (1), and little-endian operations with two different inputs (2).
1304 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1305 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1306                                SelectionDAG &DAG) {
1307   bool IsLE = DAG.getDataLayout().isLittleEndian();
1308   if (ShuffleKind == 0) {
1309     if (IsLE)
1310       return false;
1311     for (unsigned i = 0; i != 16; ++i)
1312       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1313         return false;
1314   } else if (ShuffleKind == 2) {
1315     if (!IsLE)
1316       return false;
1317     for (unsigned i = 0; i != 16; ++i)
1318       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1319         return false;
1320   } else if (ShuffleKind == 1) {
1321     unsigned j = IsLE ? 0 : 1;
1322     for (unsigned i = 0; i != 8; ++i)
1323       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1324           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1325         return false;
1326   }
1327   return true;
1328 }
1329 
1330 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1331 /// VPKUWUM instruction.
1332 /// The ShuffleKind distinguishes between big-endian operations with
1333 /// two different inputs (0), either-endian operations with two identical
1334 /// inputs (1), and little-endian operations with two different inputs (2).
1335 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1336 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1337                                SelectionDAG &DAG) {
1338   bool IsLE = DAG.getDataLayout().isLittleEndian();
1339   if (ShuffleKind == 0) {
1340     if (IsLE)
1341       return false;
1342     for (unsigned i = 0; i != 16; i += 2)
1343       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1344           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1345         return false;
1346   } else if (ShuffleKind == 2) {
1347     if (!IsLE)
1348       return false;
1349     for (unsigned i = 0; i != 16; i += 2)
1350       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1351           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1352         return false;
1353   } else if (ShuffleKind == 1) {
1354     unsigned j = IsLE ? 0 : 2;
1355     for (unsigned i = 0; i != 8; i += 2)
1356       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1357           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1358           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1359           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1360         return false;
1361   }
1362   return true;
1363 }
1364 
1365 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1366 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1367 /// current subtarget.
1368 ///
1369 /// The ShuffleKind distinguishes between big-endian operations with
1370 /// two different inputs (0), either-endian operations with two identical
1371 /// inputs (1), and little-endian operations with two different inputs (2).
1372 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1373 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1374                                SelectionDAG &DAG) {
1375   const PPCSubtarget& Subtarget =
1376     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1377   if (!Subtarget.hasP8Vector())
1378     return false;
1379 
1380   bool IsLE = DAG.getDataLayout().isLittleEndian();
1381   if (ShuffleKind == 0) {
1382     if (IsLE)
1383       return false;
1384     for (unsigned i = 0; i != 16; i += 4)
1385       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1386           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1387           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1388           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1389         return false;
1390   } else if (ShuffleKind == 2) {
1391     if (!IsLE)
1392       return false;
1393     for (unsigned i = 0; i != 16; i += 4)
1394       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1395           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1396           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1397           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1398         return false;
1399   } else if (ShuffleKind == 1) {
1400     unsigned j = IsLE ? 0 : 4;
1401     for (unsigned i = 0; i != 8; i += 4)
1402       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1403           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1404           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1405           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1406           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1407           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1408           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1409           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1410         return false;
1411   }
1412   return true;
1413 }
1414 
1415 /// isVMerge - Common function, used to match vmrg* shuffles.
1416 ///
1417 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1418                      unsigned LHSStart, unsigned RHSStart) {
1419   if (N->getValueType(0) != MVT::v16i8)
1420     return false;
1421   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1422          "Unsupported merge size!");
1423 
1424   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1425     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1426       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1427                              LHSStart+j+i*UnitSize) ||
1428           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1429                              RHSStart+j+i*UnitSize))
1430         return false;
1431     }
1432   return true;
1433 }
1434 
1435 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1436 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1437 /// The ShuffleKind distinguishes between big-endian merges with two
1438 /// different inputs (0), either-endian merges with two identical inputs (1),
1439 /// and little-endian merges with two different inputs (2).  For the latter,
1440 /// the input operands are swapped (see PPCInstrAltivec.td).
1441 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1442                              unsigned ShuffleKind, SelectionDAG &DAG) {
1443   if (DAG.getDataLayout().isLittleEndian()) {
1444     if (ShuffleKind == 1) // unary
1445       return isVMerge(N, UnitSize, 0, 0);
1446     else if (ShuffleKind == 2) // swapped
1447       return isVMerge(N, UnitSize, 0, 16);
1448     else
1449       return false;
1450   } else {
1451     if (ShuffleKind == 1) // unary
1452       return isVMerge(N, UnitSize, 8, 8);
1453     else if (ShuffleKind == 0) // normal
1454       return isVMerge(N, UnitSize, 8, 24);
1455     else
1456       return false;
1457   }
1458 }
1459 
1460 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1461 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1462 /// The ShuffleKind distinguishes between big-endian merges with two
1463 /// different inputs (0), either-endian merges with two identical inputs (1),
1464 /// and little-endian merges with two different inputs (2).  For the latter,
1465 /// the input operands are swapped (see PPCInstrAltivec.td).
1466 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1467                              unsigned ShuffleKind, SelectionDAG &DAG) {
1468   if (DAG.getDataLayout().isLittleEndian()) {
1469     if (ShuffleKind == 1) // unary
1470       return isVMerge(N, UnitSize, 8, 8);
1471     else if (ShuffleKind == 2) // swapped
1472       return isVMerge(N, UnitSize, 8, 24);
1473     else
1474       return false;
1475   } else {
1476     if (ShuffleKind == 1) // unary
1477       return isVMerge(N, UnitSize, 0, 0);
1478     else if (ShuffleKind == 0) // normal
1479       return isVMerge(N, UnitSize, 0, 16);
1480     else
1481       return false;
1482   }
1483 }
1484 
1485 /**
1486  * Common function used to match vmrgew and vmrgow shuffles
1487  *
1488  * The indexOffset determines whether to look for even or odd words in
1489  * the shuffle mask. This is based on the of the endianness of the target
1490  * machine.
1491  *   - Little Endian:
1492  *     - Use offset of 0 to check for odd elements
1493  *     - Use offset of 4 to check for even elements
1494  *   - Big Endian:
1495  *     - Use offset of 0 to check for even elements
1496  *     - Use offset of 4 to check for odd elements
1497  * A detailed description of the vector element ordering for little endian and
1498  * big endian can be found at
1499  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1500  * Targeting your applications - what little endian and big endian IBM XL C/C++
1501  * compiler differences mean to you
1502  *
1503  * The mask to the shuffle vector instruction specifies the indices of the
1504  * elements from the two input vectors to place in the result. The elements are
1505  * numbered in array-access order, starting with the first vector. These vectors
1506  * are always of type v16i8, thus each vector will contain 16 elements of size
1507  * 8. More info on the shuffle vector can be found in the
1508  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1509  * Language Reference.
1510  *
1511  * The RHSStartValue indicates whether the same input vectors are used (unary)
1512  * or two different input vectors are used, based on the following:
1513  *   - If the instruction uses the same vector for both inputs, the range of the
1514  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1515  *     be 0.
1516  *   - If the instruction has two different vectors then the range of the
1517  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1518  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1519  *     to 31 specify elements in the second vector).
1520  *
1521  * \param[in] N The shuffle vector SD Node to analyze
1522  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1523  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1524  * vector to the shuffle_vector instruction
1525  * \return true iff this shuffle vector represents an even or odd word merge
1526  */
1527 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1528                      unsigned RHSStartValue) {
1529   if (N->getValueType(0) != MVT::v16i8)
1530     return false;
1531 
1532   for (unsigned i = 0; i < 2; ++i)
1533     for (unsigned j = 0; j < 4; ++j)
1534       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1535                              i*RHSStartValue+j+IndexOffset) ||
1536           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1537                              i*RHSStartValue+j+IndexOffset+8))
1538         return false;
1539   return true;
1540 }
1541 
1542 /**
1543  * Determine if the specified shuffle mask is suitable for the vmrgew or
1544  * vmrgow instructions.
1545  *
1546  * \param[in] N The shuffle vector SD Node to analyze
1547  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1548  * \param[in] ShuffleKind Identify the type of merge:
1549  *   - 0 = big-endian merge with two different inputs;
1550  *   - 1 = either-endian merge with two identical inputs;
1551  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1552  *     little-endian merges).
1553  * \param[in] DAG The current SelectionDAG
1554  * \return true iff this shuffle mask
1555  */
1556 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1557                               unsigned ShuffleKind, SelectionDAG &DAG) {
1558   if (DAG.getDataLayout().isLittleEndian()) {
1559     unsigned indexOffset = CheckEven ? 4 : 0;
1560     if (ShuffleKind == 1) // Unary
1561       return isVMerge(N, indexOffset, 0);
1562     else if (ShuffleKind == 2) // swapped
1563       return isVMerge(N, indexOffset, 16);
1564     else
1565       return false;
1566   }
1567   else {
1568     unsigned indexOffset = CheckEven ? 0 : 4;
1569     if (ShuffleKind == 1) // Unary
1570       return isVMerge(N, indexOffset, 0);
1571     else if (ShuffleKind == 0) // Normal
1572       return isVMerge(N, indexOffset, 16);
1573     else
1574       return false;
1575   }
1576   return false;
1577 }
1578 
1579 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1580 /// amount, otherwise return -1.
1581 /// The ShuffleKind distinguishes between big-endian operations with two
1582 /// different inputs (0), either-endian operations with two identical inputs
1583 /// (1), and little-endian operations with two different inputs (2).  For the
1584 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1585 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1586                              SelectionDAG &DAG) {
1587   if (N->getValueType(0) != MVT::v16i8)
1588     return -1;
1589 
1590   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1591 
1592   // Find the first non-undef value in the shuffle mask.
1593   unsigned i;
1594   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1595     /*search*/;
1596 
1597   if (i == 16) return -1;  // all undef.
1598 
1599   // Otherwise, check to see if the rest of the elements are consecutively
1600   // numbered from this value.
1601   unsigned ShiftAmt = SVOp->getMaskElt(i);
1602   if (ShiftAmt < i) return -1;
1603 
1604   ShiftAmt -= i;
1605   bool isLE = DAG.getDataLayout().isLittleEndian();
1606 
1607   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1608     // Check the rest of the elements to see if they are consecutive.
1609     for (++i; i != 16; ++i)
1610       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1611         return -1;
1612   } else if (ShuffleKind == 1) {
1613     // Check the rest of the elements to see if they are consecutive.
1614     for (++i; i != 16; ++i)
1615       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1616         return -1;
1617   } else
1618     return -1;
1619 
1620   if (isLE)
1621     ShiftAmt = 16 - ShiftAmt;
1622 
1623   return ShiftAmt;
1624 }
1625 
1626 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1627 /// specifies a splat of a single element that is suitable for input to
1628 /// VSPLTB/VSPLTH/VSPLTW.
1629 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1630   assert(N->getValueType(0) == MVT::v16i8 &&
1631          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1632 
1633   // The consecutive indices need to specify an element, not part of two
1634   // different elements.  So abandon ship early if this isn't the case.
1635   if (N->getMaskElt(0) % EltSize != 0)
1636     return false;
1637 
1638   // This is a splat operation if each element of the permute is the same, and
1639   // if the value doesn't reference the second vector.
1640   unsigned ElementBase = N->getMaskElt(0);
1641 
1642   // FIXME: Handle UNDEF elements too!
1643   if (ElementBase >= 16)
1644     return false;
1645 
1646   // Check that the indices are consecutive, in the case of a multi-byte element
1647   // splatted with a v16i8 mask.
1648   for (unsigned i = 1; i != EltSize; ++i)
1649     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1650       return false;
1651 
1652   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1653     if (N->getMaskElt(i) < 0) continue;
1654     for (unsigned j = 0; j != EltSize; ++j)
1655       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1656         return false;
1657   }
1658   return true;
1659 }
1660 
1661 /// Check that the mask is shuffling N byte elements. Within each N byte
1662 /// element of the mask, the indices could be either in increasing or
1663 /// decreasing order as long as they are consecutive.
1664 /// \param[in] N the shuffle vector SD Node to analyze
1665 /// \param[in] Width the element width in bytes, could be 2/4/8/16 (HalfWord/
1666 /// Word/DoubleWord/QuadWord).
1667 /// \param[in] StepLen the delta indices number among the N byte element, if
1668 /// the mask is in increasing/decreasing order then it is 1/-1.
1669 /// \return true iff the mask is shuffling N byte elements.
1670 static bool isNByteElemShuffleMask(ShuffleVectorSDNode *N, unsigned Width,
1671                                    int StepLen) {
1672   assert((Width == 2 || Width == 4 || Width == 8 || Width == 16) &&
1673          "Unexpected element width.");
1674   assert((StepLen == 1 || StepLen == -1) && "Unexpected element width.");
1675 
1676   unsigned NumOfElem = 16 / Width;
1677   unsigned MaskVal[16]; //  Width is never greater than 16
1678   for (unsigned i = 0; i < NumOfElem; ++i) {
1679     MaskVal[0] = N->getMaskElt(i * Width);
1680     if ((StepLen == 1) && (MaskVal[0] % Width)) {
1681       return false;
1682     } else if ((StepLen == -1) && ((MaskVal[0] + 1) % Width)) {
1683       return false;
1684     }
1685 
1686     for (unsigned int j = 1; j < Width; ++j) {
1687       MaskVal[j] = N->getMaskElt(i * Width + j);
1688       if (MaskVal[j] != MaskVal[j-1] + StepLen) {
1689         return false;
1690       }
1691     }
1692   }
1693 
1694   return true;
1695 }
1696 
1697 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1698                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1699   if (!isNByteElemShuffleMask(N, 4, 1))
1700     return false;
1701 
1702   // Now we look at mask elements 0,4,8,12
1703   unsigned M0 = N->getMaskElt(0) / 4;
1704   unsigned M1 = N->getMaskElt(4) / 4;
1705   unsigned M2 = N->getMaskElt(8) / 4;
1706   unsigned M3 = N->getMaskElt(12) / 4;
1707   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1708   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1709 
1710   // Below, let H and L be arbitrary elements of the shuffle mask
1711   // where H is in the range [4,7] and L is in the range [0,3].
1712   // H, 1, 2, 3 or L, 5, 6, 7
1713   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1714       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1715     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1716     InsertAtByte = IsLE ? 12 : 0;
1717     Swap = M0 < 4;
1718     return true;
1719   }
1720   // 0, H, 2, 3 or 4, L, 6, 7
1721   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1722       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1723     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1724     InsertAtByte = IsLE ? 8 : 4;
1725     Swap = M1 < 4;
1726     return true;
1727   }
1728   // 0, 1, H, 3 or 4, 5, L, 7
1729   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1730       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1731     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1732     InsertAtByte = IsLE ? 4 : 8;
1733     Swap = M2 < 4;
1734     return true;
1735   }
1736   // 0, 1, 2, H or 4, 5, 6, L
1737   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1738       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1739     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1740     InsertAtByte = IsLE ? 0 : 12;
1741     Swap = M3 < 4;
1742     return true;
1743   }
1744 
1745   // If both vector operands for the shuffle are the same vector, the mask will
1746   // contain only elements from the first one and the second one will be undef.
1747   if (N->getOperand(1).isUndef()) {
1748     ShiftElts = 0;
1749     Swap = true;
1750     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1751     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1752       InsertAtByte = IsLE ? 12 : 0;
1753       return true;
1754     }
1755     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1756       InsertAtByte = IsLE ? 8 : 4;
1757       return true;
1758     }
1759     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1760       InsertAtByte = IsLE ? 4 : 8;
1761       return true;
1762     }
1763     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1764       InsertAtByte = IsLE ? 0 : 12;
1765       return true;
1766     }
1767   }
1768 
1769   return false;
1770 }
1771 
1772 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1773                                bool &Swap, bool IsLE) {
1774   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1775   // Ensure each byte index of the word is consecutive.
1776   if (!isNByteElemShuffleMask(N, 4, 1))
1777     return false;
1778 
1779   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1780   unsigned M0 = N->getMaskElt(0) / 4;
1781   unsigned M1 = N->getMaskElt(4) / 4;
1782   unsigned M2 = N->getMaskElt(8) / 4;
1783   unsigned M3 = N->getMaskElt(12) / 4;
1784 
1785   // If both vector operands for the shuffle are the same vector, the mask will
1786   // contain only elements from the first one and the second one will be undef.
1787   if (N->getOperand(1).isUndef()) {
1788     assert(M0 < 4 && "Indexing into an undef vector?");
1789     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1790       return false;
1791 
1792     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1793     Swap = false;
1794     return true;
1795   }
1796 
1797   // Ensure each word index of the ShuffleVector Mask is consecutive.
1798   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1799     return false;
1800 
1801   if (IsLE) {
1802     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1803       // Input vectors don't need to be swapped if the leading element
1804       // of the result is one of the 3 left elements of the second vector
1805       // (or if there is no shift to be done at all).
1806       Swap = false;
1807       ShiftElts = (8 - M0) % 8;
1808     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1809       // Input vectors need to be swapped if the leading element
1810       // of the result is one of the 3 left elements of the first vector
1811       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1812       Swap = true;
1813       ShiftElts = (4 - M0) % 4;
1814     }
1815 
1816     return true;
1817   } else {                                          // BE
1818     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1819       // Input vectors don't need to be swapped if the leading element
1820       // of the result is one of the 4 elements of the first vector.
1821       Swap = false;
1822       ShiftElts = M0;
1823     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1824       // Input vectors need to be swapped if the leading element
1825       // of the result is one of the 4 elements of the right vector.
1826       Swap = true;
1827       ShiftElts = M0 - 4;
1828     }
1829 
1830     return true;
1831   }
1832 }
1833 
1834 bool static isXXBRShuffleMaskHelper(ShuffleVectorSDNode *N, int Width) {
1835   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1836 
1837   if (!isNByteElemShuffleMask(N, Width, -1))
1838     return false;
1839 
1840   for (int i = 0; i < 16; i += Width)
1841     if (N->getMaskElt(i) != i + Width - 1)
1842       return false;
1843 
1844   return true;
1845 }
1846 
1847 bool PPC::isXXBRHShuffleMask(ShuffleVectorSDNode *N) {
1848   return isXXBRShuffleMaskHelper(N, 2);
1849 }
1850 
1851 bool PPC::isXXBRWShuffleMask(ShuffleVectorSDNode *N) {
1852   return isXXBRShuffleMaskHelper(N, 4);
1853 }
1854 
1855 bool PPC::isXXBRDShuffleMask(ShuffleVectorSDNode *N) {
1856   return isXXBRShuffleMaskHelper(N, 8);
1857 }
1858 
1859 bool PPC::isXXBRQShuffleMask(ShuffleVectorSDNode *N) {
1860   return isXXBRShuffleMaskHelper(N, 16);
1861 }
1862 
1863 /// Can node \p N be lowered to an XXPERMDI instruction? If so, set \p Swap
1864 /// if the inputs to the instruction should be swapped and set \p DM to the
1865 /// value for the immediate.
1866 /// Specifically, set \p Swap to true only if \p N can be lowered to XXPERMDI
1867 /// AND element 0 of the result comes from the first input (LE) or second input
1868 /// (BE). Set \p DM to the calculated result (0-3) only if \p N can be lowered.
1869 /// \return true iff the given mask of shuffle node \p N is a XXPERMDI shuffle
1870 /// mask.
1871 bool PPC::isXXPERMDIShuffleMask(ShuffleVectorSDNode *N, unsigned &DM,
1872                                bool &Swap, bool IsLE) {
1873   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1874 
1875   // Ensure each byte index of the double word is consecutive.
1876   if (!isNByteElemShuffleMask(N, 8, 1))
1877     return false;
1878 
1879   unsigned M0 = N->getMaskElt(0) / 8;
1880   unsigned M1 = N->getMaskElt(8) / 8;
1881   assert(((M0 | M1) < 4) && "A mask element out of bounds?");
1882 
1883   // If both vector operands for the shuffle are the same vector, the mask will
1884   // contain only elements from the first one and the second one will be undef.
1885   if (N->getOperand(1).isUndef()) {
1886     if ((M0 | M1) < 2) {
1887       DM = IsLE ? (((~M1) & 1) << 1) + ((~M0) & 1) : (M0 << 1) + (M1 & 1);
1888       Swap = false;
1889       return true;
1890     } else
1891       return false;
1892   }
1893 
1894   if (IsLE) {
1895     if (M0 > 1 && M1 < 2) {
1896       Swap = false;
1897     } else if (M0 < 2 && M1 > 1) {
1898       M0 = (M0 + 2) % 4;
1899       M1 = (M1 + 2) % 4;
1900       Swap = true;
1901     } else
1902       return false;
1903 
1904     // Note: if control flow comes here that means Swap is already set above
1905     DM = (((~M1) & 1) << 1) + ((~M0) & 1);
1906     return true;
1907   } else { // BE
1908     if (M0 < 2 && M1 > 1) {
1909       Swap = false;
1910     } else if (M0 > 1 && M1 < 2) {
1911       M0 = (M0 + 2) % 4;
1912       M1 = (M1 + 2) % 4;
1913       Swap = true;
1914     } else
1915       return false;
1916 
1917     // Note: if control flow comes here that means Swap is already set above
1918     DM = (M0 << 1) + (M1 & 1);
1919     return true;
1920   }
1921 }
1922 
1923 
1924 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1925 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1926 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1927                                 SelectionDAG &DAG) {
1928   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1929   assert(isSplatShuffleMask(SVOp, EltSize));
1930   if (DAG.getDataLayout().isLittleEndian())
1931     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1932   else
1933     return SVOp->getMaskElt(0) / EltSize;
1934 }
1935 
1936 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1937 /// by using a vspltis[bhw] instruction of the specified element size, return
1938 /// the constant being splatted.  The ByteSize field indicates the number of
1939 /// bytes of each element [124] -> [bhw].
1940 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1941   SDValue OpVal(nullptr, 0);
1942 
1943   // If ByteSize of the splat is bigger than the element size of the
1944   // build_vector, then we have a case where we are checking for a splat where
1945   // multiple elements of the buildvector are folded together into a single
1946   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1947   unsigned EltSize = 16/N->getNumOperands();
1948   if (EltSize < ByteSize) {
1949     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1950     SDValue UniquedVals[4];
1951     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1952 
1953     // See if all of the elements in the buildvector agree across.
1954     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1955       if (N->getOperand(i).isUndef()) continue;
1956       // If the element isn't a constant, bail fully out.
1957       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1958 
1959       if (!UniquedVals[i&(Multiple-1)].getNode())
1960         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1961       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1962         return SDValue();  // no match.
1963     }
1964 
1965     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1966     // either constant or undef values that are identical for each chunk.  See
1967     // if these chunks can form into a larger vspltis*.
1968 
1969     // Check to see if all of the leading entries are either 0 or -1.  If
1970     // neither, then this won't fit into the immediate field.
1971     bool LeadingZero = true;
1972     bool LeadingOnes = true;
1973     for (unsigned i = 0; i != Multiple-1; ++i) {
1974       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1975 
1976       LeadingZero &= isNullConstant(UniquedVals[i]);
1977       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1978     }
1979     // Finally, check the least significant entry.
1980     if (LeadingZero) {
1981       if (!UniquedVals[Multiple-1].getNode())
1982         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1983       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1984       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1985         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1986     }
1987     if (LeadingOnes) {
1988       if (!UniquedVals[Multiple-1].getNode())
1989         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1990       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1991       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1992         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1993     }
1994 
1995     return SDValue();
1996   }
1997 
1998   // Check to see if this buildvec has a single non-undef value in its elements.
1999   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2000     if (N->getOperand(i).isUndef()) continue;
2001     if (!OpVal.getNode())
2002       OpVal = N->getOperand(i);
2003     else if (OpVal != N->getOperand(i))
2004       return SDValue();
2005   }
2006 
2007   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
2008 
2009   unsigned ValSizeInBytes = EltSize;
2010   uint64_t Value = 0;
2011   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
2012     Value = CN->getZExtValue();
2013   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
2014     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
2015     Value = FloatToBits(CN->getValueAPF().convertToFloat());
2016   }
2017 
2018   // If the splat value is larger than the element value, then we can never do
2019   // this splat.  The only case that we could fit the replicated bits into our
2020   // immediate field for would be zero, and we prefer to use vxor for it.
2021   if (ValSizeInBytes < ByteSize) return SDValue();
2022 
2023   // If the element value is larger than the splat value, check if it consists
2024   // of a repeated bit pattern of size ByteSize.
2025   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
2026     return SDValue();
2027 
2028   // Properly sign extend the value.
2029   int MaskVal = SignExtend32(Value, ByteSize * 8);
2030 
2031   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
2032   if (MaskVal == 0) return SDValue();
2033 
2034   // Finally, if this value fits in a 5 bit sext field, return it
2035   if (SignExtend32<5>(MaskVal) == MaskVal)
2036     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
2037   return SDValue();
2038 }
2039 
2040 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
2041 /// amount, otherwise return -1.
2042 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
2043   EVT VT = N->getValueType(0);
2044   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
2045     return -1;
2046 
2047   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2048 
2049   // Find the first non-undef value in the shuffle mask.
2050   unsigned i;
2051   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
2052     /*search*/;
2053 
2054   if (i == 4) return -1;  // all undef.
2055 
2056   // Otherwise, check to see if the rest of the elements are consecutively
2057   // numbered from this value.
2058   unsigned ShiftAmt = SVOp->getMaskElt(i);
2059   if (ShiftAmt < i) return -1;
2060   ShiftAmt -= i;
2061 
2062   // Check the rest of the elements to see if they are consecutive.
2063   for (++i; i != 4; ++i)
2064     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
2065       return -1;
2066 
2067   return ShiftAmt;
2068 }
2069 
2070 //===----------------------------------------------------------------------===//
2071 //  Addressing Mode Selection
2072 //===----------------------------------------------------------------------===//
2073 
2074 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
2075 /// or 64-bit immediate, and if the value can be accurately represented as a
2076 /// sign extension from a 16-bit value.  If so, this returns true and the
2077 /// immediate.
2078 bool llvm::isIntS16Immediate(SDNode *N, int16_t &Imm) {
2079   if (!isa<ConstantSDNode>(N))
2080     return false;
2081 
2082   Imm = (int16_t)cast<ConstantSDNode>(N)->getZExtValue();
2083   if (N->getValueType(0) == MVT::i32)
2084     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
2085   else
2086     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
2087 }
2088 bool llvm::isIntS16Immediate(SDValue Op, int16_t &Imm) {
2089   return isIntS16Immediate(Op.getNode(), Imm);
2090 }
2091 
2092 /// SelectAddressRegReg - Given the specified addressed, check to see if it
2093 /// can be represented as an indexed [r+r] operation.  Returns false if it
2094 /// can be more efficiently represented with [r+imm].
2095 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
2096                                             SDValue &Index,
2097                                             SelectionDAG &DAG) const {
2098   int16_t imm = 0;
2099   if (N.getOpcode() == ISD::ADD) {
2100     if (isIntS16Immediate(N.getOperand(1), imm))
2101       return false;    // r+i
2102     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
2103       return false;    // r+i
2104 
2105     Base = N.getOperand(0);
2106     Index = N.getOperand(1);
2107     return true;
2108   } else if (N.getOpcode() == ISD::OR) {
2109     if (isIntS16Immediate(N.getOperand(1), imm))
2110       return false;    // r+i can fold it if we can.
2111 
2112     // If this is an or of disjoint bitfields, we can codegen this as an add
2113     // (for better address arithmetic) if the LHS and RHS of the OR are provably
2114     // disjoint.
2115     KnownBits LHSKnown, RHSKnown;
2116     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2117 
2118     if (LHSKnown.Zero.getBoolValue()) {
2119       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
2120       // If all of the bits are known zero on the LHS or RHS, the add won't
2121       // carry.
2122       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
2123         Base = N.getOperand(0);
2124         Index = N.getOperand(1);
2125         return true;
2126       }
2127     }
2128   }
2129 
2130   return false;
2131 }
2132 
2133 // If we happen to be doing an i64 load or store into a stack slot that has
2134 // less than a 4-byte alignment, then the frame-index elimination may need to
2135 // use an indexed load or store instruction (because the offset may not be a
2136 // multiple of 4). The extra register needed to hold the offset comes from the
2137 // register scavenger, and it is possible that the scavenger will need to use
2138 // an emergency spill slot. As a result, we need to make sure that a spill slot
2139 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
2140 // stack slot.
2141 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
2142   // FIXME: This does not handle the LWA case.
2143   if (VT != MVT::i64)
2144     return;
2145 
2146   // NOTE: We'll exclude negative FIs here, which come from argument
2147   // lowering, because there are no known test cases triggering this problem
2148   // using packed structures (or similar). We can remove this exclusion if
2149   // we find such a test case. The reason why this is so test-case driven is
2150   // because this entire 'fixup' is only to prevent crashes (from the
2151   // register scavenger) on not-really-valid inputs. For example, if we have:
2152   //   %a = alloca i1
2153   //   %b = bitcast i1* %a to i64*
2154   //   store i64* a, i64 b
2155   // then the store should really be marked as 'align 1', but is not. If it
2156   // were marked as 'align 1' then the indexed form would have been
2157   // instruction-selected initially, and the problem this 'fixup' is preventing
2158   // won't happen regardless.
2159   if (FrameIdx < 0)
2160     return;
2161 
2162   MachineFunction &MF = DAG.getMachineFunction();
2163   MachineFrameInfo &MFI = MF.getFrameInfo();
2164 
2165   unsigned Align = MFI.getObjectAlignment(FrameIdx);
2166   if (Align >= 4)
2167     return;
2168 
2169   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2170   FuncInfo->setHasNonRISpills();
2171 }
2172 
2173 /// Returns true if the address N can be represented by a base register plus
2174 /// a signed 16-bit displacement [r+imm], and if it is not better
2175 /// represented as reg+reg.  If \p Alignment is non-zero, only accept
2176 /// displacements that are multiples of that value.
2177 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2178                                             SDValue &Base,
2179                                             SelectionDAG &DAG,
2180                                             unsigned Alignment) const {
2181   // FIXME dl should come from parent load or store, not from address
2182   SDLoc dl(N);
2183   // If this can be more profitably realized as r+r, fail.
2184   if (SelectAddressRegReg(N, Disp, Base, DAG))
2185     return false;
2186 
2187   if (N.getOpcode() == ISD::ADD) {
2188     int16_t imm = 0;
2189     if (isIntS16Immediate(N.getOperand(1), imm) &&
2190         (!Alignment || (imm % Alignment) == 0)) {
2191       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2192       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2193         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2194         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2195       } else {
2196         Base = N.getOperand(0);
2197       }
2198       return true; // [r+i]
2199     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2200       // Match LOAD (ADD (X, Lo(G))).
2201       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2202              && "Cannot handle constant offsets yet!");
2203       Disp = N.getOperand(1).getOperand(0);  // The global address.
2204       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2205              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2206              Disp.getOpcode() == ISD::TargetConstantPool ||
2207              Disp.getOpcode() == ISD::TargetJumpTable);
2208       Base = N.getOperand(0);
2209       return true;  // [&g+r]
2210     }
2211   } else if (N.getOpcode() == ISD::OR) {
2212     int16_t imm = 0;
2213     if (isIntS16Immediate(N.getOperand(1), imm) &&
2214         (!Alignment || (imm % Alignment) == 0)) {
2215       // If this is an or of disjoint bitfields, we can codegen this as an add
2216       // (for better address arithmetic) if the LHS and RHS of the OR are
2217       // provably disjoint.
2218       KnownBits LHSKnown;
2219       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2220 
2221       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2222         // If all of the bits are known zero on the LHS or RHS, the add won't
2223         // carry.
2224         if (FrameIndexSDNode *FI =
2225               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2226           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2227           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2228         } else {
2229           Base = N.getOperand(0);
2230         }
2231         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2232         return true;
2233       }
2234     }
2235   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2236     // Loading from a constant address.
2237 
2238     // If this address fits entirely in a 16-bit sext immediate field, codegen
2239     // this as "d, 0"
2240     int16_t Imm;
2241     if (isIntS16Immediate(CN, Imm) && (!Alignment || (Imm % Alignment) == 0)) {
2242       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2243       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2244                              CN->getValueType(0));
2245       return true;
2246     }
2247 
2248     // Handle 32-bit sext immediates with LIS + addr mode.
2249     if ((CN->getValueType(0) == MVT::i32 ||
2250          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2251         (!Alignment || (CN->getZExtValue() % Alignment) == 0)) {
2252       int Addr = (int)CN->getZExtValue();
2253 
2254       // Otherwise, break this down into an LIS + disp.
2255       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2256 
2257       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2258                                    MVT::i32);
2259       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2260       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2261       return true;
2262     }
2263   }
2264 
2265   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2266   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2267     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2268     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2269   } else
2270     Base = N;
2271   return true;      // [r+0]
2272 }
2273 
2274 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2275 /// represented as an indexed [r+r] operation.
2276 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2277                                                 SDValue &Index,
2278                                                 SelectionDAG &DAG) const {
2279   // Check to see if we can easily represent this as an [r+r] address.  This
2280   // will fail if it thinks that the address is more profitably represented as
2281   // reg+imm, e.g. where imm = 0.
2282   if (SelectAddressRegReg(N, Base, Index, DAG))
2283     return true;
2284 
2285   // If the address is the result of an add, we will utilize the fact that the
2286   // address calculation includes an implicit add.  However, we can reduce
2287   // register pressure if we do not materialize a constant just for use as the
2288   // index register.  We only get rid of the add if it is not an add of a
2289   // value and a 16-bit signed constant and both have a single use.
2290   int16_t imm = 0;
2291   if (N.getOpcode() == ISD::ADD &&
2292       (!isIntS16Immediate(N.getOperand(1), imm) ||
2293        !N.getOperand(1).hasOneUse() || !N.getOperand(0).hasOneUse())) {
2294     Base = N.getOperand(0);
2295     Index = N.getOperand(1);
2296     return true;
2297   }
2298 
2299   // Otherwise, do it the hard way, using R0 as the base register.
2300   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2301                          N.getValueType());
2302   Index = N;
2303   return true;
2304 }
2305 
2306 /// getPreIndexedAddressParts - returns true by value, base pointer and
2307 /// offset pointer and addressing mode by reference if the node's address
2308 /// can be legally represented as pre-indexed load / store address.
2309 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2310                                                   SDValue &Offset,
2311                                                   ISD::MemIndexedMode &AM,
2312                                                   SelectionDAG &DAG) const {
2313   if (DisablePPCPreinc) return false;
2314 
2315   bool isLoad = true;
2316   SDValue Ptr;
2317   EVT VT;
2318   unsigned Alignment;
2319   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2320     Ptr = LD->getBasePtr();
2321     VT = LD->getMemoryVT();
2322     Alignment = LD->getAlignment();
2323   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2324     Ptr = ST->getBasePtr();
2325     VT  = ST->getMemoryVT();
2326     Alignment = ST->getAlignment();
2327     isLoad = false;
2328   } else
2329     return false;
2330 
2331   // PowerPC doesn't have preinc load/store instructions for vectors (except
2332   // for QPX, which does have preinc r+r forms).
2333   if (VT.isVector()) {
2334     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2335       return false;
2336     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2337       AM = ISD::PRE_INC;
2338       return true;
2339     }
2340   }
2341 
2342   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2343     // Common code will reject creating a pre-inc form if the base pointer
2344     // is a frame index, or if N is a store and the base pointer is either
2345     // the same as or a predecessor of the value being stored.  Check for
2346     // those situations here, and try with swapped Base/Offset instead.
2347     bool Swap = false;
2348 
2349     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2350       Swap = true;
2351     else if (!isLoad) {
2352       SDValue Val = cast<StoreSDNode>(N)->getValue();
2353       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2354         Swap = true;
2355     }
2356 
2357     if (Swap)
2358       std::swap(Base, Offset);
2359 
2360     AM = ISD::PRE_INC;
2361     return true;
2362   }
2363 
2364   // LDU/STU can only handle immediates that are a multiple of 4.
2365   if (VT != MVT::i64) {
2366     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 0))
2367       return false;
2368   } else {
2369     // LDU/STU need an address with at least 4-byte alignment.
2370     if (Alignment < 4)
2371       return false;
2372 
2373     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, 4))
2374       return false;
2375   }
2376 
2377   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2378     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2379     // sext i32 to i64 when addr mode is r+i.
2380     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2381         LD->getExtensionType() == ISD::SEXTLOAD &&
2382         isa<ConstantSDNode>(Offset))
2383       return false;
2384   }
2385 
2386   AM = ISD::PRE_INC;
2387   return true;
2388 }
2389 
2390 //===----------------------------------------------------------------------===//
2391 //  LowerOperation implementation
2392 //===----------------------------------------------------------------------===//
2393 
2394 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2395 /// and LoOpFlags to the target MO flags.
2396 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2397                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2398                                const GlobalValue *GV = nullptr) {
2399   HiOpFlags = PPCII::MO_HA;
2400   LoOpFlags = PPCII::MO_LO;
2401 
2402   // Don't use the pic base if not in PIC relocation model.
2403   if (IsPIC) {
2404     HiOpFlags |= PPCII::MO_PIC_FLAG;
2405     LoOpFlags |= PPCII::MO_PIC_FLAG;
2406   }
2407 
2408   // If this is a reference to a global value that requires a non-lazy-ptr, make
2409   // sure that instruction lowering adds it.
2410   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2411     HiOpFlags |= PPCII::MO_NLP_FLAG;
2412     LoOpFlags |= PPCII::MO_NLP_FLAG;
2413 
2414     if (GV->hasHiddenVisibility()) {
2415       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2416       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2417     }
2418   }
2419 }
2420 
2421 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2422                              SelectionDAG &DAG) {
2423   SDLoc DL(HiPart);
2424   EVT PtrVT = HiPart.getValueType();
2425   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2426 
2427   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2428   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2429 
2430   // With PIC, the first instruction is actually "GR+hi(&G)".
2431   if (isPIC)
2432     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2433                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2434 
2435   // Generate non-pic code that has direct accesses to the constant pool.
2436   // The address of the global is just (hi(&g)+lo(&g)).
2437   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2438 }
2439 
2440 static void setUsesTOCBasePtr(MachineFunction &MF) {
2441   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2442   FuncInfo->setUsesTOCBasePtr();
2443 }
2444 
2445 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2446   setUsesTOCBasePtr(DAG.getMachineFunction());
2447 }
2448 
2449 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2450                            SDValue GA) {
2451   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2452   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2453                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2454 
2455   SDValue Ops[] = { GA, Reg };
2456   return DAG.getMemIntrinsicNode(
2457       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2458       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0,
2459       MachineMemOperand::MOLoad);
2460 }
2461 
2462 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2463                                              SelectionDAG &DAG) const {
2464   EVT PtrVT = Op.getValueType();
2465   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2466   const Constant *C = CP->getConstVal();
2467 
2468   // 64-bit SVR4 ABI code is always position-independent.
2469   // The actual address of the GlobalValue is stored in the TOC.
2470   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2471     setUsesTOCBasePtr(DAG);
2472     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2473     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2474   }
2475 
2476   unsigned MOHiFlag, MOLoFlag;
2477   bool IsPIC = isPositionIndependent();
2478   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2479 
2480   if (IsPIC && Subtarget.isSVR4ABI()) {
2481     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2482                                            PPCII::MO_PIC_FLAG);
2483     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2484   }
2485 
2486   SDValue CPIHi =
2487     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2488   SDValue CPILo =
2489     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2490   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2491 }
2492 
2493 // For 64-bit PowerPC, prefer the more compact relative encodings.
2494 // This trades 32 bits per jump table entry for one or two instructions
2495 // on the jump site.
2496 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2497   if (isJumpTableRelative())
2498     return MachineJumpTableInfo::EK_LabelDifference32;
2499 
2500   return TargetLowering::getJumpTableEncoding();
2501 }
2502 
2503 bool PPCTargetLowering::isJumpTableRelative() const {
2504   if (Subtarget.isPPC64())
2505     return true;
2506   return TargetLowering::isJumpTableRelative();
2507 }
2508 
2509 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2510                                                     SelectionDAG &DAG) const {
2511   if (!Subtarget.isPPC64())
2512     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2513 
2514   switch (getTargetMachine().getCodeModel()) {
2515   case CodeModel::Small:
2516   case CodeModel::Medium:
2517     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2518   default:
2519     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2520                        getPointerTy(DAG.getDataLayout()));
2521   }
2522 }
2523 
2524 const MCExpr *
2525 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2526                                                 unsigned JTI,
2527                                                 MCContext &Ctx) const {
2528   if (!Subtarget.isPPC64())
2529     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2530 
2531   switch (getTargetMachine().getCodeModel()) {
2532   case CodeModel::Small:
2533   case CodeModel::Medium:
2534     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2535   default:
2536     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2537   }
2538 }
2539 
2540 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2541   EVT PtrVT = Op.getValueType();
2542   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2543 
2544   // 64-bit SVR4 ABI code is always position-independent.
2545   // The actual address of the GlobalValue is stored in the TOC.
2546   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2547     setUsesTOCBasePtr(DAG);
2548     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2549     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2550   }
2551 
2552   unsigned MOHiFlag, MOLoFlag;
2553   bool IsPIC = isPositionIndependent();
2554   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2555 
2556   if (IsPIC && Subtarget.isSVR4ABI()) {
2557     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2558                                         PPCII::MO_PIC_FLAG);
2559     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2560   }
2561 
2562   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2563   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2564   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2565 }
2566 
2567 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2568                                              SelectionDAG &DAG) const {
2569   EVT PtrVT = Op.getValueType();
2570   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2571   const BlockAddress *BA = BASDN->getBlockAddress();
2572 
2573   // 64-bit SVR4 ABI code is always position-independent.
2574   // The actual BlockAddress is stored in the TOC.
2575   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2576     setUsesTOCBasePtr(DAG);
2577     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2578     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2579   }
2580 
2581   unsigned MOHiFlag, MOLoFlag;
2582   bool IsPIC = isPositionIndependent();
2583   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2584   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2585   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2586   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2587 }
2588 
2589 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2590                                               SelectionDAG &DAG) const {
2591   // FIXME: TLS addresses currently use medium model code sequences,
2592   // which is the most useful form.  Eventually support for small and
2593   // large models could be added if users need it, at the cost of
2594   // additional complexity.
2595   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2596   if (DAG.getTarget().useEmulatedTLS())
2597     return LowerToTLSEmulatedModel(GA, DAG);
2598 
2599   SDLoc dl(GA);
2600   const GlobalValue *GV = GA->getGlobal();
2601   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2602   bool is64bit = Subtarget.isPPC64();
2603   const Module *M = DAG.getMachineFunction().getFunction().getParent();
2604   PICLevel::Level picLevel = M->getPICLevel();
2605 
2606   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2607 
2608   if (Model == TLSModel::LocalExec) {
2609     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2610                                                PPCII::MO_TPREL_HA);
2611     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2612                                                PPCII::MO_TPREL_LO);
2613     SDValue TLSReg = is64bit ? DAG.getRegister(PPC::X13, MVT::i64)
2614                              : DAG.getRegister(PPC::R2, MVT::i32);
2615 
2616     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2617     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2618   }
2619 
2620   if (Model == TLSModel::InitialExec) {
2621     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2622     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2623                                                 PPCII::MO_TLS);
2624     SDValue GOTPtr;
2625     if (is64bit) {
2626       setUsesTOCBasePtr(DAG);
2627       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2628       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2629                            PtrVT, GOTReg, TGA);
2630     } else
2631       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2632     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2633                                    PtrVT, TGA, GOTPtr);
2634     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2635   }
2636 
2637   if (Model == TLSModel::GeneralDynamic) {
2638     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2639     SDValue GOTPtr;
2640     if (is64bit) {
2641       setUsesTOCBasePtr(DAG);
2642       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2643       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2644                                    GOTReg, TGA);
2645     } else {
2646       if (picLevel == PICLevel::SmallPIC)
2647         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2648       else
2649         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2650     }
2651     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2652                        GOTPtr, TGA, TGA);
2653   }
2654 
2655   if (Model == TLSModel::LocalDynamic) {
2656     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2657     SDValue GOTPtr;
2658     if (is64bit) {
2659       setUsesTOCBasePtr(DAG);
2660       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2661       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2662                            GOTReg, TGA);
2663     } else {
2664       if (picLevel == PICLevel::SmallPIC)
2665         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2666       else
2667         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2668     }
2669     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2670                                   PtrVT, GOTPtr, TGA, TGA);
2671     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2672                                       PtrVT, TLSAddr, TGA);
2673     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2674   }
2675 
2676   llvm_unreachable("Unknown TLS model!");
2677 }
2678 
2679 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2680                                               SelectionDAG &DAG) const {
2681   EVT PtrVT = Op.getValueType();
2682   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2683   SDLoc DL(GSDN);
2684   const GlobalValue *GV = GSDN->getGlobal();
2685 
2686   // 64-bit SVR4 ABI code is always position-independent.
2687   // The actual address of the GlobalValue is stored in the TOC.
2688   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2689     setUsesTOCBasePtr(DAG);
2690     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2691     return getTOCEntry(DAG, DL, true, GA);
2692   }
2693 
2694   unsigned MOHiFlag, MOLoFlag;
2695   bool IsPIC = isPositionIndependent();
2696   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2697 
2698   if (IsPIC && Subtarget.isSVR4ABI()) {
2699     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2700                                             GSDN->getOffset(),
2701                                             PPCII::MO_PIC_FLAG);
2702     return getTOCEntry(DAG, DL, false, GA);
2703   }
2704 
2705   SDValue GAHi =
2706     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2707   SDValue GALo =
2708     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2709 
2710   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2711 
2712   // If the global reference is actually to a non-lazy-pointer, we have to do an
2713   // extra load to get the address of the global.
2714   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2715     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2716   return Ptr;
2717 }
2718 
2719 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2720   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2721   SDLoc dl(Op);
2722 
2723   if (Op.getValueType() == MVT::v2i64) {
2724     // When the operands themselves are v2i64 values, we need to do something
2725     // special because VSX has no underlying comparison operations for these.
2726     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2727       // Equality can be handled by casting to the legal type for Altivec
2728       // comparisons, everything else needs to be expanded.
2729       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2730         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2731                  DAG.getSetCC(dl, MVT::v4i32,
2732                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2733                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2734                    CC));
2735       }
2736 
2737       return SDValue();
2738     }
2739 
2740     // We handle most of these in the usual way.
2741     return Op;
2742   }
2743 
2744   // If we're comparing for equality to zero, expose the fact that this is
2745   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2746   // fold the new nodes.
2747   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2748     return V;
2749 
2750   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2751     // Leave comparisons against 0 and -1 alone for now, since they're usually
2752     // optimized.  FIXME: revisit this when we can custom lower all setcc
2753     // optimizations.
2754     if (C->isAllOnesValue() || C->isNullValue())
2755       return SDValue();
2756   }
2757 
2758   // If we have an integer seteq/setne, turn it into a compare against zero
2759   // by xor'ing the rhs with the lhs, which is faster than setting a
2760   // condition register, reading it back out, and masking the correct bit.  The
2761   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2762   // the result to other bit-twiddling opportunities.
2763   EVT LHSVT = Op.getOperand(0).getValueType();
2764   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2765     EVT VT = Op.getValueType();
2766     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2767                                 Op.getOperand(1));
2768     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2769   }
2770   return SDValue();
2771 }
2772 
2773 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2774   SDNode *Node = Op.getNode();
2775   EVT VT = Node->getValueType(0);
2776   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2777   SDValue InChain = Node->getOperand(0);
2778   SDValue VAListPtr = Node->getOperand(1);
2779   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2780   SDLoc dl(Node);
2781 
2782   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2783 
2784   // gpr_index
2785   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2786                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2787   InChain = GprIndex.getValue(1);
2788 
2789   if (VT == MVT::i64) {
2790     // Check if GprIndex is even
2791     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2792                                  DAG.getConstant(1, dl, MVT::i32));
2793     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2794                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2795     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2796                                           DAG.getConstant(1, dl, MVT::i32));
2797     // Align GprIndex to be even if it isn't
2798     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2799                            GprIndex);
2800   }
2801 
2802   // fpr index is 1 byte after gpr
2803   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2804                                DAG.getConstant(1, dl, MVT::i32));
2805 
2806   // fpr
2807   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2808                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2809   InChain = FprIndex.getValue(1);
2810 
2811   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2812                                        DAG.getConstant(8, dl, MVT::i32));
2813 
2814   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2815                                         DAG.getConstant(4, dl, MVT::i32));
2816 
2817   // areas
2818   SDValue OverflowArea =
2819       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2820   InChain = OverflowArea.getValue(1);
2821 
2822   SDValue RegSaveArea =
2823       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2824   InChain = RegSaveArea.getValue(1);
2825 
2826   // select overflow_area if index > 8
2827   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2828                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2829 
2830   // adjustment constant gpr_index * 4/8
2831   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2832                                     VT.isInteger() ? GprIndex : FprIndex,
2833                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2834                                                     MVT::i32));
2835 
2836   // OurReg = RegSaveArea + RegConstant
2837   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2838                                RegConstant);
2839 
2840   // Floating types are 32 bytes into RegSaveArea
2841   if (VT.isFloatingPoint())
2842     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2843                          DAG.getConstant(32, dl, MVT::i32));
2844 
2845   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2846   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2847                                    VT.isInteger() ? GprIndex : FprIndex,
2848                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2849                                                    MVT::i32));
2850 
2851   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2852                               VT.isInteger() ? VAListPtr : FprPtr,
2853                               MachinePointerInfo(SV), MVT::i8);
2854 
2855   // determine if we should load from reg_save_area or overflow_area
2856   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2857 
2858   // increase overflow_area by 4/8 if gpr/fpr > 8
2859   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2860                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2861                                           dl, MVT::i32));
2862 
2863   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2864                              OverflowAreaPlusN);
2865 
2866   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2867                               MachinePointerInfo(), MVT::i32);
2868 
2869   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2870 }
2871 
2872 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2873   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2874 
2875   // We have to copy the entire va_list struct:
2876   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2877   return DAG.getMemcpy(Op.getOperand(0), Op,
2878                        Op.getOperand(1), Op.getOperand(2),
2879                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2880                        false, MachinePointerInfo(), MachinePointerInfo());
2881 }
2882 
2883 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2884                                                   SelectionDAG &DAG) const {
2885   return Op.getOperand(0);
2886 }
2887 
2888 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2889                                                 SelectionDAG &DAG) const {
2890   SDValue Chain = Op.getOperand(0);
2891   SDValue Trmp = Op.getOperand(1); // trampoline
2892   SDValue FPtr = Op.getOperand(2); // nested function
2893   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2894   SDLoc dl(Op);
2895 
2896   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2897   bool isPPC64 = (PtrVT == MVT::i64);
2898   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2899 
2900   TargetLowering::ArgListTy Args;
2901   TargetLowering::ArgListEntry Entry;
2902 
2903   Entry.Ty = IntPtrTy;
2904   Entry.Node = Trmp; Args.push_back(Entry);
2905 
2906   // TrampSize == (isPPC64 ? 48 : 40);
2907   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2908                                isPPC64 ? MVT::i64 : MVT::i32);
2909   Args.push_back(Entry);
2910 
2911   Entry.Node = FPtr; Args.push_back(Entry);
2912   Entry.Node = Nest; Args.push_back(Entry);
2913 
2914   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2915   TargetLowering::CallLoweringInfo CLI(DAG);
2916   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2917       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2918       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2919 
2920   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2921   return CallResult.second;
2922 }
2923 
2924 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2925   MachineFunction &MF = DAG.getMachineFunction();
2926   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2927   EVT PtrVT = getPointerTy(MF.getDataLayout());
2928 
2929   SDLoc dl(Op);
2930 
2931   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2932     // vastart just stores the address of the VarArgsFrameIndex slot into the
2933     // memory location argument.
2934     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2935     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2936     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2937                         MachinePointerInfo(SV));
2938   }
2939 
2940   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2941   // We suppose the given va_list is already allocated.
2942   //
2943   // typedef struct {
2944   //  char gpr;     /* index into the array of 8 GPRs
2945   //                 * stored in the register save area
2946   //                 * gpr=0 corresponds to r3,
2947   //                 * gpr=1 to r4, etc.
2948   //                 */
2949   //  char fpr;     /* index into the array of 8 FPRs
2950   //                 * stored in the register save area
2951   //                 * fpr=0 corresponds to f1,
2952   //                 * fpr=1 to f2, etc.
2953   //                 */
2954   //  char *overflow_arg_area;
2955   //                /* location on stack that holds
2956   //                 * the next overflow argument
2957   //                 */
2958   //  char *reg_save_area;
2959   //               /* where r3:r10 and f1:f8 (if saved)
2960   //                * are stored
2961   //                */
2962   // } va_list[1];
2963 
2964   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2965   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2966   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2967                                             PtrVT);
2968   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2969                                  PtrVT);
2970 
2971   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2972   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2973 
2974   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2975   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2976 
2977   uint64_t FPROffset = 1;
2978   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2979 
2980   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2981 
2982   // Store first byte : number of int regs
2983   SDValue firstStore =
2984       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2985                         MachinePointerInfo(SV), MVT::i8);
2986   uint64_t nextOffset = FPROffset;
2987   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2988                                   ConstFPROffset);
2989 
2990   // Store second byte : number of float regs
2991   SDValue secondStore =
2992       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2993                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2994   nextOffset += StackOffset;
2995   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2996 
2997   // Store second word : arguments given on stack
2998   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2999                                     MachinePointerInfo(SV, nextOffset));
3000   nextOffset += FrameOffset;
3001   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
3002 
3003   // Store third word : arguments given in registers
3004   return DAG.getStore(thirdStore, dl, FR, nextPtr,
3005                       MachinePointerInfo(SV, nextOffset));
3006 }
3007 
3008 #include "PPCGenCallingConv.inc"
3009 
3010 // Function whose sole purpose is to kill compiler warnings
3011 // stemming from unused functions included from PPCGenCallingConv.inc.
3012 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
3013   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
3014 }
3015 
3016 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
3017                                       CCValAssign::LocInfo &LocInfo,
3018                                       ISD::ArgFlagsTy &ArgFlags,
3019                                       CCState &State) {
3020   return true;
3021 }
3022 
3023 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
3024                                              MVT &LocVT,
3025                                              CCValAssign::LocInfo &LocInfo,
3026                                              ISD::ArgFlagsTy &ArgFlags,
3027                                              CCState &State) {
3028   static const MCPhysReg ArgRegs[] = {
3029     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3030     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3031   };
3032   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3033 
3034   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3035 
3036   // Skip one register if the first unallocated register has an even register
3037   // number and there are still argument registers available which have not been
3038   // allocated yet. RegNum is actually an index into ArgRegs, which means we
3039   // need to skip a register if RegNum is odd.
3040   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
3041     State.AllocateReg(ArgRegs[RegNum]);
3042   }
3043 
3044   // Always return false here, as this function only makes sure that the first
3045   // unallocated register has an odd register number and does not actually
3046   // allocate a register for the current argument.
3047   return false;
3048 }
3049 
3050 bool
3051 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
3052                                                   MVT &LocVT,
3053                                                   CCValAssign::LocInfo &LocInfo,
3054                                                   ISD::ArgFlagsTy &ArgFlags,
3055                                                   CCState &State) {
3056   static const MCPhysReg ArgRegs[] = {
3057     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3058     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3059   };
3060   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3061 
3062   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3063   int RegsLeft = NumArgRegs - RegNum;
3064 
3065   // Skip if there is not enough registers left for long double type (4 gpr regs
3066   // in soft float mode) and put long double argument on the stack.
3067   if (RegNum != NumArgRegs && RegsLeft < 4) {
3068     for (int i = 0; i < RegsLeft; i++) {
3069       State.AllocateReg(ArgRegs[RegNum + i]);
3070     }
3071   }
3072 
3073   return false;
3074 }
3075 
3076 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
3077                                                MVT &LocVT,
3078                                                CCValAssign::LocInfo &LocInfo,
3079                                                ISD::ArgFlagsTy &ArgFlags,
3080                                                CCState &State) {
3081   static const MCPhysReg ArgRegs[] = {
3082     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3083     PPC::F8
3084   };
3085 
3086   const unsigned NumArgRegs = array_lengthof(ArgRegs);
3087 
3088   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
3089 
3090   // If there is only one Floating-point register left we need to put both f64
3091   // values of a split ppc_fp128 value on the stack.
3092   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
3093     State.AllocateReg(ArgRegs[RegNum]);
3094   }
3095 
3096   // Always return false here, as this function only makes sure that the two f64
3097   // values a ppc_fp128 value is split into are both passed in registers or both
3098   // passed on the stack and does not actually allocate a register for the
3099   // current argument.
3100   return false;
3101 }
3102 
3103 /// FPR - The set of FP registers that should be allocated for arguments,
3104 /// on Darwin.
3105 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
3106                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
3107                                 PPC::F11, PPC::F12, PPC::F13};
3108 
3109 /// QFPR - The set of QPX registers that should be allocated for arguments.
3110 static const MCPhysReg QFPR[] = {
3111     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
3112     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
3113 
3114 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
3115 /// the stack.
3116 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
3117                                        unsigned PtrByteSize) {
3118   unsigned ArgSize = ArgVT.getStoreSize();
3119   if (Flags.isByVal())
3120     ArgSize = Flags.getByValSize();
3121 
3122   // Round up to multiples of the pointer size, except for array members,
3123   // which are always packed.
3124   if (!Flags.isInConsecutiveRegs())
3125     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3126 
3127   return ArgSize;
3128 }
3129 
3130 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
3131 /// on the stack.
3132 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
3133                                             ISD::ArgFlagsTy Flags,
3134                                             unsigned PtrByteSize) {
3135   unsigned Align = PtrByteSize;
3136 
3137   // Altivec parameters are padded to a 16 byte boundary.
3138   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3139       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3140       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3141       ArgVT == MVT::v1i128)
3142     Align = 16;
3143   // QPX vector types stored in double-precision are padded to a 32 byte
3144   // boundary.
3145   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
3146     Align = 32;
3147 
3148   // ByVal parameters are aligned as requested.
3149   if (Flags.isByVal()) {
3150     unsigned BVAlign = Flags.getByValAlign();
3151     if (BVAlign > PtrByteSize) {
3152       if (BVAlign % PtrByteSize != 0)
3153           llvm_unreachable(
3154             "ByVal alignment is not a multiple of the pointer size");
3155 
3156       Align = BVAlign;
3157     }
3158   }
3159 
3160   // Array members are always packed to their original alignment.
3161   if (Flags.isInConsecutiveRegs()) {
3162     // If the array member was split into multiple registers, the first
3163     // needs to be aligned to the size of the full type.  (Except for
3164     // ppcf128, which is only aligned as its f64 components.)
3165     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
3166       Align = OrigVT.getStoreSize();
3167     else
3168       Align = ArgVT.getStoreSize();
3169   }
3170 
3171   return Align;
3172 }
3173 
3174 /// CalculateStackSlotUsed - Return whether this argument will use its
3175 /// stack slot (instead of being passed in registers).  ArgOffset,
3176 /// AvailableFPRs, and AvailableVRs must hold the current argument
3177 /// position, and will be updated to account for this argument.
3178 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3179                                    ISD::ArgFlagsTy Flags,
3180                                    unsigned PtrByteSize,
3181                                    unsigned LinkageSize,
3182                                    unsigned ParamAreaSize,
3183                                    unsigned &ArgOffset,
3184                                    unsigned &AvailableFPRs,
3185                                    unsigned &AvailableVRs, bool HasQPX) {
3186   bool UseMemory = false;
3187 
3188   // Respect alignment of argument on the stack.
3189   unsigned Align =
3190     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3191   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3192   // If there's no space left in the argument save area, we must
3193   // use memory (this check also catches zero-sized arguments).
3194   if (ArgOffset >= LinkageSize + ParamAreaSize)
3195     UseMemory = true;
3196 
3197   // Allocate argument on the stack.
3198   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3199   if (Flags.isInConsecutiveRegsLast())
3200     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3201   // If we overran the argument save area, we must use memory
3202   // (this check catches arguments passed partially in memory)
3203   if (ArgOffset > LinkageSize + ParamAreaSize)
3204     UseMemory = true;
3205 
3206   // However, if the argument is actually passed in an FPR or a VR,
3207   // we don't use memory after all.
3208   if (!Flags.isByVal()) {
3209     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3210         // QPX registers overlap with the scalar FP registers.
3211         (HasQPX && (ArgVT == MVT::v4f32 ||
3212                     ArgVT == MVT::v4f64 ||
3213                     ArgVT == MVT::v4i1)))
3214       if (AvailableFPRs > 0) {
3215         --AvailableFPRs;
3216         return false;
3217       }
3218     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3219         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3220         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3221         ArgVT == MVT::v1i128)
3222       if (AvailableVRs > 0) {
3223         --AvailableVRs;
3224         return false;
3225       }
3226   }
3227 
3228   return UseMemory;
3229 }
3230 
3231 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3232 /// ensure minimum alignment required for target.
3233 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3234                                      unsigned NumBytes) {
3235   unsigned TargetAlign = Lowering->getStackAlignment();
3236   unsigned AlignMask = TargetAlign - 1;
3237   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3238   return NumBytes;
3239 }
3240 
3241 SDValue PPCTargetLowering::LowerFormalArguments(
3242     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3243     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3244     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3245   if (Subtarget.isSVR4ABI()) {
3246     if (Subtarget.isPPC64())
3247       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3248                                          dl, DAG, InVals);
3249     else
3250       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3251                                          dl, DAG, InVals);
3252   } else {
3253     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3254                                        dl, DAG, InVals);
3255   }
3256 }
3257 
3258 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3259     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3260     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3261     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3262 
3263   // 32-bit SVR4 ABI Stack Frame Layout:
3264   //              +-----------------------------------+
3265   //        +-->  |            Back chain             |
3266   //        |     +-----------------------------------+
3267   //        |     | Floating-point register save area |
3268   //        |     +-----------------------------------+
3269   //        |     |    General register save area     |
3270   //        |     +-----------------------------------+
3271   //        |     |          CR save word             |
3272   //        |     +-----------------------------------+
3273   //        |     |         VRSAVE save word          |
3274   //        |     +-----------------------------------+
3275   //        |     |         Alignment padding         |
3276   //        |     +-----------------------------------+
3277   //        |     |     Vector register save area     |
3278   //        |     +-----------------------------------+
3279   //        |     |       Local variable space        |
3280   //        |     +-----------------------------------+
3281   //        |     |        Parameter list area        |
3282   //        |     +-----------------------------------+
3283   //        |     |           LR save word            |
3284   //        |     +-----------------------------------+
3285   // SP-->  +---  |            Back chain             |
3286   //              +-----------------------------------+
3287   //
3288   // Specifications:
3289   //   System V Application Binary Interface PowerPC Processor Supplement
3290   //   AltiVec Technology Programming Interface Manual
3291 
3292   MachineFunction &MF = DAG.getMachineFunction();
3293   MachineFrameInfo &MFI = MF.getFrameInfo();
3294   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3295 
3296   EVT PtrVT = getPointerTy(MF.getDataLayout());
3297   // Potential tail calls could cause overwriting of argument stack slots.
3298   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3299                        (CallConv == CallingConv::Fast));
3300   unsigned PtrByteSize = 4;
3301 
3302   // Assign locations to all of the incoming arguments.
3303   SmallVector<CCValAssign, 16> ArgLocs;
3304   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3305                  *DAG.getContext());
3306 
3307   // Reserve space for the linkage area on the stack.
3308   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3309   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3310   if (useSoftFloat())
3311     CCInfo.PreAnalyzeFormalArguments(Ins);
3312 
3313   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3314   CCInfo.clearWasPPCF128();
3315 
3316   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3317     CCValAssign &VA = ArgLocs[i];
3318 
3319     // Arguments stored in registers.
3320     if (VA.isRegLoc()) {
3321       const TargetRegisterClass *RC;
3322       EVT ValVT = VA.getValVT();
3323 
3324       switch (ValVT.getSimpleVT().SimpleTy) {
3325         default:
3326           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3327         case MVT::i1:
3328         case MVT::i32:
3329           RC = &PPC::GPRCRegClass;
3330           break;
3331         case MVT::f32:
3332           if (Subtarget.hasP8Vector())
3333             RC = &PPC::VSSRCRegClass;
3334           else
3335             RC = &PPC::F4RCRegClass;
3336           break;
3337         case MVT::f64:
3338           if (Subtarget.hasVSX())
3339             RC = &PPC::VSFRCRegClass;
3340           else
3341             RC = &PPC::F8RCRegClass;
3342           break;
3343         case MVT::v16i8:
3344         case MVT::v8i16:
3345         case MVT::v4i32:
3346           RC = &PPC::VRRCRegClass;
3347           break;
3348         case MVT::v4f32:
3349           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3350           break;
3351         case MVT::v2f64:
3352         case MVT::v2i64:
3353           RC = &PPC::VRRCRegClass;
3354           break;
3355         case MVT::v4f64:
3356           RC = &PPC::QFRCRegClass;
3357           break;
3358         case MVT::v4i1:
3359           RC = &PPC::QBRCRegClass;
3360           break;
3361       }
3362 
3363       // Transform the arguments stored in physical registers into virtual ones.
3364       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3365       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3366                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3367 
3368       if (ValVT == MVT::i1)
3369         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3370 
3371       InVals.push_back(ArgValue);
3372     } else {
3373       // Argument stored in memory.
3374       assert(VA.isMemLoc());
3375 
3376       unsigned ArgSize = VA.getLocVT().getStoreSize();
3377       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3378                                      isImmutable);
3379 
3380       // Create load nodes to retrieve arguments from the stack.
3381       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3382       InVals.push_back(
3383           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3384     }
3385   }
3386 
3387   // Assign locations to all of the incoming aggregate by value arguments.
3388   // Aggregates passed by value are stored in the local variable space of the
3389   // caller's stack frame, right above the parameter list area.
3390   SmallVector<CCValAssign, 16> ByValArgLocs;
3391   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3392                       ByValArgLocs, *DAG.getContext());
3393 
3394   // Reserve stack space for the allocations in CCInfo.
3395   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3396 
3397   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3398 
3399   // Area that is at least reserved in the caller of this function.
3400   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3401   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3402 
3403   // Set the size that is at least reserved in caller of this function.  Tail
3404   // call optimized function's reserved stack space needs to be aligned so that
3405   // taking the difference between two stack areas will result in an aligned
3406   // stack.
3407   MinReservedArea =
3408       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3409   FuncInfo->setMinReservedArea(MinReservedArea);
3410 
3411   SmallVector<SDValue, 8> MemOps;
3412 
3413   // If the function takes variable number of arguments, make a frame index for
3414   // the start of the first vararg value... for expansion of llvm.va_start.
3415   if (isVarArg) {
3416     static const MCPhysReg GPArgRegs[] = {
3417       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3418       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3419     };
3420     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3421 
3422     static const MCPhysReg FPArgRegs[] = {
3423       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3424       PPC::F8
3425     };
3426     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3427 
3428     if (useSoftFloat())
3429        NumFPArgRegs = 0;
3430 
3431     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3432     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3433 
3434     // Make room for NumGPArgRegs and NumFPArgRegs.
3435     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3436                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3437 
3438     FuncInfo->setVarArgsStackOffset(
3439       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3440                             CCInfo.getNextStackOffset(), true));
3441 
3442     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3443     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3444 
3445     // The fixed integer arguments of a variadic function are stored to the
3446     // VarArgsFrameIndex on the stack so that they may be loaded by
3447     // dereferencing the result of va_next.
3448     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3449       // Get an existing live-in vreg, or add a new one.
3450       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3451       if (!VReg)
3452         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3453 
3454       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3455       SDValue Store =
3456           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3457       MemOps.push_back(Store);
3458       // Increment the address by four for the next argument to store
3459       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3460       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3461     }
3462 
3463     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3464     // is set.
3465     // The double arguments are stored to the VarArgsFrameIndex
3466     // on the stack.
3467     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3468       // Get an existing live-in vreg, or add a new one.
3469       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3470       if (!VReg)
3471         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3472 
3473       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3474       SDValue Store =
3475           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3476       MemOps.push_back(Store);
3477       // Increment the address by eight for the next argument to store
3478       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3479                                          PtrVT);
3480       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3481     }
3482   }
3483 
3484   if (!MemOps.empty())
3485     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3486 
3487   return Chain;
3488 }
3489 
3490 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3491 // value to MVT::i64 and then truncate to the correct register size.
3492 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3493                                              EVT ObjectVT, SelectionDAG &DAG,
3494                                              SDValue ArgVal,
3495                                              const SDLoc &dl) const {
3496   if (Flags.isSExt())
3497     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3498                          DAG.getValueType(ObjectVT));
3499   else if (Flags.isZExt())
3500     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3501                          DAG.getValueType(ObjectVT));
3502 
3503   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3504 }
3505 
3506 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3507     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3508     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3509     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3510   // TODO: add description of PPC stack frame format, or at least some docs.
3511   //
3512   bool isELFv2ABI = Subtarget.isELFv2ABI();
3513   bool isLittleEndian = Subtarget.isLittleEndian();
3514   MachineFunction &MF = DAG.getMachineFunction();
3515   MachineFrameInfo &MFI = MF.getFrameInfo();
3516   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3517 
3518   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3519          "fastcc not supported on varargs functions");
3520 
3521   EVT PtrVT = getPointerTy(MF.getDataLayout());
3522   // Potential tail calls could cause overwriting of argument stack slots.
3523   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3524                        (CallConv == CallingConv::Fast));
3525   unsigned PtrByteSize = 8;
3526   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3527 
3528   static const MCPhysReg GPR[] = {
3529     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3530     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3531   };
3532   static const MCPhysReg VR[] = {
3533     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3534     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3535   };
3536 
3537   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3538   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3539   const unsigned Num_VR_Regs  = array_lengthof(VR);
3540   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3541 
3542   // Do a first pass over the arguments to determine whether the ABI
3543   // guarantees that our caller has allocated the parameter save area
3544   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3545   // in the ELFv2 ABI, it is true if this is a vararg function or if
3546   // any parameter is located in a stack slot.
3547 
3548   bool HasParameterArea = !isELFv2ABI || isVarArg;
3549   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3550   unsigned NumBytes = LinkageSize;
3551   unsigned AvailableFPRs = Num_FPR_Regs;
3552   unsigned AvailableVRs = Num_VR_Regs;
3553   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3554     if (Ins[i].Flags.isNest())
3555       continue;
3556 
3557     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3558                                PtrByteSize, LinkageSize, ParamAreaSize,
3559                                NumBytes, AvailableFPRs, AvailableVRs,
3560                                Subtarget.hasQPX()))
3561       HasParameterArea = true;
3562   }
3563 
3564   // Add DAG nodes to load the arguments or copy them out of registers.  On
3565   // entry to a function on PPC, the arguments start after the linkage area,
3566   // although the first ones are often in registers.
3567 
3568   unsigned ArgOffset = LinkageSize;
3569   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3570   unsigned &QFPR_idx = FPR_idx;
3571   SmallVector<SDValue, 8> MemOps;
3572   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
3573   unsigned CurArgIdx = 0;
3574   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3575     SDValue ArgVal;
3576     bool needsLoad = false;
3577     EVT ObjectVT = Ins[ArgNo].VT;
3578     EVT OrigVT = Ins[ArgNo].ArgVT;
3579     unsigned ObjSize = ObjectVT.getStoreSize();
3580     unsigned ArgSize = ObjSize;
3581     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3582     if (Ins[ArgNo].isOrigArg()) {
3583       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3584       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3585     }
3586     // We re-align the argument offset for each argument, except when using the
3587     // fast calling convention, when we need to make sure we do that only when
3588     // we'll actually use a stack slot.
3589     unsigned CurArgOffset, Align;
3590     auto ComputeArgOffset = [&]() {
3591       /* Respect alignment of argument on the stack.  */
3592       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3593       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3594       CurArgOffset = ArgOffset;
3595     };
3596 
3597     if (CallConv != CallingConv::Fast) {
3598       ComputeArgOffset();
3599 
3600       /* Compute GPR index associated with argument offset.  */
3601       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3602       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3603     }
3604 
3605     // FIXME the codegen can be much improved in some cases.
3606     // We do not have to keep everything in memory.
3607     if (Flags.isByVal()) {
3608       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3609 
3610       if (CallConv == CallingConv::Fast)
3611         ComputeArgOffset();
3612 
3613       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3614       ObjSize = Flags.getByValSize();
3615       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3616       // Empty aggregate parameters do not take up registers.  Examples:
3617       //   struct { } a;
3618       //   union  { } b;
3619       //   int c[0];
3620       // etc.  However, we have to provide a place-holder in InVals, so
3621       // pretend we have an 8-byte item at the current address for that
3622       // purpose.
3623       if (!ObjSize) {
3624         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3625         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3626         InVals.push_back(FIN);
3627         continue;
3628       }
3629 
3630       // Create a stack object covering all stack doublewords occupied
3631       // by the argument.  If the argument is (fully or partially) on
3632       // the stack, or if the argument is fully in registers but the
3633       // caller has allocated the parameter save anyway, we can refer
3634       // directly to the caller's stack frame.  Otherwise, create a
3635       // local copy in our own frame.
3636       int FI;
3637       if (HasParameterArea ||
3638           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3639         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3640       else
3641         FI = MFI.CreateStackObject(ArgSize, Align, false);
3642       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3643 
3644       // Handle aggregates smaller than 8 bytes.
3645       if (ObjSize < PtrByteSize) {
3646         // The value of the object is its address, which differs from the
3647         // address of the enclosing doubleword on big-endian systems.
3648         SDValue Arg = FIN;
3649         if (!isLittleEndian) {
3650           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3651           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3652         }
3653         InVals.push_back(Arg);
3654 
3655         if (GPR_idx != Num_GPR_Regs) {
3656           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3657           FuncInfo->addLiveInAttr(VReg, Flags);
3658           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3659           SDValue Store;
3660 
3661           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3662             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3663                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3664             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3665                                       MachinePointerInfo(&*FuncArg), ObjType);
3666           } else {
3667             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3668             // store the whole register as-is to the parameter save area
3669             // slot.
3670             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3671                                  MachinePointerInfo(&*FuncArg));
3672           }
3673 
3674           MemOps.push_back(Store);
3675         }
3676         // Whether we copied from a register or not, advance the offset
3677         // into the parameter save area by a full doubleword.
3678         ArgOffset += PtrByteSize;
3679         continue;
3680       }
3681 
3682       // The value of the object is its address, which is the address of
3683       // its first stack doubleword.
3684       InVals.push_back(FIN);
3685 
3686       // Store whatever pieces of the object are in registers to memory.
3687       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3688         if (GPR_idx == Num_GPR_Regs)
3689           break;
3690 
3691         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3692         FuncInfo->addLiveInAttr(VReg, Flags);
3693         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3694         SDValue Addr = FIN;
3695         if (j) {
3696           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3697           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3698         }
3699         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3700                                      MachinePointerInfo(&*FuncArg, j));
3701         MemOps.push_back(Store);
3702         ++GPR_idx;
3703       }
3704       ArgOffset += ArgSize;
3705       continue;
3706     }
3707 
3708     switch (ObjectVT.getSimpleVT().SimpleTy) {
3709     default: llvm_unreachable("Unhandled argument type!");
3710     case MVT::i1:
3711     case MVT::i32:
3712     case MVT::i64:
3713       if (Flags.isNest()) {
3714         // The 'nest' parameter, if any, is passed in R11.
3715         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3716         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3717 
3718         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3719           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3720 
3721         break;
3722       }
3723 
3724       // These can be scalar arguments or elements of an integer array type
3725       // passed directly.  Clang may use those instead of "byval" aggregate
3726       // types to avoid forcing arguments to memory unnecessarily.
3727       if (GPR_idx != Num_GPR_Regs) {
3728         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3729         FuncInfo->addLiveInAttr(VReg, Flags);
3730         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3731 
3732         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3733           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3734           // value to MVT::i64 and then truncate to the correct register size.
3735           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3736       } else {
3737         if (CallConv == CallingConv::Fast)
3738           ComputeArgOffset();
3739 
3740         needsLoad = true;
3741         ArgSize = PtrByteSize;
3742       }
3743       if (CallConv != CallingConv::Fast || needsLoad)
3744         ArgOffset += 8;
3745       break;
3746 
3747     case MVT::f32:
3748     case MVT::f64:
3749       // These can be scalar arguments or elements of a float array type
3750       // passed directly.  The latter are used to implement ELFv2 homogenous
3751       // float aggregates.
3752       if (FPR_idx != Num_FPR_Regs) {
3753         unsigned VReg;
3754 
3755         if (ObjectVT == MVT::f32)
3756           VReg = MF.addLiveIn(FPR[FPR_idx],
3757                               Subtarget.hasP8Vector()
3758                                   ? &PPC::VSSRCRegClass
3759                                   : &PPC::F4RCRegClass);
3760         else
3761           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3762                                                 ? &PPC::VSFRCRegClass
3763                                                 : &PPC::F8RCRegClass);
3764 
3765         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3766         ++FPR_idx;
3767       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3768         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3769         // once we support fp <-> gpr moves.
3770 
3771         // This can only ever happen in the presence of f32 array types,
3772         // since otherwise we never run out of FPRs before running out
3773         // of GPRs.
3774         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3775         FuncInfo->addLiveInAttr(VReg, Flags);
3776         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3777 
3778         if (ObjectVT == MVT::f32) {
3779           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3780             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3781                                  DAG.getConstant(32, dl, MVT::i32));
3782           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3783         }
3784 
3785         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3786       } else {
3787         if (CallConv == CallingConv::Fast)
3788           ComputeArgOffset();
3789 
3790         needsLoad = true;
3791       }
3792 
3793       // When passing an array of floats, the array occupies consecutive
3794       // space in the argument area; only round up to the next doubleword
3795       // at the end of the array.  Otherwise, each float takes 8 bytes.
3796       if (CallConv != CallingConv::Fast || needsLoad) {
3797         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3798         ArgOffset += ArgSize;
3799         if (Flags.isInConsecutiveRegsLast())
3800           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3801       }
3802       break;
3803     case MVT::v4f32:
3804     case MVT::v4i32:
3805     case MVT::v8i16:
3806     case MVT::v16i8:
3807     case MVT::v2f64:
3808     case MVT::v2i64:
3809     case MVT::v1i128:
3810       if (!Subtarget.hasQPX()) {
3811         // These can be scalar arguments or elements of a vector array type
3812         // passed directly.  The latter are used to implement ELFv2 homogenous
3813         // vector aggregates.
3814         if (VR_idx != Num_VR_Regs) {
3815           unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3816           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3817           ++VR_idx;
3818         } else {
3819           if (CallConv == CallingConv::Fast)
3820             ComputeArgOffset();
3821           needsLoad = true;
3822         }
3823         if (CallConv != CallingConv::Fast || needsLoad)
3824           ArgOffset += 16;
3825         break;
3826       } // not QPX
3827 
3828       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3829              "Invalid QPX parameter type");
3830       /* fall through */
3831 
3832     case MVT::v4f64:
3833     case MVT::v4i1:
3834       // QPX vectors are treated like their scalar floating-point subregisters
3835       // (except that they're larger).
3836       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3837       if (QFPR_idx != Num_QFPR_Regs) {
3838         const TargetRegisterClass *RC;
3839         switch (ObjectVT.getSimpleVT().SimpleTy) {
3840         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3841         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3842         default:         RC = &PPC::QBRCRegClass; break;
3843         }
3844 
3845         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3846         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3847         ++QFPR_idx;
3848       } else {
3849         if (CallConv == CallingConv::Fast)
3850           ComputeArgOffset();
3851         needsLoad = true;
3852       }
3853       if (CallConv != CallingConv::Fast || needsLoad)
3854         ArgOffset += Sz;
3855       break;
3856     }
3857 
3858     // We need to load the argument to a virtual register if we determined
3859     // above that we ran out of physical registers of the appropriate type.
3860     if (needsLoad) {
3861       if (ObjSize < ArgSize && !isLittleEndian)
3862         CurArgOffset += ArgSize - ObjSize;
3863       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3864       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3865       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3866     }
3867 
3868     InVals.push_back(ArgVal);
3869   }
3870 
3871   // Area that is at least reserved in the caller of this function.
3872   unsigned MinReservedArea;
3873   if (HasParameterArea)
3874     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3875   else
3876     MinReservedArea = LinkageSize;
3877 
3878   // Set the size that is at least reserved in caller of this function.  Tail
3879   // call optimized functions' reserved stack space needs to be aligned so that
3880   // taking the difference between two stack areas will result in an aligned
3881   // stack.
3882   MinReservedArea =
3883       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3884   FuncInfo->setMinReservedArea(MinReservedArea);
3885 
3886   // If the function takes variable number of arguments, make a frame index for
3887   // the start of the first vararg value... for expansion of llvm.va_start.
3888   if (isVarArg) {
3889     int Depth = ArgOffset;
3890 
3891     FuncInfo->setVarArgsFrameIndex(
3892       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3893     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3894 
3895     // If this function is vararg, store any remaining integer argument regs
3896     // to their spots on the stack so that they may be loaded by dereferencing
3897     // the result of va_next.
3898     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3899          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3900       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3901       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3902       SDValue Store =
3903           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3904       MemOps.push_back(Store);
3905       // Increment the address by four for the next argument to store
3906       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3907       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3908     }
3909   }
3910 
3911   if (!MemOps.empty())
3912     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3913 
3914   return Chain;
3915 }
3916 
3917 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3918     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3919     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3920     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3921   // TODO: add description of PPC stack frame format, or at least some docs.
3922   //
3923   MachineFunction &MF = DAG.getMachineFunction();
3924   MachineFrameInfo &MFI = MF.getFrameInfo();
3925   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3926 
3927   EVT PtrVT = getPointerTy(MF.getDataLayout());
3928   bool isPPC64 = PtrVT == MVT::i64;
3929   // Potential tail calls could cause overwriting of argument stack slots.
3930   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3931                        (CallConv == CallingConv::Fast));
3932   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3933   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3934   unsigned ArgOffset = LinkageSize;
3935   // Area that is at least reserved in caller of this function.
3936   unsigned MinReservedArea = ArgOffset;
3937 
3938   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3939     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3940     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3941   };
3942   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3943     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3944     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3945   };
3946   static const MCPhysReg VR[] = {
3947     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3948     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3949   };
3950 
3951   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3952   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3953   const unsigned Num_VR_Regs  = array_lengthof( VR);
3954 
3955   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3956 
3957   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3958 
3959   // In 32-bit non-varargs functions, the stack space for vectors is after the
3960   // stack space for non-vectors.  We do not use this space unless we have
3961   // too many vectors to fit in registers, something that only occurs in
3962   // constructed examples:), but we have to walk the arglist to figure
3963   // that out...for the pathological case, compute VecArgOffset as the
3964   // start of the vector parameter area.  Computing VecArgOffset is the
3965   // entire point of the following loop.
3966   unsigned VecArgOffset = ArgOffset;
3967   if (!isVarArg && !isPPC64) {
3968     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3969          ++ArgNo) {
3970       EVT ObjectVT = Ins[ArgNo].VT;
3971       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3972 
3973       if (Flags.isByVal()) {
3974         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3975         unsigned ObjSize = Flags.getByValSize();
3976         unsigned ArgSize =
3977                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3978         VecArgOffset += ArgSize;
3979         continue;
3980       }
3981 
3982       switch(ObjectVT.getSimpleVT().SimpleTy) {
3983       default: llvm_unreachable("Unhandled argument type!");
3984       case MVT::i1:
3985       case MVT::i32:
3986       case MVT::f32:
3987         VecArgOffset += 4;
3988         break;
3989       case MVT::i64:  // PPC64
3990       case MVT::f64:
3991         // FIXME: We are guaranteed to be !isPPC64 at this point.
3992         // Does MVT::i64 apply?
3993         VecArgOffset += 8;
3994         break;
3995       case MVT::v4f32:
3996       case MVT::v4i32:
3997       case MVT::v8i16:
3998       case MVT::v16i8:
3999         // Nothing to do, we're only looking at Nonvector args here.
4000         break;
4001       }
4002     }
4003   }
4004   // We've found where the vector parameter area in memory is.  Skip the
4005   // first 12 parameters; these don't use that memory.
4006   VecArgOffset = ((VecArgOffset+15)/16)*16;
4007   VecArgOffset += 12*16;
4008 
4009   // Add DAG nodes to load the arguments or copy them out of registers.  On
4010   // entry to a function on PPC, the arguments start after the linkage area,
4011   // although the first ones are often in registers.
4012 
4013   SmallVector<SDValue, 8> MemOps;
4014   unsigned nAltivecParamsAtEnd = 0;
4015   Function::const_arg_iterator FuncArg = MF.getFunction().arg_begin();
4016   unsigned CurArgIdx = 0;
4017   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
4018     SDValue ArgVal;
4019     bool needsLoad = false;
4020     EVT ObjectVT = Ins[ArgNo].VT;
4021     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
4022     unsigned ArgSize = ObjSize;
4023     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
4024     if (Ins[ArgNo].isOrigArg()) {
4025       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
4026       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
4027     }
4028     unsigned CurArgOffset = ArgOffset;
4029 
4030     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
4031     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
4032         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
4033       if (isVarArg || isPPC64) {
4034         MinReservedArea = ((MinReservedArea+15)/16)*16;
4035         MinReservedArea += CalculateStackSlotSize(ObjectVT,
4036                                                   Flags,
4037                                                   PtrByteSize);
4038       } else  nAltivecParamsAtEnd++;
4039     } else
4040       // Calculate min reserved area.
4041       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
4042                                                 Flags,
4043                                                 PtrByteSize);
4044 
4045     // FIXME the codegen can be much improved in some cases.
4046     // We do not have to keep everything in memory.
4047     if (Flags.isByVal()) {
4048       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
4049 
4050       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
4051       ObjSize = Flags.getByValSize();
4052       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4053       // Objects of size 1 and 2 are right justified, everything else is
4054       // left justified.  This means the memory address is adjusted forwards.
4055       if (ObjSize==1 || ObjSize==2) {
4056         CurArgOffset = CurArgOffset + (4 - ObjSize);
4057       }
4058       // The value of the object is its address.
4059       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
4060       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4061       InVals.push_back(FIN);
4062       if (ObjSize==1 || ObjSize==2) {
4063         if (GPR_idx != Num_GPR_Regs) {
4064           unsigned VReg;
4065           if (isPPC64)
4066             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4067           else
4068             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4069           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4070           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
4071           SDValue Store =
4072               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
4073                                 MachinePointerInfo(&*FuncArg), ObjType);
4074           MemOps.push_back(Store);
4075           ++GPR_idx;
4076         }
4077 
4078         ArgOffset += PtrByteSize;
4079 
4080         continue;
4081       }
4082       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
4083         // Store whatever pieces of the object are in registers
4084         // to memory.  ArgOffset will be the address of the beginning
4085         // of the object.
4086         if (GPR_idx != Num_GPR_Regs) {
4087           unsigned VReg;
4088           if (isPPC64)
4089             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4090           else
4091             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4092           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
4093           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4094           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4095           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
4096                                        MachinePointerInfo(&*FuncArg, j));
4097           MemOps.push_back(Store);
4098           ++GPR_idx;
4099           ArgOffset += PtrByteSize;
4100         } else {
4101           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
4102           break;
4103         }
4104       }
4105       continue;
4106     }
4107 
4108     switch (ObjectVT.getSimpleVT().SimpleTy) {
4109     default: llvm_unreachable("Unhandled argument type!");
4110     case MVT::i1:
4111     case MVT::i32:
4112       if (!isPPC64) {
4113         if (GPR_idx != Num_GPR_Regs) {
4114           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4115           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
4116 
4117           if (ObjectVT == MVT::i1)
4118             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
4119 
4120           ++GPR_idx;
4121         } else {
4122           needsLoad = true;
4123           ArgSize = PtrByteSize;
4124         }
4125         // All int arguments reserve stack space in the Darwin ABI.
4126         ArgOffset += PtrByteSize;
4127         break;
4128       }
4129       LLVM_FALLTHROUGH;
4130     case MVT::i64:  // PPC64
4131       if (GPR_idx != Num_GPR_Regs) {
4132         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4133         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
4134 
4135         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
4136           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
4137           // value to MVT::i64 and then truncate to the correct register size.
4138           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
4139 
4140         ++GPR_idx;
4141       } else {
4142         needsLoad = true;
4143         ArgSize = PtrByteSize;
4144       }
4145       // All int arguments reserve stack space in the Darwin ABI.
4146       ArgOffset += 8;
4147       break;
4148 
4149     case MVT::f32:
4150     case MVT::f64:
4151       // Every 4 bytes of argument space consumes one of the GPRs available for
4152       // argument passing.
4153       if (GPR_idx != Num_GPR_Regs) {
4154         ++GPR_idx;
4155         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
4156           ++GPR_idx;
4157       }
4158       if (FPR_idx != Num_FPR_Regs) {
4159         unsigned VReg;
4160 
4161         if (ObjectVT == MVT::f32)
4162           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
4163         else
4164           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
4165 
4166         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4167         ++FPR_idx;
4168       } else {
4169         needsLoad = true;
4170       }
4171 
4172       // All FP arguments reserve stack space in the Darwin ABI.
4173       ArgOffset += isPPC64 ? 8 : ObjSize;
4174       break;
4175     case MVT::v4f32:
4176     case MVT::v4i32:
4177     case MVT::v8i16:
4178     case MVT::v16i8:
4179       // Note that vector arguments in registers don't reserve stack space,
4180       // except in varargs functions.
4181       if (VR_idx != Num_VR_Regs) {
4182         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4183         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4184         if (isVarArg) {
4185           while ((ArgOffset % 16) != 0) {
4186             ArgOffset += PtrByteSize;
4187             if (GPR_idx != Num_GPR_Regs)
4188               GPR_idx++;
4189           }
4190           ArgOffset += 16;
4191           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4192         }
4193         ++VR_idx;
4194       } else {
4195         if (!isVarArg && !isPPC64) {
4196           // Vectors go after all the nonvectors.
4197           CurArgOffset = VecArgOffset;
4198           VecArgOffset += 16;
4199         } else {
4200           // Vectors are aligned.
4201           ArgOffset = ((ArgOffset+15)/16)*16;
4202           CurArgOffset = ArgOffset;
4203           ArgOffset += 16;
4204         }
4205         needsLoad = true;
4206       }
4207       break;
4208     }
4209 
4210     // We need to load the argument to a virtual register if we determined above
4211     // that we ran out of physical registers of the appropriate type.
4212     if (needsLoad) {
4213       int FI = MFI.CreateFixedObject(ObjSize,
4214                                      CurArgOffset + (ArgSize - ObjSize),
4215                                      isImmutable);
4216       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4217       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4218     }
4219 
4220     InVals.push_back(ArgVal);
4221   }
4222 
4223   // Allow for Altivec parameters at the end, if needed.
4224   if (nAltivecParamsAtEnd) {
4225     MinReservedArea = ((MinReservedArea+15)/16)*16;
4226     MinReservedArea += 16*nAltivecParamsAtEnd;
4227   }
4228 
4229   // Area that is at least reserved in the caller of this function.
4230   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4231 
4232   // Set the size that is at least reserved in caller of this function.  Tail
4233   // call optimized functions' reserved stack space needs to be aligned so that
4234   // taking the difference between two stack areas will result in an aligned
4235   // stack.
4236   MinReservedArea =
4237       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4238   FuncInfo->setMinReservedArea(MinReservedArea);
4239 
4240   // If the function takes variable number of arguments, make a frame index for
4241   // the start of the first vararg value... for expansion of llvm.va_start.
4242   if (isVarArg) {
4243     int Depth = ArgOffset;
4244 
4245     FuncInfo->setVarArgsFrameIndex(
4246       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4247                             Depth, true));
4248     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4249 
4250     // If this function is vararg, store any remaining integer argument regs
4251     // to their spots on the stack so that they may be loaded by dereferencing
4252     // the result of va_next.
4253     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4254       unsigned VReg;
4255 
4256       if (isPPC64)
4257         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4258       else
4259         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4260 
4261       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4262       SDValue Store =
4263           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4264       MemOps.push_back(Store);
4265       // Increment the address by four for the next argument to store
4266       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4267       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4268     }
4269   }
4270 
4271   if (!MemOps.empty())
4272     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4273 
4274   return Chain;
4275 }
4276 
4277 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4278 /// adjusted to accommodate the arguments for the tailcall.
4279 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4280                                    unsigned ParamSize) {
4281 
4282   if (!isTailCall) return 0;
4283 
4284   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4285   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4286   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4287   // Remember only if the new adjustement is bigger.
4288   if (SPDiff < FI->getTailCallSPDelta())
4289     FI->setTailCallSPDelta(SPDiff);
4290 
4291   return SPDiff;
4292 }
4293 
4294 static bool isFunctionGlobalAddress(SDValue Callee);
4295 
4296 static bool
4297 callsShareTOCBase(const Function *Caller, SDValue Callee,
4298                     const TargetMachine &TM) {
4299   // If !G, Callee can be an external symbol.
4300   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4301   if (!G)
4302     return false;
4303 
4304   // The medium and large code models are expected to provide a sufficiently
4305   // large TOC to provide all data addressing needs of a module with a
4306   // single TOC. Since each module will be addressed with a single TOC then we
4307   // only need to check that caller and callee don't cross dso boundaries.
4308   if (CodeModel::Medium == TM.getCodeModel() ||
4309       CodeModel::Large == TM.getCodeModel())
4310     return TM.shouldAssumeDSOLocal(*Caller->getParent(), G->getGlobal());
4311 
4312   // Otherwise we need to ensure callee and caller are in the same section,
4313   // since the linker may allocate multiple TOCs, and we don't know which
4314   // sections will belong to the same TOC base.
4315 
4316   const GlobalValue *GV = G->getGlobal();
4317   if (!GV->isStrongDefinitionForLinker())
4318     return false;
4319 
4320   // Any explicitly-specified sections and section prefixes must also match.
4321   // Also, if we're using -ffunction-sections, then each function is always in
4322   // a different section (the same is true for COMDAT functions).
4323   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4324       GV->getSection() != Caller->getSection())
4325     return false;
4326   if (const auto *F = dyn_cast<Function>(GV)) {
4327     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4328       return false;
4329   }
4330 
4331   // If the callee might be interposed, then we can't assume the ultimate call
4332   // target will be in the same section. Even in cases where we can assume that
4333   // interposition won't happen, in any case where the linker might insert a
4334   // stub to allow for interposition, we must generate code as though
4335   // interposition might occur. To understand why this matters, consider a
4336   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4337   // in the same section, but a is in a different module (i.e. has a different
4338   // TOC base pointer). If the linker allows for interposition between b and c,
4339   // then it will generate a stub for the call edge between b and c which will
4340   // save the TOC pointer into the designated stack slot allocated by b. If we
4341   // return true here, and therefore allow a tail call between b and c, that
4342   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4343   // pointer into the stack slot allocated by a (where the a -> b stub saved
4344   // a's TOC base pointer). If we're not considering a tail call, but rather,
4345   // whether a nop is needed after the call instruction in b, because the linker
4346   // will insert a stub, it might complain about a missing nop if we omit it
4347   // (although many don't complain in this case).
4348   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4349     return false;
4350 
4351   return true;
4352 }
4353 
4354 static bool
4355 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4356                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4357   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4358 
4359   const unsigned PtrByteSize = 8;
4360   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4361 
4362   static const MCPhysReg GPR[] = {
4363     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4364     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4365   };
4366   static const MCPhysReg VR[] = {
4367     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4368     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4369   };
4370 
4371   const unsigned NumGPRs = array_lengthof(GPR);
4372   const unsigned NumFPRs = 13;
4373   const unsigned NumVRs = array_lengthof(VR);
4374   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4375 
4376   unsigned NumBytes = LinkageSize;
4377   unsigned AvailableFPRs = NumFPRs;
4378   unsigned AvailableVRs = NumVRs;
4379 
4380   for (const ISD::OutputArg& Param : Outs) {
4381     if (Param.Flags.isNest()) continue;
4382 
4383     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4384                                PtrByteSize, LinkageSize, ParamAreaSize,
4385                                NumBytes, AvailableFPRs, AvailableVRs,
4386                                Subtarget.hasQPX()))
4387       return true;
4388   }
4389   return false;
4390 }
4391 
4392 static bool
4393 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite CS) {
4394   if (CS.arg_size() != CallerFn->arg_size())
4395     return false;
4396 
4397   ImmutableCallSite::arg_iterator CalleeArgIter = CS.arg_begin();
4398   ImmutableCallSite::arg_iterator CalleeArgEnd = CS.arg_end();
4399   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4400 
4401   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4402     const Value* CalleeArg = *CalleeArgIter;
4403     const Value* CallerArg = &(*CallerArgIter);
4404     if (CalleeArg == CallerArg)
4405       continue;
4406 
4407     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4408     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4409     //      }
4410     // 1st argument of callee is undef and has the same type as caller.
4411     if (CalleeArg->getType() == CallerArg->getType() &&
4412         isa<UndefValue>(CalleeArg))
4413       continue;
4414 
4415     return false;
4416   }
4417 
4418   return true;
4419 }
4420 
4421 // Returns true if TCO is possible between the callers and callees
4422 // calling conventions.
4423 static bool
4424 areCallingConvEligibleForTCO_64SVR4(CallingConv::ID CallerCC,
4425                                     CallingConv::ID CalleeCC) {
4426   // Tail calls are possible with fastcc and ccc.
4427   auto isTailCallableCC  = [] (CallingConv::ID CC){
4428       return  CC == CallingConv::C || CC == CallingConv::Fast;
4429   };
4430   if (!isTailCallableCC(CallerCC) || !isTailCallableCC(CalleeCC))
4431     return false;
4432 
4433   // We can safely tail call both fastcc and ccc callees from a c calling
4434   // convention caller. If the caller is fastcc, we may have less stack space
4435   // than a non-fastcc caller with the same signature so disable tail-calls in
4436   // that case.
4437   return CallerCC == CallingConv::C || CallerCC == CalleeCC;
4438 }
4439 
4440 bool
4441 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4442                                     SDValue Callee,
4443                                     CallingConv::ID CalleeCC,
4444                                     ImmutableCallSite CS,
4445                                     bool isVarArg,
4446                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4447                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4448                                     SelectionDAG& DAG) const {
4449   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4450 
4451   if (DisableSCO && !TailCallOpt) return false;
4452 
4453   // Variadic argument functions are not supported.
4454   if (isVarArg) return false;
4455 
4456   auto &Caller = DAG.getMachineFunction().getFunction();
4457   // Check that the calling conventions are compatible for tco.
4458   if (!areCallingConvEligibleForTCO_64SVR4(Caller.getCallingConv(), CalleeCC))
4459     return false;
4460 
4461   // Caller contains any byval parameter is not supported.
4462   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4463     return false;
4464 
4465   // Callee contains any byval parameter is not supported, too.
4466   // Note: This is a quick work around, because in some cases, e.g.
4467   // caller's stack size > callee's stack size, we are still able to apply
4468   // sibling call optimization. For example, gcc is able to do SCO for caller1
4469   // in the following example, but not for caller2.
4470   //   struct test {
4471   //     long int a;
4472   //     char ary[56];
4473   //   } gTest;
4474   //   __attribute__((noinline)) int callee(struct test v, struct test *b) {
4475   //     b->a = v.a;
4476   //     return 0;
4477   //   }
4478   //   void caller1(struct test a, struct test c, struct test *b) {
4479   //     callee(gTest, b); }
4480   //   void caller2(struct test *b) { callee(gTest, b); }
4481   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4482     return false;
4483 
4484   // If callee and caller use different calling conventions, we cannot pass
4485   // parameters on stack since offsets for the parameter area may be different.
4486   if (Caller.getCallingConv() != CalleeCC &&
4487       needStackSlotPassParameters(Subtarget, Outs))
4488     return false;
4489 
4490   // No TCO/SCO on indirect call because Caller have to restore its TOC
4491   if (!isFunctionGlobalAddress(Callee) &&
4492       !isa<ExternalSymbolSDNode>(Callee))
4493     return false;
4494 
4495   // If the caller and callee potentially have different TOC bases then we
4496   // cannot tail call since we need to restore the TOC pointer after the call.
4497   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4498   if (!callsShareTOCBase(&Caller, Callee, getTargetMachine()))
4499     return false;
4500 
4501   // TCO allows altering callee ABI, so we don't have to check further.
4502   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4503     return true;
4504 
4505   if (DisableSCO) return false;
4506 
4507   // If callee use the same argument list that caller is using, then we can
4508   // apply SCO on this case. If it is not, then we need to check if callee needs
4509   // stack for passing arguments.
4510   if (!hasSameArgumentList(&Caller, CS) &&
4511       needStackSlotPassParameters(Subtarget, Outs)) {
4512     return false;
4513   }
4514 
4515   return true;
4516 }
4517 
4518 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4519 /// for tail call optimization. Targets which want to do tail call
4520 /// optimization should implement this function.
4521 bool
4522 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4523                                                      CallingConv::ID CalleeCC,
4524                                                      bool isVarArg,
4525                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4526                                                      SelectionDAG& DAG) const {
4527   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4528     return false;
4529 
4530   // Variable argument functions are not supported.
4531   if (isVarArg)
4532     return false;
4533 
4534   MachineFunction &MF = DAG.getMachineFunction();
4535   CallingConv::ID CallerCC = MF.getFunction().getCallingConv();
4536   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4537     // Functions containing by val parameters are not supported.
4538     for (unsigned i = 0; i != Ins.size(); i++) {
4539        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4540        if (Flags.isByVal()) return false;
4541     }
4542 
4543     // Non-PIC/GOT tail calls are supported.
4544     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4545       return true;
4546 
4547     // At the moment we can only do local tail calls (in same module, hidden
4548     // or protected) if we are generating PIC.
4549     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4550       return G->getGlobal()->hasHiddenVisibility()
4551           || G->getGlobal()->hasProtectedVisibility();
4552   }
4553 
4554   return false;
4555 }
4556 
4557 /// isCallCompatibleAddress - Return the immediate to use if the specified
4558 /// 32-bit value is representable in the immediate field of a BxA instruction.
4559 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4560   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4561   if (!C) return nullptr;
4562 
4563   int Addr = C->getZExtValue();
4564   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4565       SignExtend32<26>(Addr) != Addr)
4566     return nullptr;  // Top 6 bits have to be sext of immediate.
4567 
4568   return DAG
4569       .getConstant(
4570           (int)C->getZExtValue() >> 2, SDLoc(Op),
4571           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4572       .getNode();
4573 }
4574 
4575 namespace {
4576 
4577 struct TailCallArgumentInfo {
4578   SDValue Arg;
4579   SDValue FrameIdxOp;
4580   int FrameIdx = 0;
4581 
4582   TailCallArgumentInfo() = default;
4583 };
4584 
4585 } // end anonymous namespace
4586 
4587 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4588 static void StoreTailCallArgumentsToStackSlot(
4589     SelectionDAG &DAG, SDValue Chain,
4590     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4591     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4592   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4593     SDValue Arg = TailCallArgs[i].Arg;
4594     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4595     int FI = TailCallArgs[i].FrameIdx;
4596     // Store relative to framepointer.
4597     MemOpChains.push_back(DAG.getStore(
4598         Chain, dl, Arg, FIN,
4599         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4600   }
4601 }
4602 
4603 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4604 /// the appropriate stack slot for the tail call optimized function call.
4605 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4606                                              SDValue OldRetAddr, SDValue OldFP,
4607                                              int SPDiff, const SDLoc &dl) {
4608   if (SPDiff) {
4609     // Calculate the new stack slot for the return address.
4610     MachineFunction &MF = DAG.getMachineFunction();
4611     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4612     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4613     bool isPPC64 = Subtarget.isPPC64();
4614     int SlotSize = isPPC64 ? 8 : 4;
4615     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4616     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4617                                                          NewRetAddrLoc, true);
4618     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4619     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4620     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4621                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4622 
4623     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4624     // slot as the FP is never overwritten.
4625     if (Subtarget.isDarwinABI()) {
4626       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4627       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4628                                                          true);
4629       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4630       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4631                            MachinePointerInfo::getFixedStack(
4632                                DAG.getMachineFunction(), NewFPIdx));
4633     }
4634   }
4635   return Chain;
4636 }
4637 
4638 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4639 /// the position of the argument.
4640 static void
4641 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4642                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4643                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4644   int Offset = ArgOffset + SPDiff;
4645   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4646   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4647   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4648   SDValue FIN = DAG.getFrameIndex(FI, VT);
4649   TailCallArgumentInfo Info;
4650   Info.Arg = Arg;
4651   Info.FrameIdxOp = FIN;
4652   Info.FrameIdx = FI;
4653   TailCallArguments.push_back(Info);
4654 }
4655 
4656 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4657 /// stack slot. Returns the chain as result and the loaded frame pointers in
4658 /// LROpOut/FPOpout. Used when tail calling.
4659 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4660     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4661     SDValue &FPOpOut, const SDLoc &dl) const {
4662   if (SPDiff) {
4663     // Load the LR and FP stack slot for later adjusting.
4664     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4665     LROpOut = getReturnAddrFrameIndex(DAG);
4666     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4667     Chain = SDValue(LROpOut.getNode(), 1);
4668 
4669     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4670     // slot as the FP is never overwritten.
4671     if (Subtarget.isDarwinABI()) {
4672       FPOpOut = getFramePointerFrameIndex(DAG);
4673       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4674       Chain = SDValue(FPOpOut.getNode(), 1);
4675     }
4676   }
4677   return Chain;
4678 }
4679 
4680 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4681 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4682 /// specified by the specific parameter attribute. The copy will be passed as
4683 /// a byval function parameter.
4684 /// Sometimes what we are copying is the end of a larger object, the part that
4685 /// does not fit in registers.
4686 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4687                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4688                                          SelectionDAG &DAG, const SDLoc &dl) {
4689   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4690   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4691                        false, false, false, MachinePointerInfo(),
4692                        MachinePointerInfo());
4693 }
4694 
4695 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4696 /// tail calls.
4697 static void LowerMemOpCallTo(
4698     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4699     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4700     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4701     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4702   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4703   if (!isTailCall) {
4704     if (isVector) {
4705       SDValue StackPtr;
4706       if (isPPC64)
4707         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4708       else
4709         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4710       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4711                            DAG.getConstant(ArgOffset, dl, PtrVT));
4712     }
4713     MemOpChains.push_back(
4714         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4715     // Calculate and remember argument location.
4716   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4717                                   TailCallArguments);
4718 }
4719 
4720 static void
4721 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4722                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4723                 SDValue FPOp,
4724                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4725   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4726   // might overwrite each other in case of tail call optimization.
4727   SmallVector<SDValue, 8> MemOpChains2;
4728   // Do not flag preceding copytoreg stuff together with the following stuff.
4729   InFlag = SDValue();
4730   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4731                                     MemOpChains2, dl);
4732   if (!MemOpChains2.empty())
4733     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4734 
4735   // Store the return address to the appropriate stack slot.
4736   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4737 
4738   // Emit callseq_end just before tailcall node.
4739   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4740                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4741   InFlag = Chain.getValue(1);
4742 }
4743 
4744 // Is this global address that of a function that can be called by name? (as
4745 // opposed to something that must hold a descriptor for an indirect call).
4746 static bool isFunctionGlobalAddress(SDValue Callee) {
4747   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4748     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4749         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4750       return false;
4751 
4752     return G->getGlobal()->getValueType()->isFunctionTy();
4753   }
4754 
4755   return false;
4756 }
4757 
4758 static unsigned
4759 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4760             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4761             bool isPatchPoint, bool hasNest,
4762             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4763             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4764             ImmutableCallSite CS, const PPCSubtarget &Subtarget) {
4765   bool isPPC64 = Subtarget.isPPC64();
4766   bool isSVR4ABI = Subtarget.isSVR4ABI();
4767   bool isELFv2ABI = Subtarget.isELFv2ABI();
4768 
4769   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4770   NodeTys.push_back(MVT::Other);   // Returns a chain
4771   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4772 
4773   unsigned CallOpc = PPCISD::CALL;
4774 
4775   bool needIndirectCall = true;
4776   if (!isSVR4ABI || !isPPC64)
4777     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4778       // If this is an absolute destination address, use the munged value.
4779       Callee = SDValue(Dest, 0);
4780       needIndirectCall = false;
4781     }
4782 
4783   // PC-relative references to external symbols should go through $stub, unless
4784   // we're building with the leopard linker or later, which automatically
4785   // synthesizes these stubs.
4786   const TargetMachine &TM = DAG.getTarget();
4787   const Module *Mod = DAG.getMachineFunction().getFunction().getParent();
4788   const GlobalValue *GV = nullptr;
4789   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4790     GV = G->getGlobal();
4791   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4792   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4793 
4794   if (isFunctionGlobalAddress(Callee)) {
4795     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4796     // A call to a TLS address is actually an indirect call to a
4797     // thread-specific pointer.
4798     unsigned OpFlags = 0;
4799     if (UsePlt)
4800       OpFlags = PPCII::MO_PLT;
4801 
4802     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4803     // every direct call is) turn it into a TargetGlobalAddress /
4804     // TargetExternalSymbol node so that legalize doesn't hack it.
4805     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4806                                         Callee.getValueType(), 0, OpFlags);
4807     needIndirectCall = false;
4808   }
4809 
4810   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4811     unsigned char OpFlags = 0;
4812 
4813     if (UsePlt)
4814       OpFlags = PPCII::MO_PLT;
4815 
4816     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4817                                          OpFlags);
4818     needIndirectCall = false;
4819   }
4820 
4821   if (isPatchPoint) {
4822     // We'll form an invalid direct call when lowering a patchpoint; the full
4823     // sequence for an indirect call is complicated, and many of the
4824     // instructions introduced might have side effects (and, thus, can't be
4825     // removed later). The call itself will be removed as soon as the
4826     // argument/return lowering is complete, so the fact that it has the wrong
4827     // kind of operands should not really matter.
4828     needIndirectCall = false;
4829   }
4830 
4831   if (needIndirectCall) {
4832     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4833     // to do the call, we can't use PPCISD::CALL.
4834     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4835 
4836     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4837       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4838       // entry point, but to the function descriptor (the function entry point
4839       // address is part of the function descriptor though).
4840       // The function descriptor is a three doubleword structure with the
4841       // following fields: function entry point, TOC base address and
4842       // environment pointer.
4843       // Thus for a call through a function pointer, the following actions need
4844       // to be performed:
4845       //   1. Save the TOC of the caller in the TOC save area of its stack
4846       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4847       //   2. Load the address of the function entry point from the function
4848       //      descriptor.
4849       //   3. Load the TOC of the callee from the function descriptor into r2.
4850       //   4. Load the environment pointer from the function descriptor into
4851       //      r11.
4852       //   5. Branch to the function entry point address.
4853       //   6. On return of the callee, the TOC of the caller needs to be
4854       //      restored (this is done in FinishCall()).
4855       //
4856       // The loads are scheduled at the beginning of the call sequence, and the
4857       // register copies are flagged together to ensure that no other
4858       // operations can be scheduled in between. E.g. without flagging the
4859       // copies together, a TOC access in the caller could be scheduled between
4860       // the assignment of the callee TOC and the branch to the callee, which
4861       // results in the TOC access going through the TOC of the callee instead
4862       // of going through the TOC of the caller, which leads to incorrect code.
4863 
4864       // Load the address of the function entry point from the function
4865       // descriptor.
4866       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4867       if (LDChain.getValueType() == MVT::Glue)
4868         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4869 
4870       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4871                           ? (MachineMemOperand::MODereferenceable |
4872                              MachineMemOperand::MOInvariant)
4873                           : MachineMemOperand::MONone;
4874 
4875       MachinePointerInfo MPI(CS ? CS.getCalledValue() : nullptr);
4876       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4877                                         /* Alignment = */ 8, MMOFlags);
4878 
4879       // Load environment pointer into r11.
4880       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4881       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4882       SDValue LoadEnvPtr =
4883           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4884                       /* Alignment = */ 8, MMOFlags);
4885 
4886       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4887       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4888       SDValue TOCPtr =
4889           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4890                       /* Alignment = */ 8, MMOFlags);
4891 
4892       setUsesTOCBasePtr(DAG);
4893       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4894                                         InFlag);
4895       Chain = TOCVal.getValue(0);
4896       InFlag = TOCVal.getValue(1);
4897 
4898       // If the function call has an explicit 'nest' parameter, it takes the
4899       // place of the environment pointer.
4900       if (!hasNest) {
4901         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4902                                           InFlag);
4903 
4904         Chain = EnvVal.getValue(0);
4905         InFlag = EnvVal.getValue(1);
4906       }
4907 
4908       MTCTROps[0] = Chain;
4909       MTCTROps[1] = LoadFuncPtr;
4910       MTCTROps[2] = InFlag;
4911     }
4912 
4913     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4914                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4915     InFlag = Chain.getValue(1);
4916 
4917     NodeTys.clear();
4918     NodeTys.push_back(MVT::Other);
4919     NodeTys.push_back(MVT::Glue);
4920     Ops.push_back(Chain);
4921     CallOpc = PPCISD::BCTRL;
4922     Callee.setNode(nullptr);
4923     // Add use of X11 (holding environment pointer)
4924     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4925       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4926     // Add CTR register as callee so a bctr can be emitted later.
4927     if (isTailCall)
4928       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4929   }
4930 
4931   // If this is a direct call, pass the chain and the callee.
4932   if (Callee.getNode()) {
4933     Ops.push_back(Chain);
4934     Ops.push_back(Callee);
4935   }
4936   // If this is a tail call add stack pointer delta.
4937   if (isTailCall)
4938     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4939 
4940   // Add argument registers to the end of the list so that they are known live
4941   // into the call.
4942   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4943     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4944                                   RegsToPass[i].second.getValueType()));
4945 
4946   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4947   // into the call.
4948   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4949     setUsesTOCBasePtr(DAG);
4950     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4951   }
4952 
4953   return CallOpc;
4954 }
4955 
4956 SDValue PPCTargetLowering::LowerCallResult(
4957     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4958     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4959     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4960   SmallVector<CCValAssign, 16> RVLocs;
4961   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4962                     *DAG.getContext());
4963 
4964   CCRetInfo.AnalyzeCallResult(
4965       Ins, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
4966                ? RetCC_PPC_Cold
4967                : RetCC_PPC);
4968 
4969   // Copy all of the result registers out of their specified physreg.
4970   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4971     CCValAssign &VA = RVLocs[i];
4972     assert(VA.isRegLoc() && "Can only return in registers!");
4973 
4974     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4975                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4976     Chain = Val.getValue(1);
4977     InFlag = Val.getValue(2);
4978 
4979     switch (VA.getLocInfo()) {
4980     default: llvm_unreachable("Unknown loc info!");
4981     case CCValAssign::Full: break;
4982     case CCValAssign::AExt:
4983       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4984       break;
4985     case CCValAssign::ZExt:
4986       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4987                         DAG.getValueType(VA.getValVT()));
4988       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4989       break;
4990     case CCValAssign::SExt:
4991       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4992                         DAG.getValueType(VA.getValVT()));
4993       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4994       break;
4995     }
4996 
4997     InVals.push_back(Val);
4998   }
4999 
5000   return Chain;
5001 }
5002 
5003 SDValue PPCTargetLowering::FinishCall(
5004     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
5005     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
5006     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
5007     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
5008     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
5009     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite CS) const {
5010   std::vector<EVT> NodeTys;
5011   SmallVector<SDValue, 8> Ops;
5012   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
5013                                  SPDiff, isTailCall, isPatchPoint, hasNest,
5014                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
5015 
5016   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
5017   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
5018     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
5019 
5020   // When performing tail call optimization the callee pops its arguments off
5021   // the stack. Account for this here so these bytes can be pushed back on in
5022   // PPCFrameLowering::eliminateCallFramePseudoInstr.
5023   int BytesCalleePops =
5024     (CallConv == CallingConv::Fast &&
5025      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
5026 
5027   // Add a register mask operand representing the call-preserved registers.
5028   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
5029   const uint32_t *Mask =
5030       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
5031   assert(Mask && "Missing call preserved mask for calling convention");
5032   Ops.push_back(DAG.getRegisterMask(Mask));
5033 
5034   if (InFlag.getNode())
5035     Ops.push_back(InFlag);
5036 
5037   // Emit tail call.
5038   if (isTailCall) {
5039     assert(((Callee.getOpcode() == ISD::Register &&
5040              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
5041             Callee.getOpcode() == ISD::TargetExternalSymbol ||
5042             Callee.getOpcode() == ISD::TargetGlobalAddress ||
5043             isa<ConstantSDNode>(Callee)) &&
5044     "Expecting an global address, external symbol, absolute value or register");
5045 
5046     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
5047     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
5048   }
5049 
5050   // Add a NOP immediately after the branch instruction when using the 64-bit
5051   // SVR4 ABI. At link time, if caller and callee are in a different module and
5052   // thus have a different TOC, the call will be replaced with a call to a stub
5053   // function which saves the current TOC, loads the TOC of the callee and
5054   // branches to the callee. The NOP will be replaced with a load instruction
5055   // which restores the TOC of the caller from the TOC save slot of the current
5056   // stack frame. If caller and callee belong to the same module (and have the
5057   // same TOC), the NOP will remain unchanged.
5058 
5059   MachineFunction &MF = DAG.getMachineFunction();
5060   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
5061       !isPatchPoint) {
5062     if (CallOpc == PPCISD::BCTRL) {
5063       // This is a call through a function pointer.
5064       // Restore the caller TOC from the save area into R2.
5065       // See PrepareCall() for more information about calls through function
5066       // pointers in the 64-bit SVR4 ABI.
5067       // We are using a target-specific load with r2 hard coded, because the
5068       // result of a target-independent load would never go directly into r2,
5069       // since r2 is a reserved register (which prevents the register allocator
5070       // from allocating it), resulting in an additional register being
5071       // allocated and an unnecessary move instruction being generated.
5072       CallOpc = PPCISD::BCTRL_LOAD_TOC;
5073 
5074       EVT PtrVT = getPointerTy(DAG.getDataLayout());
5075       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
5076       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5077       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5078       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
5079 
5080       // The address needs to go after the chain input but before the flag (or
5081       // any other variadic arguments).
5082       Ops.insert(std::next(Ops.begin()), AddTOC);
5083     } else if (CallOpc == PPCISD::CALL &&
5084       !callsShareTOCBase(&MF.getFunction(), Callee, DAG.getTarget())) {
5085       // Otherwise insert NOP for non-local calls.
5086       CallOpc = PPCISD::CALL_NOP;
5087     }
5088   }
5089 
5090   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
5091   InFlag = Chain.getValue(1);
5092 
5093   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
5094                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
5095                              InFlag, dl);
5096   if (!Ins.empty())
5097     InFlag = Chain.getValue(1);
5098 
5099   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
5100                          Ins, dl, DAG, InVals);
5101 }
5102 
5103 SDValue
5104 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
5105                              SmallVectorImpl<SDValue> &InVals) const {
5106   SelectionDAG &DAG                     = CLI.DAG;
5107   SDLoc &dl                             = CLI.DL;
5108   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
5109   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
5110   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
5111   SDValue Chain                         = CLI.Chain;
5112   SDValue Callee                        = CLI.Callee;
5113   bool &isTailCall                      = CLI.IsTailCall;
5114   CallingConv::ID CallConv              = CLI.CallConv;
5115   bool isVarArg                         = CLI.IsVarArg;
5116   bool isPatchPoint                     = CLI.IsPatchPoint;
5117   ImmutableCallSite CS                  = CLI.CS;
5118 
5119   if (isTailCall) {
5120     if (Subtarget.useLongCalls() && !(CS && CS.isMustTailCall()))
5121       isTailCall = false;
5122     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
5123       isTailCall =
5124         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
5125                                                  isVarArg, Outs, Ins, DAG);
5126     else
5127       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
5128                                                      Ins, DAG);
5129     if (isTailCall) {
5130       ++NumTailCalls;
5131       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
5132         ++NumSiblingCalls;
5133 
5134       assert(isa<GlobalAddressSDNode>(Callee) &&
5135              "Callee should be an llvm::Function object.");
5136       LLVM_DEBUG(
5137           const GlobalValue *GV =
5138               cast<GlobalAddressSDNode>(Callee)->getGlobal();
5139           const unsigned Width =
5140               80 - strlen("TCO caller: ") - strlen(", callee linkage: 0, 0");
5141           dbgs() << "TCO caller: "
5142                  << left_justify(DAG.getMachineFunction().getName(), Width)
5143                  << ", callee linkage: " << GV->getVisibility() << ", "
5144                  << GV->getLinkage() << "\n");
5145     }
5146   }
5147 
5148   if (!isTailCall && CS && CS.isMustTailCall())
5149     report_fatal_error("failed to perform tail call elimination on a call "
5150                        "site marked musttail");
5151 
5152   // When long calls (i.e. indirect calls) are always used, calls are always
5153   // made via function pointer. If we have a function name, first translate it
5154   // into a pointer.
5155   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
5156       !isTailCall)
5157     Callee = LowerGlobalAddress(Callee, DAG);
5158 
5159   if (Subtarget.isSVR4ABI()) {
5160     if (Subtarget.isPPC64())
5161       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
5162                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5163                               dl, DAG, InVals, CS);
5164     else
5165       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
5166                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
5167                               dl, DAG, InVals, CS);
5168   }
5169 
5170   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
5171                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
5172                           dl, DAG, InVals, CS);
5173 }
5174 
5175 SDValue PPCTargetLowering::LowerCall_32SVR4(
5176     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5177     bool isTailCall, bool isPatchPoint,
5178     const SmallVectorImpl<ISD::OutputArg> &Outs,
5179     const SmallVectorImpl<SDValue> &OutVals,
5180     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5181     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5182     ImmutableCallSite CS) const {
5183   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
5184   // of the 32-bit SVR4 ABI stack frame layout.
5185 
5186   assert((CallConv == CallingConv::C ||
5187           CallConv == CallingConv::Cold ||
5188           CallConv == CallingConv::Fast) && "Unknown calling convention!");
5189 
5190   unsigned PtrByteSize = 4;
5191 
5192   MachineFunction &MF = DAG.getMachineFunction();
5193 
5194   // Mark this function as potentially containing a function that contains a
5195   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5196   // and restoring the callers stack pointer in this functions epilog. This is
5197   // done because by tail calling the called function might overwrite the value
5198   // in this function's (MF) stack pointer stack slot 0(SP).
5199   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5200       CallConv == CallingConv::Fast)
5201     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5202 
5203   // Count how many bytes are to be pushed on the stack, including the linkage
5204   // area, parameter list area and the part of the local variable space which
5205   // contains copies of aggregates which are passed by value.
5206 
5207   // Assign locations to all of the outgoing arguments.
5208   SmallVector<CCValAssign, 16> ArgLocs;
5209   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
5210 
5211   // Reserve space for the linkage area on the stack.
5212   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
5213                        PtrByteSize);
5214   if (useSoftFloat())
5215     CCInfo.PreAnalyzeCallOperands(Outs);
5216 
5217   if (isVarArg) {
5218     // Handle fixed and variable vector arguments differently.
5219     // Fixed vector arguments go into registers as long as registers are
5220     // available. Variable vector arguments always go into memory.
5221     unsigned NumArgs = Outs.size();
5222 
5223     for (unsigned i = 0; i != NumArgs; ++i) {
5224       MVT ArgVT = Outs[i].VT;
5225       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
5226       bool Result;
5227 
5228       if (Outs[i].IsFixed) {
5229         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5230                                CCInfo);
5231       } else {
5232         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5233                                       ArgFlags, CCInfo);
5234       }
5235 
5236       if (Result) {
5237 #ifndef NDEBUG
5238         errs() << "Call operand #" << i << " has unhandled type "
5239              << EVT(ArgVT).getEVTString() << "\n";
5240 #endif
5241         llvm_unreachable(nullptr);
5242       }
5243     }
5244   } else {
5245     // All arguments are treated the same.
5246     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5247   }
5248   CCInfo.clearWasPPCF128();
5249 
5250   // Assign locations to all of the outgoing aggregate by value arguments.
5251   SmallVector<CCValAssign, 16> ByValArgLocs;
5252   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5253 
5254   // Reserve stack space for the allocations in CCInfo.
5255   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5256 
5257   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5258 
5259   // Size of the linkage area, parameter list area and the part of the local
5260   // space variable where copies of aggregates which are passed by value are
5261   // stored.
5262   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5263 
5264   // Calculate by how many bytes the stack has to be adjusted in case of tail
5265   // call optimization.
5266   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5267 
5268   // Adjust the stack pointer for the new arguments...
5269   // These operations are automatically eliminated by the prolog/epilog pass
5270   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5271   SDValue CallSeqStart = Chain;
5272 
5273   // Load the return address and frame pointer so it can be moved somewhere else
5274   // later.
5275   SDValue LROp, FPOp;
5276   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5277 
5278   // Set up a copy of the stack pointer for use loading and storing any
5279   // arguments that may not fit in the registers available for argument
5280   // passing.
5281   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5282 
5283   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5284   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5285   SmallVector<SDValue, 8> MemOpChains;
5286 
5287   bool seenFloatArg = false;
5288   // Walk the register/memloc assignments, inserting copies/loads.
5289   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5290        i != e;
5291        ++i) {
5292     CCValAssign &VA = ArgLocs[i];
5293     SDValue Arg = OutVals[i];
5294     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5295 
5296     if (Flags.isByVal()) {
5297       // Argument is an aggregate which is passed by value, thus we need to
5298       // create a copy of it in the local variable space of the current stack
5299       // frame (which is the stack frame of the caller) and pass the address of
5300       // this copy to the callee.
5301       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5302       CCValAssign &ByValVA = ByValArgLocs[j++];
5303       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5304 
5305       // Memory reserved in the local variable space of the callers stack frame.
5306       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5307 
5308       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5309       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5310                            StackPtr, PtrOff);
5311 
5312       // Create a copy of the argument in the local area of the current
5313       // stack frame.
5314       SDValue MemcpyCall =
5315         CreateCopyOfByValArgument(Arg, PtrOff,
5316                                   CallSeqStart.getNode()->getOperand(0),
5317                                   Flags, DAG, dl);
5318 
5319       // This must go outside the CALLSEQ_START..END.
5320       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5321                                                      SDLoc(MemcpyCall));
5322       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5323                              NewCallSeqStart.getNode());
5324       Chain = CallSeqStart = NewCallSeqStart;
5325 
5326       // Pass the address of the aggregate copy on the stack either in a
5327       // physical register or in the parameter list area of the current stack
5328       // frame to the callee.
5329       Arg = PtrOff;
5330     }
5331 
5332     if (VA.isRegLoc()) {
5333       if (Arg.getValueType() == MVT::i1)
5334         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5335 
5336       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5337       // Put argument in a physical register.
5338       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5339     } else {
5340       // Put argument in the parameter list area of the current stack frame.
5341       assert(VA.isMemLoc());
5342       unsigned LocMemOffset = VA.getLocMemOffset();
5343 
5344       if (!isTailCall) {
5345         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5346         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5347                              StackPtr, PtrOff);
5348 
5349         MemOpChains.push_back(
5350             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5351       } else {
5352         // Calculate and remember argument location.
5353         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5354                                  TailCallArguments);
5355       }
5356     }
5357   }
5358 
5359   if (!MemOpChains.empty())
5360     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5361 
5362   // Build a sequence of copy-to-reg nodes chained together with token chain
5363   // and flag operands which copy the outgoing args into the appropriate regs.
5364   SDValue InFlag;
5365   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5366     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5367                              RegsToPass[i].second, InFlag);
5368     InFlag = Chain.getValue(1);
5369   }
5370 
5371   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5372   // registers.
5373   if (isVarArg) {
5374     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5375     SDValue Ops[] = { Chain, InFlag };
5376 
5377     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5378                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5379 
5380     InFlag = Chain.getValue(1);
5381   }
5382 
5383   if (isTailCall)
5384     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5385                     TailCallArguments);
5386 
5387   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5388                     /* unused except on PPC64 ELFv1 */ false, DAG,
5389                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5390                     NumBytes, Ins, InVals, CS);
5391 }
5392 
5393 // Copy an argument into memory, being careful to do this outside the
5394 // call sequence for the call to which the argument belongs.
5395 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5396     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5397     SelectionDAG &DAG, const SDLoc &dl) const {
5398   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5399                         CallSeqStart.getNode()->getOperand(0),
5400                         Flags, DAG, dl);
5401   // The MEMCPY must go outside the CALLSEQ_START..END.
5402   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5403   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5404                                                  SDLoc(MemcpyCall));
5405   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5406                          NewCallSeqStart.getNode());
5407   return NewCallSeqStart;
5408 }
5409 
5410 SDValue PPCTargetLowering::LowerCall_64SVR4(
5411     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5412     bool isTailCall, bool isPatchPoint,
5413     const SmallVectorImpl<ISD::OutputArg> &Outs,
5414     const SmallVectorImpl<SDValue> &OutVals,
5415     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5416     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5417     ImmutableCallSite CS) const {
5418   bool isELFv2ABI = Subtarget.isELFv2ABI();
5419   bool isLittleEndian = Subtarget.isLittleEndian();
5420   unsigned NumOps = Outs.size();
5421   bool hasNest = false;
5422   bool IsSibCall = false;
5423 
5424   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5425   unsigned PtrByteSize = 8;
5426 
5427   MachineFunction &MF = DAG.getMachineFunction();
5428 
5429   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5430     IsSibCall = true;
5431 
5432   // Mark this function as potentially containing a function that contains a
5433   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5434   // and restoring the callers stack pointer in this functions epilog. This is
5435   // done because by tail calling the called function might overwrite the value
5436   // in this function's (MF) stack pointer stack slot 0(SP).
5437   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5438       CallConv == CallingConv::Fast)
5439     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5440 
5441   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5442          "fastcc not supported on varargs functions");
5443 
5444   // Count how many bytes are to be pushed on the stack, including the linkage
5445   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5446   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5447   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5448   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5449   unsigned NumBytes = LinkageSize;
5450   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5451   unsigned &QFPR_idx = FPR_idx;
5452 
5453   static const MCPhysReg GPR[] = {
5454     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5455     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5456   };
5457   static const MCPhysReg VR[] = {
5458     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5459     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5460   };
5461 
5462   const unsigned NumGPRs = array_lengthof(GPR);
5463   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5464   const unsigned NumVRs  = array_lengthof(VR);
5465   const unsigned NumQFPRs = NumFPRs;
5466 
5467   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5468   // can be passed to the callee in registers.
5469   // For the fast calling convention, there is another check below.
5470   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5471   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5472   if (!HasParameterArea) {
5473     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5474     unsigned AvailableFPRs = NumFPRs;
5475     unsigned AvailableVRs = NumVRs;
5476     unsigned NumBytesTmp = NumBytes;
5477     for (unsigned i = 0; i != NumOps; ++i) {
5478       if (Outs[i].Flags.isNest()) continue;
5479       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5480                                 PtrByteSize, LinkageSize, ParamAreaSize,
5481                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5482                                 Subtarget.hasQPX()))
5483         HasParameterArea = true;
5484     }
5485   }
5486 
5487   // When using the fast calling convention, we don't provide backing for
5488   // arguments that will be in registers.
5489   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5490 
5491   // Avoid allocating parameter area for fastcc functions if all the arguments
5492   // can be passed in the registers.
5493   if (CallConv == CallingConv::Fast)
5494     HasParameterArea = false;
5495 
5496   // Add up all the space actually used.
5497   for (unsigned i = 0; i != NumOps; ++i) {
5498     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5499     EVT ArgVT = Outs[i].VT;
5500     EVT OrigVT = Outs[i].ArgVT;
5501 
5502     if (Flags.isNest())
5503       continue;
5504 
5505     if (CallConv == CallingConv::Fast) {
5506       if (Flags.isByVal()) {
5507         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5508         if (NumGPRsUsed > NumGPRs)
5509           HasParameterArea = true;
5510       } else {
5511         switch (ArgVT.getSimpleVT().SimpleTy) {
5512         default: llvm_unreachable("Unexpected ValueType for argument!");
5513         case MVT::i1:
5514         case MVT::i32:
5515         case MVT::i64:
5516           if (++NumGPRsUsed <= NumGPRs)
5517             continue;
5518           break;
5519         case MVT::v4i32:
5520         case MVT::v8i16:
5521         case MVT::v16i8:
5522         case MVT::v2f64:
5523         case MVT::v2i64:
5524         case MVT::v1i128:
5525           if (++NumVRsUsed <= NumVRs)
5526             continue;
5527           break;
5528         case MVT::v4f32:
5529           // When using QPX, this is handled like a FP register, otherwise, it
5530           // is an Altivec register.
5531           if (Subtarget.hasQPX()) {
5532             if (++NumFPRsUsed <= NumFPRs)
5533               continue;
5534           } else {
5535             if (++NumVRsUsed <= NumVRs)
5536               continue;
5537           }
5538           break;
5539         case MVT::f32:
5540         case MVT::f64:
5541         case MVT::v4f64: // QPX
5542         case MVT::v4i1:  // QPX
5543           if (++NumFPRsUsed <= NumFPRs)
5544             continue;
5545           break;
5546         }
5547         HasParameterArea = true;
5548       }
5549     }
5550 
5551     /* Respect alignment of argument on the stack.  */
5552     unsigned Align =
5553       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5554     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5555 
5556     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5557     if (Flags.isInConsecutiveRegsLast())
5558       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5559   }
5560 
5561   unsigned NumBytesActuallyUsed = NumBytes;
5562 
5563   // In the old ELFv1 ABI,
5564   // the prolog code of the callee may store up to 8 GPR argument registers to
5565   // the stack, allowing va_start to index over them in memory if its varargs.
5566   // Because we cannot tell if this is needed on the caller side, we have to
5567   // conservatively assume that it is needed.  As such, make sure we have at
5568   // least enough stack space for the caller to store the 8 GPRs.
5569   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5570   // really requires memory operands, e.g. a vararg function.
5571   if (HasParameterArea)
5572     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5573   else
5574     NumBytes = LinkageSize;
5575 
5576   // Tail call needs the stack to be aligned.
5577   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5578       CallConv == CallingConv::Fast)
5579     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5580 
5581   int SPDiff = 0;
5582 
5583   // Calculate by how many bytes the stack has to be adjusted in case of tail
5584   // call optimization.
5585   if (!IsSibCall)
5586     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5587 
5588   // To protect arguments on the stack from being clobbered in a tail call,
5589   // force all the loads to happen before doing any other lowering.
5590   if (isTailCall)
5591     Chain = DAG.getStackArgumentTokenFactor(Chain);
5592 
5593   // Adjust the stack pointer for the new arguments...
5594   // These operations are automatically eliminated by the prolog/epilog pass
5595   if (!IsSibCall)
5596     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5597   SDValue CallSeqStart = Chain;
5598 
5599   // Load the return address and frame pointer so it can be move somewhere else
5600   // later.
5601   SDValue LROp, FPOp;
5602   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5603 
5604   // Set up a copy of the stack pointer for use loading and storing any
5605   // arguments that may not fit in the registers available for argument
5606   // passing.
5607   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5608 
5609   // Figure out which arguments are going to go in registers, and which in
5610   // memory.  Also, if this is a vararg function, floating point operations
5611   // must be stored to our stack, and loaded into integer regs as well, if
5612   // any integer regs are available for argument passing.
5613   unsigned ArgOffset = LinkageSize;
5614 
5615   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5616   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5617 
5618   SmallVector<SDValue, 8> MemOpChains;
5619   for (unsigned i = 0; i != NumOps; ++i) {
5620     SDValue Arg = OutVals[i];
5621     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5622     EVT ArgVT = Outs[i].VT;
5623     EVT OrigVT = Outs[i].ArgVT;
5624 
5625     // PtrOff will be used to store the current argument to the stack if a
5626     // register cannot be found for it.
5627     SDValue PtrOff;
5628 
5629     // We re-align the argument offset for each argument, except when using the
5630     // fast calling convention, when we need to make sure we do that only when
5631     // we'll actually use a stack slot.
5632     auto ComputePtrOff = [&]() {
5633       /* Respect alignment of argument on the stack.  */
5634       unsigned Align =
5635         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5636       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5637 
5638       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5639 
5640       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5641     };
5642 
5643     if (CallConv != CallingConv::Fast) {
5644       ComputePtrOff();
5645 
5646       /* Compute GPR index associated with argument offset.  */
5647       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5648       GPR_idx = std::min(GPR_idx, NumGPRs);
5649     }
5650 
5651     // Promote integers to 64-bit values.
5652     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5653       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5654       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5655       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5656     }
5657 
5658     // FIXME memcpy is used way more than necessary.  Correctness first.
5659     // Note: "by value" is code for passing a structure by value, not
5660     // basic types.
5661     if (Flags.isByVal()) {
5662       // Note: Size includes alignment padding, so
5663       //   struct x { short a; char b; }
5664       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5665       // These are the proper values we need for right-justifying the
5666       // aggregate in a parameter register.
5667       unsigned Size = Flags.getByValSize();
5668 
5669       // An empty aggregate parameter takes up no storage and no
5670       // registers.
5671       if (Size == 0)
5672         continue;
5673 
5674       if (CallConv == CallingConv::Fast)
5675         ComputePtrOff();
5676 
5677       // All aggregates smaller than 8 bytes must be passed right-justified.
5678       if (Size==1 || Size==2 || Size==4) {
5679         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5680         if (GPR_idx != NumGPRs) {
5681           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5682                                         MachinePointerInfo(), VT);
5683           MemOpChains.push_back(Load.getValue(1));
5684           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5685 
5686           ArgOffset += PtrByteSize;
5687           continue;
5688         }
5689       }
5690 
5691       if (GPR_idx == NumGPRs && Size < 8) {
5692         SDValue AddPtr = PtrOff;
5693         if (!isLittleEndian) {
5694           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5695                                           PtrOff.getValueType());
5696           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5697         }
5698         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5699                                                           CallSeqStart,
5700                                                           Flags, DAG, dl);
5701         ArgOffset += PtrByteSize;
5702         continue;
5703       }
5704       // Copy entire object into memory.  There are cases where gcc-generated
5705       // code assumes it is there, even if it could be put entirely into
5706       // registers.  (This is not what the doc says.)
5707 
5708       // FIXME: The above statement is likely due to a misunderstanding of the
5709       // documents.  All arguments must be copied into the parameter area BY
5710       // THE CALLEE in the event that the callee takes the address of any
5711       // formal argument.  That has not yet been implemented.  However, it is
5712       // reasonable to use the stack area as a staging area for the register
5713       // load.
5714 
5715       // Skip this for small aggregates, as we will use the same slot for a
5716       // right-justified copy, below.
5717       if (Size >= 8)
5718         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5719                                                           CallSeqStart,
5720                                                           Flags, DAG, dl);
5721 
5722       // When a register is available, pass a small aggregate right-justified.
5723       if (Size < 8 && GPR_idx != NumGPRs) {
5724         // The easiest way to get this right-justified in a register
5725         // is to copy the structure into the rightmost portion of a
5726         // local variable slot, then load the whole slot into the
5727         // register.
5728         // FIXME: The memcpy seems to produce pretty awful code for
5729         // small aggregates, particularly for packed ones.
5730         // FIXME: It would be preferable to use the slot in the
5731         // parameter save area instead of a new local variable.
5732         SDValue AddPtr = PtrOff;
5733         if (!isLittleEndian) {
5734           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5735           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5736         }
5737         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5738                                                           CallSeqStart,
5739                                                           Flags, DAG, dl);
5740 
5741         // Load the slot into the register.
5742         SDValue Load =
5743             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5744         MemOpChains.push_back(Load.getValue(1));
5745         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5746 
5747         // Done with this argument.
5748         ArgOffset += PtrByteSize;
5749         continue;
5750       }
5751 
5752       // For aggregates larger than PtrByteSize, copy the pieces of the
5753       // object that fit into registers from the parameter save area.
5754       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5755         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5756         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5757         if (GPR_idx != NumGPRs) {
5758           SDValue Load =
5759               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5760           MemOpChains.push_back(Load.getValue(1));
5761           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5762           ArgOffset += PtrByteSize;
5763         } else {
5764           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5765           break;
5766         }
5767       }
5768       continue;
5769     }
5770 
5771     switch (Arg.getSimpleValueType().SimpleTy) {
5772     default: llvm_unreachable("Unexpected ValueType for argument!");
5773     case MVT::i1:
5774     case MVT::i32:
5775     case MVT::i64:
5776       if (Flags.isNest()) {
5777         // The 'nest' parameter, if any, is passed in R11.
5778         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5779         hasNest = true;
5780         break;
5781       }
5782 
5783       // These can be scalar arguments or elements of an integer array type
5784       // passed directly.  Clang may use those instead of "byval" aggregate
5785       // types to avoid forcing arguments to memory unnecessarily.
5786       if (GPR_idx != NumGPRs) {
5787         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5788       } else {
5789         if (CallConv == CallingConv::Fast)
5790           ComputePtrOff();
5791 
5792         assert(HasParameterArea &&
5793                "Parameter area must exist to pass an argument in memory.");
5794         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5795                          true, isTailCall, false, MemOpChains,
5796                          TailCallArguments, dl);
5797         if (CallConv == CallingConv::Fast)
5798           ArgOffset += PtrByteSize;
5799       }
5800       if (CallConv != CallingConv::Fast)
5801         ArgOffset += PtrByteSize;
5802       break;
5803     case MVT::f32:
5804     case MVT::f64: {
5805       // These can be scalar arguments or elements of a float array type
5806       // passed directly.  The latter are used to implement ELFv2 homogenous
5807       // float aggregates.
5808 
5809       // Named arguments go into FPRs first, and once they overflow, the
5810       // remaining arguments go into GPRs and then the parameter save area.
5811       // Unnamed arguments for vararg functions always go to GPRs and
5812       // then the parameter save area.  For now, put all arguments to vararg
5813       // routines always in both locations (FPR *and* GPR or stack slot).
5814       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5815       bool NeededLoad = false;
5816 
5817       // First load the argument into the next available FPR.
5818       if (FPR_idx != NumFPRs)
5819         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5820 
5821       // Next, load the argument into GPR or stack slot if needed.
5822       if (!NeedGPROrStack)
5823         ;
5824       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5825         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5826         // once we support fp <-> gpr moves.
5827 
5828         // In the non-vararg case, this can only ever happen in the
5829         // presence of f32 array types, since otherwise we never run
5830         // out of FPRs before running out of GPRs.
5831         SDValue ArgVal;
5832 
5833         // Double values are always passed in a single GPR.
5834         if (Arg.getValueType() != MVT::f32) {
5835           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5836 
5837         // Non-array float values are extended and passed in a GPR.
5838         } else if (!Flags.isInConsecutiveRegs()) {
5839           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5840           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5841 
5842         // If we have an array of floats, we collect every odd element
5843         // together with its predecessor into one GPR.
5844         } else if (ArgOffset % PtrByteSize != 0) {
5845           SDValue Lo, Hi;
5846           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5847           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5848           if (!isLittleEndian)
5849             std::swap(Lo, Hi);
5850           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5851 
5852         // The final element, if even, goes into the first half of a GPR.
5853         } else if (Flags.isInConsecutiveRegsLast()) {
5854           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5855           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5856           if (!isLittleEndian)
5857             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5858                                  DAG.getConstant(32, dl, MVT::i32));
5859 
5860         // Non-final even elements are skipped; they will be handled
5861         // together the with subsequent argument on the next go-around.
5862         } else
5863           ArgVal = SDValue();
5864 
5865         if (ArgVal.getNode())
5866           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5867       } else {
5868         if (CallConv == CallingConv::Fast)
5869           ComputePtrOff();
5870 
5871         // Single-precision floating-point values are mapped to the
5872         // second (rightmost) word of the stack doubleword.
5873         if (Arg.getValueType() == MVT::f32 &&
5874             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5875           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5876           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5877         }
5878 
5879         assert(HasParameterArea &&
5880                "Parameter area must exist to pass an argument in memory.");
5881         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5882                          true, isTailCall, false, MemOpChains,
5883                          TailCallArguments, dl);
5884 
5885         NeededLoad = true;
5886       }
5887       // When passing an array of floats, the array occupies consecutive
5888       // space in the argument area; only round up to the next doubleword
5889       // at the end of the array.  Otherwise, each float takes 8 bytes.
5890       if (CallConv != CallingConv::Fast || NeededLoad) {
5891         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5892                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5893         if (Flags.isInConsecutiveRegsLast())
5894           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5895       }
5896       break;
5897     }
5898     case MVT::v4f32:
5899     case MVT::v4i32:
5900     case MVT::v8i16:
5901     case MVT::v16i8:
5902     case MVT::v2f64:
5903     case MVT::v2i64:
5904     case MVT::v1i128:
5905       if (!Subtarget.hasQPX()) {
5906       // These can be scalar arguments or elements of a vector array type
5907       // passed directly.  The latter are used to implement ELFv2 homogenous
5908       // vector aggregates.
5909 
5910       // For a varargs call, named arguments go into VRs or on the stack as
5911       // usual; unnamed arguments always go to the stack or the corresponding
5912       // GPRs when within range.  For now, we always put the value in both
5913       // locations (or even all three).
5914       if (isVarArg) {
5915         assert(HasParameterArea &&
5916                "Parameter area must exist if we have a varargs call.");
5917         // We could elide this store in the case where the object fits
5918         // entirely in R registers.  Maybe later.
5919         SDValue Store =
5920             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5921         MemOpChains.push_back(Store);
5922         if (VR_idx != NumVRs) {
5923           SDValue Load =
5924               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5925           MemOpChains.push_back(Load.getValue(1));
5926           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5927         }
5928         ArgOffset += 16;
5929         for (unsigned i=0; i<16; i+=PtrByteSize) {
5930           if (GPR_idx == NumGPRs)
5931             break;
5932           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5933                                    DAG.getConstant(i, dl, PtrVT));
5934           SDValue Load =
5935               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5936           MemOpChains.push_back(Load.getValue(1));
5937           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5938         }
5939         break;
5940       }
5941 
5942       // Non-varargs Altivec params go into VRs or on the stack.
5943       if (VR_idx != NumVRs) {
5944         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5945       } else {
5946         if (CallConv == CallingConv::Fast)
5947           ComputePtrOff();
5948 
5949         assert(HasParameterArea &&
5950                "Parameter area must exist to pass an argument in memory.");
5951         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5952                          true, isTailCall, true, MemOpChains,
5953                          TailCallArguments, dl);
5954         if (CallConv == CallingConv::Fast)
5955           ArgOffset += 16;
5956       }
5957 
5958       if (CallConv != CallingConv::Fast)
5959         ArgOffset += 16;
5960       break;
5961       } // not QPX
5962 
5963       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5964              "Invalid QPX parameter type");
5965 
5966       /* fall through */
5967     case MVT::v4f64:
5968     case MVT::v4i1: {
5969       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5970       if (isVarArg) {
5971         assert(HasParameterArea &&
5972                "Parameter area must exist if we have a varargs call.");
5973         // We could elide this store in the case where the object fits
5974         // entirely in R registers.  Maybe later.
5975         SDValue Store =
5976             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5977         MemOpChains.push_back(Store);
5978         if (QFPR_idx != NumQFPRs) {
5979           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5980                                      PtrOff, MachinePointerInfo());
5981           MemOpChains.push_back(Load.getValue(1));
5982           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5983         }
5984         ArgOffset += (IsF32 ? 16 : 32);
5985         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5986           if (GPR_idx == NumGPRs)
5987             break;
5988           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5989                                    DAG.getConstant(i, dl, PtrVT));
5990           SDValue Load =
5991               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5992           MemOpChains.push_back(Load.getValue(1));
5993           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5994         }
5995         break;
5996       }
5997 
5998       // Non-varargs QPX params go into registers or on the stack.
5999       if (QFPR_idx != NumQFPRs) {
6000         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
6001       } else {
6002         if (CallConv == CallingConv::Fast)
6003           ComputePtrOff();
6004 
6005         assert(HasParameterArea &&
6006                "Parameter area must exist to pass an argument in memory.");
6007         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6008                          true, isTailCall, true, MemOpChains,
6009                          TailCallArguments, dl);
6010         if (CallConv == CallingConv::Fast)
6011           ArgOffset += (IsF32 ? 16 : 32);
6012       }
6013 
6014       if (CallConv != CallingConv::Fast)
6015         ArgOffset += (IsF32 ? 16 : 32);
6016       break;
6017       }
6018     }
6019   }
6020 
6021   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
6022          "mismatch in size of parameter area");
6023   (void)NumBytesActuallyUsed;
6024 
6025   if (!MemOpChains.empty())
6026     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6027 
6028   // Check if this is an indirect call (MTCTR/BCTRL).
6029   // See PrepareCall() for more information about calls through function
6030   // pointers in the 64-bit SVR4 ABI.
6031   if (!isTailCall && !isPatchPoint &&
6032       !isFunctionGlobalAddress(Callee) &&
6033       !isa<ExternalSymbolSDNode>(Callee)) {
6034     // Load r2 into a virtual register and store it to the TOC save area.
6035     setUsesTOCBasePtr(DAG);
6036     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
6037     // TOC save area offset.
6038     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
6039     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
6040     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6041     Chain = DAG.getStore(
6042         Val.getValue(1), dl, Val, AddPtr,
6043         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
6044     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
6045     // This does not mean the MTCTR instruction must use R12; it's easier
6046     // to model this as an extra parameter, so do that.
6047     if (isELFv2ABI && !isPatchPoint)
6048       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
6049   }
6050 
6051   // Build a sequence of copy-to-reg nodes chained together with token chain
6052   // and flag operands which copy the outgoing args into the appropriate regs.
6053   SDValue InFlag;
6054   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6055     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6056                              RegsToPass[i].second, InFlag);
6057     InFlag = Chain.getValue(1);
6058   }
6059 
6060   if (isTailCall && !IsSibCall)
6061     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6062                     TailCallArguments);
6063 
6064   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
6065                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
6066                     SPDiff, NumBytes, Ins, InVals, CS);
6067 }
6068 
6069 SDValue PPCTargetLowering::LowerCall_Darwin(
6070     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
6071     bool isTailCall, bool isPatchPoint,
6072     const SmallVectorImpl<ISD::OutputArg> &Outs,
6073     const SmallVectorImpl<SDValue> &OutVals,
6074     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
6075     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
6076     ImmutableCallSite CS) const {
6077   unsigned NumOps = Outs.size();
6078 
6079   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6080   bool isPPC64 = PtrVT == MVT::i64;
6081   unsigned PtrByteSize = isPPC64 ? 8 : 4;
6082 
6083   MachineFunction &MF = DAG.getMachineFunction();
6084 
6085   // Mark this function as potentially containing a function that contains a
6086   // tail call. As a consequence the frame pointer will be used for dynamicalloc
6087   // and restoring the callers stack pointer in this functions epilog. This is
6088   // done because by tail calling the called function might overwrite the value
6089   // in this function's (MF) stack pointer stack slot 0(SP).
6090   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6091       CallConv == CallingConv::Fast)
6092     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
6093 
6094   // Count how many bytes are to be pushed on the stack, including the linkage
6095   // area, and parameter passing area.  We start with 24/48 bytes, which is
6096   // prereserved space for [SP][CR][LR][3 x unused].
6097   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
6098   unsigned NumBytes = LinkageSize;
6099 
6100   // Add up all the space actually used.
6101   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
6102   // they all go in registers, but we must reserve stack space for them for
6103   // possible use by the caller.  In varargs or 64-bit calls, parameters are
6104   // assigned stack space in order, with padding so Altivec parameters are
6105   // 16-byte aligned.
6106   unsigned nAltivecParamsAtEnd = 0;
6107   for (unsigned i = 0; i != NumOps; ++i) {
6108     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6109     EVT ArgVT = Outs[i].VT;
6110     // Varargs Altivec parameters are padded to a 16 byte boundary.
6111     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
6112         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
6113         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
6114       if (!isVarArg && !isPPC64) {
6115         // Non-varargs Altivec parameters go after all the non-Altivec
6116         // parameters; handle those later so we know how much padding we need.
6117         nAltivecParamsAtEnd++;
6118         continue;
6119       }
6120       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
6121       NumBytes = ((NumBytes+15)/16)*16;
6122     }
6123     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
6124   }
6125 
6126   // Allow for Altivec parameters at the end, if needed.
6127   if (nAltivecParamsAtEnd) {
6128     NumBytes = ((NumBytes+15)/16)*16;
6129     NumBytes += 16*nAltivecParamsAtEnd;
6130   }
6131 
6132   // The prolog code of the callee may store up to 8 GPR argument registers to
6133   // the stack, allowing va_start to index over them in memory if its varargs.
6134   // Because we cannot tell if this is needed on the caller side, we have to
6135   // conservatively assume that it is needed.  As such, make sure we have at
6136   // least enough stack space for the caller to store the 8 GPRs.
6137   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
6138 
6139   // Tail call needs the stack to be aligned.
6140   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
6141       CallConv == CallingConv::Fast)
6142     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
6143 
6144   // Calculate by how many bytes the stack has to be adjusted in case of tail
6145   // call optimization.
6146   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
6147 
6148   // To protect arguments on the stack from being clobbered in a tail call,
6149   // force all the loads to happen before doing any other lowering.
6150   if (isTailCall)
6151     Chain = DAG.getStackArgumentTokenFactor(Chain);
6152 
6153   // Adjust the stack pointer for the new arguments...
6154   // These operations are automatically eliminated by the prolog/epilog pass
6155   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
6156   SDValue CallSeqStart = Chain;
6157 
6158   // Load the return address and frame pointer so it can be move somewhere else
6159   // later.
6160   SDValue LROp, FPOp;
6161   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
6162 
6163   // Set up a copy of the stack pointer for use loading and storing any
6164   // arguments that may not fit in the registers available for argument
6165   // passing.
6166   SDValue StackPtr;
6167   if (isPPC64)
6168     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
6169   else
6170     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
6171 
6172   // Figure out which arguments are going to go in registers, and which in
6173   // memory.  Also, if this is a vararg function, floating point operations
6174   // must be stored to our stack, and loaded into integer regs as well, if
6175   // any integer regs are available for argument passing.
6176   unsigned ArgOffset = LinkageSize;
6177   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
6178 
6179   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
6180     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
6181     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
6182   };
6183   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
6184     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
6185     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
6186   };
6187   static const MCPhysReg VR[] = {
6188     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
6189     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
6190   };
6191   const unsigned NumGPRs = array_lengthof(GPR_32);
6192   const unsigned NumFPRs = 13;
6193   const unsigned NumVRs  = array_lengthof(VR);
6194 
6195   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
6196 
6197   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
6198   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
6199 
6200   SmallVector<SDValue, 8> MemOpChains;
6201   for (unsigned i = 0; i != NumOps; ++i) {
6202     SDValue Arg = OutVals[i];
6203     ISD::ArgFlagsTy Flags = Outs[i].Flags;
6204 
6205     // PtrOff will be used to store the current argument to the stack if a
6206     // register cannot be found for it.
6207     SDValue PtrOff;
6208 
6209     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
6210 
6211     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
6212 
6213     // On PPC64, promote integers to 64-bit values.
6214     if (isPPC64 && Arg.getValueType() == MVT::i32) {
6215       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
6216       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6217       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
6218     }
6219 
6220     // FIXME memcpy is used way more than necessary.  Correctness first.
6221     // Note: "by value" is code for passing a structure by value, not
6222     // basic types.
6223     if (Flags.isByVal()) {
6224       unsigned Size = Flags.getByValSize();
6225       // Very small objects are passed right-justified.  Everything else is
6226       // passed left-justified.
6227       if (Size==1 || Size==2) {
6228         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
6229         if (GPR_idx != NumGPRs) {
6230           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
6231                                         MachinePointerInfo(), VT);
6232           MemOpChains.push_back(Load.getValue(1));
6233           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6234 
6235           ArgOffset += PtrByteSize;
6236         } else {
6237           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6238                                           PtrOff.getValueType());
6239           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6240           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6241                                                             CallSeqStart,
6242                                                             Flags, DAG, dl);
6243           ArgOffset += PtrByteSize;
6244         }
6245         continue;
6246       }
6247       // Copy entire object into memory.  There are cases where gcc-generated
6248       // code assumes it is there, even if it could be put entirely into
6249       // registers.  (This is not what the doc says.)
6250       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6251                                                         CallSeqStart,
6252                                                         Flags, DAG, dl);
6253 
6254       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6255       // copy the pieces of the object that fit into registers from the
6256       // parameter save area.
6257       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6258         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6259         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6260         if (GPR_idx != NumGPRs) {
6261           SDValue Load =
6262               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6263           MemOpChains.push_back(Load.getValue(1));
6264           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6265           ArgOffset += PtrByteSize;
6266         } else {
6267           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6268           break;
6269         }
6270       }
6271       continue;
6272     }
6273 
6274     switch (Arg.getSimpleValueType().SimpleTy) {
6275     default: llvm_unreachable("Unexpected ValueType for argument!");
6276     case MVT::i1:
6277     case MVT::i32:
6278     case MVT::i64:
6279       if (GPR_idx != NumGPRs) {
6280         if (Arg.getValueType() == MVT::i1)
6281           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6282 
6283         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6284       } else {
6285         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6286                          isPPC64, isTailCall, false, MemOpChains,
6287                          TailCallArguments, dl);
6288       }
6289       ArgOffset += PtrByteSize;
6290       break;
6291     case MVT::f32:
6292     case MVT::f64:
6293       if (FPR_idx != NumFPRs) {
6294         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6295 
6296         if (isVarArg) {
6297           SDValue Store =
6298               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6299           MemOpChains.push_back(Store);
6300 
6301           // Float varargs are always shadowed in available integer registers
6302           if (GPR_idx != NumGPRs) {
6303             SDValue Load =
6304                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6305             MemOpChains.push_back(Load.getValue(1));
6306             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6307           }
6308           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6309             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6310             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6311             SDValue Load =
6312                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6313             MemOpChains.push_back(Load.getValue(1));
6314             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6315           }
6316         } else {
6317           // If we have any FPRs remaining, we may also have GPRs remaining.
6318           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6319           // GPRs.
6320           if (GPR_idx != NumGPRs)
6321             ++GPR_idx;
6322           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6323               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6324             ++GPR_idx;
6325         }
6326       } else
6327         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6328                          isPPC64, isTailCall, false, MemOpChains,
6329                          TailCallArguments, dl);
6330       if (isPPC64)
6331         ArgOffset += 8;
6332       else
6333         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6334       break;
6335     case MVT::v4f32:
6336     case MVT::v4i32:
6337     case MVT::v8i16:
6338     case MVT::v16i8:
6339       if (isVarArg) {
6340         // These go aligned on the stack, or in the corresponding R registers
6341         // when within range.  The Darwin PPC ABI doc claims they also go in
6342         // V registers; in fact gcc does this only for arguments that are
6343         // prototyped, not for those that match the ...  We do it for all
6344         // arguments, seems to work.
6345         while (ArgOffset % 16 !=0) {
6346           ArgOffset += PtrByteSize;
6347           if (GPR_idx != NumGPRs)
6348             GPR_idx++;
6349         }
6350         // We could elide this store in the case where the object fits
6351         // entirely in R registers.  Maybe later.
6352         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6353                              DAG.getConstant(ArgOffset, dl, PtrVT));
6354         SDValue Store =
6355             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6356         MemOpChains.push_back(Store);
6357         if (VR_idx != NumVRs) {
6358           SDValue Load =
6359               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6360           MemOpChains.push_back(Load.getValue(1));
6361           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6362         }
6363         ArgOffset += 16;
6364         for (unsigned i=0; i<16; i+=PtrByteSize) {
6365           if (GPR_idx == NumGPRs)
6366             break;
6367           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6368                                    DAG.getConstant(i, dl, PtrVT));
6369           SDValue Load =
6370               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6371           MemOpChains.push_back(Load.getValue(1));
6372           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6373         }
6374         break;
6375       }
6376 
6377       // Non-varargs Altivec params generally go in registers, but have
6378       // stack space allocated at the end.
6379       if (VR_idx != NumVRs) {
6380         // Doesn't have GPR space allocated.
6381         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6382       } else if (nAltivecParamsAtEnd==0) {
6383         // We are emitting Altivec params in order.
6384         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6385                          isPPC64, isTailCall, true, MemOpChains,
6386                          TailCallArguments, dl);
6387         ArgOffset += 16;
6388       }
6389       break;
6390     }
6391   }
6392   // If all Altivec parameters fit in registers, as they usually do,
6393   // they get stack space following the non-Altivec parameters.  We
6394   // don't track this here because nobody below needs it.
6395   // If there are more Altivec parameters than fit in registers emit
6396   // the stores here.
6397   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6398     unsigned j = 0;
6399     // Offset is aligned; skip 1st 12 params which go in V registers.
6400     ArgOffset = ((ArgOffset+15)/16)*16;
6401     ArgOffset += 12*16;
6402     for (unsigned i = 0; i != NumOps; ++i) {
6403       SDValue Arg = OutVals[i];
6404       EVT ArgType = Outs[i].VT;
6405       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6406           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6407         if (++j > NumVRs) {
6408           SDValue PtrOff;
6409           // We are emitting Altivec params in order.
6410           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6411                            isPPC64, isTailCall, true, MemOpChains,
6412                            TailCallArguments, dl);
6413           ArgOffset += 16;
6414         }
6415       }
6416     }
6417   }
6418 
6419   if (!MemOpChains.empty())
6420     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6421 
6422   // On Darwin, R12 must contain the address of an indirect callee.  This does
6423   // not mean the MTCTR instruction must use R12; it's easier to model this as
6424   // an extra parameter, so do that.
6425   if (!isTailCall &&
6426       !isFunctionGlobalAddress(Callee) &&
6427       !isa<ExternalSymbolSDNode>(Callee) &&
6428       !isBLACompatibleAddress(Callee, DAG))
6429     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6430                                                    PPC::R12), Callee));
6431 
6432   // Build a sequence of copy-to-reg nodes chained together with token chain
6433   // and flag operands which copy the outgoing args into the appropriate regs.
6434   SDValue InFlag;
6435   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6436     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6437                              RegsToPass[i].second, InFlag);
6438     InFlag = Chain.getValue(1);
6439   }
6440 
6441   if (isTailCall)
6442     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6443                     TailCallArguments);
6444 
6445   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6446                     /* unused except on PPC64 ELFv1 */ false, DAG,
6447                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6448                     NumBytes, Ins, InVals, CS);
6449 }
6450 
6451 bool
6452 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6453                                   MachineFunction &MF, bool isVarArg,
6454                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6455                                   LLVMContext &Context) const {
6456   SmallVector<CCValAssign, 16> RVLocs;
6457   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6458   return CCInfo.CheckReturn(
6459       Outs, (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6460                 ? RetCC_PPC_Cold
6461                 : RetCC_PPC);
6462 }
6463 
6464 SDValue
6465 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6466                                bool isVarArg,
6467                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6468                                const SmallVectorImpl<SDValue> &OutVals,
6469                                const SDLoc &dl, SelectionDAG &DAG) const {
6470   SmallVector<CCValAssign, 16> RVLocs;
6471   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6472                  *DAG.getContext());
6473   CCInfo.AnalyzeReturn(Outs,
6474                        (Subtarget.isSVR4ABI() && CallConv == CallingConv::Cold)
6475                            ? RetCC_PPC_Cold
6476                            : RetCC_PPC);
6477 
6478   SDValue Flag;
6479   SmallVector<SDValue, 4> RetOps(1, Chain);
6480 
6481   // Copy the result values into the output registers.
6482   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6483     CCValAssign &VA = RVLocs[i];
6484     assert(VA.isRegLoc() && "Can only return in registers!");
6485 
6486     SDValue Arg = OutVals[i];
6487 
6488     switch (VA.getLocInfo()) {
6489     default: llvm_unreachable("Unknown loc info!");
6490     case CCValAssign::Full: break;
6491     case CCValAssign::AExt:
6492       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6493       break;
6494     case CCValAssign::ZExt:
6495       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6496       break;
6497     case CCValAssign::SExt:
6498       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6499       break;
6500     }
6501 
6502     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6503     Flag = Chain.getValue(1);
6504     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6505   }
6506 
6507   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6508   const MCPhysReg *I =
6509     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6510   if (I) {
6511     for (; *I; ++I) {
6512 
6513       if (PPC::G8RCRegClass.contains(*I))
6514         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6515       else if (PPC::F8RCRegClass.contains(*I))
6516         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6517       else if (PPC::CRRCRegClass.contains(*I))
6518         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6519       else if (PPC::VRRCRegClass.contains(*I))
6520         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6521       else
6522         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6523     }
6524   }
6525 
6526   RetOps[0] = Chain;  // Update chain.
6527 
6528   // Add the flag if we have it.
6529   if (Flag.getNode())
6530     RetOps.push_back(Flag);
6531 
6532   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6533 }
6534 
6535 SDValue
6536 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6537                                                 SelectionDAG &DAG) const {
6538   SDLoc dl(Op);
6539 
6540   // Get the correct type for integers.
6541   EVT IntVT = Op.getValueType();
6542 
6543   // Get the inputs.
6544   SDValue Chain = Op.getOperand(0);
6545   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6546   // Build a DYNAREAOFFSET node.
6547   SDValue Ops[2] = {Chain, FPSIdx};
6548   SDVTList VTs = DAG.getVTList(IntVT);
6549   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6550 }
6551 
6552 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6553                                              SelectionDAG &DAG) const {
6554   // When we pop the dynamic allocation we need to restore the SP link.
6555   SDLoc dl(Op);
6556 
6557   // Get the correct type for pointers.
6558   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6559 
6560   // Construct the stack pointer operand.
6561   bool isPPC64 = Subtarget.isPPC64();
6562   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6563   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6564 
6565   // Get the operands for the STACKRESTORE.
6566   SDValue Chain = Op.getOperand(0);
6567   SDValue SaveSP = Op.getOperand(1);
6568 
6569   // Load the old link SP.
6570   SDValue LoadLinkSP =
6571       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6572 
6573   // Restore the stack pointer.
6574   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6575 
6576   // Store the old link SP.
6577   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6578 }
6579 
6580 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6581   MachineFunction &MF = DAG.getMachineFunction();
6582   bool isPPC64 = Subtarget.isPPC64();
6583   EVT PtrVT = getPointerTy(MF.getDataLayout());
6584 
6585   // Get current frame pointer save index.  The users of this index will be
6586   // primarily DYNALLOC instructions.
6587   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6588   int RASI = FI->getReturnAddrSaveIndex();
6589 
6590   // If the frame pointer save index hasn't been defined yet.
6591   if (!RASI) {
6592     // Find out what the fix offset of the frame pointer save area.
6593     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6594     // Allocate the frame index for frame pointer save area.
6595     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6596     // Save the result.
6597     FI->setReturnAddrSaveIndex(RASI);
6598   }
6599   return DAG.getFrameIndex(RASI, PtrVT);
6600 }
6601 
6602 SDValue
6603 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6604   MachineFunction &MF = DAG.getMachineFunction();
6605   bool isPPC64 = Subtarget.isPPC64();
6606   EVT PtrVT = getPointerTy(MF.getDataLayout());
6607 
6608   // Get current frame pointer save index.  The users of this index will be
6609   // primarily DYNALLOC instructions.
6610   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6611   int FPSI = FI->getFramePointerSaveIndex();
6612 
6613   // If the frame pointer save index hasn't been defined yet.
6614   if (!FPSI) {
6615     // Find out what the fix offset of the frame pointer save area.
6616     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6617     // Allocate the frame index for frame pointer save area.
6618     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6619     // Save the result.
6620     FI->setFramePointerSaveIndex(FPSI);
6621   }
6622   return DAG.getFrameIndex(FPSI, PtrVT);
6623 }
6624 
6625 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6626                                                    SelectionDAG &DAG) const {
6627   // Get the inputs.
6628   SDValue Chain = Op.getOperand(0);
6629   SDValue Size  = Op.getOperand(1);
6630   SDLoc dl(Op);
6631 
6632   // Get the correct type for pointers.
6633   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6634   // Negate the size.
6635   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6636                                 DAG.getConstant(0, dl, PtrVT), Size);
6637   // Construct a node for the frame pointer save index.
6638   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6639   // Build a DYNALLOC node.
6640   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6641   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6642   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6643 }
6644 
6645 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6646                                                      SelectionDAG &DAG) const {
6647   MachineFunction &MF = DAG.getMachineFunction();
6648 
6649   bool isPPC64 = Subtarget.isPPC64();
6650   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6651 
6652   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6653   return DAG.getFrameIndex(FI, PtrVT);
6654 }
6655 
6656 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6657                                                SelectionDAG &DAG) const {
6658   SDLoc DL(Op);
6659   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6660                      DAG.getVTList(MVT::i32, MVT::Other),
6661                      Op.getOperand(0), Op.getOperand(1));
6662 }
6663 
6664 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6665                                                 SelectionDAG &DAG) const {
6666   SDLoc DL(Op);
6667   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6668                      Op.getOperand(0), Op.getOperand(1));
6669 }
6670 
6671 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6672   if (Op.getValueType().isVector())
6673     return LowerVectorLoad(Op, DAG);
6674 
6675   assert(Op.getValueType() == MVT::i1 &&
6676          "Custom lowering only for i1 loads");
6677 
6678   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6679 
6680   SDLoc dl(Op);
6681   LoadSDNode *LD = cast<LoadSDNode>(Op);
6682 
6683   SDValue Chain = LD->getChain();
6684   SDValue BasePtr = LD->getBasePtr();
6685   MachineMemOperand *MMO = LD->getMemOperand();
6686 
6687   SDValue NewLD =
6688       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6689                      BasePtr, MVT::i8, MMO);
6690   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6691 
6692   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6693   return DAG.getMergeValues(Ops, dl);
6694 }
6695 
6696 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6697   if (Op.getOperand(1).getValueType().isVector())
6698     return LowerVectorStore(Op, DAG);
6699 
6700   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6701          "Custom lowering only for i1 stores");
6702 
6703   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6704 
6705   SDLoc dl(Op);
6706   StoreSDNode *ST = cast<StoreSDNode>(Op);
6707 
6708   SDValue Chain = ST->getChain();
6709   SDValue BasePtr = ST->getBasePtr();
6710   SDValue Value = ST->getValue();
6711   MachineMemOperand *MMO = ST->getMemOperand();
6712 
6713   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6714                       Value);
6715   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6716 }
6717 
6718 // FIXME: Remove this once the ANDI glue bug is fixed:
6719 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6720   assert(Op.getValueType() == MVT::i1 &&
6721          "Custom lowering only for i1 results");
6722 
6723   SDLoc DL(Op);
6724   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6725                      Op.getOperand(0));
6726 }
6727 
6728 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6729 /// possible.
6730 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6731   // Not FP? Not a fsel.
6732   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6733       !Op.getOperand(2).getValueType().isFloatingPoint())
6734     return Op;
6735 
6736   // We might be able to do better than this under some circumstances, but in
6737   // general, fsel-based lowering of select is a finite-math-only optimization.
6738   // For more information, see section F.3 of the 2.06 ISA specification.
6739   if (!DAG.getTarget().Options.NoInfsFPMath ||
6740       !DAG.getTarget().Options.NoNaNsFPMath)
6741     return Op;
6742   // TODO: Propagate flags from the select rather than global settings.
6743   SDNodeFlags Flags;
6744   Flags.setNoInfs(true);
6745   Flags.setNoNaNs(true);
6746 
6747   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6748 
6749   EVT ResVT = Op.getValueType();
6750   EVT CmpVT = Op.getOperand(0).getValueType();
6751   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6752   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6753   SDLoc dl(Op);
6754 
6755   // If the RHS of the comparison is a 0.0, we don't need to do the
6756   // subtraction at all.
6757   SDValue Sel1;
6758   if (isFloatingPointZero(RHS))
6759     switch (CC) {
6760     default: break;       // SETUO etc aren't handled by fsel.
6761     case ISD::SETNE:
6762       std::swap(TV, FV);
6763       LLVM_FALLTHROUGH;
6764     case ISD::SETEQ:
6765       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6766         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6767       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6768       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6769         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6770       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6771                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6772     case ISD::SETULT:
6773     case ISD::SETLT:
6774       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6775       LLVM_FALLTHROUGH;
6776     case ISD::SETOGE:
6777     case ISD::SETGE:
6778       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6779         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6780       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6781     case ISD::SETUGT:
6782     case ISD::SETGT:
6783       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6784       LLVM_FALLTHROUGH;
6785     case ISD::SETOLE:
6786     case ISD::SETLE:
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,
6790                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6791     }
6792 
6793   SDValue Cmp;
6794   switch (CC) {
6795   default: break;       // SETUO etc aren't handled by fsel.
6796   case ISD::SETNE:
6797     std::swap(TV, FV);
6798     LLVM_FALLTHROUGH;
6799   case ISD::SETEQ:
6800     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6801     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6802       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6803     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6804     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6805       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6806     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6807                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6808   case ISD::SETULT:
6809   case ISD::SETLT:
6810     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6811     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6812       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6813     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6814   case ISD::SETOGE:
6815   case ISD::SETGE:
6816     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6817     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6818       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6819     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6820   case ISD::SETUGT:
6821   case ISD::SETGT:
6822     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6823     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6824       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6825     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6826   case ISD::SETOLE:
6827   case ISD::SETLE:
6828     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6829     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6830       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6831     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6832   }
6833   return Op;
6834 }
6835 
6836 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6837                                                SelectionDAG &DAG,
6838                                                const SDLoc &dl) const {
6839   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6840   SDValue Src = Op.getOperand(0);
6841   if (Src.getValueType() == MVT::f32)
6842     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6843 
6844   SDValue Tmp;
6845   switch (Op.getSimpleValueType().SimpleTy) {
6846   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6847   case MVT::i32:
6848     Tmp = DAG.getNode(
6849         Op.getOpcode() == ISD::FP_TO_SINT
6850             ? PPCISD::FCTIWZ
6851             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6852         dl, MVT::f64, Src);
6853     break;
6854   case MVT::i64:
6855     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6856            "i64 FP_TO_UINT is supported only with FPCVT");
6857     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6858                                                         PPCISD::FCTIDUZ,
6859                       dl, MVT::f64, Src);
6860     break;
6861   }
6862 
6863   // Convert the FP value to an int value through memory.
6864   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6865     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6866   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6867   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6868   MachinePointerInfo MPI =
6869       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6870 
6871   // Emit a store to the stack slot.
6872   SDValue Chain;
6873   if (i32Stack) {
6874     MachineFunction &MF = DAG.getMachineFunction();
6875     MachineMemOperand *MMO =
6876       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6877     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6878     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6879               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6880   } else
6881     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6882 
6883   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6884   // add in a bias on big endian.
6885   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6886     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6887                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6888     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6889   }
6890 
6891   RLI.Chain = Chain;
6892   RLI.Ptr = FIPtr;
6893   RLI.MPI = MPI;
6894 }
6895 
6896 /// Custom lowers floating point to integer conversions to use
6897 /// the direct move instructions available in ISA 2.07 to avoid the
6898 /// need for load/store combinations.
6899 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6900                                                     SelectionDAG &DAG,
6901                                                     const SDLoc &dl) const {
6902   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6903   SDValue Src = Op.getOperand(0);
6904 
6905   if (Src.getValueType() == MVT::f32)
6906     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6907 
6908   SDValue Tmp;
6909   switch (Op.getSimpleValueType().SimpleTy) {
6910   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6911   case MVT::i32:
6912     Tmp = DAG.getNode(
6913         Op.getOpcode() == ISD::FP_TO_SINT
6914             ? PPCISD::FCTIWZ
6915             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6916         dl, MVT::f64, Src);
6917     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6918     break;
6919   case MVT::i64:
6920     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6921            "i64 FP_TO_UINT is supported only with FPCVT");
6922     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6923                                                         PPCISD::FCTIDUZ,
6924                       dl, MVT::f64, Src);
6925     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6926     break;
6927   }
6928   return Tmp;
6929 }
6930 
6931 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6932                                           const SDLoc &dl) const {
6933 
6934   // FP to INT conversions are legal for f128.
6935   if (EnableQuadPrecision && (Op->getOperand(0).getValueType() == MVT::f128))
6936     return Op;
6937 
6938   // Expand ppcf128 to i32 by hand for the benefit of llvm-gcc bootstrap on
6939   // PPC (the libcall is not available).
6940   if (Op.getOperand(0).getValueType() == MVT::ppcf128) {
6941     if (Op.getValueType() == MVT::i32) {
6942       if (Op.getOpcode() == ISD::FP_TO_SINT) {
6943         SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6944                                  MVT::f64, Op.getOperand(0),
6945                                  DAG.getIntPtrConstant(0, dl));
6946         SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6947                                  MVT::f64, Op.getOperand(0),
6948                                  DAG.getIntPtrConstant(1, dl));
6949 
6950         // Add the two halves of the long double in round-to-zero mode.
6951         SDValue Res = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6952 
6953         // Now use a smaller FP_TO_SINT.
6954         return DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Res);
6955       }
6956       if (Op.getOpcode() == ISD::FP_TO_UINT) {
6957         const uint64_t TwoE31[] = {0x41e0000000000000LL, 0};
6958         APFloat APF = APFloat(APFloat::PPCDoubleDouble(), APInt(128, TwoE31));
6959         SDValue Tmp = DAG.getConstantFP(APF, dl, MVT::ppcf128);
6960         //  X>=2^31 ? (int)(X-2^31)+0x80000000 : (int)X
6961         // FIXME: generated code sucks.
6962         // TODO: Are there fast-math-flags to propagate to this FSUB?
6963         SDValue True = DAG.getNode(ISD::FSUB, dl, MVT::ppcf128,
6964                                    Op.getOperand(0), Tmp);
6965         True = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, True);
6966         True = DAG.getNode(ISD::ADD, dl, MVT::i32, True,
6967                            DAG.getConstant(0x80000000, dl, MVT::i32));
6968         SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32,
6969                                     Op.getOperand(0));
6970         return DAG.getSelectCC(dl, Op.getOperand(0), Tmp, True, False,
6971                                ISD::SETGE);
6972       }
6973     }
6974 
6975     return SDValue();
6976   }
6977 
6978   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6979     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6980 
6981   ReuseLoadInfo RLI;
6982   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6983 
6984   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6985                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6986 }
6987 
6988 // We're trying to insert a regular store, S, and then a load, L. If the
6989 // incoming value, O, is a load, we might just be able to have our load use the
6990 // address used by O. However, we don't know if anything else will store to
6991 // that address before we can load from it. To prevent this situation, we need
6992 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6993 // the same chain operand as O, we create a token factor from the chain results
6994 // of O and L, and we replace all uses of O's chain result with that token
6995 // factor (see spliceIntoChain below for this last part).
6996 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6997                                             ReuseLoadInfo &RLI,
6998                                             SelectionDAG &DAG,
6999                                             ISD::LoadExtType ET) const {
7000   SDLoc dl(Op);
7001   if (ET == ISD::NON_EXTLOAD &&
7002       (Op.getOpcode() == ISD::FP_TO_UINT ||
7003        Op.getOpcode() == ISD::FP_TO_SINT) &&
7004       isOperationLegalOrCustom(Op.getOpcode(),
7005                                Op.getOperand(0).getValueType())) {
7006 
7007     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
7008     return true;
7009   }
7010 
7011   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
7012   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
7013       LD->isNonTemporal())
7014     return false;
7015   if (LD->getMemoryVT() != MemVT)
7016     return false;
7017 
7018   RLI.Ptr = LD->getBasePtr();
7019   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
7020     assert(LD->getAddressingMode() == ISD::PRE_INC &&
7021            "Non-pre-inc AM on PPC?");
7022     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
7023                           LD->getOffset());
7024   }
7025 
7026   RLI.Chain = LD->getChain();
7027   RLI.MPI = LD->getPointerInfo();
7028   RLI.IsDereferenceable = LD->isDereferenceable();
7029   RLI.IsInvariant = LD->isInvariant();
7030   RLI.Alignment = LD->getAlignment();
7031   RLI.AAInfo = LD->getAAInfo();
7032   RLI.Ranges = LD->getRanges();
7033 
7034   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
7035   return true;
7036 }
7037 
7038 // Given the head of the old chain, ResChain, insert a token factor containing
7039 // it and NewResChain, and make users of ResChain now be users of that token
7040 // factor.
7041 // TODO: Remove and use DAG::makeEquivalentMemoryOrdering() instead.
7042 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
7043                                         SDValue NewResChain,
7044                                         SelectionDAG &DAG) const {
7045   if (!ResChain)
7046     return;
7047 
7048   SDLoc dl(NewResChain);
7049 
7050   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7051                            NewResChain, DAG.getUNDEF(MVT::Other));
7052   assert(TF.getNode() != NewResChain.getNode() &&
7053          "A new TF really is required here");
7054 
7055   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
7056   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
7057 }
7058 
7059 /// Analyze profitability of direct move
7060 /// prefer float load to int load plus direct move
7061 /// when there is no integer use of int load
7062 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
7063   SDNode *Origin = Op.getOperand(0).getNode();
7064   if (Origin->getOpcode() != ISD::LOAD)
7065     return true;
7066 
7067   // If there is no LXSIBZX/LXSIHZX, like Power8,
7068   // prefer direct move if the memory size is 1 or 2 bytes.
7069   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
7070   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
7071     return true;
7072 
7073   for (SDNode::use_iterator UI = Origin->use_begin(),
7074                             UE = Origin->use_end();
7075        UI != UE; ++UI) {
7076 
7077     // Only look at the users of the loaded value.
7078     if (UI.getUse().get().getResNo() != 0)
7079       continue;
7080 
7081     if (UI->getOpcode() != ISD::SINT_TO_FP &&
7082         UI->getOpcode() != ISD::UINT_TO_FP)
7083       return true;
7084   }
7085 
7086   return false;
7087 }
7088 
7089 /// Custom lowers integer to floating point conversions to use
7090 /// the direct move instructions available in ISA 2.07 to avoid the
7091 /// need for load/store combinations.
7092 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
7093                                                     SelectionDAG &DAG,
7094                                                     const SDLoc &dl) const {
7095   assert((Op.getValueType() == MVT::f32 ||
7096           Op.getValueType() == MVT::f64) &&
7097          "Invalid floating point type as target of conversion");
7098   assert(Subtarget.hasFPCVT() &&
7099          "Int to FP conversions with direct moves require FPCVT");
7100   SDValue FP;
7101   SDValue Src = Op.getOperand(0);
7102   bool SinglePrec = Op.getValueType() == MVT::f32;
7103   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
7104   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
7105   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
7106                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
7107 
7108   if (WordInt) {
7109     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
7110                      dl, MVT::f64, Src);
7111     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7112   }
7113   else {
7114     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
7115     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
7116   }
7117 
7118   return FP;
7119 }
7120 
7121 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
7122                                           SelectionDAG &DAG) const {
7123   SDLoc dl(Op);
7124 
7125   // Conversions to f128 are legal.
7126   if (EnableQuadPrecision && (Op.getValueType() == MVT::f128))
7127     return Op;
7128 
7129   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
7130     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
7131       return SDValue();
7132 
7133     SDValue Value = Op.getOperand(0);
7134     // The values are now known to be -1 (false) or 1 (true). To convert this
7135     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
7136     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
7137     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
7138 
7139     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
7140 
7141     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
7142 
7143     if (Op.getValueType() != MVT::v4f64)
7144       Value = DAG.getNode(ISD::FP_ROUND, dl,
7145                           Op.getValueType(), Value,
7146                           DAG.getIntPtrConstant(1, dl));
7147     return Value;
7148   }
7149 
7150   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
7151   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
7152     return SDValue();
7153 
7154   if (Op.getOperand(0).getValueType() == MVT::i1)
7155     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
7156                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
7157                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
7158 
7159   // If we have direct moves, we can do all the conversion, skip the store/load
7160   // however, without FPCVT we can't do most conversions.
7161   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
7162       Subtarget.isPPC64() && Subtarget.hasFPCVT())
7163     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
7164 
7165   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
7166          "UINT_TO_FP is supported only with FPCVT");
7167 
7168   // If we have FCFIDS, then use it when converting to single-precision.
7169   // Otherwise, convert to double-precision and then round.
7170   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7171                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
7172                                                             : PPCISD::FCFIDS)
7173                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
7174                                                             : PPCISD::FCFID);
7175   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
7176                   ? MVT::f32
7177                   : MVT::f64;
7178 
7179   if (Op.getOperand(0).getValueType() == MVT::i64) {
7180     SDValue SINT = Op.getOperand(0);
7181     // When converting to single-precision, we actually need to convert
7182     // to double-precision first and then round to single-precision.
7183     // To avoid double-rounding effects during that operation, we have
7184     // to prepare the input operand.  Bits that might be truncated when
7185     // converting to double-precision are replaced by a bit that won't
7186     // be lost at this stage, but is below the single-precision rounding
7187     // position.
7188     //
7189     // However, if -enable-unsafe-fp-math is in effect, accept double
7190     // rounding to avoid the extra overhead.
7191     if (Op.getValueType() == MVT::f32 &&
7192         !Subtarget.hasFPCVT() &&
7193         !DAG.getTarget().Options.UnsafeFPMath) {
7194 
7195       // Twiddle input to make sure the low 11 bits are zero.  (If this
7196       // is the case, we are guaranteed the value will fit into the 53 bit
7197       // mantissa of an IEEE double-precision value without rounding.)
7198       // If any of those low 11 bits were not zero originally, make sure
7199       // bit 12 (value 2048) is set instead, so that the final rounding
7200       // to single-precision gets the correct result.
7201       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7202                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
7203       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
7204                           Round, DAG.getConstant(2047, dl, MVT::i64));
7205       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
7206       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
7207                           Round, DAG.getConstant(-2048, dl, MVT::i64));
7208 
7209       // However, we cannot use that value unconditionally: if the magnitude
7210       // of the input value is small, the bit-twiddling we did above might
7211       // end up visibly changing the output.  Fortunately, in that case, we
7212       // don't need to twiddle bits since the original input will convert
7213       // exactly to double-precision floating-point already.  Therefore,
7214       // construct a conditional to use the original value if the top 11
7215       // bits are all sign-bit copies, and use the rounded value computed
7216       // above otherwise.
7217       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
7218                                  SINT, DAG.getConstant(53, dl, MVT::i32));
7219       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
7220                          Cond, DAG.getConstant(1, dl, MVT::i64));
7221       Cond = DAG.getSetCC(dl, MVT::i32,
7222                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
7223 
7224       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
7225     }
7226 
7227     ReuseLoadInfo RLI;
7228     SDValue Bits;
7229 
7230     MachineFunction &MF = DAG.getMachineFunction();
7231     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
7232       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
7233                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
7234       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7235     } else if (Subtarget.hasLFIWAX() &&
7236                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
7237       MachineMemOperand *MMO =
7238         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7239                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7240       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7241       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
7242                                      DAG.getVTList(MVT::f64, MVT::Other),
7243                                      Ops, MVT::i32, MMO);
7244       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7245     } else if (Subtarget.hasFPCVT() &&
7246                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
7247       MachineMemOperand *MMO =
7248         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7249                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7250       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7251       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
7252                                      DAG.getVTList(MVT::f64, MVT::Other),
7253                                      Ops, MVT::i32, MMO);
7254       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
7255     } else if (((Subtarget.hasLFIWAX() &&
7256                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
7257                 (Subtarget.hasFPCVT() &&
7258                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
7259                SINT.getOperand(0).getValueType() == MVT::i32) {
7260       MachineFrameInfo &MFI = MF.getFrameInfo();
7261       EVT PtrVT = getPointerTy(DAG.getDataLayout());
7262 
7263       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7264       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7265 
7266       SDValue Store =
7267           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
7268                        MachinePointerInfo::getFixedStack(
7269                            DAG.getMachineFunction(), FrameIdx));
7270 
7271       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7272              "Expected an i32 store");
7273 
7274       RLI.Ptr = FIdx;
7275       RLI.Chain = Store;
7276       RLI.MPI =
7277           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7278       RLI.Alignment = 4;
7279 
7280       MachineMemOperand *MMO =
7281         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7282                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7283       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7284       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
7285                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
7286                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
7287                                      Ops, MVT::i32, MMO);
7288     } else
7289       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
7290 
7291     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
7292 
7293     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7294       FP = DAG.getNode(ISD::FP_ROUND, dl,
7295                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
7296     return FP;
7297   }
7298 
7299   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7300          "Unhandled INT_TO_FP type in custom expander!");
7301   // Since we only generate this in 64-bit mode, we can take advantage of
7302   // 64-bit registers.  In particular, sign extend the input value into the
7303   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7304   // then lfd it and fcfid it.
7305   MachineFunction &MF = DAG.getMachineFunction();
7306   MachineFrameInfo &MFI = MF.getFrameInfo();
7307   EVT PtrVT = getPointerTy(MF.getDataLayout());
7308 
7309   SDValue Ld;
7310   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7311     ReuseLoadInfo RLI;
7312     bool ReusingLoad;
7313     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7314                                             DAG))) {
7315       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7316       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7317 
7318       SDValue Store =
7319           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7320                        MachinePointerInfo::getFixedStack(
7321                            DAG.getMachineFunction(), FrameIdx));
7322 
7323       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7324              "Expected an i32 store");
7325 
7326       RLI.Ptr = FIdx;
7327       RLI.Chain = Store;
7328       RLI.MPI =
7329           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7330       RLI.Alignment = 4;
7331     }
7332 
7333     MachineMemOperand *MMO =
7334       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7335                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7336     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7337     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7338                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7339                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7340                                  Ops, MVT::i32, MMO);
7341     if (ReusingLoad)
7342       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7343   } else {
7344     assert(Subtarget.isPPC64() &&
7345            "i32->FP without LFIWAX supported only on PPC64");
7346 
7347     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7348     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7349 
7350     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7351                                 Op.getOperand(0));
7352 
7353     // STD the extended value into the stack slot.
7354     SDValue Store = DAG.getStore(
7355         DAG.getEntryNode(), dl, Ext64, FIdx,
7356         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7357 
7358     // Load the value as a double.
7359     Ld = DAG.getLoad(
7360         MVT::f64, dl, Store, FIdx,
7361         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7362   }
7363 
7364   // FCFID it and return it.
7365   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7366   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7367     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7368                      DAG.getIntPtrConstant(0, dl));
7369   return FP;
7370 }
7371 
7372 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7373                                             SelectionDAG &DAG) const {
7374   SDLoc dl(Op);
7375   /*
7376    The rounding mode is in bits 30:31 of FPSR, and has the following
7377    settings:
7378      00 Round to nearest
7379      01 Round to 0
7380      10 Round to +inf
7381      11 Round to -inf
7382 
7383   FLT_ROUNDS, on the other hand, expects the following:
7384     -1 Undefined
7385      0 Round to 0
7386      1 Round to nearest
7387      2 Round to +inf
7388      3 Round to -inf
7389 
7390   To perform the conversion, we do:
7391     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7392   */
7393 
7394   MachineFunction &MF = DAG.getMachineFunction();
7395   EVT VT = Op.getValueType();
7396   EVT PtrVT = getPointerTy(MF.getDataLayout());
7397 
7398   // Save FP Control Word to register
7399   EVT NodeTys[] = {
7400     MVT::f64,    // return register
7401     MVT::Glue    // unused in this context
7402   };
7403   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7404 
7405   // Save FP register to stack slot
7406   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7407   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7408   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7409                                MachinePointerInfo());
7410 
7411   // Load FP Control Word from low 32 bits of stack slot.
7412   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7413   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7414   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7415 
7416   // Transform as necessary
7417   SDValue CWD1 =
7418     DAG.getNode(ISD::AND, dl, MVT::i32,
7419                 CWD, DAG.getConstant(3, dl, MVT::i32));
7420   SDValue CWD2 =
7421     DAG.getNode(ISD::SRL, dl, MVT::i32,
7422                 DAG.getNode(ISD::AND, dl, MVT::i32,
7423                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7424                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7425                             DAG.getConstant(3, dl, MVT::i32)),
7426                 DAG.getConstant(1, dl, MVT::i32));
7427 
7428   SDValue RetVal =
7429     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7430 
7431   return DAG.getNode((VT.getSizeInBits() < 16 ?
7432                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7433 }
7434 
7435 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7436   EVT VT = Op.getValueType();
7437   unsigned BitWidth = VT.getSizeInBits();
7438   SDLoc dl(Op);
7439   assert(Op.getNumOperands() == 3 &&
7440          VT == Op.getOperand(1).getValueType() &&
7441          "Unexpected SHL!");
7442 
7443   // Expand into a bunch of logical ops.  Note that these ops
7444   // depend on the PPC behavior for oversized shift amounts.
7445   SDValue Lo = Op.getOperand(0);
7446   SDValue Hi = Op.getOperand(1);
7447   SDValue Amt = Op.getOperand(2);
7448   EVT AmtVT = Amt.getValueType();
7449 
7450   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7451                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7452   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7453   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7454   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7455   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7456                              DAG.getConstant(-BitWidth, dl, AmtVT));
7457   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7458   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7459   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7460   SDValue OutOps[] = { OutLo, OutHi };
7461   return DAG.getMergeValues(OutOps, dl);
7462 }
7463 
7464 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7465   EVT VT = Op.getValueType();
7466   SDLoc dl(Op);
7467   unsigned BitWidth = VT.getSizeInBits();
7468   assert(Op.getNumOperands() == 3 &&
7469          VT == Op.getOperand(1).getValueType() &&
7470          "Unexpected SRL!");
7471 
7472   // Expand into a bunch of logical ops.  Note that these ops
7473   // depend on the PPC behavior for oversized shift amounts.
7474   SDValue Lo = Op.getOperand(0);
7475   SDValue Hi = Op.getOperand(1);
7476   SDValue Amt = Op.getOperand(2);
7477   EVT AmtVT = Amt.getValueType();
7478 
7479   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7480                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7481   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7482   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7483   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7484   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7485                              DAG.getConstant(-BitWidth, dl, AmtVT));
7486   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7487   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7488   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7489   SDValue OutOps[] = { OutLo, OutHi };
7490   return DAG.getMergeValues(OutOps, dl);
7491 }
7492 
7493 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7494   SDLoc dl(Op);
7495   EVT VT = Op.getValueType();
7496   unsigned BitWidth = VT.getSizeInBits();
7497   assert(Op.getNumOperands() == 3 &&
7498          VT == Op.getOperand(1).getValueType() &&
7499          "Unexpected SRA!");
7500 
7501   // Expand into a bunch of logical ops, followed by a select_cc.
7502   SDValue Lo = Op.getOperand(0);
7503   SDValue Hi = Op.getOperand(1);
7504   SDValue Amt = Op.getOperand(2);
7505   EVT AmtVT = Amt.getValueType();
7506 
7507   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7508                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7509   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7510   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7511   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7512   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7513                              DAG.getConstant(-BitWidth, dl, AmtVT));
7514   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7515   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7516   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7517                                   Tmp4, Tmp6, ISD::SETLE);
7518   SDValue OutOps[] = { OutLo, OutHi };
7519   return DAG.getMergeValues(OutOps, dl);
7520 }
7521 
7522 //===----------------------------------------------------------------------===//
7523 // Vector related lowering.
7524 //
7525 
7526 /// BuildSplatI - Build a canonical splati of Val with an element size of
7527 /// SplatSize.  Cast the result to VT.
7528 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7529                            SelectionDAG &DAG, const SDLoc &dl) {
7530   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7531 
7532   static const MVT VTys[] = { // canonical VT to use for each size.
7533     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7534   };
7535 
7536   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7537 
7538   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7539   if (Val == -1)
7540     SplatSize = 1;
7541 
7542   EVT CanonicalVT = VTys[SplatSize-1];
7543 
7544   // Build a canonical splat for this value.
7545   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7546 }
7547 
7548 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7549 /// specified intrinsic ID.
7550 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7551                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7552   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7553   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7554                      DAG.getConstant(IID, dl, MVT::i32), Op);
7555 }
7556 
7557 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7558 /// specified intrinsic ID.
7559 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7560                                 SelectionDAG &DAG, const SDLoc &dl,
7561                                 EVT DestVT = MVT::Other) {
7562   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7563   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7564                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7565 }
7566 
7567 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7568 /// specified intrinsic ID.
7569 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7570                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7571                                 EVT DestVT = MVT::Other) {
7572   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7573   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7574                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7575 }
7576 
7577 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7578 /// amount.  The result has the specified value type.
7579 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7580                            SelectionDAG &DAG, const SDLoc &dl) {
7581   // Force LHS/RHS to be the right type.
7582   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7583   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7584 
7585   int Ops[16];
7586   for (unsigned i = 0; i != 16; ++i)
7587     Ops[i] = i + Amt;
7588   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7589   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7590 }
7591 
7592 /// Do we have an efficient pattern in a .td file for this node?
7593 ///
7594 /// \param V - pointer to the BuildVectorSDNode being matched
7595 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7596 ///
7597 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7598 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7599 /// the opposite is true (expansion is beneficial) are:
7600 /// - The node builds a vector out of integers that are not 32 or 64-bits
7601 /// - The node builds a vector out of constants
7602 /// - The node is a "load-and-splat"
7603 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7604 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7605                                             bool HasDirectMove,
7606                                             bool HasP8Vector) {
7607   EVT VecVT = V->getValueType(0);
7608   bool RightType = VecVT == MVT::v2f64 ||
7609     (HasP8Vector && VecVT == MVT::v4f32) ||
7610     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7611   if (!RightType)
7612     return false;
7613 
7614   bool IsSplat = true;
7615   bool IsLoad = false;
7616   SDValue Op0 = V->getOperand(0);
7617 
7618   // This function is called in a block that confirms the node is not a constant
7619   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7620   // different constants.
7621   if (V->isConstant())
7622     return false;
7623   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7624     if (V->getOperand(i).isUndef())
7625       return false;
7626     // We want to expand nodes that represent load-and-splat even if the
7627     // loaded value is a floating point truncation or conversion to int.
7628     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7629         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7630          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7631         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7632          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7633         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7634          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7635       IsLoad = true;
7636     // If the operands are different or the input is not a load and has more
7637     // uses than just this BV node, then it isn't a splat.
7638     if (V->getOperand(i) != Op0 ||
7639         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7640       IsSplat = false;
7641   }
7642   return !(IsSplat && IsLoad);
7643 }
7644 
7645 // If this is a case we can't handle, return null and let the default
7646 // expansion code take care of it.  If we CAN select this case, and if it
7647 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7648 // this case more efficiently than a constant pool load, lower it to the
7649 // sequence of ops that should be used.
7650 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7651                                              SelectionDAG &DAG) const {
7652   SDLoc dl(Op);
7653   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7654   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7655 
7656   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7657     // We first build an i32 vector, load it into a QPX register,
7658     // then convert it to a floating-point vector and compare it
7659     // to a zero vector to get the boolean result.
7660     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7661     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7662     MachinePointerInfo PtrInfo =
7663         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7664     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7665     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7666 
7667     assert(BVN->getNumOperands() == 4 &&
7668       "BUILD_VECTOR for v4i1 does not have 4 operands");
7669 
7670     bool IsConst = true;
7671     for (unsigned i = 0; i < 4; ++i) {
7672       if (BVN->getOperand(i).isUndef()) continue;
7673       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7674         IsConst = false;
7675         break;
7676       }
7677     }
7678 
7679     if (IsConst) {
7680       Constant *One =
7681         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7682       Constant *NegOne =
7683         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7684 
7685       Constant *CV[4];
7686       for (unsigned i = 0; i < 4; ++i) {
7687         if (BVN->getOperand(i).isUndef())
7688           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7689         else if (isNullConstant(BVN->getOperand(i)))
7690           CV[i] = NegOne;
7691         else
7692           CV[i] = One;
7693       }
7694 
7695       Constant *CP = ConstantVector::get(CV);
7696       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7697                                           16 /* alignment */);
7698 
7699       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7700       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7701       return DAG.getMemIntrinsicNode(
7702           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7703           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7704     }
7705 
7706     SmallVector<SDValue, 4> Stores;
7707     for (unsigned i = 0; i < 4; ++i) {
7708       if (BVN->getOperand(i).isUndef()) continue;
7709 
7710       unsigned Offset = 4*i;
7711       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7712       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7713 
7714       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7715       if (StoreSize > 4) {
7716         Stores.push_back(
7717             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7718                               PtrInfo.getWithOffset(Offset), MVT::i32));
7719       } else {
7720         SDValue StoreValue = BVN->getOperand(i);
7721         if (StoreSize < 4)
7722           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7723 
7724         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7725                                       PtrInfo.getWithOffset(Offset)));
7726       }
7727     }
7728 
7729     SDValue StoreChain;
7730     if (!Stores.empty())
7731       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7732     else
7733       StoreChain = DAG.getEntryNode();
7734 
7735     // Now load from v4i32 into the QPX register; this will extend it to
7736     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7737     // is typed as v4f64 because the QPX register integer states are not
7738     // explicitly represented.
7739 
7740     SDValue Ops[] = {StoreChain,
7741                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7742                      FIdx};
7743     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7744 
7745     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7746       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7747     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7748       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7749       LoadedVect);
7750 
7751     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7752 
7753     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7754   }
7755 
7756   // All other QPX vectors are handled by generic code.
7757   if (Subtarget.hasQPX())
7758     return SDValue();
7759 
7760   // Check if this is a splat of a constant value.
7761   APInt APSplatBits, APSplatUndef;
7762   unsigned SplatBitSize;
7763   bool HasAnyUndefs;
7764   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7765                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7766       SplatBitSize > 32) {
7767     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7768     // lowered to VSX instructions under certain conditions.
7769     // Without VSX, there is no pattern more efficient than expanding the node.
7770     if (Subtarget.hasVSX() &&
7771         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove(),
7772                                         Subtarget.hasP8Vector()))
7773       return Op;
7774     return SDValue();
7775   }
7776 
7777   unsigned SplatBits = APSplatBits.getZExtValue();
7778   unsigned SplatUndef = APSplatUndef.getZExtValue();
7779   unsigned SplatSize = SplatBitSize / 8;
7780 
7781   // First, handle single instruction cases.
7782 
7783   // All zeros?
7784   if (SplatBits == 0) {
7785     // Canonicalize all zero vectors to be v4i32.
7786     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7787       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7788       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7789     }
7790     return Op;
7791   }
7792 
7793   // We have XXSPLTIB for constant splats one byte wide
7794   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7795     // This is a splat of 1-byte elements with some elements potentially undef.
7796     // Rather than trying to match undef in the SDAG patterns, ensure that all
7797     // elements are the same constant.
7798     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7799       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7800                                                        dl, MVT::i32));
7801       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7802       if (Op.getValueType() != MVT::v16i8)
7803         return DAG.getBitcast(Op.getValueType(), NewBV);
7804       return NewBV;
7805     }
7806 
7807     // BuildVectorSDNode::isConstantSplat() is actually pretty smart. It'll
7808     // detect that constant splats like v8i16: 0xABAB are really just splats
7809     // of a 1-byte constant. In this case, we need to convert the node to a
7810     // splat of v16i8 and a bitcast.
7811     if (Op.getValueType() != MVT::v16i8)
7812       return DAG.getBitcast(Op.getValueType(),
7813                             DAG.getConstant(SplatBits, dl, MVT::v16i8));
7814 
7815     return Op;
7816   }
7817 
7818   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7819   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7820                     (32-SplatBitSize));
7821   if (SextVal >= -16 && SextVal <= 15)
7822     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7823 
7824   // Two instruction sequences.
7825 
7826   // If this value is in the range [-32,30] and is even, use:
7827   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7828   // If this value is in the range [17,31] and is odd, use:
7829   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7830   // If this value is in the range [-31,-17] and is odd, use:
7831   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7832   // Note the last two are three-instruction sequences.
7833   if (SextVal >= -32 && SextVal <= 31) {
7834     // To avoid having these optimizations undone by constant folding,
7835     // we convert to a pseudo that will be expanded later into one of
7836     // the above forms.
7837     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7838     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7839               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7840     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7841     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7842     if (VT == Op.getValueType())
7843       return RetVal;
7844     else
7845       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7846   }
7847 
7848   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7849   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7850   // for fneg/fabs.
7851   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7852     // Make -1 and vspltisw -1:
7853     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7854 
7855     // Make the VSLW intrinsic, computing 0x8000_0000.
7856     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7857                                    OnesV, DAG, dl);
7858 
7859     // xor by OnesV to invert it.
7860     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7861     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7862   }
7863 
7864   // Check to see if this is a wide variety of vsplti*, binop self cases.
7865   static const signed char SplatCsts[] = {
7866     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7867     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7868   };
7869 
7870   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7871     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7872     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7873     int i = SplatCsts[idx];
7874 
7875     // Figure out what shift amount will be used by altivec if shifted by i in
7876     // this splat size.
7877     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7878 
7879     // vsplti + shl self.
7880     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7881       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7882       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7883         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7884         Intrinsic::ppc_altivec_vslw
7885       };
7886       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7887       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7888     }
7889 
7890     // vsplti + srl self.
7891     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7892       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7893       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7894         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7895         Intrinsic::ppc_altivec_vsrw
7896       };
7897       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7898       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7899     }
7900 
7901     // vsplti + sra self.
7902     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7903       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7904       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7905         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7906         Intrinsic::ppc_altivec_vsraw
7907       };
7908       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7909       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7910     }
7911 
7912     // vsplti + rol self.
7913     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7914                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7915       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7916       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7917         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7918         Intrinsic::ppc_altivec_vrlw
7919       };
7920       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7921       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7922     }
7923 
7924     // t = vsplti c, result = vsldoi t, t, 1
7925     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7926       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7927       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7928       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7929     }
7930     // t = vsplti c, result = vsldoi t, t, 2
7931     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7932       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7933       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7934       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7935     }
7936     // t = vsplti c, result = vsldoi t, t, 3
7937     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7938       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7939       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7940       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7941     }
7942   }
7943 
7944   return SDValue();
7945 }
7946 
7947 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7948 /// the specified operations to build the shuffle.
7949 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7950                                       SDValue RHS, SelectionDAG &DAG,
7951                                       const SDLoc &dl) {
7952   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7953   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7954   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7955 
7956   enum {
7957     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7958     OP_VMRGHW,
7959     OP_VMRGLW,
7960     OP_VSPLTISW0,
7961     OP_VSPLTISW1,
7962     OP_VSPLTISW2,
7963     OP_VSPLTISW3,
7964     OP_VSLDOI4,
7965     OP_VSLDOI8,
7966     OP_VSLDOI12
7967   };
7968 
7969   if (OpNum == OP_COPY) {
7970     if (LHSID == (1*9+2)*9+3) return LHS;
7971     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7972     return RHS;
7973   }
7974 
7975   SDValue OpLHS, OpRHS;
7976   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7977   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7978 
7979   int ShufIdxs[16];
7980   switch (OpNum) {
7981   default: llvm_unreachable("Unknown i32 permute!");
7982   case OP_VMRGHW:
7983     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7984     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7985     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7986     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7987     break;
7988   case OP_VMRGLW:
7989     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7990     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7991     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7992     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7993     break;
7994   case OP_VSPLTISW0:
7995     for (unsigned i = 0; i != 16; ++i)
7996       ShufIdxs[i] = (i&3)+0;
7997     break;
7998   case OP_VSPLTISW1:
7999     for (unsigned i = 0; i != 16; ++i)
8000       ShufIdxs[i] = (i&3)+4;
8001     break;
8002   case OP_VSPLTISW2:
8003     for (unsigned i = 0; i != 16; ++i)
8004       ShufIdxs[i] = (i&3)+8;
8005     break;
8006   case OP_VSPLTISW3:
8007     for (unsigned i = 0; i != 16; ++i)
8008       ShufIdxs[i] = (i&3)+12;
8009     break;
8010   case OP_VSLDOI4:
8011     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
8012   case OP_VSLDOI8:
8013     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
8014   case OP_VSLDOI12:
8015     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
8016   }
8017   EVT VT = OpLHS.getValueType();
8018   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
8019   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
8020   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
8021   return DAG.getNode(ISD::BITCAST, dl, VT, T);
8022 }
8023 
8024 /// lowerToVINSERTB - Return the SDValue if this VECTOR_SHUFFLE can be handled
8025 /// by the VINSERTB instruction introduced in ISA 3.0, else just return default
8026 /// SDValue.
8027 SDValue PPCTargetLowering::lowerToVINSERTB(ShuffleVectorSDNode *N,
8028                                            SelectionDAG &DAG) const {
8029   const unsigned BytesInVector = 16;
8030   bool IsLE = Subtarget.isLittleEndian();
8031   SDLoc dl(N);
8032   SDValue V1 = N->getOperand(0);
8033   SDValue V2 = N->getOperand(1);
8034   unsigned ShiftElts = 0, InsertAtByte = 0;
8035   bool Swap = false;
8036 
8037   // Shifts required to get the byte we want at element 7.
8038   unsigned LittleEndianShifts[] = {8, 7,  6,  5,  4,  3,  2,  1,
8039                                    0, 15, 14, 13, 12, 11, 10, 9};
8040   unsigned BigEndianShifts[] = {9, 10, 11, 12, 13, 14, 15, 0,
8041                                 1, 2,  3,  4,  5,  6,  7,  8};
8042 
8043   ArrayRef<int> Mask = N->getMask();
8044   int OriginalOrder[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
8045 
8046   // For each mask element, find out if we're just inserting something
8047   // from V2 into V1 or vice versa.
8048   // Possible permutations inserting an element from V2 into V1:
8049   //   X, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8050   //   0, X, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
8051   //   ...
8052   //   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, X
8053   // Inserting from V1 into V2 will be similar, except mask range will be
8054   // [16,31].
8055 
8056   bool FoundCandidate = false;
8057   // If both vector operands for the shuffle are the same vector, the mask
8058   // will contain only elements from the first one and the second one will be
8059   // undef.
8060   unsigned VINSERTBSrcElem = IsLE ? 8 : 7;
8061   // Go through the mask of half-words to find an element that's being moved
8062   // from one vector to the other.
8063   for (unsigned i = 0; i < BytesInVector; ++i) {
8064     unsigned CurrentElement = Mask[i];
8065     // If 2nd operand is undefined, we should only look for element 7 in the
8066     // Mask.
8067     if (V2.isUndef() && CurrentElement != VINSERTBSrcElem)
8068       continue;
8069 
8070     bool OtherElementsInOrder = true;
8071     // Examine the other elements in the Mask to see if they're in original
8072     // order.
8073     for (unsigned j = 0; j < BytesInVector; ++j) {
8074       if (j == i)
8075         continue;
8076       // If CurrentElement is from V1 [0,15], then we the rest of the Mask to be
8077       // from V2 [16,31] and vice versa.  Unless the 2nd operand is undefined,
8078       // in which we always assume we're always picking from the 1st operand.
8079       int MaskOffset =
8080           (!V2.isUndef() && CurrentElement < BytesInVector) ? BytesInVector : 0;
8081       if (Mask[j] != OriginalOrder[j] + MaskOffset) {
8082         OtherElementsInOrder = false;
8083         break;
8084       }
8085     }
8086     // If other elements are in original order, we record the number of shifts
8087     // we need to get the element we want into element 7. Also record which byte
8088     // in the vector we should insert into.
8089     if (OtherElementsInOrder) {
8090       // If 2nd operand is undefined, we assume no shifts and no swapping.
8091       if (V2.isUndef()) {
8092         ShiftElts = 0;
8093         Swap = false;
8094       } else {
8095         // Only need the last 4-bits for shifts because operands will be swapped if CurrentElement is >= 2^4.
8096         ShiftElts = IsLE ? LittleEndianShifts[CurrentElement & 0xF]
8097                          : BigEndianShifts[CurrentElement & 0xF];
8098         Swap = CurrentElement < BytesInVector;
8099       }
8100       InsertAtByte = IsLE ? BytesInVector - (i + 1) : i;
8101       FoundCandidate = true;
8102       break;
8103     }
8104   }
8105 
8106   if (!FoundCandidate)
8107     return SDValue();
8108 
8109   // Candidate found, construct the proper SDAG sequence with VINSERTB,
8110   // optionally with VECSHL if shift is required.
8111   if (Swap)
8112     std::swap(V1, V2);
8113   if (V2.isUndef())
8114     V2 = V1;
8115   if (ShiftElts) {
8116     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8117                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8118     return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, Shl,
8119                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
8120   }
8121   return DAG.getNode(PPCISD::VECINSERT, dl, MVT::v16i8, V1, V2,
8122                      DAG.getConstant(InsertAtByte, dl, MVT::i32));
8123 }
8124 
8125 /// lowerToVINSERTH - Return the SDValue if this VECTOR_SHUFFLE can be handled
8126 /// by the VINSERTH instruction introduced in ISA 3.0, else just return default
8127 /// SDValue.
8128 SDValue PPCTargetLowering::lowerToVINSERTH(ShuffleVectorSDNode *N,
8129                                            SelectionDAG &DAG) const {
8130   const unsigned NumHalfWords = 8;
8131   const unsigned BytesInVector = NumHalfWords * 2;
8132   // Check that the shuffle is on half-words.
8133   if (!isNByteElemShuffleMask(N, 2, 1))
8134     return SDValue();
8135 
8136   bool IsLE = Subtarget.isLittleEndian();
8137   SDLoc dl(N);
8138   SDValue V1 = N->getOperand(0);
8139   SDValue V2 = N->getOperand(1);
8140   unsigned ShiftElts = 0, InsertAtByte = 0;
8141   bool Swap = false;
8142 
8143   // Shifts required to get the half-word we want at element 3.
8144   unsigned LittleEndianShifts[] = {4, 3, 2, 1, 0, 7, 6, 5};
8145   unsigned BigEndianShifts[] = {5, 6, 7, 0, 1, 2, 3, 4};
8146 
8147   uint32_t Mask = 0;
8148   uint32_t OriginalOrderLow = 0x1234567;
8149   uint32_t OriginalOrderHigh = 0x89ABCDEF;
8150   // Now we look at mask elements 0,2,4,6,8,10,12,14.  Pack the mask into a
8151   // 32-bit space, only need 4-bit nibbles per element.
8152   for (unsigned i = 0; i < NumHalfWords; ++i) {
8153     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8154     Mask |= ((uint32_t)(N->getMaskElt(i * 2) / 2) << MaskShift);
8155   }
8156 
8157   // For each mask element, find out if we're just inserting something
8158   // from V2 into V1 or vice versa.  Possible permutations inserting an element
8159   // from V2 into V1:
8160   //   X, 1, 2, 3, 4, 5, 6, 7
8161   //   0, X, 2, 3, 4, 5, 6, 7
8162   //   0, 1, X, 3, 4, 5, 6, 7
8163   //   0, 1, 2, X, 4, 5, 6, 7
8164   //   0, 1, 2, 3, X, 5, 6, 7
8165   //   0, 1, 2, 3, 4, X, 6, 7
8166   //   0, 1, 2, 3, 4, 5, X, 7
8167   //   0, 1, 2, 3, 4, 5, 6, X
8168   // Inserting from V1 into V2 will be similar, except mask range will be [8,15].
8169 
8170   bool FoundCandidate = false;
8171   // Go through the mask of half-words to find an element that's being moved
8172   // from one vector to the other.
8173   for (unsigned i = 0; i < NumHalfWords; ++i) {
8174     unsigned MaskShift = (NumHalfWords - 1 - i) * 4;
8175     uint32_t MaskOneElt = (Mask >> MaskShift) & 0xF;
8176     uint32_t MaskOtherElts = ~(0xF << MaskShift);
8177     uint32_t TargetOrder = 0x0;
8178 
8179     // If both vector operands for the shuffle are the same vector, the mask
8180     // will contain only elements from the first one and the second one will be
8181     // undef.
8182     if (V2.isUndef()) {
8183       ShiftElts = 0;
8184       unsigned VINSERTHSrcElem = IsLE ? 4 : 3;
8185       TargetOrder = OriginalOrderLow;
8186       Swap = false;
8187       // Skip if not the correct element or mask of other elements don't equal
8188       // to our expected order.
8189       if (MaskOneElt == VINSERTHSrcElem &&
8190           (Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8191         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8192         FoundCandidate = true;
8193         break;
8194       }
8195     } else { // If both operands are defined.
8196       // Target order is [8,15] if the current mask is between [0,7].
8197       TargetOrder =
8198           (MaskOneElt < NumHalfWords) ? OriginalOrderHigh : OriginalOrderLow;
8199       // Skip if mask of other elements don't equal our expected order.
8200       if ((Mask & MaskOtherElts) == (TargetOrder & MaskOtherElts)) {
8201         // We only need the last 3 bits for the number of shifts.
8202         ShiftElts = IsLE ? LittleEndianShifts[MaskOneElt & 0x7]
8203                          : BigEndianShifts[MaskOneElt & 0x7];
8204         InsertAtByte = IsLE ? BytesInVector - (i + 1) * 2 : i * 2;
8205         Swap = MaskOneElt < NumHalfWords;
8206         FoundCandidate = true;
8207         break;
8208       }
8209     }
8210   }
8211 
8212   if (!FoundCandidate)
8213     return SDValue();
8214 
8215   // Candidate found, construct the proper SDAG sequence with VINSERTH,
8216   // optionally with VECSHL if shift is required.
8217   if (Swap)
8218     std::swap(V1, V2);
8219   if (V2.isUndef())
8220     V2 = V1;
8221   SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8222   if (ShiftElts) {
8223     // Double ShiftElts because we're left shifting on v16i8 type.
8224     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v16i8, V2, V2,
8225                               DAG.getConstant(2 * ShiftElts, dl, MVT::i32));
8226     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, Shl);
8227     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8228                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8229     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8230   }
8231   SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8232   SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v8i16, Conv1, Conv2,
8233                             DAG.getConstant(InsertAtByte, dl, MVT::i32));
8234   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8235 }
8236 
8237 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
8238 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
8239 /// return the code it can be lowered into.  Worst case, it can always be
8240 /// lowered into a vperm.
8241 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
8242                                                SelectionDAG &DAG) const {
8243   SDLoc dl(Op);
8244   SDValue V1 = Op.getOperand(0);
8245   SDValue V2 = Op.getOperand(1);
8246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8247   EVT VT = Op.getValueType();
8248   bool isLittleEndian = Subtarget.isLittleEndian();
8249 
8250   unsigned ShiftElts, InsertAtByte;
8251   bool Swap = false;
8252   if (Subtarget.hasP9Vector() &&
8253       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
8254                            isLittleEndian)) {
8255     if (Swap)
8256       std::swap(V1, V2);
8257     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8258     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
8259     if (ShiftElts) {
8260       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
8261                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
8262       SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Shl,
8263                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
8264       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8265     }
8266     SDValue Ins = DAG.getNode(PPCISD::VECINSERT, dl, MVT::v4i32, Conv1, Conv2,
8267                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
8268     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
8269   }
8270 
8271   if (Subtarget.hasP9Altivec()) {
8272     SDValue NewISDNode;
8273     if ((NewISDNode = lowerToVINSERTH(SVOp, DAG)))
8274       return NewISDNode;
8275 
8276     if ((NewISDNode = lowerToVINSERTB(SVOp, DAG)))
8277       return NewISDNode;
8278   }
8279 
8280   if (Subtarget.hasVSX() &&
8281       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8282     if (Swap)
8283       std::swap(V1, V2);
8284     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8285     SDValue Conv2 =
8286         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
8287 
8288     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
8289                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8290     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
8291   }
8292 
8293   if (Subtarget.hasVSX() &&
8294     PPC::isXXPERMDIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
8295     if (Swap)
8296       std::swap(V1, V2);
8297     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8298     SDValue Conv2 =
8299         DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2.isUndef() ? V1 : V2);
8300 
8301     SDValue PermDI = DAG.getNode(PPCISD::XXPERMDI, dl, MVT::v2i64, Conv1, Conv2,
8302                               DAG.getConstant(ShiftElts, dl, MVT::i32));
8303     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, PermDI);
8304   }
8305 
8306   if (Subtarget.hasP9Vector()) {
8307      if (PPC::isXXBRHShuffleMask(SVOp)) {
8308       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8309       SDValue ReveHWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v8i16, Conv);
8310       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveHWord);
8311     } else if (PPC::isXXBRWShuffleMask(SVOp)) {
8312       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8313       SDValue ReveWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v4i32, Conv);
8314       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveWord);
8315     } else if (PPC::isXXBRDShuffleMask(SVOp)) {
8316       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1);
8317       SDValue ReveDWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Conv);
8318       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveDWord);
8319     } else if (PPC::isXXBRQShuffleMask(SVOp)) {
8320       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v1i128, V1);
8321       SDValue ReveQWord = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v1i128, Conv);
8322       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, ReveQWord);
8323     }
8324   }
8325 
8326   if (Subtarget.hasVSX()) {
8327     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
8328       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
8329 
8330       // If the source for the shuffle is a scalar_to_vector that came from a
8331       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
8332       if (Subtarget.hasP9Vector() &&
8333           ((isLittleEndian && SplatIdx == 3) ||
8334            (!isLittleEndian && SplatIdx == 0))) {
8335         SDValue Src = V1.getOperand(0);
8336         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8337             Src.getOperand(0).getOpcode() == ISD::LOAD &&
8338             Src.getOperand(0).hasOneUse())
8339           return V1;
8340       }
8341       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
8342       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
8343                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
8344       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
8345     }
8346 
8347     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
8348     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
8349       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8350       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
8351       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
8352     }
8353   }
8354 
8355   if (Subtarget.hasQPX()) {
8356     if (VT.getVectorNumElements() != 4)
8357       return SDValue();
8358 
8359     if (V2.isUndef()) V2 = V1;
8360 
8361     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
8362     if (AlignIdx != -1) {
8363       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
8364                          DAG.getConstant(AlignIdx, dl, MVT::i32));
8365     } else if (SVOp->isSplat()) {
8366       int SplatIdx = SVOp->getSplatIndex();
8367       if (SplatIdx >= 4) {
8368         std::swap(V1, V2);
8369         SplatIdx -= 4;
8370       }
8371 
8372       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
8373                          DAG.getConstant(SplatIdx, dl, MVT::i32));
8374     }
8375 
8376     // Lower this into a qvgpci/qvfperm pair.
8377 
8378     // Compute the qvgpci literal
8379     unsigned idx = 0;
8380     for (unsigned i = 0; i < 4; ++i) {
8381       int m = SVOp->getMaskElt(i);
8382       unsigned mm = m >= 0 ? (unsigned) m : i;
8383       idx |= mm << (3-i)*3;
8384     }
8385 
8386     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
8387                              DAG.getConstant(idx, dl, MVT::i32));
8388     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
8389   }
8390 
8391   // Cases that are handled by instructions that take permute immediates
8392   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
8393   // selected by the instruction selector.
8394   if (V2.isUndef()) {
8395     if (PPC::isSplatShuffleMask(SVOp, 1) ||
8396         PPC::isSplatShuffleMask(SVOp, 2) ||
8397         PPC::isSplatShuffleMask(SVOp, 4) ||
8398         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
8399         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
8400         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
8401         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
8402         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
8403         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
8404         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
8405         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
8406         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
8407         (Subtarget.hasP8Altivec() && (
8408          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
8409          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
8410          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
8411       return Op;
8412     }
8413   }
8414 
8415   // Altivec has a variety of "shuffle immediates" that take two vector inputs
8416   // and produce a fixed permutation.  If any of these match, do not lower to
8417   // VPERM.
8418   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
8419   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8420       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8421       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
8422       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8423       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8424       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8425       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
8426       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
8427       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
8428       (Subtarget.hasP8Altivec() && (
8429        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
8430        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
8431        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
8432     return Op;
8433 
8434   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
8435   // perfect shuffle table to emit an optimal matching sequence.
8436   ArrayRef<int> PermMask = SVOp->getMask();
8437 
8438   unsigned PFIndexes[4];
8439   bool isFourElementShuffle = true;
8440   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
8441     unsigned EltNo = 8;   // Start out undef.
8442     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
8443       if (PermMask[i*4+j] < 0)
8444         continue;   // Undef, ignore it.
8445 
8446       unsigned ByteSource = PermMask[i*4+j];
8447       if ((ByteSource & 3) != j) {
8448         isFourElementShuffle = false;
8449         break;
8450       }
8451 
8452       if (EltNo == 8) {
8453         EltNo = ByteSource/4;
8454       } else if (EltNo != ByteSource/4) {
8455         isFourElementShuffle = false;
8456         break;
8457       }
8458     }
8459     PFIndexes[i] = EltNo;
8460   }
8461 
8462   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
8463   // perfect shuffle vector to determine if it is cost effective to do this as
8464   // discrete instructions, or whether we should use a vperm.
8465   // For now, we skip this for little endian until such time as we have a
8466   // little-endian perfect shuffle table.
8467   if (isFourElementShuffle && !isLittleEndian) {
8468     // Compute the index in the perfect shuffle table.
8469     unsigned PFTableIndex =
8470       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
8471 
8472     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
8473     unsigned Cost  = (PFEntry >> 30);
8474 
8475     // Determining when to avoid vperm is tricky.  Many things affect the cost
8476     // of vperm, particularly how many times the perm mask needs to be computed.
8477     // For example, if the perm mask can be hoisted out of a loop or is already
8478     // used (perhaps because there are multiple permutes with the same shuffle
8479     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
8480     // the loop requires an extra register.
8481     //
8482     // As a compromise, we only emit discrete instructions if the shuffle can be
8483     // generated in 3 or fewer operations.  When we have loop information
8484     // available, if this block is within a loop, we should avoid using vperm
8485     // for 3-operation perms and use a constant pool load instead.
8486     if (Cost < 3)
8487       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
8488   }
8489 
8490   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
8491   // vector that will get spilled to the constant pool.
8492   if (V2.isUndef()) V2 = V1;
8493 
8494   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
8495   // that it is in input element units, not in bytes.  Convert now.
8496 
8497   // For little endian, the order of the input vectors is reversed, and
8498   // the permutation mask is complemented with respect to 31.  This is
8499   // necessary to produce proper semantics with the big-endian-biased vperm
8500   // instruction.
8501   EVT EltVT = V1.getValueType().getVectorElementType();
8502   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
8503 
8504   SmallVector<SDValue, 16> ResultMask;
8505   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
8506     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
8507 
8508     for (unsigned j = 0; j != BytesPerElement; ++j)
8509       if (isLittleEndian)
8510         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
8511                                              dl, MVT::i32));
8512       else
8513         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
8514                                              MVT::i32));
8515   }
8516 
8517   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
8518   if (isLittleEndian)
8519     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8520                        V2, V1, VPermMask);
8521   else
8522     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
8523                        V1, V2, VPermMask);
8524 }
8525 
8526 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
8527 /// vector comparison.  If it is, return true and fill in Opc/isDot with
8528 /// information about the intrinsic.
8529 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
8530                                  bool &isDot, const PPCSubtarget &Subtarget) {
8531   unsigned IntrinsicID =
8532       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
8533   CompareOpc = -1;
8534   isDot = false;
8535   switch (IntrinsicID) {
8536   default:
8537     return false;
8538   // Comparison predicates.
8539   case Intrinsic::ppc_altivec_vcmpbfp_p:
8540     CompareOpc = 966;
8541     isDot = true;
8542     break;
8543   case Intrinsic::ppc_altivec_vcmpeqfp_p:
8544     CompareOpc = 198;
8545     isDot = true;
8546     break;
8547   case Intrinsic::ppc_altivec_vcmpequb_p:
8548     CompareOpc = 6;
8549     isDot = true;
8550     break;
8551   case Intrinsic::ppc_altivec_vcmpequh_p:
8552     CompareOpc = 70;
8553     isDot = true;
8554     break;
8555   case Intrinsic::ppc_altivec_vcmpequw_p:
8556     CompareOpc = 134;
8557     isDot = true;
8558     break;
8559   case Intrinsic::ppc_altivec_vcmpequd_p:
8560     if (Subtarget.hasP8Altivec()) {
8561       CompareOpc = 199;
8562       isDot = true;
8563     } else
8564       return false;
8565     break;
8566   case Intrinsic::ppc_altivec_vcmpneb_p:
8567   case Intrinsic::ppc_altivec_vcmpneh_p:
8568   case Intrinsic::ppc_altivec_vcmpnew_p:
8569   case Intrinsic::ppc_altivec_vcmpnezb_p:
8570   case Intrinsic::ppc_altivec_vcmpnezh_p:
8571   case Intrinsic::ppc_altivec_vcmpnezw_p:
8572     if (Subtarget.hasP9Altivec()) {
8573       switch (IntrinsicID) {
8574       default:
8575         llvm_unreachable("Unknown comparison intrinsic.");
8576       case Intrinsic::ppc_altivec_vcmpneb_p:
8577         CompareOpc = 7;
8578         break;
8579       case Intrinsic::ppc_altivec_vcmpneh_p:
8580         CompareOpc = 71;
8581         break;
8582       case Intrinsic::ppc_altivec_vcmpnew_p:
8583         CompareOpc = 135;
8584         break;
8585       case Intrinsic::ppc_altivec_vcmpnezb_p:
8586         CompareOpc = 263;
8587         break;
8588       case Intrinsic::ppc_altivec_vcmpnezh_p:
8589         CompareOpc = 327;
8590         break;
8591       case Intrinsic::ppc_altivec_vcmpnezw_p:
8592         CompareOpc = 391;
8593         break;
8594       }
8595       isDot = true;
8596     } else
8597       return false;
8598     break;
8599   case Intrinsic::ppc_altivec_vcmpgefp_p:
8600     CompareOpc = 454;
8601     isDot = true;
8602     break;
8603   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8604     CompareOpc = 710;
8605     isDot = true;
8606     break;
8607   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8608     CompareOpc = 774;
8609     isDot = true;
8610     break;
8611   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8612     CompareOpc = 838;
8613     isDot = true;
8614     break;
8615   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8616     CompareOpc = 902;
8617     isDot = true;
8618     break;
8619   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8620     if (Subtarget.hasP8Altivec()) {
8621       CompareOpc = 967;
8622       isDot = true;
8623     } else
8624       return false;
8625     break;
8626   case Intrinsic::ppc_altivec_vcmpgtub_p:
8627     CompareOpc = 518;
8628     isDot = true;
8629     break;
8630   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8631     CompareOpc = 582;
8632     isDot = true;
8633     break;
8634   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8635     CompareOpc = 646;
8636     isDot = true;
8637     break;
8638   case Intrinsic::ppc_altivec_vcmpgtud_p:
8639     if (Subtarget.hasP8Altivec()) {
8640       CompareOpc = 711;
8641       isDot = true;
8642     } else
8643       return false;
8644     break;
8645 
8646   // VSX predicate comparisons use the same infrastructure
8647   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8648   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8649   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8650   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8651   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8652   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8653     if (Subtarget.hasVSX()) {
8654       switch (IntrinsicID) {
8655       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8656         CompareOpc = 99;
8657         break;
8658       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8659         CompareOpc = 115;
8660         break;
8661       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8662         CompareOpc = 107;
8663         break;
8664       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8665         CompareOpc = 67;
8666         break;
8667       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8668         CompareOpc = 83;
8669         break;
8670       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8671         CompareOpc = 75;
8672         break;
8673       }
8674       isDot = true;
8675     } else
8676       return false;
8677     break;
8678 
8679   // Normal Comparisons.
8680   case Intrinsic::ppc_altivec_vcmpbfp:
8681     CompareOpc = 966;
8682     break;
8683   case Intrinsic::ppc_altivec_vcmpeqfp:
8684     CompareOpc = 198;
8685     break;
8686   case Intrinsic::ppc_altivec_vcmpequb:
8687     CompareOpc = 6;
8688     break;
8689   case Intrinsic::ppc_altivec_vcmpequh:
8690     CompareOpc = 70;
8691     break;
8692   case Intrinsic::ppc_altivec_vcmpequw:
8693     CompareOpc = 134;
8694     break;
8695   case Intrinsic::ppc_altivec_vcmpequd:
8696     if (Subtarget.hasP8Altivec())
8697       CompareOpc = 199;
8698     else
8699       return false;
8700     break;
8701   case Intrinsic::ppc_altivec_vcmpneb:
8702   case Intrinsic::ppc_altivec_vcmpneh:
8703   case Intrinsic::ppc_altivec_vcmpnew:
8704   case Intrinsic::ppc_altivec_vcmpnezb:
8705   case Intrinsic::ppc_altivec_vcmpnezh:
8706   case Intrinsic::ppc_altivec_vcmpnezw:
8707     if (Subtarget.hasP9Altivec())
8708       switch (IntrinsicID) {
8709       default:
8710         llvm_unreachable("Unknown comparison intrinsic.");
8711       case Intrinsic::ppc_altivec_vcmpneb:
8712         CompareOpc = 7;
8713         break;
8714       case Intrinsic::ppc_altivec_vcmpneh:
8715         CompareOpc = 71;
8716         break;
8717       case Intrinsic::ppc_altivec_vcmpnew:
8718         CompareOpc = 135;
8719         break;
8720       case Intrinsic::ppc_altivec_vcmpnezb:
8721         CompareOpc = 263;
8722         break;
8723       case Intrinsic::ppc_altivec_vcmpnezh:
8724         CompareOpc = 327;
8725         break;
8726       case Intrinsic::ppc_altivec_vcmpnezw:
8727         CompareOpc = 391;
8728         break;
8729       }
8730     else
8731       return false;
8732     break;
8733   case Intrinsic::ppc_altivec_vcmpgefp:
8734     CompareOpc = 454;
8735     break;
8736   case Intrinsic::ppc_altivec_vcmpgtfp:
8737     CompareOpc = 710;
8738     break;
8739   case Intrinsic::ppc_altivec_vcmpgtsb:
8740     CompareOpc = 774;
8741     break;
8742   case Intrinsic::ppc_altivec_vcmpgtsh:
8743     CompareOpc = 838;
8744     break;
8745   case Intrinsic::ppc_altivec_vcmpgtsw:
8746     CompareOpc = 902;
8747     break;
8748   case Intrinsic::ppc_altivec_vcmpgtsd:
8749     if (Subtarget.hasP8Altivec())
8750       CompareOpc = 967;
8751     else
8752       return false;
8753     break;
8754   case Intrinsic::ppc_altivec_vcmpgtub:
8755     CompareOpc = 518;
8756     break;
8757   case Intrinsic::ppc_altivec_vcmpgtuh:
8758     CompareOpc = 582;
8759     break;
8760   case Intrinsic::ppc_altivec_vcmpgtuw:
8761     CompareOpc = 646;
8762     break;
8763   case Intrinsic::ppc_altivec_vcmpgtud:
8764     if (Subtarget.hasP8Altivec())
8765       CompareOpc = 711;
8766     else
8767       return false;
8768     break;
8769   }
8770   return true;
8771 }
8772 
8773 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8774 /// lower, do it, otherwise return null.
8775 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8776                                                    SelectionDAG &DAG) const {
8777   unsigned IntrinsicID =
8778     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8779 
8780   SDLoc dl(Op);
8781 
8782   if (IntrinsicID == Intrinsic::thread_pointer) {
8783     // Reads the thread pointer register, used for __builtin_thread_pointer.
8784     if (Subtarget.isPPC64())
8785       return DAG.getRegister(PPC::X13, MVT::i64);
8786     return DAG.getRegister(PPC::R2, MVT::i32);
8787   }
8788 
8789   // We are looking for absolute values here.
8790   // The idea is to try to fit one of two patterns:
8791   //  max (a, (0-a))  OR  max ((0-a), a)
8792   if (Subtarget.hasP9Vector() &&
8793       (IntrinsicID == Intrinsic::ppc_altivec_vmaxsw ||
8794        IntrinsicID == Intrinsic::ppc_altivec_vmaxsh ||
8795        IntrinsicID == Intrinsic::ppc_altivec_vmaxsb)) {
8796     SDValue V1 = Op.getOperand(1);
8797     SDValue V2 = Op.getOperand(2);
8798     if (V1.getSimpleValueType() == V2.getSimpleValueType() &&
8799         (V1.getSimpleValueType() == MVT::v4i32 ||
8800          V1.getSimpleValueType() == MVT::v8i16 ||
8801          V1.getSimpleValueType() == MVT::v16i8)) {
8802       if ( V1.getOpcode() == ISD::SUB &&
8803            ISD::isBuildVectorAllZeros(V1.getOperand(0).getNode()) &&
8804            V1.getOperand(1) == V2 ) {
8805         // Generate the abs instruction with the operands
8806         return DAG.getNode(ISD::ABS, dl, V2.getValueType(),V2);
8807       }
8808 
8809       if ( V2.getOpcode() == ISD::SUB &&
8810            ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()) &&
8811            V2.getOperand(1) == V1 ) {
8812         // Generate the abs instruction with the operands
8813         return DAG.getNode(ISD::ABS, dl, V1.getValueType(),V1);
8814       }
8815     }
8816   }
8817 
8818   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8819   // opcode number of the comparison.
8820   int CompareOpc;
8821   bool isDot;
8822   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8823     return SDValue();    // Don't custom lower most intrinsics.
8824 
8825   // If this is a non-dot comparison, make the VCMP node and we are done.
8826   if (!isDot) {
8827     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8828                               Op.getOperand(1), Op.getOperand(2),
8829                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8830     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8831   }
8832 
8833   // Create the PPCISD altivec 'dot' comparison node.
8834   SDValue Ops[] = {
8835     Op.getOperand(2),  // LHS
8836     Op.getOperand(3),  // RHS
8837     DAG.getConstant(CompareOpc, dl, MVT::i32)
8838   };
8839   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8840   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8841 
8842   // Now that we have the comparison, emit a copy from the CR to a GPR.
8843   // This is flagged to the above dot comparison.
8844   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8845                                 DAG.getRegister(PPC::CR6, MVT::i32),
8846                                 CompNode.getValue(1));
8847 
8848   // Unpack the result based on how the target uses it.
8849   unsigned BitNo;   // Bit # of CR6.
8850   bool InvertBit;   // Invert result?
8851   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8852   default:  // Can't happen, don't crash on invalid number though.
8853   case 0:   // Return the value of the EQ bit of CR6.
8854     BitNo = 0; InvertBit = false;
8855     break;
8856   case 1:   // Return the inverted value of the EQ bit of CR6.
8857     BitNo = 0; InvertBit = true;
8858     break;
8859   case 2:   // Return the value of the LT bit of CR6.
8860     BitNo = 2; InvertBit = false;
8861     break;
8862   case 3:   // Return the inverted value of the LT bit of CR6.
8863     BitNo = 2; InvertBit = true;
8864     break;
8865   }
8866 
8867   // Shift the bit into the low position.
8868   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8869                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8870   // Isolate the bit.
8871   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8872                       DAG.getConstant(1, dl, MVT::i32));
8873 
8874   // If we are supposed to, toggle the bit.
8875   if (InvertBit)
8876     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8877                         DAG.getConstant(1, dl, MVT::i32));
8878   return Flags;
8879 }
8880 
8881 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8882                                                SelectionDAG &DAG) const {
8883   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8884   // the beginning of the argument list.
8885   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8886   SDLoc DL(Op);
8887   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8888   case Intrinsic::ppc_cfence: {
8889     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8890     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8891     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8892                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8893                                                   Op.getOperand(ArgStart + 1)),
8894                                       Op.getOperand(0)),
8895                    0);
8896   }
8897   default:
8898     break;
8899   }
8900   return SDValue();
8901 }
8902 
8903 SDValue PPCTargetLowering::LowerREM(SDValue Op, SelectionDAG &DAG) const {
8904   // Check for a DIV with the same operands as this REM.
8905   for (auto UI : Op.getOperand(1)->uses()) {
8906     if ((Op.getOpcode() == ISD::SREM && UI->getOpcode() == ISD::SDIV) ||
8907         (Op.getOpcode() == ISD::UREM && UI->getOpcode() == ISD::UDIV))
8908       if (UI->getOperand(0) == Op.getOperand(0) &&
8909           UI->getOperand(1) == Op.getOperand(1))
8910         return SDValue();
8911   }
8912   return Op;
8913 }
8914 
8915 // Lower scalar BSWAP64 to xxbrd.
8916 SDValue PPCTargetLowering::LowerBSWAP(SDValue Op, SelectionDAG &DAG) const {
8917   SDLoc dl(Op);
8918   // MTVSRDD
8919   Op = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, Op.getOperand(0),
8920                    Op.getOperand(0));
8921   // XXBRD
8922   Op = DAG.getNode(PPCISD::XXREVERSE, dl, MVT::v2i64, Op);
8923   // MFVSRD
8924   int VectorIndex = 0;
8925   if (Subtarget.isLittleEndian())
8926     VectorIndex = 1;
8927   Op = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Op,
8928                    DAG.getTargetConstant(VectorIndex, dl, MVT::i32));
8929   return Op;
8930 }
8931 
8932 // ATOMIC_CMP_SWAP for i8/i16 needs to zero-extend its input since it will be
8933 // compared to a value that is atomically loaded (atomic loads zero-extend).
8934 SDValue PPCTargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op,
8935                                                 SelectionDAG &DAG) const {
8936   assert(Op.getOpcode() == ISD::ATOMIC_CMP_SWAP &&
8937          "Expecting an atomic compare-and-swap here.");
8938   SDLoc dl(Op);
8939   auto *AtomicNode = cast<AtomicSDNode>(Op.getNode());
8940   EVT MemVT = AtomicNode->getMemoryVT();
8941   if (MemVT.getSizeInBits() >= 32)
8942     return Op;
8943 
8944   SDValue CmpOp = Op.getOperand(2);
8945   // If this is already correctly zero-extended, leave it alone.
8946   auto HighBits = APInt::getHighBitsSet(32, 32 - MemVT.getSizeInBits());
8947   if (DAG.MaskedValueIsZero(CmpOp, HighBits))
8948     return Op;
8949 
8950   // Clear the high bits of the compare operand.
8951   unsigned MaskVal = (1 << MemVT.getSizeInBits()) - 1;
8952   SDValue NewCmpOp =
8953     DAG.getNode(ISD::AND, dl, MVT::i32, CmpOp,
8954                 DAG.getConstant(MaskVal, dl, MVT::i32));
8955 
8956   // Replace the existing compare operand with the properly zero-extended one.
8957   SmallVector<SDValue, 4> Ops;
8958   for (int i = 0, e = AtomicNode->getNumOperands(); i < e; i++)
8959     Ops.push_back(AtomicNode->getOperand(i));
8960   Ops[2] = NewCmpOp;
8961   MachineMemOperand *MMO = AtomicNode->getMemOperand();
8962   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::Other);
8963   auto NodeTy =
8964     (MemVT == MVT::i8) ? PPCISD::ATOMIC_CMP_SWAP_8 : PPCISD::ATOMIC_CMP_SWAP_16;
8965   return DAG.getMemIntrinsicNode(NodeTy, dl, Tys, Ops, MemVT, MMO);
8966 }
8967 
8968 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8969                                                   SelectionDAG &DAG) const {
8970   SDLoc dl(Op);
8971   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8972   // instructions), but for smaller types, we need to first extend up to v2i32
8973   // before doing going farther.
8974   if (Op.getValueType() == MVT::v2i64) {
8975     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8976     if (ExtVT != MVT::v2i32) {
8977       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8978       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8979                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8980                                         ExtVT.getVectorElementType(), 4)));
8981       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8982       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8983                        DAG.getValueType(MVT::v2i32));
8984     }
8985 
8986     return Op;
8987   }
8988 
8989   return SDValue();
8990 }
8991 
8992 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8993                                                  SelectionDAG &DAG) const {
8994   SDLoc dl(Op);
8995   // Create a stack slot that is 16-byte aligned.
8996   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8997   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8998   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8999   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9000 
9001   // Store the input value into Value#0 of the stack slot.
9002   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
9003                                MachinePointerInfo());
9004   // Load it out.
9005   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
9006 }
9007 
9008 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
9009                                                   SelectionDAG &DAG) const {
9010   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
9011          "Should only be called for ISD::INSERT_VECTOR_ELT");
9012 
9013   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
9014   // We have legal lowering for constant indices but not for variable ones.
9015   if (!C)
9016     return SDValue();
9017 
9018   EVT VT = Op.getValueType();
9019   SDLoc dl(Op);
9020   SDValue V1 = Op.getOperand(0);
9021   SDValue V2 = Op.getOperand(1);
9022   // We can use MTVSRZ + VECINSERT for v8i16 and v16i8 types.
9023   if (VT == MVT::v8i16 || VT == MVT::v16i8) {
9024     SDValue Mtvsrz = DAG.getNode(PPCISD::MTVSRZ, dl, VT, V2);
9025     unsigned BytesInEachElement = VT.getVectorElementType().getSizeInBits() / 8;
9026     unsigned InsertAtElement = C->getZExtValue();
9027     unsigned InsertAtByte = InsertAtElement * BytesInEachElement;
9028     if (Subtarget.isLittleEndian()) {
9029       InsertAtByte = (16 - BytesInEachElement) - InsertAtByte;
9030     }
9031     return DAG.getNode(PPCISD::VECINSERT, dl, VT, V1, Mtvsrz,
9032                        DAG.getConstant(InsertAtByte, dl, MVT::i32));
9033   }
9034   return Op;
9035 }
9036 
9037 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9038                                                    SelectionDAG &DAG) const {
9039   SDLoc dl(Op);
9040   SDNode *N = Op.getNode();
9041 
9042   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
9043          "Unknown extract_vector_elt type");
9044 
9045   SDValue Value = N->getOperand(0);
9046 
9047   // The first part of this is like the store lowering except that we don't
9048   // need to track the chain.
9049 
9050   // The values are now known to be -1 (false) or 1 (true). To convert this
9051   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9052   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9053   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9054 
9055   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9056   // understand how to form the extending load.
9057   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9058 
9059   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9060 
9061   // Now convert to an integer and store.
9062   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9063     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9064     Value);
9065 
9066   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9067   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9068   MachinePointerInfo PtrInfo =
9069       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9070   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9071   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9072 
9073   SDValue StoreChain = DAG.getEntryNode();
9074   SDValue Ops[] = {StoreChain,
9075                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9076                    Value, FIdx};
9077   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9078 
9079   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9080     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9081 
9082   // Extract the value requested.
9083   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9084   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9085   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9086 
9087   SDValue IntVal =
9088       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
9089 
9090   if (!Subtarget.useCRBits())
9091     return IntVal;
9092 
9093   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
9094 }
9095 
9096 /// Lowering for QPX v4i1 loads
9097 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
9098                                            SelectionDAG &DAG) const {
9099   SDLoc dl(Op);
9100   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
9101   SDValue LoadChain = LN->getChain();
9102   SDValue BasePtr = LN->getBasePtr();
9103 
9104   if (Op.getValueType() == MVT::v4f64 ||
9105       Op.getValueType() == MVT::v4f32) {
9106     EVT MemVT = LN->getMemoryVT();
9107     unsigned Alignment = LN->getAlignment();
9108 
9109     // If this load is properly aligned, then it is legal.
9110     if (Alignment >= MemVT.getStoreSize())
9111       return Op;
9112 
9113     EVT ScalarVT = Op.getValueType().getScalarType(),
9114         ScalarMemVT = MemVT.getScalarType();
9115     unsigned Stride = ScalarMemVT.getStoreSize();
9116 
9117     SDValue Vals[4], LoadChains[4];
9118     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9119       SDValue Load;
9120       if (ScalarVT != ScalarMemVT)
9121         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
9122                               BasePtr,
9123                               LN->getPointerInfo().getWithOffset(Idx * Stride),
9124                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9125                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
9126       else
9127         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
9128                            LN->getPointerInfo().getWithOffset(Idx * Stride),
9129                            MinAlign(Alignment, Idx * Stride),
9130                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
9131 
9132       if (Idx == 0 && LN->isIndexed()) {
9133         assert(LN->getAddressingMode() == ISD::PRE_INC &&
9134                "Unknown addressing mode on vector load");
9135         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
9136                                   LN->getAddressingMode());
9137       }
9138 
9139       Vals[Idx] = Load;
9140       LoadChains[Idx] = Load.getValue(1);
9141 
9142       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9143                             DAG.getConstant(Stride, dl,
9144                                             BasePtr.getValueType()));
9145     }
9146 
9147     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9148     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
9149 
9150     if (LN->isIndexed()) {
9151       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
9152       return DAG.getMergeValues(RetOps, dl);
9153     }
9154 
9155     SDValue RetOps[] = { Value, TF };
9156     return DAG.getMergeValues(RetOps, dl);
9157   }
9158 
9159   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
9160   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
9161 
9162   // To lower v4i1 from a byte array, we load the byte elements of the
9163   // vector and then reuse the BUILD_VECTOR logic.
9164 
9165   SDValue VectElmts[4], VectElmtChains[4];
9166   for (unsigned i = 0; i < 4; ++i) {
9167     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9168     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9169 
9170     VectElmts[i] = DAG.getExtLoad(
9171         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
9172         LN->getPointerInfo().getWithOffset(i), MVT::i8,
9173         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
9174     VectElmtChains[i] = VectElmts[i].getValue(1);
9175   }
9176 
9177   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
9178   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
9179 
9180   SDValue RVals[] = { Value, LoadChain };
9181   return DAG.getMergeValues(RVals, dl);
9182 }
9183 
9184 /// Lowering for QPX v4i1 stores
9185 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
9186                                             SelectionDAG &DAG) const {
9187   SDLoc dl(Op);
9188   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
9189   SDValue StoreChain = SN->getChain();
9190   SDValue BasePtr = SN->getBasePtr();
9191   SDValue Value = SN->getValue();
9192 
9193   if (Value.getValueType() == MVT::v4f64 ||
9194       Value.getValueType() == MVT::v4f32) {
9195     EVT MemVT = SN->getMemoryVT();
9196     unsigned Alignment = SN->getAlignment();
9197 
9198     // If this store is properly aligned, then it is legal.
9199     if (Alignment >= MemVT.getStoreSize())
9200       return Op;
9201 
9202     EVT ScalarVT = Value.getValueType().getScalarType(),
9203         ScalarMemVT = MemVT.getScalarType();
9204     unsigned Stride = ScalarMemVT.getStoreSize();
9205 
9206     SDValue Stores[4];
9207     for (unsigned Idx = 0; Idx < 4; ++Idx) {
9208       SDValue Ex = DAG.getNode(
9209           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
9210           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
9211       SDValue Store;
9212       if (ScalarVT != ScalarMemVT)
9213         Store =
9214             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
9215                               SN->getPointerInfo().getWithOffset(Idx * Stride),
9216                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
9217                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
9218       else
9219         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
9220                              SN->getPointerInfo().getWithOffset(Idx * Stride),
9221                              MinAlign(Alignment, Idx * Stride),
9222                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
9223 
9224       if (Idx == 0 && SN->isIndexed()) {
9225         assert(SN->getAddressingMode() == ISD::PRE_INC &&
9226                "Unknown addressing mode on vector store");
9227         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
9228                                     SN->getAddressingMode());
9229       }
9230 
9231       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
9232                             DAG.getConstant(Stride, dl,
9233                                             BasePtr.getValueType()));
9234       Stores[Idx] = Store;
9235     }
9236 
9237     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9238 
9239     if (SN->isIndexed()) {
9240       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
9241       return DAG.getMergeValues(RetOps, dl);
9242     }
9243 
9244     return TF;
9245   }
9246 
9247   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
9248   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
9249 
9250   // The values are now known to be -1 (false) or 1 (true). To convert this
9251   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
9252   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
9253   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
9254 
9255   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
9256   // understand how to form the extending load.
9257   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
9258 
9259   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
9260 
9261   // Now convert to an integer and store.
9262   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
9263     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
9264     Value);
9265 
9266   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9267   int FrameIdx = MFI.CreateStackObject(16, 16, false);
9268   MachinePointerInfo PtrInfo =
9269       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
9270   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9271   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
9272 
9273   SDValue Ops[] = {StoreChain,
9274                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
9275                    Value, FIdx};
9276   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
9277 
9278   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
9279     dl, VTs, Ops, MVT::v4i32, PtrInfo);
9280 
9281   // Move data into the byte array.
9282   SDValue Loads[4], LoadChains[4];
9283   for (unsigned i = 0; i < 4; ++i) {
9284     unsigned Offset = 4*i;
9285     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
9286     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
9287 
9288     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
9289                            PtrInfo.getWithOffset(Offset));
9290     LoadChains[i] = Loads[i].getValue(1);
9291   }
9292 
9293   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
9294 
9295   SDValue Stores[4];
9296   for (unsigned i = 0; i < 4; ++i) {
9297     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
9298     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
9299 
9300     Stores[i] = DAG.getTruncStore(
9301         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
9302         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
9303         SN->getAAInfo());
9304   }
9305 
9306   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9307 
9308   return StoreChain;
9309 }
9310 
9311 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
9312   SDLoc dl(Op);
9313   if (Op.getValueType() == MVT::v4i32) {
9314     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9315 
9316     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
9317     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
9318 
9319     SDValue RHSSwap =   // = vrlw RHS, 16
9320       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
9321 
9322     // Shrinkify inputs to v8i16.
9323     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
9324     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
9325     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
9326 
9327     // Low parts multiplied together, generating 32-bit results (we ignore the
9328     // top parts).
9329     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
9330                                         LHS, RHS, DAG, dl, MVT::v4i32);
9331 
9332     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
9333                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
9334     // Shift the high parts up 16 bits.
9335     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
9336                               Neg16, DAG, dl);
9337     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
9338   } else if (Op.getValueType() == MVT::v8i16) {
9339     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9340 
9341     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
9342 
9343     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
9344                             LHS, RHS, Zero, DAG, dl);
9345   } else if (Op.getValueType() == MVT::v16i8) {
9346     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
9347     bool isLittleEndian = Subtarget.isLittleEndian();
9348 
9349     // Multiply the even 8-bit parts, producing 16-bit sums.
9350     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
9351                                            LHS, RHS, DAG, dl, MVT::v8i16);
9352     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
9353 
9354     // Multiply the odd 8-bit parts, producing 16-bit sums.
9355     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
9356                                           LHS, RHS, DAG, dl, MVT::v8i16);
9357     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
9358 
9359     // Merge the results together.  Because vmuleub and vmuloub are
9360     // instructions with a big-endian bias, we must reverse the
9361     // element numbering and reverse the meaning of "odd" and "even"
9362     // when generating little endian code.
9363     int Ops[16];
9364     for (unsigned i = 0; i != 8; ++i) {
9365       if (isLittleEndian) {
9366         Ops[i*2  ] = 2*i;
9367         Ops[i*2+1] = 2*i+16;
9368       } else {
9369         Ops[i*2  ] = 2*i+1;
9370         Ops[i*2+1] = 2*i+1+16;
9371       }
9372     }
9373     if (isLittleEndian)
9374       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
9375     else
9376       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
9377   } else {
9378     llvm_unreachable("Unknown mul to lower!");
9379   }
9380 }
9381 
9382 /// LowerOperation - Provide custom lowering hooks for some operations.
9383 ///
9384 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
9385   switch (Op.getOpcode()) {
9386   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
9387   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
9388   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
9389   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
9390   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
9391   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
9392   case ISD::SETCC:              return LowerSETCC(Op, DAG);
9393   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
9394   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
9395 
9396   // Variable argument lowering.
9397   case ISD::VASTART:            return LowerVASTART(Op, DAG);
9398   case ISD::VAARG:              return LowerVAARG(Op, DAG);
9399   case ISD::VACOPY:             return LowerVACOPY(Op, DAG);
9400 
9401   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG);
9402   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
9403   case ISD::GET_DYNAMIC_AREA_OFFSET:
9404     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
9405 
9406   // Exception handling lowering.
9407   case ISD::EH_DWARF_CFA:       return LowerEH_DWARF_CFA(Op, DAG);
9408   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
9409   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
9410 
9411   case ISD::LOAD:               return LowerLOAD(Op, DAG);
9412   case ISD::STORE:              return LowerSTORE(Op, DAG);
9413   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
9414   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
9415   case ISD::FP_TO_UINT:
9416   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG, SDLoc(Op));
9417   case ISD::UINT_TO_FP:
9418   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
9419   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
9420 
9421   // Lower 64-bit shifts.
9422   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
9423   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
9424   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
9425 
9426   // Vector-related lowering.
9427   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
9428   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
9429   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
9430   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
9431   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
9432   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
9433   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
9434   case ISD::MUL:                return LowerMUL(Op, DAG);
9435 
9436   // For counter-based loop handling.
9437   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
9438 
9439   // Frame & Return address.
9440   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
9441   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
9442 
9443   case ISD::INTRINSIC_VOID:
9444     return LowerINTRINSIC_VOID(Op, DAG);
9445   case ISD::SREM:
9446   case ISD::UREM:
9447     return LowerREM(Op, DAG);
9448   case ISD::BSWAP:
9449     return LowerBSWAP(Op, DAG);
9450   case ISD::ATOMIC_CMP_SWAP:
9451     return LowerATOMIC_CMP_SWAP(Op, DAG);
9452   }
9453 }
9454 
9455 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
9456                                            SmallVectorImpl<SDValue>&Results,
9457                                            SelectionDAG &DAG) const {
9458   SDLoc dl(N);
9459   switch (N->getOpcode()) {
9460   default:
9461     llvm_unreachable("Do not know how to custom type legalize this operation!");
9462   case ISD::READCYCLECOUNTER: {
9463     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
9464     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
9465 
9466     Results.push_back(RTB);
9467     Results.push_back(RTB.getValue(1));
9468     Results.push_back(RTB.getValue(2));
9469     break;
9470   }
9471   case ISD::INTRINSIC_W_CHAIN: {
9472     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
9473         Intrinsic::ppc_is_decremented_ctr_nonzero)
9474       break;
9475 
9476     assert(N->getValueType(0) == MVT::i1 &&
9477            "Unexpected result type for CTR decrement intrinsic");
9478     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
9479                                  N->getValueType(0));
9480     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
9481     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
9482                                  N->getOperand(1));
9483 
9484     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewInt));
9485     Results.push_back(NewInt.getValue(1));
9486     break;
9487   }
9488   case ISD::VAARG: {
9489     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
9490       return;
9491 
9492     EVT VT = N->getValueType(0);
9493 
9494     if (VT == MVT::i64) {
9495       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
9496 
9497       Results.push_back(NewNode);
9498       Results.push_back(NewNode.getValue(1));
9499     }
9500     return;
9501   }
9502   case ISD::FP_TO_SINT:
9503   case ISD::FP_TO_UINT:
9504     // LowerFP_TO_INT() can only handle f32 and f64.
9505     if (N->getOperand(0).getValueType() == MVT::ppcf128)
9506       return;
9507     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
9508     return;
9509   }
9510 }
9511 
9512 //===----------------------------------------------------------------------===//
9513 //  Other Lowering Code
9514 //===----------------------------------------------------------------------===//
9515 
9516 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
9517   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9518   Function *Func = Intrinsic::getDeclaration(M, Id);
9519   return Builder.CreateCall(Func, {});
9520 }
9521 
9522 // The mappings for emitLeading/TrailingFence is taken from
9523 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
9524 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
9525                                                  Instruction *Inst,
9526                                                  AtomicOrdering Ord) const {
9527   if (Ord == AtomicOrdering::SequentiallyConsistent)
9528     return callIntrinsic(Builder, Intrinsic::ppc_sync);
9529   if (isReleaseOrStronger(Ord))
9530     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9531   return nullptr;
9532 }
9533 
9534 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
9535                                                   Instruction *Inst,
9536                                                   AtomicOrdering Ord) const {
9537   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
9538     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
9539     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
9540     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
9541     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
9542       return Builder.CreateCall(
9543           Intrinsic::getDeclaration(
9544               Builder.GetInsertBlock()->getParent()->getParent(),
9545               Intrinsic::ppc_cfence, {Inst->getType()}),
9546           {Inst});
9547     // FIXME: Can use isync for rmw operation.
9548     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
9549   }
9550   return nullptr;
9551 }
9552 
9553 MachineBasicBlock *
9554 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
9555                                     unsigned AtomicSize,
9556                                     unsigned BinOpcode,
9557                                     unsigned CmpOpcode,
9558                                     unsigned CmpPred) const {
9559   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9560   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9561 
9562   auto LoadMnemonic = PPC::LDARX;
9563   auto StoreMnemonic = PPC::STDCX;
9564   switch (AtomicSize) {
9565   default:
9566     llvm_unreachable("Unexpected size of atomic entity");
9567   case 1:
9568     LoadMnemonic = PPC::LBARX;
9569     StoreMnemonic = PPC::STBCX;
9570     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9571     break;
9572   case 2:
9573     LoadMnemonic = PPC::LHARX;
9574     StoreMnemonic = PPC::STHCX;
9575     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
9576     break;
9577   case 4:
9578     LoadMnemonic = PPC::LWARX;
9579     StoreMnemonic = PPC::STWCX;
9580     break;
9581   case 8:
9582     LoadMnemonic = PPC::LDARX;
9583     StoreMnemonic = PPC::STDCX;
9584     break;
9585   }
9586 
9587   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9588   MachineFunction *F = BB->getParent();
9589   MachineFunction::iterator It = ++BB->getIterator();
9590 
9591   unsigned dest = MI.getOperand(0).getReg();
9592   unsigned ptrA = MI.getOperand(1).getReg();
9593   unsigned ptrB = MI.getOperand(2).getReg();
9594   unsigned incr = MI.getOperand(3).getReg();
9595   DebugLoc dl = MI.getDebugLoc();
9596 
9597   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9598   MachineBasicBlock *loop2MBB =
9599     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9600   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9601   F->insert(It, loopMBB);
9602   if (CmpOpcode)
9603     F->insert(It, loop2MBB);
9604   F->insert(It, exitMBB);
9605   exitMBB->splice(exitMBB->begin(), BB,
9606                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9607   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9608 
9609   MachineRegisterInfo &RegInfo = F->getRegInfo();
9610   unsigned TmpReg = (!BinOpcode) ? incr :
9611     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
9612                                            : &PPC::GPRCRegClass);
9613 
9614   //  thisMBB:
9615   //   ...
9616   //   fallthrough --> loopMBB
9617   BB->addSuccessor(loopMBB);
9618 
9619   //  loopMBB:
9620   //   l[wd]arx dest, ptr
9621   //   add r0, dest, incr
9622   //   st[wd]cx. r0, ptr
9623   //   bne- loopMBB
9624   //   fallthrough --> exitMBB
9625 
9626   // For max/min...
9627   //  loopMBB:
9628   //   l[wd]arx dest, ptr
9629   //   cmpl?[wd] incr, dest
9630   //   bgt exitMBB
9631   //  loop2MBB:
9632   //   st[wd]cx. dest, ptr
9633   //   bne- loopMBB
9634   //   fallthrough --> exitMBB
9635 
9636   BB = loopMBB;
9637   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9638     .addReg(ptrA).addReg(ptrB);
9639   if (BinOpcode)
9640     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
9641   if (CmpOpcode) {
9642     // Signed comparisons of byte or halfword values must be sign-extended.
9643     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
9644       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9645       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
9646               ExtReg).addReg(dest);
9647       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9648         .addReg(incr).addReg(ExtReg);
9649     } else
9650       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9651         .addReg(incr).addReg(dest);
9652 
9653     BuildMI(BB, dl, TII->get(PPC::BCC))
9654       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9655     BB->addSuccessor(loop2MBB);
9656     BB->addSuccessor(exitMBB);
9657     BB = loop2MBB;
9658   }
9659   BuildMI(BB, dl, TII->get(StoreMnemonic))
9660     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9661   BuildMI(BB, dl, TII->get(PPC::BCC))
9662     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9663   BB->addSuccessor(loopMBB);
9664   BB->addSuccessor(exitMBB);
9665 
9666   //  exitMBB:
9667   //   ...
9668   BB = exitMBB;
9669   return BB;
9670 }
9671 
9672 MachineBasicBlock *
9673 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9674                                             MachineBasicBlock *BB,
9675                                             bool is8bit, // operation
9676                                             unsigned BinOpcode,
9677                                             unsigned CmpOpcode,
9678                                             unsigned CmpPred) const {
9679   // If we support part-word atomic mnemonics, just use them
9680   if (Subtarget.hasPartwordAtomics())
9681     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9682                             CmpOpcode, CmpPred);
9683 
9684   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9685   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9686   // In 64 bit mode we have to use 64 bits for addresses, even though the
9687   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9688   // registers without caring whether they're 32 or 64, but here we're
9689   // doing actual arithmetic on the addresses.
9690   bool is64bit = Subtarget.isPPC64();
9691   bool isLittleEndian = Subtarget.isLittleEndian();
9692   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9693 
9694   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9695   MachineFunction *F = BB->getParent();
9696   MachineFunction::iterator It = ++BB->getIterator();
9697 
9698   unsigned dest = MI.getOperand(0).getReg();
9699   unsigned ptrA = MI.getOperand(1).getReg();
9700   unsigned ptrB = MI.getOperand(2).getReg();
9701   unsigned incr = MI.getOperand(3).getReg();
9702   DebugLoc dl = MI.getDebugLoc();
9703 
9704   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9705   MachineBasicBlock *loop2MBB =
9706     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9707   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9708   F->insert(It, loopMBB);
9709   if (CmpOpcode)
9710     F->insert(It, loop2MBB);
9711   F->insert(It, exitMBB);
9712   exitMBB->splice(exitMBB->begin(), BB,
9713                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9714   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9715 
9716   MachineRegisterInfo &RegInfo = F->getRegInfo();
9717   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9718                                           : &PPC::GPRCRegClass;
9719   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9720   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9721   unsigned ShiftReg =
9722     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9723   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9724   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9725   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9726   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9727   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9728   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9729   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9730   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9731   unsigned Ptr1Reg;
9732   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9733 
9734   //  thisMBB:
9735   //   ...
9736   //   fallthrough --> loopMBB
9737   BB->addSuccessor(loopMBB);
9738 
9739   // The 4-byte load must be aligned, while a char or short may be
9740   // anywhere in the word.  Hence all this nasty bookkeeping code.
9741   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9742   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9743   //   xori shift, shift1, 24 [16]
9744   //   rlwinm ptr, ptr1, 0, 0, 29
9745   //   slw incr2, incr, shift
9746   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9747   //   slw mask, mask2, shift
9748   //  loopMBB:
9749   //   lwarx tmpDest, ptr
9750   //   add tmp, tmpDest, incr2
9751   //   andc tmp2, tmpDest, mask
9752   //   and tmp3, tmp, mask
9753   //   or tmp4, tmp3, tmp2
9754   //   stwcx. tmp4, ptr
9755   //   bne- loopMBB
9756   //   fallthrough --> exitMBB
9757   //   srw dest, tmpDest, shift
9758   if (ptrA != ZeroReg) {
9759     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9760     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9761       .addReg(ptrA).addReg(ptrB);
9762   } else {
9763     Ptr1Reg = ptrB;
9764   }
9765   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9766       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9767   if (!isLittleEndian)
9768     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9769         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9770   if (is64bit)
9771     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9772       .addReg(Ptr1Reg).addImm(0).addImm(61);
9773   else
9774     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9775       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9776   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9777       .addReg(incr).addReg(ShiftReg);
9778   if (is8bit)
9779     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9780   else {
9781     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9782     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9783   }
9784   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9785       .addReg(Mask2Reg).addReg(ShiftReg);
9786 
9787   BB = loopMBB;
9788   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9789     .addReg(ZeroReg).addReg(PtrReg);
9790   if (BinOpcode)
9791     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9792       .addReg(Incr2Reg).addReg(TmpDestReg);
9793   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9794     .addReg(TmpDestReg).addReg(MaskReg);
9795   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9796     .addReg(TmpReg).addReg(MaskReg);
9797   if (CmpOpcode) {
9798     // For unsigned comparisons, we can directly compare the shifted values.
9799     // For signed comparisons we shift and sign extend.
9800     unsigned SReg = RegInfo.createVirtualRegister(RC);
9801     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9802       .addReg(TmpDestReg).addReg(MaskReg);
9803     unsigned ValueReg = SReg;
9804     unsigned CmpReg = Incr2Reg;
9805     if (CmpOpcode == PPC::CMPW) {
9806       ValueReg = RegInfo.createVirtualRegister(RC);
9807       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9808         .addReg(SReg).addReg(ShiftReg);
9809       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9810       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9811         .addReg(ValueReg);
9812       ValueReg = ValueSReg;
9813       CmpReg = incr;
9814     }
9815     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9816       .addReg(CmpReg).addReg(ValueReg);
9817     BuildMI(BB, dl, TII->get(PPC::BCC))
9818       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9819     BB->addSuccessor(loop2MBB);
9820     BB->addSuccessor(exitMBB);
9821     BB = loop2MBB;
9822   }
9823   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9824     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9825   BuildMI(BB, dl, TII->get(PPC::STWCX))
9826     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9827   BuildMI(BB, dl, TII->get(PPC::BCC))
9828     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9829   BB->addSuccessor(loopMBB);
9830   BB->addSuccessor(exitMBB);
9831 
9832   //  exitMBB:
9833   //   ...
9834   BB = exitMBB;
9835   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9836     .addReg(ShiftReg);
9837   return BB;
9838 }
9839 
9840 llvm::MachineBasicBlock *
9841 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9842                                     MachineBasicBlock *MBB) const {
9843   DebugLoc DL = MI.getDebugLoc();
9844   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9845   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9846 
9847   MachineFunction *MF = MBB->getParent();
9848   MachineRegisterInfo &MRI = MF->getRegInfo();
9849 
9850   const BasicBlock *BB = MBB->getBasicBlock();
9851   MachineFunction::iterator I = ++MBB->getIterator();
9852 
9853   // Memory Reference
9854   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9855   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9856 
9857   unsigned DstReg = MI.getOperand(0).getReg();
9858   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9859   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9860   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9861   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9862 
9863   MVT PVT = getPointerTy(MF->getDataLayout());
9864   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9865          "Invalid Pointer Size!");
9866   // For v = setjmp(buf), we generate
9867   //
9868   // thisMBB:
9869   //  SjLjSetup mainMBB
9870   //  bl mainMBB
9871   //  v_restore = 1
9872   //  b sinkMBB
9873   //
9874   // mainMBB:
9875   //  buf[LabelOffset] = LR
9876   //  v_main = 0
9877   //
9878   // sinkMBB:
9879   //  v = phi(main, restore)
9880   //
9881 
9882   MachineBasicBlock *thisMBB = MBB;
9883   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9884   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9885   MF->insert(I, mainMBB);
9886   MF->insert(I, sinkMBB);
9887 
9888   MachineInstrBuilder MIB;
9889 
9890   // Transfer the remainder of BB and its successor edges to sinkMBB.
9891   sinkMBB->splice(sinkMBB->begin(), MBB,
9892                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9893   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9894 
9895   // Note that the structure of the jmp_buf used here is not compatible
9896   // with that used by libc, and is not designed to be. Specifically, it
9897   // stores only those 'reserved' registers that LLVM does not otherwise
9898   // understand how to spill. Also, by convention, by the time this
9899   // intrinsic is called, Clang has already stored the frame address in the
9900   // first slot of the buffer and stack address in the third. Following the
9901   // X86 target code, we'll store the jump address in the second slot. We also
9902   // need to save the TOC pointer (R2) to handle jumps between shared
9903   // libraries, and that will be stored in the fourth slot. The thread
9904   // identifier (R13) is not affected.
9905 
9906   // thisMBB:
9907   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9908   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9909   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9910 
9911   // Prepare IP either in reg.
9912   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9913   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9914   unsigned BufReg = MI.getOperand(1).getReg();
9915 
9916   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9917     setUsesTOCBasePtr(*MBB->getParent());
9918     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9919             .addReg(PPC::X2)
9920             .addImm(TOCOffset)
9921             .addReg(BufReg);
9922     MIB.setMemRefs(MMOBegin, MMOEnd);
9923   }
9924 
9925   // Naked functions never have a base pointer, and so we use r1. For all
9926   // other functions, this decision must be delayed until during PEI.
9927   unsigned BaseReg;
9928   if (MF->getFunction().hasFnAttribute(Attribute::Naked))
9929     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9930   else
9931     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9932 
9933   MIB = BuildMI(*thisMBB, MI, DL,
9934                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9935             .addReg(BaseReg)
9936             .addImm(BPOffset)
9937             .addReg(BufReg);
9938   MIB.setMemRefs(MMOBegin, MMOEnd);
9939 
9940   // Setup
9941   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9942   MIB.addRegMask(TRI->getNoPreservedMask());
9943 
9944   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9945 
9946   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9947           .addMBB(mainMBB);
9948   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9949 
9950   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9951   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9952 
9953   // mainMBB:
9954   //  mainDstReg = 0
9955   MIB =
9956       BuildMI(mainMBB, DL,
9957               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9958 
9959   // Store IP
9960   if (Subtarget.isPPC64()) {
9961     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9962             .addReg(LabelReg)
9963             .addImm(LabelOffset)
9964             .addReg(BufReg);
9965   } else {
9966     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9967             .addReg(LabelReg)
9968             .addImm(LabelOffset)
9969             .addReg(BufReg);
9970   }
9971 
9972   MIB.setMemRefs(MMOBegin, MMOEnd);
9973 
9974   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9975   mainMBB->addSuccessor(sinkMBB);
9976 
9977   // sinkMBB:
9978   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9979           TII->get(PPC::PHI), DstReg)
9980     .addReg(mainDstReg).addMBB(mainMBB)
9981     .addReg(restoreDstReg).addMBB(thisMBB);
9982 
9983   MI.eraseFromParent();
9984   return sinkMBB;
9985 }
9986 
9987 MachineBasicBlock *
9988 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9989                                      MachineBasicBlock *MBB) const {
9990   DebugLoc DL = MI.getDebugLoc();
9991   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9992 
9993   MachineFunction *MF = MBB->getParent();
9994   MachineRegisterInfo &MRI = MF->getRegInfo();
9995 
9996   // Memory Reference
9997   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9998   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9999 
10000   MVT PVT = getPointerTy(MF->getDataLayout());
10001   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
10002          "Invalid Pointer Size!");
10003 
10004   const TargetRegisterClass *RC =
10005     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
10006   unsigned Tmp = MRI.createVirtualRegister(RC);
10007   // Since FP is only updated here but NOT referenced, it's treated as GPR.
10008   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
10009   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
10010   unsigned BP =
10011       (PVT == MVT::i64)
10012           ? PPC::X30
10013           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
10014                                                               : PPC::R30);
10015 
10016   MachineInstrBuilder MIB;
10017 
10018   const int64_t LabelOffset = 1 * PVT.getStoreSize();
10019   const int64_t SPOffset    = 2 * PVT.getStoreSize();
10020   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
10021   const int64_t BPOffset    = 4 * PVT.getStoreSize();
10022 
10023   unsigned BufReg = MI.getOperand(0).getReg();
10024 
10025   // Reload FP (the jumped-to function may not have had a
10026   // frame pointer, and if so, then its r31 will be restored
10027   // as necessary).
10028   if (PVT == MVT::i64) {
10029     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
10030             .addImm(0)
10031             .addReg(BufReg);
10032   } else {
10033     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
10034             .addImm(0)
10035             .addReg(BufReg);
10036   }
10037   MIB.setMemRefs(MMOBegin, MMOEnd);
10038 
10039   // Reload IP
10040   if (PVT == MVT::i64) {
10041     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
10042             .addImm(LabelOffset)
10043             .addReg(BufReg);
10044   } else {
10045     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
10046             .addImm(LabelOffset)
10047             .addReg(BufReg);
10048   }
10049   MIB.setMemRefs(MMOBegin, MMOEnd);
10050 
10051   // Reload SP
10052   if (PVT == MVT::i64) {
10053     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
10054             .addImm(SPOffset)
10055             .addReg(BufReg);
10056   } else {
10057     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
10058             .addImm(SPOffset)
10059             .addReg(BufReg);
10060   }
10061   MIB.setMemRefs(MMOBegin, MMOEnd);
10062 
10063   // Reload BP
10064   if (PVT == MVT::i64) {
10065     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
10066             .addImm(BPOffset)
10067             .addReg(BufReg);
10068   } else {
10069     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
10070             .addImm(BPOffset)
10071             .addReg(BufReg);
10072   }
10073   MIB.setMemRefs(MMOBegin, MMOEnd);
10074 
10075   // Reload TOC
10076   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
10077     setUsesTOCBasePtr(*MBB->getParent());
10078     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
10079             .addImm(TOCOffset)
10080             .addReg(BufReg);
10081 
10082     MIB.setMemRefs(MMOBegin, MMOEnd);
10083   }
10084 
10085   // Jump
10086   BuildMI(*MBB, MI, DL,
10087           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
10088   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
10089 
10090   MI.eraseFromParent();
10091   return MBB;
10092 }
10093 
10094 MachineBasicBlock *
10095 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
10096                                                MachineBasicBlock *BB) const {
10097   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
10098       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10099     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
10100         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
10101       // Call lowering should have added an r2 operand to indicate a dependence
10102       // on the TOC base pointer value. It can't however, because there is no
10103       // way to mark the dependence as implicit there, and so the stackmap code
10104       // will confuse it with a regular operand. Instead, add the dependence
10105       // here.
10106       setUsesTOCBasePtr(*BB->getParent());
10107       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
10108     }
10109 
10110     return emitPatchPoint(MI, BB);
10111   }
10112 
10113   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
10114       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
10115     return emitEHSjLjSetJmp(MI, BB);
10116   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
10117              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
10118     return emitEHSjLjLongJmp(MI, BB);
10119   }
10120 
10121   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
10122 
10123   // To "insert" these instructions we actually have to insert their
10124   // control-flow patterns.
10125   const BasicBlock *LLVM_BB = BB->getBasicBlock();
10126   MachineFunction::iterator It = ++BB->getIterator();
10127 
10128   MachineFunction *F = BB->getParent();
10129 
10130   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10131        MI.getOpcode() == PPC::SELECT_CC_I8 ||
10132        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
10133     SmallVector<MachineOperand, 2> Cond;
10134     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10135         MI.getOpcode() == PPC::SELECT_CC_I8)
10136       Cond.push_back(MI.getOperand(4));
10137     else
10138       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
10139     Cond.push_back(MI.getOperand(1));
10140 
10141     DebugLoc dl = MI.getDebugLoc();
10142     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
10143                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
10144   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
10145              MI.getOpcode() == PPC::SELECT_CC_I8 ||
10146              MI.getOpcode() == PPC::SELECT_CC_F4 ||
10147              MI.getOpcode() == PPC::SELECT_CC_F8 ||
10148              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
10149              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
10150              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
10151              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
10152              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
10153              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
10154              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
10155              MI.getOpcode() == PPC::SELECT_I4 ||
10156              MI.getOpcode() == PPC::SELECT_I8 ||
10157              MI.getOpcode() == PPC::SELECT_F4 ||
10158              MI.getOpcode() == PPC::SELECT_F8 ||
10159              MI.getOpcode() == PPC::SELECT_QFRC ||
10160              MI.getOpcode() == PPC::SELECT_QSRC ||
10161              MI.getOpcode() == PPC::SELECT_QBRC ||
10162              MI.getOpcode() == PPC::SELECT_VRRC ||
10163              MI.getOpcode() == PPC::SELECT_VSFRC ||
10164              MI.getOpcode() == PPC::SELECT_VSSRC ||
10165              MI.getOpcode() == PPC::SELECT_VSRC) {
10166     // The incoming instruction knows the destination vreg to set, the
10167     // condition code register to branch on, the true/false values to
10168     // select between, and a branch opcode to use.
10169 
10170     //  thisMBB:
10171     //  ...
10172     //   TrueVal = ...
10173     //   cmpTY ccX, r1, r2
10174     //   bCC copy1MBB
10175     //   fallthrough --> copy0MBB
10176     MachineBasicBlock *thisMBB = BB;
10177     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
10178     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10179     DebugLoc dl = MI.getDebugLoc();
10180     F->insert(It, copy0MBB);
10181     F->insert(It, sinkMBB);
10182 
10183     // Transfer the remainder of BB and its successor edges to sinkMBB.
10184     sinkMBB->splice(sinkMBB->begin(), BB,
10185                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10186     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10187 
10188     // Next, add the true and fallthrough blocks as its successors.
10189     BB->addSuccessor(copy0MBB);
10190     BB->addSuccessor(sinkMBB);
10191 
10192     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
10193         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
10194         MI.getOpcode() == PPC::SELECT_QFRC ||
10195         MI.getOpcode() == PPC::SELECT_QSRC ||
10196         MI.getOpcode() == PPC::SELECT_QBRC ||
10197         MI.getOpcode() == PPC::SELECT_VRRC ||
10198         MI.getOpcode() == PPC::SELECT_VSFRC ||
10199         MI.getOpcode() == PPC::SELECT_VSSRC ||
10200         MI.getOpcode() == PPC::SELECT_VSRC) {
10201       BuildMI(BB, dl, TII->get(PPC::BC))
10202           .addReg(MI.getOperand(1).getReg())
10203           .addMBB(sinkMBB);
10204     } else {
10205       unsigned SelectPred = MI.getOperand(4).getImm();
10206       BuildMI(BB, dl, TII->get(PPC::BCC))
10207           .addImm(SelectPred)
10208           .addReg(MI.getOperand(1).getReg())
10209           .addMBB(sinkMBB);
10210     }
10211 
10212     //  copy0MBB:
10213     //   %FalseValue = ...
10214     //   # fallthrough to sinkMBB
10215     BB = copy0MBB;
10216 
10217     // Update machine-CFG edges
10218     BB->addSuccessor(sinkMBB);
10219 
10220     //  sinkMBB:
10221     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
10222     //  ...
10223     BB = sinkMBB;
10224     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
10225         .addReg(MI.getOperand(3).getReg())
10226         .addMBB(copy0MBB)
10227         .addReg(MI.getOperand(2).getReg())
10228         .addMBB(thisMBB);
10229   } else if (MI.getOpcode() == PPC::ReadTB) {
10230     // To read the 64-bit time-base register on a 32-bit target, we read the
10231     // two halves. Should the counter have wrapped while it was being read, we
10232     // need to try again.
10233     // ...
10234     // readLoop:
10235     // mfspr Rx,TBU # load from TBU
10236     // mfspr Ry,TB  # load from TB
10237     // mfspr Rz,TBU # load from TBU
10238     // cmpw crX,Rx,Rz # check if 'old'='new'
10239     // bne readLoop   # branch if they're not equal
10240     // ...
10241 
10242     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
10243     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
10244     DebugLoc dl = MI.getDebugLoc();
10245     F->insert(It, readMBB);
10246     F->insert(It, sinkMBB);
10247 
10248     // Transfer the remainder of BB and its successor edges to sinkMBB.
10249     sinkMBB->splice(sinkMBB->begin(), BB,
10250                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10251     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
10252 
10253     BB->addSuccessor(readMBB);
10254     BB = readMBB;
10255 
10256     MachineRegisterInfo &RegInfo = F->getRegInfo();
10257     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
10258     unsigned LoReg = MI.getOperand(0).getReg();
10259     unsigned HiReg = MI.getOperand(1).getReg();
10260 
10261     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
10262     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
10263     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
10264 
10265     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10266 
10267     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
10268       .addReg(HiReg).addReg(ReadAgainReg);
10269     BuildMI(BB, dl, TII->get(PPC::BCC))
10270       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
10271 
10272     BB->addSuccessor(readMBB);
10273     BB->addSuccessor(sinkMBB);
10274   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
10275     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
10276   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
10277     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
10278   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
10279     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
10280   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
10281     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
10282 
10283   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
10284     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
10285   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
10286     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
10287   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
10288     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
10289   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
10290     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
10291 
10292   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
10293     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
10294   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
10295     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
10296   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
10297     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
10298   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
10299     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
10300 
10301   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
10302     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
10303   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
10304     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
10305   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
10306     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
10307   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
10308     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
10309 
10310   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
10311     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
10312   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
10313     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
10314   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
10315     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
10316   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
10317     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
10318 
10319   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
10320     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
10321   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
10322     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
10323   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
10324     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
10325   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
10326     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
10327 
10328   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
10329     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
10330   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
10331     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
10332   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
10333     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
10334   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
10335     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
10336 
10337   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
10338     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
10339   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
10340     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
10341   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
10342     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
10343   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
10344     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
10345 
10346   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
10347     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
10348   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
10349     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
10350   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
10351     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
10352   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
10353     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
10354 
10355   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
10356     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
10357   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
10358     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
10359   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
10360     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
10361   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
10362     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
10363 
10364   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
10365     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
10366   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
10367     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
10368   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
10369     BB = EmitAtomicBinary(MI, BB, 4, 0);
10370   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
10371     BB = EmitAtomicBinary(MI, BB, 8, 0);
10372   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
10373            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
10374            (Subtarget.hasPartwordAtomics() &&
10375             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
10376            (Subtarget.hasPartwordAtomics() &&
10377             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
10378     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
10379 
10380     auto LoadMnemonic = PPC::LDARX;
10381     auto StoreMnemonic = PPC::STDCX;
10382     switch (MI.getOpcode()) {
10383     default:
10384       llvm_unreachable("Compare and swap of unknown size");
10385     case PPC::ATOMIC_CMP_SWAP_I8:
10386       LoadMnemonic = PPC::LBARX;
10387       StoreMnemonic = PPC::STBCX;
10388       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10389       break;
10390     case PPC::ATOMIC_CMP_SWAP_I16:
10391       LoadMnemonic = PPC::LHARX;
10392       StoreMnemonic = PPC::STHCX;
10393       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
10394       break;
10395     case PPC::ATOMIC_CMP_SWAP_I32:
10396       LoadMnemonic = PPC::LWARX;
10397       StoreMnemonic = PPC::STWCX;
10398       break;
10399     case PPC::ATOMIC_CMP_SWAP_I64:
10400       LoadMnemonic = PPC::LDARX;
10401       StoreMnemonic = PPC::STDCX;
10402       break;
10403     }
10404     unsigned dest = MI.getOperand(0).getReg();
10405     unsigned ptrA = MI.getOperand(1).getReg();
10406     unsigned ptrB = MI.getOperand(2).getReg();
10407     unsigned oldval = MI.getOperand(3).getReg();
10408     unsigned newval = MI.getOperand(4).getReg();
10409     DebugLoc dl = MI.getDebugLoc();
10410 
10411     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10412     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10413     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10414     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10415     F->insert(It, loop1MBB);
10416     F->insert(It, loop2MBB);
10417     F->insert(It, midMBB);
10418     F->insert(It, exitMBB);
10419     exitMBB->splice(exitMBB->begin(), BB,
10420                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10421     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10422 
10423     //  thisMBB:
10424     //   ...
10425     //   fallthrough --> loopMBB
10426     BB->addSuccessor(loop1MBB);
10427 
10428     // loop1MBB:
10429     //   l[bhwd]arx dest, ptr
10430     //   cmp[wd] dest, oldval
10431     //   bne- midMBB
10432     // loop2MBB:
10433     //   st[bhwd]cx. newval, ptr
10434     //   bne- loopMBB
10435     //   b exitBB
10436     // midMBB:
10437     //   st[bhwd]cx. dest, ptr
10438     // exitBB:
10439     BB = loop1MBB;
10440     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
10441       .addReg(ptrA).addReg(ptrB);
10442     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
10443       .addReg(oldval).addReg(dest);
10444     BuildMI(BB, dl, TII->get(PPC::BCC))
10445       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10446     BB->addSuccessor(loop2MBB);
10447     BB->addSuccessor(midMBB);
10448 
10449     BB = loop2MBB;
10450     BuildMI(BB, dl, TII->get(StoreMnemonic))
10451       .addReg(newval).addReg(ptrA).addReg(ptrB);
10452     BuildMI(BB, dl, TII->get(PPC::BCC))
10453       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10454     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10455     BB->addSuccessor(loop1MBB);
10456     BB->addSuccessor(exitMBB);
10457 
10458     BB = midMBB;
10459     BuildMI(BB, dl, TII->get(StoreMnemonic))
10460       .addReg(dest).addReg(ptrA).addReg(ptrB);
10461     BB->addSuccessor(exitMBB);
10462 
10463     //  exitMBB:
10464     //   ...
10465     BB = exitMBB;
10466   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
10467              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
10468     // We must use 64-bit registers for addresses when targeting 64-bit,
10469     // since we're actually doing arithmetic on them.  Other registers
10470     // can be 32-bit.
10471     bool is64bit = Subtarget.isPPC64();
10472     bool isLittleEndian = Subtarget.isLittleEndian();
10473     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
10474 
10475     unsigned dest = MI.getOperand(0).getReg();
10476     unsigned ptrA = MI.getOperand(1).getReg();
10477     unsigned ptrB = MI.getOperand(2).getReg();
10478     unsigned oldval = MI.getOperand(3).getReg();
10479     unsigned newval = MI.getOperand(4).getReg();
10480     DebugLoc dl = MI.getDebugLoc();
10481 
10482     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
10483     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
10484     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
10485     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
10486     F->insert(It, loop1MBB);
10487     F->insert(It, loop2MBB);
10488     F->insert(It, midMBB);
10489     F->insert(It, exitMBB);
10490     exitMBB->splice(exitMBB->begin(), BB,
10491                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
10492     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
10493 
10494     MachineRegisterInfo &RegInfo = F->getRegInfo();
10495     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
10496                                             : &PPC::GPRCRegClass;
10497     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
10498     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
10499     unsigned ShiftReg =
10500       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
10501     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
10502     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
10503     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
10504     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
10505     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
10506     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
10507     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
10508     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
10509     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
10510     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
10511     unsigned Ptr1Reg;
10512     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
10513     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
10514     //  thisMBB:
10515     //   ...
10516     //   fallthrough --> loopMBB
10517     BB->addSuccessor(loop1MBB);
10518 
10519     // The 4-byte load must be aligned, while a char or short may be
10520     // anywhere in the word.  Hence all this nasty bookkeeping code.
10521     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
10522     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
10523     //   xori shift, shift1, 24 [16]
10524     //   rlwinm ptr, ptr1, 0, 0, 29
10525     //   slw newval2, newval, shift
10526     //   slw oldval2, oldval,shift
10527     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
10528     //   slw mask, mask2, shift
10529     //   and newval3, newval2, mask
10530     //   and oldval3, oldval2, mask
10531     // loop1MBB:
10532     //   lwarx tmpDest, ptr
10533     //   and tmp, tmpDest, mask
10534     //   cmpw tmp, oldval3
10535     //   bne- midMBB
10536     // loop2MBB:
10537     //   andc tmp2, tmpDest, mask
10538     //   or tmp4, tmp2, newval3
10539     //   stwcx. tmp4, ptr
10540     //   bne- loop1MBB
10541     //   b exitBB
10542     // midMBB:
10543     //   stwcx. tmpDest, ptr
10544     // exitBB:
10545     //   srw dest, tmpDest, shift
10546     if (ptrA != ZeroReg) {
10547       Ptr1Reg = RegInfo.createVirtualRegister(RC);
10548       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
10549         .addReg(ptrA).addReg(ptrB);
10550     } else {
10551       Ptr1Reg = ptrB;
10552     }
10553     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
10554         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
10555     if (!isLittleEndian)
10556       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
10557           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
10558     if (is64bit)
10559       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
10560         .addReg(Ptr1Reg).addImm(0).addImm(61);
10561     else
10562       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
10563         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
10564     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
10565         .addReg(newval).addReg(ShiftReg);
10566     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
10567         .addReg(oldval).addReg(ShiftReg);
10568     if (is8bit)
10569       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
10570     else {
10571       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
10572       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
10573         .addReg(Mask3Reg).addImm(65535);
10574     }
10575     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
10576         .addReg(Mask2Reg).addReg(ShiftReg);
10577     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
10578         .addReg(NewVal2Reg).addReg(MaskReg);
10579     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
10580         .addReg(OldVal2Reg).addReg(MaskReg);
10581 
10582     BB = loop1MBB;
10583     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
10584         .addReg(ZeroReg).addReg(PtrReg);
10585     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
10586         .addReg(TmpDestReg).addReg(MaskReg);
10587     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
10588         .addReg(TmpReg).addReg(OldVal3Reg);
10589     BuildMI(BB, dl, TII->get(PPC::BCC))
10590         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
10591     BB->addSuccessor(loop2MBB);
10592     BB->addSuccessor(midMBB);
10593 
10594     BB = loop2MBB;
10595     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
10596         .addReg(TmpDestReg).addReg(MaskReg);
10597     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
10598         .addReg(Tmp2Reg).addReg(NewVal3Reg);
10599     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
10600         .addReg(ZeroReg).addReg(PtrReg);
10601     BuildMI(BB, dl, TII->get(PPC::BCC))
10602       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
10603     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
10604     BB->addSuccessor(loop1MBB);
10605     BB->addSuccessor(exitMBB);
10606 
10607     BB = midMBB;
10608     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
10609       .addReg(ZeroReg).addReg(PtrReg);
10610     BB->addSuccessor(exitMBB);
10611 
10612     //  exitMBB:
10613     //   ...
10614     BB = exitMBB;
10615     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
10616       .addReg(ShiftReg);
10617   } else if (MI.getOpcode() == PPC::FADDrtz) {
10618     // This pseudo performs an FADD with rounding mode temporarily forced
10619     // to round-to-zero.  We emit this via custom inserter since the FPSCR
10620     // is not modeled at the SelectionDAG level.
10621     unsigned Dest = MI.getOperand(0).getReg();
10622     unsigned Src1 = MI.getOperand(1).getReg();
10623     unsigned Src2 = MI.getOperand(2).getReg();
10624     DebugLoc dl = MI.getDebugLoc();
10625 
10626     MachineRegisterInfo &RegInfo = F->getRegInfo();
10627     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
10628 
10629     // Save FPSCR value.
10630     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
10631 
10632     // Set rounding mode to round-to-zero.
10633     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
10634     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
10635 
10636     // Perform addition.
10637     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
10638 
10639     // Restore FPSCR value.
10640     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
10641   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10642              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
10643              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10644              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
10645     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
10646                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
10647                           ? PPC::ANDIo8
10648                           : PPC::ANDIo;
10649     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
10650                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
10651 
10652     MachineRegisterInfo &RegInfo = F->getRegInfo();
10653     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
10654                                                   &PPC::GPRCRegClass :
10655                                                   &PPC::G8RCRegClass);
10656 
10657     DebugLoc dl = MI.getDebugLoc();
10658     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10659         .addReg(MI.getOperand(1).getReg())
10660         .addImm(1);
10661     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10662             MI.getOperand(0).getReg())
10663         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10664   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10665     DebugLoc Dl = MI.getDebugLoc();
10666     MachineRegisterInfo &RegInfo = F->getRegInfo();
10667     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10668     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10669     return BB;
10670   } else {
10671     llvm_unreachable("Unexpected instr type to insert");
10672   }
10673 
10674   MI.eraseFromParent(); // The pseudo instruction is gone now.
10675   return BB;
10676 }
10677 
10678 //===----------------------------------------------------------------------===//
10679 // Target Optimization Hooks
10680 //===----------------------------------------------------------------------===//
10681 
10682 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10683   // For the estimates, convergence is quadratic, so we essentially double the
10684   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10685   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10686   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10687   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10688   if (VT.getScalarType() == MVT::f64)
10689     RefinementSteps++;
10690   return RefinementSteps;
10691 }
10692 
10693 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10694                                            int Enabled, int &RefinementSteps,
10695                                            bool &UseOneConstNR,
10696                                            bool Reciprocal) const {
10697   EVT VT = Operand.getValueType();
10698   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10699       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10700       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10701       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10702       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10703       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10704     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10705       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10706 
10707     UseOneConstNR = true;
10708     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10709   }
10710   return SDValue();
10711 }
10712 
10713 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10714                                             int Enabled,
10715                                             int &RefinementSteps) const {
10716   EVT VT = Operand.getValueType();
10717   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10718       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10719       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10720       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10721       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10722       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10723     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10724       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10725     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10726   }
10727   return SDValue();
10728 }
10729 
10730 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10731   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10732   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10733   // enabled for division), this functionality is redundant with the default
10734   // combiner logic (once the division -> reciprocal/multiply transformation
10735   // has taken place). As a result, this matters more for older cores than for
10736   // newer ones.
10737 
10738   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10739   // reciprocal if there are two or more FDIVs (for embedded cores with only
10740   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10741   switch (Subtarget.getDarwinDirective()) {
10742   default:
10743     return 3;
10744   case PPC::DIR_440:
10745   case PPC::DIR_A2:
10746   case PPC::DIR_E500mc:
10747   case PPC::DIR_E5500:
10748     return 2;
10749   }
10750 }
10751 
10752 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10753 // collapsed, and so we need to look through chains of them.
10754 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10755                                      int64_t& Offset, SelectionDAG &DAG) {
10756   if (DAG.isBaseWithConstantOffset(Loc)) {
10757     Base = Loc.getOperand(0);
10758     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10759 
10760     // The base might itself be a base plus an offset, and if so, accumulate
10761     // that as well.
10762     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10763   }
10764 }
10765 
10766 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10767                             unsigned Bytes, int Dist,
10768                             SelectionDAG &DAG) {
10769   if (VT.getSizeInBits() / 8 != Bytes)
10770     return false;
10771 
10772   SDValue BaseLoc = Base->getBasePtr();
10773   if (Loc.getOpcode() == ISD::FrameIndex) {
10774     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10775       return false;
10776     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10777     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10778     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10779     int FS  = MFI.getObjectSize(FI);
10780     int BFS = MFI.getObjectSize(BFI);
10781     if (FS != BFS || FS != (int)Bytes) return false;
10782     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10783   }
10784 
10785   SDValue Base1 = Loc, Base2 = BaseLoc;
10786   int64_t Offset1 = 0, Offset2 = 0;
10787   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10788   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10789   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10790     return true;
10791 
10792   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10793   const GlobalValue *GV1 = nullptr;
10794   const GlobalValue *GV2 = nullptr;
10795   Offset1 = 0;
10796   Offset2 = 0;
10797   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10798   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10799   if (isGA1 && isGA2 && GV1 == GV2)
10800     return Offset1 == (Offset2 + Dist*Bytes);
10801   return false;
10802 }
10803 
10804 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10805 // not enforce equality of the chain operands.
10806 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10807                             unsigned Bytes, int Dist,
10808                             SelectionDAG &DAG) {
10809   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10810     EVT VT = LS->getMemoryVT();
10811     SDValue Loc = LS->getBasePtr();
10812     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10813   }
10814 
10815   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10816     EVT VT;
10817     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10818     default: return false;
10819     case Intrinsic::ppc_qpx_qvlfd:
10820     case Intrinsic::ppc_qpx_qvlfda:
10821       VT = MVT::v4f64;
10822       break;
10823     case Intrinsic::ppc_qpx_qvlfs:
10824     case Intrinsic::ppc_qpx_qvlfsa:
10825       VT = MVT::v4f32;
10826       break;
10827     case Intrinsic::ppc_qpx_qvlfcd:
10828     case Intrinsic::ppc_qpx_qvlfcda:
10829       VT = MVT::v2f64;
10830       break;
10831     case Intrinsic::ppc_qpx_qvlfcs:
10832     case Intrinsic::ppc_qpx_qvlfcsa:
10833       VT = MVT::v2f32;
10834       break;
10835     case Intrinsic::ppc_qpx_qvlfiwa:
10836     case Intrinsic::ppc_qpx_qvlfiwz:
10837     case Intrinsic::ppc_altivec_lvx:
10838     case Intrinsic::ppc_altivec_lvxl:
10839     case Intrinsic::ppc_vsx_lxvw4x:
10840     case Intrinsic::ppc_vsx_lxvw4x_be:
10841       VT = MVT::v4i32;
10842       break;
10843     case Intrinsic::ppc_vsx_lxvd2x:
10844     case Intrinsic::ppc_vsx_lxvd2x_be:
10845       VT = MVT::v2f64;
10846       break;
10847     case Intrinsic::ppc_altivec_lvebx:
10848       VT = MVT::i8;
10849       break;
10850     case Intrinsic::ppc_altivec_lvehx:
10851       VT = MVT::i16;
10852       break;
10853     case Intrinsic::ppc_altivec_lvewx:
10854       VT = MVT::i32;
10855       break;
10856     }
10857 
10858     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10859   }
10860 
10861   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10862     EVT VT;
10863     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10864     default: return false;
10865     case Intrinsic::ppc_qpx_qvstfd:
10866     case Intrinsic::ppc_qpx_qvstfda:
10867       VT = MVT::v4f64;
10868       break;
10869     case Intrinsic::ppc_qpx_qvstfs:
10870     case Intrinsic::ppc_qpx_qvstfsa:
10871       VT = MVT::v4f32;
10872       break;
10873     case Intrinsic::ppc_qpx_qvstfcd:
10874     case Intrinsic::ppc_qpx_qvstfcda:
10875       VT = MVT::v2f64;
10876       break;
10877     case Intrinsic::ppc_qpx_qvstfcs:
10878     case Intrinsic::ppc_qpx_qvstfcsa:
10879       VT = MVT::v2f32;
10880       break;
10881     case Intrinsic::ppc_qpx_qvstfiw:
10882     case Intrinsic::ppc_qpx_qvstfiwa:
10883     case Intrinsic::ppc_altivec_stvx:
10884     case Intrinsic::ppc_altivec_stvxl:
10885     case Intrinsic::ppc_vsx_stxvw4x:
10886       VT = MVT::v4i32;
10887       break;
10888     case Intrinsic::ppc_vsx_stxvd2x:
10889       VT = MVT::v2f64;
10890       break;
10891     case Intrinsic::ppc_vsx_stxvw4x_be:
10892       VT = MVT::v4i32;
10893       break;
10894     case Intrinsic::ppc_vsx_stxvd2x_be:
10895       VT = MVT::v2f64;
10896       break;
10897     case Intrinsic::ppc_altivec_stvebx:
10898       VT = MVT::i8;
10899       break;
10900     case Intrinsic::ppc_altivec_stvehx:
10901       VT = MVT::i16;
10902       break;
10903     case Intrinsic::ppc_altivec_stvewx:
10904       VT = MVT::i32;
10905       break;
10906     }
10907 
10908     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10909   }
10910 
10911   return false;
10912 }
10913 
10914 // Return true is there is a nearyby consecutive load to the one provided
10915 // (regardless of alignment). We search up and down the chain, looking though
10916 // token factors and other loads (but nothing else). As a result, a true result
10917 // indicates that it is safe to create a new consecutive load adjacent to the
10918 // load provided.
10919 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10920   SDValue Chain = LD->getChain();
10921   EVT VT = LD->getMemoryVT();
10922 
10923   SmallSet<SDNode *, 16> LoadRoots;
10924   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10925   SmallSet<SDNode *, 16> Visited;
10926 
10927   // First, search up the chain, branching to follow all token-factor operands.
10928   // If we find a consecutive load, then we're done, otherwise, record all
10929   // nodes just above the top-level loads and token factors.
10930   while (!Queue.empty()) {
10931     SDNode *ChainNext = Queue.pop_back_val();
10932     if (!Visited.insert(ChainNext).second)
10933       continue;
10934 
10935     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10936       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10937         return true;
10938 
10939       if (!Visited.count(ChainLD->getChain().getNode()))
10940         Queue.push_back(ChainLD->getChain().getNode());
10941     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10942       for (const SDUse &O : ChainNext->ops())
10943         if (!Visited.count(O.getNode()))
10944           Queue.push_back(O.getNode());
10945     } else
10946       LoadRoots.insert(ChainNext);
10947   }
10948 
10949   // Second, search down the chain, starting from the top-level nodes recorded
10950   // in the first phase. These top-level nodes are the nodes just above all
10951   // loads and token factors. Starting with their uses, recursively look though
10952   // all loads (just the chain uses) and token factors to find a consecutive
10953   // load.
10954   Visited.clear();
10955   Queue.clear();
10956 
10957   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10958        IE = LoadRoots.end(); I != IE; ++I) {
10959     Queue.push_back(*I);
10960 
10961     while (!Queue.empty()) {
10962       SDNode *LoadRoot = Queue.pop_back_val();
10963       if (!Visited.insert(LoadRoot).second)
10964         continue;
10965 
10966       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10967         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10968           return true;
10969 
10970       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10971            UE = LoadRoot->use_end(); UI != UE; ++UI)
10972         if (((isa<MemSDNode>(*UI) &&
10973             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10974             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10975           Queue.push_back(*UI);
10976     }
10977   }
10978 
10979   return false;
10980 }
10981 
10982 /// This function is called when we have proved that a SETCC node can be replaced
10983 /// by subtraction (and other supporting instructions) so that the result of
10984 /// comparison is kept in a GPR instead of CR. This function is purely for
10985 /// codegen purposes and has some flags to guide the codegen process.
10986 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10987                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10988   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10989 
10990   // Zero extend the operands to the largest legal integer. Originally, they
10991   // must be of a strictly smaller size.
10992   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10993                          DAG.getConstant(Size, DL, MVT::i32));
10994   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10995                          DAG.getConstant(Size, DL, MVT::i32));
10996 
10997   // Swap if needed. Depends on the condition code.
10998   if (Swap)
10999     std::swap(Op0, Op1);
11000 
11001   // Subtract extended integers.
11002   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
11003 
11004   // Move the sign bit to the least significant position and zero out the rest.
11005   // Now the least significant bit carries the result of original comparison.
11006   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
11007                              DAG.getConstant(Size - 1, DL, MVT::i32));
11008   auto Final = Shifted;
11009 
11010   // Complement the result if needed. Based on the condition code.
11011   if (Complement)
11012     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
11013                         DAG.getConstant(1, DL, MVT::i64));
11014 
11015   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
11016 }
11017 
11018 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
11019                                                   DAGCombinerInfo &DCI) const {
11020   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
11021 
11022   SelectionDAG &DAG = DCI.DAG;
11023   SDLoc DL(N);
11024 
11025   // Size of integers being compared has a critical role in the following
11026   // analysis, so we prefer to do this when all types are legal.
11027   if (!DCI.isAfterLegalizeDAG())
11028     return SDValue();
11029 
11030   // If all users of SETCC extend its value to a legal integer type
11031   // then we replace SETCC with a subtraction
11032   for (SDNode::use_iterator UI = N->use_begin(),
11033        UE = N->use_end(); UI != UE; ++UI) {
11034     if (UI->getOpcode() != ISD::ZERO_EXTEND)
11035       return SDValue();
11036   }
11037 
11038   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
11039   auto OpSize = N->getOperand(0).getValueSizeInBits();
11040 
11041   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
11042 
11043   if (OpSize < Size) {
11044     switch (CC) {
11045     default: break;
11046     case ISD::SETULT:
11047       return generateEquivalentSub(N, Size, false, false, DL, DAG);
11048     case ISD::SETULE:
11049       return generateEquivalentSub(N, Size, true, true, DL, DAG);
11050     case ISD::SETUGT:
11051       return generateEquivalentSub(N, Size, false, true, DL, DAG);
11052     case ISD::SETUGE:
11053       return generateEquivalentSub(N, Size, true, false, DL, DAG);
11054     }
11055   }
11056 
11057   return SDValue();
11058 }
11059 
11060 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
11061                                                   DAGCombinerInfo &DCI) const {
11062   SelectionDAG &DAG = DCI.DAG;
11063   SDLoc dl(N);
11064 
11065   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
11066   // If we're tracking CR bits, we need to be careful that we don't have:
11067   //   trunc(binary-ops(zext(x), zext(y)))
11068   // or
11069   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
11070   // such that we're unnecessarily moving things into GPRs when it would be
11071   // better to keep them in CR bits.
11072 
11073   // Note that trunc here can be an actual i1 trunc, or can be the effective
11074   // truncation that comes from a setcc or select_cc.
11075   if (N->getOpcode() == ISD::TRUNCATE &&
11076       N->getValueType(0) != MVT::i1)
11077     return SDValue();
11078 
11079   if (N->getOperand(0).getValueType() != MVT::i32 &&
11080       N->getOperand(0).getValueType() != MVT::i64)
11081     return SDValue();
11082 
11083   if (N->getOpcode() == ISD::SETCC ||
11084       N->getOpcode() == ISD::SELECT_CC) {
11085     // If we're looking at a comparison, then we need to make sure that the
11086     // high bits (all except for the first) don't matter the result.
11087     ISD::CondCode CC =
11088       cast<CondCodeSDNode>(N->getOperand(
11089         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
11090     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
11091 
11092     if (ISD::isSignedIntSetCC(CC)) {
11093       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
11094           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
11095         return SDValue();
11096     } else if (ISD::isUnsignedIntSetCC(CC)) {
11097       if (!DAG.MaskedValueIsZero(N->getOperand(0),
11098                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
11099           !DAG.MaskedValueIsZero(N->getOperand(1),
11100                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
11101         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
11102                                              : SDValue());
11103     } else {
11104       // This is neither a signed nor an unsigned comparison, just make sure
11105       // that the high bits are equal.
11106       KnownBits Op1Known, Op2Known;
11107       DAG.computeKnownBits(N->getOperand(0), Op1Known);
11108       DAG.computeKnownBits(N->getOperand(1), Op2Known);
11109 
11110       // We don't really care about what is known about the first bit (if
11111       // anything), so clear it in all masks prior to comparing them.
11112       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
11113       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
11114 
11115       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
11116         return SDValue();
11117     }
11118   }
11119 
11120   // We now know that the higher-order bits are irrelevant, we just need to
11121   // make sure that all of the intermediate operations are bit operations, and
11122   // all inputs are extensions.
11123   if (N->getOperand(0).getOpcode() != ISD::AND &&
11124       N->getOperand(0).getOpcode() != ISD::OR  &&
11125       N->getOperand(0).getOpcode() != ISD::XOR &&
11126       N->getOperand(0).getOpcode() != ISD::SELECT &&
11127       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
11128       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
11129       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
11130       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
11131       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
11132     return SDValue();
11133 
11134   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
11135       N->getOperand(1).getOpcode() != ISD::AND &&
11136       N->getOperand(1).getOpcode() != ISD::OR  &&
11137       N->getOperand(1).getOpcode() != ISD::XOR &&
11138       N->getOperand(1).getOpcode() != ISD::SELECT &&
11139       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
11140       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
11141       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
11142       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
11143       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
11144     return SDValue();
11145 
11146   SmallVector<SDValue, 4> Inputs;
11147   SmallVector<SDValue, 8> BinOps, PromOps;
11148   SmallPtrSet<SDNode *, 16> Visited;
11149 
11150   for (unsigned i = 0; i < 2; ++i) {
11151     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11152           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11153           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11154           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11155         isa<ConstantSDNode>(N->getOperand(i)))
11156       Inputs.push_back(N->getOperand(i));
11157     else
11158       BinOps.push_back(N->getOperand(i));
11159 
11160     if (N->getOpcode() == ISD::TRUNCATE)
11161       break;
11162   }
11163 
11164   // Visit all inputs, collect all binary operations (and, or, xor and
11165   // select) that are all fed by extensions.
11166   while (!BinOps.empty()) {
11167     SDValue BinOp = BinOps.back();
11168     BinOps.pop_back();
11169 
11170     if (!Visited.insert(BinOp.getNode()).second)
11171       continue;
11172 
11173     PromOps.push_back(BinOp);
11174 
11175     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11176       // The condition of the select is not promoted.
11177       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11178         continue;
11179       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11180         continue;
11181 
11182       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11183             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11184             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
11185            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
11186           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11187         Inputs.push_back(BinOp.getOperand(i));
11188       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11189                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11190                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11191                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11192                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
11193                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11194                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
11195                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
11196                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
11197         BinOps.push_back(BinOp.getOperand(i));
11198       } else {
11199         // We have an input that is not an extension or another binary
11200         // operation; we'll abort this transformation.
11201         return SDValue();
11202       }
11203     }
11204   }
11205 
11206   // Make sure that this is a self-contained cluster of operations (which
11207   // is not quite the same thing as saying that everything has only one
11208   // use).
11209   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11210     if (isa<ConstantSDNode>(Inputs[i]))
11211       continue;
11212 
11213     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11214                               UE = Inputs[i].getNode()->use_end();
11215          UI != UE; ++UI) {
11216       SDNode *User = *UI;
11217       if (User != N && !Visited.count(User))
11218         return SDValue();
11219 
11220       // Make sure that we're not going to promote the non-output-value
11221       // operand(s) or SELECT or SELECT_CC.
11222       // FIXME: Although we could sometimes handle this, and it does occur in
11223       // practice that one of the condition inputs to the select is also one of
11224       // the outputs, we currently can't deal with this.
11225       if (User->getOpcode() == ISD::SELECT) {
11226         if (User->getOperand(0) == Inputs[i])
11227           return SDValue();
11228       } else if (User->getOpcode() == ISD::SELECT_CC) {
11229         if (User->getOperand(0) == Inputs[i] ||
11230             User->getOperand(1) == Inputs[i])
11231           return SDValue();
11232       }
11233     }
11234   }
11235 
11236   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11237     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11238                               UE = PromOps[i].getNode()->use_end();
11239          UI != UE; ++UI) {
11240       SDNode *User = *UI;
11241       if (User != N && !Visited.count(User))
11242         return SDValue();
11243 
11244       // Make sure that we're not going to promote the non-output-value
11245       // operand(s) or SELECT or SELECT_CC.
11246       // FIXME: Although we could sometimes handle this, and it does occur in
11247       // practice that one of the condition inputs to the select is also one of
11248       // the outputs, we currently can't deal with this.
11249       if (User->getOpcode() == ISD::SELECT) {
11250         if (User->getOperand(0) == PromOps[i])
11251           return SDValue();
11252       } else if (User->getOpcode() == ISD::SELECT_CC) {
11253         if (User->getOperand(0) == PromOps[i] ||
11254             User->getOperand(1) == PromOps[i])
11255           return SDValue();
11256       }
11257     }
11258   }
11259 
11260   // Replace all inputs with the extension operand.
11261   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11262     // Constants may have users outside the cluster of to-be-promoted nodes,
11263     // and so we need to replace those as we do the promotions.
11264     if (isa<ConstantSDNode>(Inputs[i]))
11265       continue;
11266     else
11267       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
11268   }
11269 
11270   std::list<HandleSDNode> PromOpHandles;
11271   for (auto &PromOp : PromOps)
11272     PromOpHandles.emplace_back(PromOp);
11273 
11274   // Replace all operations (these are all the same, but have a different
11275   // (i1) return type). DAG.getNode will validate that the types of
11276   // a binary operator match, so go through the list in reverse so that
11277   // we've likely promoted both operands first. Any intermediate truncations or
11278   // extensions disappear.
11279   while (!PromOpHandles.empty()) {
11280     SDValue PromOp = PromOpHandles.back().getValue();
11281     PromOpHandles.pop_back();
11282 
11283     if (PromOp.getOpcode() == ISD::TRUNCATE ||
11284         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
11285         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
11286         PromOp.getOpcode() == ISD::ANY_EXTEND) {
11287       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
11288           PromOp.getOperand(0).getValueType() != MVT::i1) {
11289         // The operand is not yet ready (see comment below).
11290         PromOpHandles.emplace_front(PromOp);
11291         continue;
11292       }
11293 
11294       SDValue RepValue = PromOp.getOperand(0);
11295       if (isa<ConstantSDNode>(RepValue))
11296         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
11297 
11298       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
11299       continue;
11300     }
11301 
11302     unsigned C;
11303     switch (PromOp.getOpcode()) {
11304     default:             C = 0; break;
11305     case ISD::SELECT:    C = 1; break;
11306     case ISD::SELECT_CC: C = 2; break;
11307     }
11308 
11309     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11310          PromOp.getOperand(C).getValueType() != MVT::i1) ||
11311         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11312          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
11313       // The to-be-promoted operands of this node have not yet been
11314       // promoted (this should be rare because we're going through the
11315       // list backward, but if one of the operands has several users in
11316       // this cluster of to-be-promoted nodes, it is possible).
11317       PromOpHandles.emplace_front(PromOp);
11318       continue;
11319     }
11320 
11321     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11322                                 PromOp.getNode()->op_end());
11323 
11324     // If there are any constant inputs, make sure they're replaced now.
11325     for (unsigned i = 0; i < 2; ++i)
11326       if (isa<ConstantSDNode>(Ops[C+i]))
11327         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
11328 
11329     DAG.ReplaceAllUsesOfValueWith(PromOp,
11330       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
11331   }
11332 
11333   // Now we're left with the initial truncation itself.
11334   if (N->getOpcode() == ISD::TRUNCATE)
11335     return N->getOperand(0);
11336 
11337   // Otherwise, this is a comparison. The operands to be compared have just
11338   // changed type (to i1), but everything else is the same.
11339   return SDValue(N, 0);
11340 }
11341 
11342 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
11343                                                   DAGCombinerInfo &DCI) const {
11344   SelectionDAG &DAG = DCI.DAG;
11345   SDLoc dl(N);
11346 
11347   // If we're tracking CR bits, we need to be careful that we don't have:
11348   //   zext(binary-ops(trunc(x), trunc(y)))
11349   // or
11350   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
11351   // such that we're unnecessarily moving things into CR bits that can more
11352   // efficiently stay in GPRs. Note that if we're not certain that the high
11353   // bits are set as required by the final extension, we still may need to do
11354   // some masking to get the proper behavior.
11355 
11356   // This same functionality is important on PPC64 when dealing with
11357   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
11358   // the return values of functions. Because it is so similar, it is handled
11359   // here as well.
11360 
11361   if (N->getValueType(0) != MVT::i32 &&
11362       N->getValueType(0) != MVT::i64)
11363     return SDValue();
11364 
11365   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
11366         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
11367     return SDValue();
11368 
11369   if (N->getOperand(0).getOpcode() != ISD::AND &&
11370       N->getOperand(0).getOpcode() != ISD::OR  &&
11371       N->getOperand(0).getOpcode() != ISD::XOR &&
11372       N->getOperand(0).getOpcode() != ISD::SELECT &&
11373       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
11374     return SDValue();
11375 
11376   SmallVector<SDValue, 4> Inputs;
11377   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
11378   SmallPtrSet<SDNode *, 16> Visited;
11379 
11380   // Visit all inputs, collect all binary operations (and, or, xor and
11381   // select) that are all fed by truncations.
11382   while (!BinOps.empty()) {
11383     SDValue BinOp = BinOps.back();
11384     BinOps.pop_back();
11385 
11386     if (!Visited.insert(BinOp.getNode()).second)
11387       continue;
11388 
11389     PromOps.push_back(BinOp);
11390 
11391     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
11392       // The condition of the select is not promoted.
11393       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
11394         continue;
11395       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
11396         continue;
11397 
11398       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
11399           isa<ConstantSDNode>(BinOp.getOperand(i))) {
11400         Inputs.push_back(BinOp.getOperand(i));
11401       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
11402                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
11403                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
11404                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
11405                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
11406         BinOps.push_back(BinOp.getOperand(i));
11407       } else {
11408         // We have an input that is not a truncation or another binary
11409         // operation; we'll abort this transformation.
11410         return SDValue();
11411       }
11412     }
11413   }
11414 
11415   // The operands of a select that must be truncated when the select is
11416   // promoted because the operand is actually part of the to-be-promoted set.
11417   DenseMap<SDNode *, EVT> SelectTruncOp[2];
11418 
11419   // Make sure that this is a self-contained cluster of operations (which
11420   // is not quite the same thing as saying that everything has only one
11421   // use).
11422   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11423     if (isa<ConstantSDNode>(Inputs[i]))
11424       continue;
11425 
11426     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
11427                               UE = Inputs[i].getNode()->use_end();
11428          UI != UE; ++UI) {
11429       SDNode *User = *UI;
11430       if (User != N && !Visited.count(User))
11431         return SDValue();
11432 
11433       // If we're going to promote the non-output-value operand(s) or SELECT or
11434       // SELECT_CC, record them for truncation.
11435       if (User->getOpcode() == ISD::SELECT) {
11436         if (User->getOperand(0) == Inputs[i])
11437           SelectTruncOp[0].insert(std::make_pair(User,
11438                                     User->getOperand(0).getValueType()));
11439       } else if (User->getOpcode() == ISD::SELECT_CC) {
11440         if (User->getOperand(0) == Inputs[i])
11441           SelectTruncOp[0].insert(std::make_pair(User,
11442                                     User->getOperand(0).getValueType()));
11443         if (User->getOperand(1) == Inputs[i])
11444           SelectTruncOp[1].insert(std::make_pair(User,
11445                                     User->getOperand(1).getValueType()));
11446       }
11447     }
11448   }
11449 
11450   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
11451     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
11452                               UE = PromOps[i].getNode()->use_end();
11453          UI != UE; ++UI) {
11454       SDNode *User = *UI;
11455       if (User != N && !Visited.count(User))
11456         return SDValue();
11457 
11458       // If we're going to promote the non-output-value operand(s) or SELECT or
11459       // SELECT_CC, record them for truncation.
11460       if (User->getOpcode() == ISD::SELECT) {
11461         if (User->getOperand(0) == PromOps[i])
11462           SelectTruncOp[0].insert(std::make_pair(User,
11463                                     User->getOperand(0).getValueType()));
11464       } else if (User->getOpcode() == ISD::SELECT_CC) {
11465         if (User->getOperand(0) == PromOps[i])
11466           SelectTruncOp[0].insert(std::make_pair(User,
11467                                     User->getOperand(0).getValueType()));
11468         if (User->getOperand(1) == PromOps[i])
11469           SelectTruncOp[1].insert(std::make_pair(User,
11470                                     User->getOperand(1).getValueType()));
11471       }
11472     }
11473   }
11474 
11475   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
11476   bool ReallyNeedsExt = false;
11477   if (N->getOpcode() != ISD::ANY_EXTEND) {
11478     // If all of the inputs are not already sign/zero extended, then
11479     // we'll still need to do that at the end.
11480     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11481       if (isa<ConstantSDNode>(Inputs[i]))
11482         continue;
11483 
11484       unsigned OpBits =
11485         Inputs[i].getOperand(0).getValueSizeInBits();
11486       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
11487 
11488       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
11489            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
11490                                   APInt::getHighBitsSet(OpBits,
11491                                                         OpBits-PromBits))) ||
11492           (N->getOpcode() == ISD::SIGN_EXTEND &&
11493            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
11494              (OpBits-(PromBits-1)))) {
11495         ReallyNeedsExt = true;
11496         break;
11497       }
11498     }
11499   }
11500 
11501   // Replace all inputs, either with the truncation operand, or a
11502   // truncation or extension to the final output type.
11503   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
11504     // Constant inputs need to be replaced with the to-be-promoted nodes that
11505     // use them because they might have users outside of the cluster of
11506     // promoted nodes.
11507     if (isa<ConstantSDNode>(Inputs[i]))
11508       continue;
11509 
11510     SDValue InSrc = Inputs[i].getOperand(0);
11511     if (Inputs[i].getValueType() == N->getValueType(0))
11512       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
11513     else if (N->getOpcode() == ISD::SIGN_EXTEND)
11514       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11515         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
11516     else if (N->getOpcode() == ISD::ZERO_EXTEND)
11517       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11518         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
11519     else
11520       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
11521         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
11522   }
11523 
11524   std::list<HandleSDNode> PromOpHandles;
11525   for (auto &PromOp : PromOps)
11526     PromOpHandles.emplace_back(PromOp);
11527 
11528   // Replace all operations (these are all the same, but have a different
11529   // (promoted) return type). DAG.getNode will validate that the types of
11530   // a binary operator match, so go through the list in reverse so that
11531   // we've likely promoted both operands first.
11532   while (!PromOpHandles.empty()) {
11533     SDValue PromOp = PromOpHandles.back().getValue();
11534     PromOpHandles.pop_back();
11535 
11536     unsigned C;
11537     switch (PromOp.getOpcode()) {
11538     default:             C = 0; break;
11539     case ISD::SELECT:    C = 1; break;
11540     case ISD::SELECT_CC: C = 2; break;
11541     }
11542 
11543     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
11544          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
11545         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
11546          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
11547       // The to-be-promoted operands of this node have not yet been
11548       // promoted (this should be rare because we're going through the
11549       // list backward, but if one of the operands has several users in
11550       // this cluster of to-be-promoted nodes, it is possible).
11551       PromOpHandles.emplace_front(PromOp);
11552       continue;
11553     }
11554 
11555     // For SELECT and SELECT_CC nodes, we do a similar check for any
11556     // to-be-promoted comparison inputs.
11557     if (PromOp.getOpcode() == ISD::SELECT ||
11558         PromOp.getOpcode() == ISD::SELECT_CC) {
11559       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
11560            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
11561           (SelectTruncOp[1].count(PromOp.getNode()) &&
11562            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
11563         PromOpHandles.emplace_front(PromOp);
11564         continue;
11565       }
11566     }
11567 
11568     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
11569                                 PromOp.getNode()->op_end());
11570 
11571     // If this node has constant inputs, then they'll need to be promoted here.
11572     for (unsigned i = 0; i < 2; ++i) {
11573       if (!isa<ConstantSDNode>(Ops[C+i]))
11574         continue;
11575       if (Ops[C+i].getValueType() == N->getValueType(0))
11576         continue;
11577 
11578       if (N->getOpcode() == ISD::SIGN_EXTEND)
11579         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11580       else if (N->getOpcode() == ISD::ZERO_EXTEND)
11581         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11582       else
11583         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
11584     }
11585 
11586     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
11587     // truncate them again to the original value type.
11588     if (PromOp.getOpcode() == ISD::SELECT ||
11589         PromOp.getOpcode() == ISD::SELECT_CC) {
11590       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
11591       if (SI0 != SelectTruncOp[0].end())
11592         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
11593       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
11594       if (SI1 != SelectTruncOp[1].end())
11595         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
11596     }
11597 
11598     DAG.ReplaceAllUsesOfValueWith(PromOp,
11599       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
11600   }
11601 
11602   // Now we're left with the initial extension itself.
11603   if (!ReallyNeedsExt)
11604     return N->getOperand(0);
11605 
11606   // To zero extend, just mask off everything except for the first bit (in the
11607   // i1 case).
11608   if (N->getOpcode() == ISD::ZERO_EXTEND)
11609     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
11610                        DAG.getConstant(APInt::getLowBitsSet(
11611                                          N->getValueSizeInBits(0), PromBits),
11612                                        dl, N->getValueType(0)));
11613 
11614   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
11615          "Invalid extension type");
11616   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
11617   SDValue ShiftCst =
11618       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
11619   return DAG.getNode(
11620       ISD::SRA, dl, N->getValueType(0),
11621       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
11622       ShiftCst);
11623 }
11624 
11625 /// Reduces the number of fp-to-int conversion when building a vector.
11626 ///
11627 /// If this vector is built out of floating to integer conversions,
11628 /// transform it to a vector built out of floating point values followed by a
11629 /// single floating to integer conversion of the vector.
11630 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
11631 /// becomes (fptosi (build_vector ($A, $B, ...)))
11632 SDValue PPCTargetLowering::
11633 combineElementTruncationToVectorTruncation(SDNode *N,
11634                                            DAGCombinerInfo &DCI) const {
11635   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11636          "Should be called with a BUILD_VECTOR node");
11637 
11638   SelectionDAG &DAG = DCI.DAG;
11639   SDLoc dl(N);
11640 
11641   SDValue FirstInput = N->getOperand(0);
11642   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
11643          "The input operand must be an fp-to-int conversion.");
11644 
11645   // This combine happens after legalization so the fp_to_[su]i nodes are
11646   // already converted to PPCSISD nodes.
11647   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
11648   if (FirstConversion == PPCISD::FCTIDZ ||
11649       FirstConversion == PPCISD::FCTIDUZ ||
11650       FirstConversion == PPCISD::FCTIWZ ||
11651       FirstConversion == PPCISD::FCTIWUZ) {
11652     bool IsSplat = true;
11653     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
11654       FirstConversion == PPCISD::FCTIWUZ;
11655     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11656     SmallVector<SDValue, 4> Ops;
11657     EVT TargetVT = N->getValueType(0);
11658     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11659       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11660         return SDValue();
11661       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11662       if (NextConversion != FirstConversion)
11663         return SDValue();
11664       if (N->getOperand(i) != FirstInput)
11665         IsSplat = false;
11666     }
11667 
11668     // If this is a splat, we leave it as-is since there will be only a single
11669     // fp-to-int conversion followed by a splat of the integer. This is better
11670     // for 32-bit and smaller ints and neutral for 64-bit ints.
11671     if (IsSplat)
11672       return SDValue();
11673 
11674     // Now that we know we have the right type of node, get its operands
11675     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11676       SDValue In = N->getOperand(i).getOperand(0);
11677       // For 32-bit values, we need to add an FP_ROUND node.
11678       if (Is32Bit) {
11679         if (In.isUndef())
11680           Ops.push_back(DAG.getUNDEF(SrcVT));
11681         else {
11682           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11683                                       MVT::f32, In.getOperand(0),
11684                                       DAG.getIntPtrConstant(1, dl));
11685           Ops.push_back(Trunc);
11686         }
11687       } else
11688         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11689     }
11690 
11691     unsigned Opcode;
11692     if (FirstConversion == PPCISD::FCTIDZ ||
11693         FirstConversion == PPCISD::FCTIWZ)
11694       Opcode = ISD::FP_TO_SINT;
11695     else
11696       Opcode = ISD::FP_TO_UINT;
11697 
11698     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11699     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11700     return DAG.getNode(Opcode, dl, TargetVT, BV);
11701   }
11702   return SDValue();
11703 }
11704 
11705 /// Reduce the number of loads when building a vector.
11706 ///
11707 /// Building a vector out of multiple loads can be converted to a load
11708 /// of the vector type if the loads are consecutive. If the loads are
11709 /// consecutive but in descending order, a shuffle is added at the end
11710 /// to reorder the vector.
11711 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11712   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11713          "Should be called with a BUILD_VECTOR node");
11714 
11715   SDLoc dl(N);
11716   bool InputsAreConsecutiveLoads = true;
11717   bool InputsAreReverseConsecutive = true;
11718   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11719   SDValue FirstInput = N->getOperand(0);
11720   bool IsRoundOfExtLoad = false;
11721 
11722   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11723       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11724     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11725     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11726   }
11727   // Not a build vector of (possibly fp_rounded) loads.
11728   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11729     return SDValue();
11730 
11731   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11732     // If any inputs are fp_round(extload), they all must be.
11733     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11734       return SDValue();
11735 
11736     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11737       N->getOperand(i);
11738     if (NextInput.getOpcode() != ISD::LOAD)
11739       return SDValue();
11740 
11741     SDValue PreviousInput =
11742       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11743     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11744     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11745 
11746     // If any inputs are fp_round(extload), they all must be.
11747     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11748       return SDValue();
11749 
11750     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11751       InputsAreConsecutiveLoads = false;
11752     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11753       InputsAreReverseConsecutive = false;
11754 
11755     // Exit early if the loads are neither consecutive nor reverse consecutive.
11756     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11757       return SDValue();
11758   }
11759 
11760   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11761          "The loads cannot be both consecutive and reverse consecutive.");
11762 
11763   SDValue FirstLoadOp =
11764     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11765   SDValue LastLoadOp =
11766     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11767                        N->getOperand(N->getNumOperands()-1);
11768 
11769   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11770   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11771   if (InputsAreConsecutiveLoads) {
11772     assert(LD1 && "Input needs to be a LoadSDNode.");
11773     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11774                        LD1->getBasePtr(), LD1->getPointerInfo(),
11775                        LD1->getAlignment());
11776   }
11777   if (InputsAreReverseConsecutive) {
11778     assert(LDL && "Input needs to be a LoadSDNode.");
11779     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11780                                LDL->getBasePtr(), LDL->getPointerInfo(),
11781                                LDL->getAlignment());
11782     SmallVector<int, 16> Ops;
11783     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11784       Ops.push_back(i);
11785 
11786     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11787                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11788   }
11789   return SDValue();
11790 }
11791 
11792 // This function adds the required vector_shuffle needed to get
11793 // the elements of the vector extract in the correct position
11794 // as specified by the CorrectElems encoding.
11795 static SDValue addShuffleForVecExtend(SDNode *N, SelectionDAG &DAG,
11796                                       SDValue Input, uint64_t Elems,
11797                                       uint64_t CorrectElems) {
11798   SDLoc dl(N);
11799 
11800   unsigned NumElems = Input.getValueType().getVectorNumElements();
11801   SmallVector<int, 16> ShuffleMask(NumElems, -1);
11802 
11803   // Knowing the element indices being extracted from the original
11804   // vector and the order in which they're being inserted, just put
11805   // them at element indices required for the instruction.
11806   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11807     if (DAG.getDataLayout().isLittleEndian())
11808       ShuffleMask[CorrectElems & 0xF] = Elems & 0xF;
11809     else
11810       ShuffleMask[(CorrectElems & 0xF0) >> 4] = (Elems & 0xF0) >> 4;
11811     CorrectElems = CorrectElems >> 8;
11812     Elems = Elems >> 8;
11813   }
11814 
11815   SDValue Shuffle =
11816       DAG.getVectorShuffle(Input.getValueType(), dl, Input,
11817                            DAG.getUNDEF(Input.getValueType()), ShuffleMask);
11818 
11819   EVT Ty = N->getValueType(0);
11820   SDValue BV = DAG.getNode(PPCISD::SExtVElems, dl, Ty, Shuffle);
11821   return BV;
11822 }
11823 
11824 // Look for build vector patterns where input operands come from sign
11825 // extended vector_extract elements of specific indices. If the correct indices
11826 // aren't used, add a vector shuffle to fix up the indices and create a new
11827 // PPCISD:SExtVElems node which selects the vector sign extend instructions
11828 // during instruction selection.
11829 static SDValue combineBVOfVecSExt(SDNode *N, SelectionDAG &DAG) {
11830   // This array encodes the indices that the vector sign extend instructions
11831   // extract from when extending from one type to another for both BE and LE.
11832   // The right nibble of each byte corresponds to the LE incides.
11833   // and the left nibble of each byte corresponds to the BE incides.
11834   // For example: 0x3074B8FC  byte->word
11835   // For LE: the allowed indices are: 0x0,0x4,0x8,0xC
11836   // For BE: the allowed indices are: 0x3,0x7,0xB,0xF
11837   // For example: 0x000070F8  byte->double word
11838   // For LE: the allowed indices are: 0x0,0x8
11839   // For BE: the allowed indices are: 0x7,0xF
11840   uint64_t TargetElems[] = {
11841       0x3074B8FC, // b->w
11842       0x000070F8, // b->d
11843       0x10325476, // h->w
11844       0x00003074, // h->d
11845       0x00001032, // w->d
11846   };
11847 
11848   uint64_t Elems = 0;
11849   int Index;
11850   SDValue Input;
11851 
11852   auto isSExtOfVecExtract = [&](SDValue Op) -> bool {
11853     if (!Op)
11854       return false;
11855     if (Op.getOpcode() != ISD::SIGN_EXTEND)
11856       return false;
11857 
11858     SDValue Extract = Op.getOperand(0);
11859     if (Extract.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11860       return false;
11861 
11862     ConstantSDNode *ExtOp = dyn_cast<ConstantSDNode>(Extract.getOperand(1));
11863     if (!ExtOp)
11864       return false;
11865 
11866     Index = ExtOp->getZExtValue();
11867     if (Input && Input != Extract.getOperand(0))
11868       return false;
11869 
11870     if (!Input)
11871       Input = Extract.getOperand(0);
11872 
11873     Elems = Elems << 8;
11874     Index = DAG.getDataLayout().isLittleEndian() ? Index : Index << 4;
11875     Elems |= Index;
11876 
11877     return true;
11878   };
11879 
11880   // If the build vector operands aren't sign extended vector extracts,
11881   // of the same input vector, then return.
11882   for (unsigned i = 0; i < N->getNumOperands(); i++) {
11883     if (!isSExtOfVecExtract(N->getOperand(i))) {
11884       return SDValue();
11885     }
11886   }
11887 
11888   // If the vector extract indicies are not correct, add the appropriate
11889   // vector_shuffle.
11890   int TgtElemArrayIdx;
11891   int InputSize = Input.getValueType().getScalarSizeInBits();
11892   int OutputSize = N->getValueType(0).getScalarSizeInBits();
11893   if (InputSize + OutputSize == 40)
11894     TgtElemArrayIdx = 0;
11895   else if (InputSize + OutputSize == 72)
11896     TgtElemArrayIdx = 1;
11897   else if (InputSize + OutputSize == 48)
11898     TgtElemArrayIdx = 2;
11899   else if (InputSize + OutputSize == 80)
11900     TgtElemArrayIdx = 3;
11901   else if (InputSize + OutputSize == 96)
11902     TgtElemArrayIdx = 4;
11903   else
11904     return SDValue();
11905 
11906   uint64_t CorrectElems = TargetElems[TgtElemArrayIdx];
11907   CorrectElems = DAG.getDataLayout().isLittleEndian()
11908                      ? CorrectElems & 0x0F0F0F0F0F0F0F0F
11909                      : CorrectElems & 0xF0F0F0F0F0F0F0F0;
11910   if (Elems != CorrectElems) {
11911     return addShuffleForVecExtend(N, DAG, Input, Elems, CorrectElems);
11912   }
11913 
11914   // Regular lowering will catch cases where a shuffle is not needed.
11915   return SDValue();
11916 }
11917 
11918 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11919                                                  DAGCombinerInfo &DCI) const {
11920   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11921          "Should be called with a BUILD_VECTOR node");
11922 
11923   SelectionDAG &DAG = DCI.DAG;
11924   SDLoc dl(N);
11925 
11926   if (!Subtarget.hasVSX())
11927     return SDValue();
11928 
11929   // The target independent DAG combiner will leave a build_vector of
11930   // float-to-int conversions intact. We can generate MUCH better code for
11931   // a float-to-int conversion of a vector of floats.
11932   SDValue FirstInput = N->getOperand(0);
11933   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11934     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11935     if (Reduced)
11936       return Reduced;
11937   }
11938 
11939   // If we're building a vector out of consecutive loads, just load that
11940   // vector type.
11941   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11942   if (Reduced)
11943     return Reduced;
11944 
11945   // If we're building a vector out of extended elements from another vector
11946   // we have P9 vector integer extend instructions.
11947   if (Subtarget.hasP9Altivec()) {
11948     Reduced = combineBVOfVecSExt(N, DAG);
11949     if (Reduced)
11950       return Reduced;
11951   }
11952 
11953 
11954   if (N->getValueType(0) != MVT::v2f64)
11955     return SDValue();
11956 
11957   // Looking for:
11958   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11959   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11960       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11961     return SDValue();
11962   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11963       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11964     return SDValue();
11965   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11966     return SDValue();
11967 
11968   SDValue Ext1 = FirstInput.getOperand(0);
11969   SDValue Ext2 = N->getOperand(1).getOperand(0);
11970   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11971      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11972     return SDValue();
11973 
11974   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11975   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11976   if (!Ext1Op || !Ext2Op)
11977     return SDValue();
11978   if (Ext1.getValueType() != MVT::i32 ||
11979       Ext2.getValueType() != MVT::i32)
11980   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11981     return SDValue();
11982 
11983   int FirstElem = Ext1Op->getZExtValue();
11984   int SecondElem = Ext2Op->getZExtValue();
11985   int SubvecIdx;
11986   if (FirstElem == 0 && SecondElem == 1)
11987     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11988   else if (FirstElem == 2 && SecondElem == 3)
11989     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11990   else
11991     return SDValue();
11992 
11993   SDValue SrcVec = Ext1.getOperand(0);
11994   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11995     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11996   return DAG.getNode(NodeType, dl, MVT::v2f64,
11997                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11998 }
11999 
12000 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
12001                                               DAGCombinerInfo &DCI) const {
12002   assert((N->getOpcode() == ISD::SINT_TO_FP ||
12003           N->getOpcode() == ISD::UINT_TO_FP) &&
12004          "Need an int -> FP conversion node here");
12005 
12006   if (useSoftFloat() || !Subtarget.has64BitSupport())
12007     return SDValue();
12008 
12009   SelectionDAG &DAG = DCI.DAG;
12010   SDLoc dl(N);
12011   SDValue Op(N, 0);
12012 
12013   // Don't handle ppc_fp128 here or conversions that are out-of-range capable
12014   // from the hardware.
12015   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
12016     return SDValue();
12017   if (Op.getOperand(0).getValueType().getSimpleVT() <= MVT(MVT::i1) ||
12018       Op.getOperand(0).getValueType().getSimpleVT() > MVT(MVT::i64))
12019     return SDValue();
12020 
12021   SDValue FirstOperand(Op.getOperand(0));
12022   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
12023     (FirstOperand.getValueType() == MVT::i8 ||
12024      FirstOperand.getValueType() == MVT::i16);
12025   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
12026     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
12027     bool DstDouble = Op.getValueType() == MVT::f64;
12028     unsigned ConvOp = Signed ?
12029       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
12030       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
12031     SDValue WidthConst =
12032       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
12033                             dl, false);
12034     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
12035     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
12036     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
12037                                          DAG.getVTList(MVT::f64, MVT::Other),
12038                                          Ops, MVT::i8, LDN->getMemOperand());
12039 
12040     // For signed conversion, we need to sign-extend the value in the VSR
12041     if (Signed) {
12042       SDValue ExtOps[] = { Ld, WidthConst };
12043       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
12044       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
12045     } else
12046       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
12047   }
12048 
12049 
12050   // For i32 intermediate values, unfortunately, the conversion functions
12051   // leave the upper 32 bits of the value are undefined. Within the set of
12052   // scalar instructions, we have no method for zero- or sign-extending the
12053   // value. Thus, we cannot handle i32 intermediate values here.
12054   if (Op.getOperand(0).getValueType() == MVT::i32)
12055     return SDValue();
12056 
12057   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
12058          "UINT_TO_FP is supported only with FPCVT");
12059 
12060   // If we have FCFIDS, then use it when converting to single-precision.
12061   // Otherwise, convert to double-precision and then round.
12062   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12063                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
12064                                                             : PPCISD::FCFIDS)
12065                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
12066                                                             : PPCISD::FCFID);
12067   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
12068                   ? MVT::f32
12069                   : MVT::f64;
12070 
12071   // If we're converting from a float, to an int, and back to a float again,
12072   // then we don't need the store/load pair at all.
12073   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
12074        Subtarget.hasFPCVT()) ||
12075       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
12076     SDValue Src = Op.getOperand(0).getOperand(0);
12077     if (Src.getValueType() == MVT::f32) {
12078       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
12079       DCI.AddToWorklist(Src.getNode());
12080     } else if (Src.getValueType() != MVT::f64) {
12081       // Make sure that we don't pick up a ppc_fp128 source value.
12082       return SDValue();
12083     }
12084 
12085     unsigned FCTOp =
12086       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
12087                                                         PPCISD::FCTIDUZ;
12088 
12089     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
12090     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
12091 
12092     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
12093       FP = DAG.getNode(ISD::FP_ROUND, dl,
12094                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
12095       DCI.AddToWorklist(FP.getNode());
12096     }
12097 
12098     return FP;
12099   }
12100 
12101   return SDValue();
12102 }
12103 
12104 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
12105 // builtins) into loads with swaps.
12106 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
12107                                               DAGCombinerInfo &DCI) const {
12108   SelectionDAG &DAG = DCI.DAG;
12109   SDLoc dl(N);
12110   SDValue Chain;
12111   SDValue Base;
12112   MachineMemOperand *MMO;
12113 
12114   switch (N->getOpcode()) {
12115   default:
12116     llvm_unreachable("Unexpected opcode for little endian VSX load");
12117   case ISD::LOAD: {
12118     LoadSDNode *LD = cast<LoadSDNode>(N);
12119     Chain = LD->getChain();
12120     Base = LD->getBasePtr();
12121     MMO = LD->getMemOperand();
12122     // If the MMO suggests this isn't a load of a full vector, leave
12123     // things alone.  For a built-in, we have to make the change for
12124     // correctness, so if there is a size problem that will be a bug.
12125     if (MMO->getSize() < 16)
12126       return SDValue();
12127     break;
12128   }
12129   case ISD::INTRINSIC_W_CHAIN: {
12130     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12131     Chain = Intrin->getChain();
12132     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
12133     // us what we want. Get operand 2 instead.
12134     Base = Intrin->getOperand(2);
12135     MMO = Intrin->getMemOperand();
12136     break;
12137   }
12138   }
12139 
12140   MVT VecTy = N->getValueType(0).getSimpleVT();
12141 
12142   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
12143   // aligned and the type is a vector with elements up to 4 bytes
12144   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12145       && VecTy.getScalarSizeInBits() <= 32 ) {
12146     return SDValue();
12147   }
12148 
12149   SDValue LoadOps[] = { Chain, Base };
12150   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
12151                                          DAG.getVTList(MVT::v2f64, MVT::Other),
12152                                          LoadOps, MVT::v2f64, MMO);
12153 
12154   DCI.AddToWorklist(Load.getNode());
12155   Chain = Load.getValue(1);
12156   SDValue Swap = DAG.getNode(
12157       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
12158   DCI.AddToWorklist(Swap.getNode());
12159 
12160   // Add a bitcast if the resulting load type doesn't match v2f64.
12161   if (VecTy != MVT::v2f64) {
12162     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
12163     DCI.AddToWorklist(N.getNode());
12164     // Package {bitcast value, swap's chain} to match Load's shape.
12165     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
12166                        N, Swap.getValue(1));
12167   }
12168 
12169   return Swap;
12170 }
12171 
12172 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
12173 // builtins) into stores with swaps.
12174 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
12175                                                DAGCombinerInfo &DCI) const {
12176   SelectionDAG &DAG = DCI.DAG;
12177   SDLoc dl(N);
12178   SDValue Chain;
12179   SDValue Base;
12180   unsigned SrcOpnd;
12181   MachineMemOperand *MMO;
12182 
12183   switch (N->getOpcode()) {
12184   default:
12185     llvm_unreachable("Unexpected opcode for little endian VSX store");
12186   case ISD::STORE: {
12187     StoreSDNode *ST = cast<StoreSDNode>(N);
12188     Chain = ST->getChain();
12189     Base = ST->getBasePtr();
12190     MMO = ST->getMemOperand();
12191     SrcOpnd = 1;
12192     // If the MMO suggests this isn't a store of a full vector, leave
12193     // things alone.  For a built-in, we have to make the change for
12194     // correctness, so if there is a size problem that will be a bug.
12195     if (MMO->getSize() < 16)
12196       return SDValue();
12197     break;
12198   }
12199   case ISD::INTRINSIC_VOID: {
12200     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
12201     Chain = Intrin->getChain();
12202     // Intrin->getBasePtr() oddly does not get what we want.
12203     Base = Intrin->getOperand(3);
12204     MMO = Intrin->getMemOperand();
12205     SrcOpnd = 2;
12206     break;
12207   }
12208   }
12209 
12210   SDValue Src = N->getOperand(SrcOpnd);
12211   MVT VecTy = Src.getValueType().getSimpleVT();
12212 
12213   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
12214   // aligned and the type is a vector with elements up to 4 bytes
12215   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
12216       && VecTy.getScalarSizeInBits() <= 32 ) {
12217     return SDValue();
12218   }
12219 
12220   // All stores are done as v2f64 and possible bit cast.
12221   if (VecTy != MVT::v2f64) {
12222     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
12223     DCI.AddToWorklist(Src.getNode());
12224   }
12225 
12226   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
12227                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
12228   DCI.AddToWorklist(Swap.getNode());
12229   Chain = Swap.getValue(1);
12230   SDValue StoreOps[] = { Chain, Swap, Base };
12231   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
12232                                           DAG.getVTList(MVT::Other),
12233                                           StoreOps, VecTy, MMO);
12234   DCI.AddToWorklist(Store.getNode());
12235   return Store;
12236 }
12237 
12238 // Handle DAG combine for STORE (FP_TO_INT F).
12239 SDValue PPCTargetLowering::combineStoreFPToInt(SDNode *N,
12240                                                DAGCombinerInfo &DCI) const {
12241 
12242   SelectionDAG &DAG = DCI.DAG;
12243   SDLoc dl(N);
12244   unsigned Opcode = N->getOperand(1).getOpcode();
12245 
12246   assert((Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT)
12247          && "Not a FP_TO_INT Instruction!");
12248 
12249   SDValue Val = N->getOperand(1).getOperand(0);
12250   EVT Op1VT = N->getOperand(1).getValueType();
12251   EVT ResVT = Val.getValueType();
12252 
12253   // Floating point types smaller than 32 bits are not legal on Power.
12254   if (ResVT.getScalarSizeInBits() < 32)
12255     return SDValue();
12256 
12257   // Only perform combine for conversion to i64/i32 or power9 i16/i8.
12258   bool ValidTypeForStoreFltAsInt =
12259         (Op1VT == MVT::i32 || Op1VT == MVT::i64 ||
12260          (Subtarget.hasP9Vector() && (Op1VT == MVT::i16 || Op1VT == MVT::i8)));
12261 
12262   if (ResVT == MVT::ppcf128 || !Subtarget.hasP8Altivec() ||
12263       cast<StoreSDNode>(N)->isTruncatingStore() || !ValidTypeForStoreFltAsInt)
12264     return SDValue();
12265 
12266   // Extend f32 values to f64
12267   if (ResVT.getScalarSizeInBits() == 32) {
12268     Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
12269     DCI.AddToWorklist(Val.getNode());
12270   }
12271 
12272   // Set signed or unsigned conversion opcode.
12273   unsigned ConvOpcode = (Opcode == ISD::FP_TO_SINT) ?
12274                           PPCISD::FP_TO_SINT_IN_VSR :
12275                           PPCISD::FP_TO_UINT_IN_VSR;
12276 
12277   Val = DAG.getNode(ConvOpcode,
12278                     dl, ResVT == MVT::f128 ? MVT::f128 : MVT::f64, Val);
12279   DCI.AddToWorklist(Val.getNode());
12280 
12281   // Set number of bytes being converted.
12282   unsigned ByteSize = Op1VT.getScalarSizeInBits() / 8;
12283   SDValue Ops[] = { N->getOperand(0), Val, N->getOperand(2),
12284                     DAG.getIntPtrConstant(ByteSize, dl, false),
12285                     DAG.getValueType(Op1VT) };
12286 
12287   Val = DAG.getMemIntrinsicNode(PPCISD::ST_VSR_SCAL_INT, dl,
12288           DAG.getVTList(MVT::Other), Ops,
12289           cast<StoreSDNode>(N)->getMemoryVT(),
12290           cast<StoreSDNode>(N)->getMemOperand());
12291 
12292   DCI.AddToWorklist(Val.getNode());
12293   return Val;
12294 }
12295 
12296 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
12297                                              DAGCombinerInfo &DCI) const {
12298   SelectionDAG &DAG = DCI.DAG;
12299   SDLoc dl(N);
12300   switch (N->getOpcode()) {
12301   default: break;
12302   case ISD::SHL:
12303     return combineSHL(N, DCI);
12304   case ISD::SRA:
12305     return combineSRA(N, DCI);
12306   case ISD::SRL:
12307     return combineSRL(N, DCI);
12308   case PPCISD::SHL:
12309     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
12310         return N->getOperand(0);
12311     break;
12312   case PPCISD::SRL:
12313     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
12314         return N->getOperand(0);
12315     break;
12316   case PPCISD::SRA:
12317     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
12318       if (C->isNullValue() ||   //  0 >>s V -> 0.
12319           C->isAllOnesValue())    // -1 >>s V -> -1.
12320         return N->getOperand(0);
12321     }
12322     break;
12323   case ISD::SIGN_EXTEND:
12324   case ISD::ZERO_EXTEND:
12325   case ISD::ANY_EXTEND:
12326     return DAGCombineExtBoolTrunc(N, DCI);
12327   case ISD::TRUNCATE:
12328   case ISD::SETCC:
12329   case ISD::SELECT_CC:
12330     return DAGCombineTruncBoolExt(N, DCI);
12331   case ISD::SINT_TO_FP:
12332   case ISD::UINT_TO_FP:
12333     return combineFPToIntToFP(N, DCI);
12334   case ISD::STORE: {
12335 
12336     EVT Op1VT = N->getOperand(1).getValueType();
12337     unsigned Opcode = N->getOperand(1).getOpcode();
12338 
12339     if (Opcode == ISD::FP_TO_SINT || Opcode == ISD::FP_TO_UINT) {
12340       SDValue Val= combineStoreFPToInt(N, DCI);
12341       if (Val)
12342         return Val;
12343     }
12344 
12345     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
12346     if (cast<StoreSDNode>(N)->isUnindexed() && Opcode == ISD::BSWAP &&
12347         N->getOperand(1).getNode()->hasOneUse() &&
12348         (Op1VT == MVT::i32 || Op1VT == MVT::i16 ||
12349          (Subtarget.hasLDBRX() && Subtarget.isPPC64() && Op1VT == MVT::i64))) {
12350 
12351       // STBRX can only handle simple types.
12352       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
12353       if (mVT.isExtended())
12354         break;
12355 
12356       SDValue BSwapOp = N->getOperand(1).getOperand(0);
12357       // Do an any-extend to 32-bits if this is a half-word input.
12358       if (BSwapOp.getValueType() == MVT::i16)
12359         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
12360 
12361       // If the type of BSWAP operand is wider than stored memory width
12362       // it need to be shifted to the right side before STBRX.
12363       if (Op1VT.bitsGT(mVT)) {
12364         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
12365         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
12366                               DAG.getConstant(Shift, dl, MVT::i32));
12367         // Need to truncate if this is a bswap of i64 stored as i32/i16.
12368         if (Op1VT == MVT::i64)
12369           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
12370       }
12371 
12372       SDValue Ops[] = {
12373         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
12374       };
12375       return
12376         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
12377                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
12378                                 cast<StoreSDNode>(N)->getMemOperand());
12379     }
12380 
12381     // STORE Constant:i32<0>  ->  STORE<trunc to i32> Constant:i64<0>
12382     // So it can increase the chance of CSE constant construction.
12383     if (Subtarget.isPPC64() && !DCI.isBeforeLegalize() &&
12384         isa<ConstantSDNode>(N->getOperand(1)) && Op1VT == MVT::i32) {
12385       // Need to sign-extended to 64-bits to handle negative values.
12386       EVT MemVT = cast<StoreSDNode>(N)->getMemoryVT();
12387       uint64_t Val64 = SignExtend64(N->getConstantOperandVal(1),
12388                                     MemVT.getSizeInBits());
12389       SDValue Const64 = DAG.getConstant(Val64, dl, MVT::i64);
12390 
12391       // DAG.getTruncStore() can't be used here because it doesn't accept
12392       // the general (base + offset) addressing mode.
12393       // So we use UpdateNodeOperands and setTruncatingStore instead.
12394       DAG.UpdateNodeOperands(N, N->getOperand(0), Const64, N->getOperand(2),
12395                              N->getOperand(3));
12396       cast<StoreSDNode>(N)->setTruncatingStore(true);
12397       return SDValue(N, 0);
12398     }
12399 
12400     // For little endian, VSX stores require generating xxswapd/lxvd2x.
12401     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12402     if (Op1VT.isSimple()) {
12403       MVT StoreVT = Op1VT.getSimpleVT();
12404       if (Subtarget.needsSwapsForVSXMemOps() &&
12405           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
12406            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
12407         return expandVSXStoreForLE(N, DCI);
12408     }
12409     break;
12410   }
12411   case ISD::LOAD: {
12412     LoadSDNode *LD = cast<LoadSDNode>(N);
12413     EVT VT = LD->getValueType(0);
12414 
12415     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12416     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12417     if (VT.isSimple()) {
12418       MVT LoadVT = VT.getSimpleVT();
12419       if (Subtarget.needsSwapsForVSXMemOps() &&
12420           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
12421            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
12422         return expandVSXLoadForLE(N, DCI);
12423     }
12424 
12425     // We sometimes end up with a 64-bit integer load, from which we extract
12426     // two single-precision floating-point numbers. This happens with
12427     // std::complex<float>, and other similar structures, because of the way we
12428     // canonicalize structure copies. However, if we lack direct moves,
12429     // then the final bitcasts from the extracted integer values to the
12430     // floating-point numbers turn into store/load pairs. Even with direct moves,
12431     // just loading the two floating-point numbers is likely better.
12432     auto ReplaceTwoFloatLoad = [&]() {
12433       if (VT != MVT::i64)
12434         return false;
12435 
12436       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
12437           LD->isVolatile())
12438         return false;
12439 
12440       //  We're looking for a sequence like this:
12441       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
12442       //      t16: i64 = srl t13, Constant:i32<32>
12443       //    t17: i32 = truncate t16
12444       //  t18: f32 = bitcast t17
12445       //    t19: i32 = truncate t13
12446       //  t20: f32 = bitcast t19
12447 
12448       if (!LD->hasNUsesOfValue(2, 0))
12449         return false;
12450 
12451       auto UI = LD->use_begin();
12452       while (UI.getUse().getResNo() != 0) ++UI;
12453       SDNode *Trunc = *UI++;
12454       while (UI.getUse().getResNo() != 0) ++UI;
12455       SDNode *RightShift = *UI;
12456       if (Trunc->getOpcode() != ISD::TRUNCATE)
12457         std::swap(Trunc, RightShift);
12458 
12459       if (Trunc->getOpcode() != ISD::TRUNCATE ||
12460           Trunc->getValueType(0) != MVT::i32 ||
12461           !Trunc->hasOneUse())
12462         return false;
12463       if (RightShift->getOpcode() != ISD::SRL ||
12464           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
12465           RightShift->getConstantOperandVal(1) != 32 ||
12466           !RightShift->hasOneUse())
12467         return false;
12468 
12469       SDNode *Trunc2 = *RightShift->use_begin();
12470       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
12471           Trunc2->getValueType(0) != MVT::i32 ||
12472           !Trunc2->hasOneUse())
12473         return false;
12474 
12475       SDNode *Bitcast = *Trunc->use_begin();
12476       SDNode *Bitcast2 = *Trunc2->use_begin();
12477 
12478       if (Bitcast->getOpcode() != ISD::BITCAST ||
12479           Bitcast->getValueType(0) != MVT::f32)
12480         return false;
12481       if (Bitcast2->getOpcode() != ISD::BITCAST ||
12482           Bitcast2->getValueType(0) != MVT::f32)
12483         return false;
12484 
12485       if (Subtarget.isLittleEndian())
12486         std::swap(Bitcast, Bitcast2);
12487 
12488       // Bitcast has the second float (in memory-layout order) and Bitcast2
12489       // has the first one.
12490 
12491       SDValue BasePtr = LD->getBasePtr();
12492       if (LD->isIndexed()) {
12493         assert(LD->getAddressingMode() == ISD::PRE_INC &&
12494                "Non-pre-inc AM on PPC?");
12495         BasePtr =
12496           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
12497                       LD->getOffset());
12498       }
12499 
12500       auto MMOFlags =
12501           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
12502       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
12503                                       LD->getPointerInfo(), LD->getAlignment(),
12504                                       MMOFlags, LD->getAAInfo());
12505       SDValue AddPtr =
12506         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
12507                     BasePtr, DAG.getIntPtrConstant(4, dl));
12508       SDValue FloatLoad2 = DAG.getLoad(
12509           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
12510           LD->getPointerInfo().getWithOffset(4),
12511           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
12512 
12513       if (LD->isIndexed()) {
12514         // Note that DAGCombine should re-form any pre-increment load(s) from
12515         // what is produced here if that makes sense.
12516         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
12517       }
12518 
12519       DCI.CombineTo(Bitcast2, FloatLoad);
12520       DCI.CombineTo(Bitcast, FloatLoad2);
12521 
12522       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
12523                                     SDValue(FloatLoad2.getNode(), 1));
12524       return true;
12525     };
12526 
12527     if (ReplaceTwoFloatLoad())
12528       return SDValue(N, 0);
12529 
12530     EVT MemVT = LD->getMemoryVT();
12531     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
12532     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
12533     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
12534     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
12535     if (LD->isUnindexed() && VT.isVector() &&
12536         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
12537           // P8 and later hardware should just use LOAD.
12538           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
12539                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
12540          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
12541           LD->getAlignment() >= ScalarABIAlignment)) &&
12542         LD->getAlignment() < ABIAlignment) {
12543       // This is a type-legal unaligned Altivec or QPX load.
12544       SDValue Chain = LD->getChain();
12545       SDValue Ptr = LD->getBasePtr();
12546       bool isLittleEndian = Subtarget.isLittleEndian();
12547 
12548       // This implements the loading of unaligned vectors as described in
12549       // the venerable Apple Velocity Engine overview. Specifically:
12550       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
12551       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
12552       //
12553       // The general idea is to expand a sequence of one or more unaligned
12554       // loads into an alignment-based permutation-control instruction (lvsl
12555       // or lvsr), a series of regular vector loads (which always truncate
12556       // their input address to an aligned address), and a series of
12557       // permutations.  The results of these permutations are the requested
12558       // loaded values.  The trick is that the last "extra" load is not taken
12559       // from the address you might suspect (sizeof(vector) bytes after the
12560       // last requested load), but rather sizeof(vector) - 1 bytes after the
12561       // last requested vector. The point of this is to avoid a page fault if
12562       // the base address happened to be aligned. This works because if the
12563       // base address is aligned, then adding less than a full vector length
12564       // will cause the last vector in the sequence to be (re)loaded.
12565       // Otherwise, the next vector will be fetched as you might suspect was
12566       // necessary.
12567 
12568       // We might be able to reuse the permutation generation from
12569       // a different base address offset from this one by an aligned amount.
12570       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
12571       // optimization later.
12572       Intrinsic::ID Intr, IntrLD, IntrPerm;
12573       MVT PermCntlTy, PermTy, LDTy;
12574       if (Subtarget.hasAltivec()) {
12575         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
12576                                  Intrinsic::ppc_altivec_lvsl;
12577         IntrLD = Intrinsic::ppc_altivec_lvx;
12578         IntrPerm = Intrinsic::ppc_altivec_vperm;
12579         PermCntlTy = MVT::v16i8;
12580         PermTy = MVT::v4i32;
12581         LDTy = MVT::v4i32;
12582       } else {
12583         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
12584                                        Intrinsic::ppc_qpx_qvlpcls;
12585         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
12586                                        Intrinsic::ppc_qpx_qvlfs;
12587         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
12588         PermCntlTy = MVT::v4f64;
12589         PermTy = MVT::v4f64;
12590         LDTy = MemVT.getSimpleVT();
12591       }
12592 
12593       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
12594 
12595       // Create the new MMO for the new base load. It is like the original MMO,
12596       // but represents an area in memory almost twice the vector size centered
12597       // on the original address. If the address is unaligned, we might start
12598       // reading up to (sizeof(vector)-1) bytes below the address of the
12599       // original unaligned load.
12600       MachineFunction &MF = DAG.getMachineFunction();
12601       MachineMemOperand *BaseMMO =
12602         MF.getMachineMemOperand(LD->getMemOperand(),
12603                                 -(long)MemVT.getStoreSize()+1,
12604                                 2*MemVT.getStoreSize()-1);
12605 
12606       // Create the new base load.
12607       SDValue LDXIntID =
12608           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
12609       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
12610       SDValue BaseLoad =
12611         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12612                                 DAG.getVTList(PermTy, MVT::Other),
12613                                 BaseLoadOps, LDTy, BaseMMO);
12614 
12615       // Note that the value of IncOffset (which is provided to the next
12616       // load's pointer info offset value, and thus used to calculate the
12617       // alignment), and the value of IncValue (which is actually used to
12618       // increment the pointer value) are different! This is because we
12619       // require the next load to appear to be aligned, even though it
12620       // is actually offset from the base pointer by a lesser amount.
12621       int IncOffset = VT.getSizeInBits() / 8;
12622       int IncValue = IncOffset;
12623 
12624       // Walk (both up and down) the chain looking for another load at the real
12625       // (aligned) offset (the alignment of the other load does not matter in
12626       // this case). If found, then do not use the offset reduction trick, as
12627       // that will prevent the loads from being later combined (as they would
12628       // otherwise be duplicates).
12629       if (!findConsecutiveLoad(LD, DAG))
12630         --IncValue;
12631 
12632       SDValue Increment =
12633           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
12634       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
12635 
12636       MachineMemOperand *ExtraMMO =
12637         MF.getMachineMemOperand(LD->getMemOperand(),
12638                                 1, 2*MemVT.getStoreSize()-1);
12639       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
12640       SDValue ExtraLoad =
12641         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
12642                                 DAG.getVTList(PermTy, MVT::Other),
12643                                 ExtraLoadOps, LDTy, ExtraMMO);
12644 
12645       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
12646         BaseLoad.getValue(1), ExtraLoad.getValue(1));
12647 
12648       // Because vperm has a big-endian bias, we must reverse the order
12649       // of the input vectors and complement the permute control vector
12650       // when generating little endian code.  We have already handled the
12651       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
12652       // and ExtraLoad here.
12653       SDValue Perm;
12654       if (isLittleEndian)
12655         Perm = BuildIntrinsicOp(IntrPerm,
12656                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
12657       else
12658         Perm = BuildIntrinsicOp(IntrPerm,
12659                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
12660 
12661       if (VT != PermTy)
12662         Perm = Subtarget.hasAltivec() ?
12663                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
12664                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
12665                                DAG.getTargetConstant(1, dl, MVT::i64));
12666                                // second argument is 1 because this rounding
12667                                // is always exact.
12668 
12669       // The output of the permutation is our loaded result, the TokenFactor is
12670       // our new chain.
12671       DCI.CombineTo(N, Perm, TF);
12672       return SDValue(N, 0);
12673     }
12674     }
12675     break;
12676     case ISD::INTRINSIC_WO_CHAIN: {
12677       bool isLittleEndian = Subtarget.isLittleEndian();
12678       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12679       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
12680                                            : Intrinsic::ppc_altivec_lvsl);
12681       if ((IID == Intr ||
12682            IID == Intrinsic::ppc_qpx_qvlpcld  ||
12683            IID == Intrinsic::ppc_qpx_qvlpcls) &&
12684         N->getOperand(1)->getOpcode() == ISD::ADD) {
12685         SDValue Add = N->getOperand(1);
12686 
12687         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
12688                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
12689 
12690         if (DAG.MaskedValueIsZero(Add->getOperand(1),
12691                                   APInt::getAllOnesValue(Bits /* alignment */)
12692                                       .zext(Add.getScalarValueSizeInBits()))) {
12693           SDNode *BasePtr = Add->getOperand(0).getNode();
12694           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12695                                     UE = BasePtr->use_end();
12696                UI != UE; ++UI) {
12697             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12698                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
12699               // We've found another LVSL/LVSR, and this address is an aligned
12700               // multiple of that one. The results will be the same, so use the
12701               // one we've just found instead.
12702 
12703               return SDValue(*UI, 0);
12704             }
12705           }
12706         }
12707 
12708         if (isa<ConstantSDNode>(Add->getOperand(1))) {
12709           SDNode *BasePtr = Add->getOperand(0).getNode();
12710           for (SDNode::use_iterator UI = BasePtr->use_begin(),
12711                UE = BasePtr->use_end(); UI != UE; ++UI) {
12712             if (UI->getOpcode() == ISD::ADD &&
12713                 isa<ConstantSDNode>(UI->getOperand(1)) &&
12714                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
12715                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
12716                 (1ULL << Bits) == 0) {
12717               SDNode *OtherAdd = *UI;
12718               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
12719                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
12720                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12721                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
12722                   return SDValue(*VI, 0);
12723                 }
12724               }
12725             }
12726           }
12727         }
12728       }
12729     }
12730 
12731     break;
12732   case ISD::INTRINSIC_W_CHAIN:
12733     // For little endian, VSX loads require generating lxvd2x/xxswapd.
12734     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
12735     if (Subtarget.needsSwapsForVSXMemOps()) {
12736       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12737       default:
12738         break;
12739       case Intrinsic::ppc_vsx_lxvw4x:
12740       case Intrinsic::ppc_vsx_lxvd2x:
12741         return expandVSXLoadForLE(N, DCI);
12742       }
12743     }
12744     break;
12745   case ISD::INTRINSIC_VOID:
12746     // For little endian, VSX stores require generating xxswapd/stxvd2x.
12747     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
12748     if (Subtarget.needsSwapsForVSXMemOps()) {
12749       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12750       default:
12751         break;
12752       case Intrinsic::ppc_vsx_stxvw4x:
12753       case Intrinsic::ppc_vsx_stxvd2x:
12754         return expandVSXStoreForLE(N, DCI);
12755       }
12756     }
12757     break;
12758   case ISD::BSWAP:
12759     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
12760     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
12761         N->getOperand(0).hasOneUse() &&
12762         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
12763          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
12764           N->getValueType(0) == MVT::i64))) {
12765       SDValue Load = N->getOperand(0);
12766       LoadSDNode *LD = cast<LoadSDNode>(Load);
12767       // Create the byte-swapping load.
12768       SDValue Ops[] = {
12769         LD->getChain(),    // Chain
12770         LD->getBasePtr(),  // Ptr
12771         DAG.getValueType(N->getValueType(0)) // VT
12772       };
12773       SDValue BSLoad =
12774         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
12775                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
12776                                               MVT::i64 : MVT::i32, MVT::Other),
12777                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
12778 
12779       // If this is an i16 load, insert the truncate.
12780       SDValue ResVal = BSLoad;
12781       if (N->getValueType(0) == MVT::i16)
12782         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
12783 
12784       // First, combine the bswap away.  This makes the value produced by the
12785       // load dead.
12786       DCI.CombineTo(N, ResVal);
12787 
12788       // Next, combine the load away, we give it a bogus result value but a real
12789       // chain result.  The result value is dead because the bswap is dead.
12790       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
12791 
12792       // Return N so it doesn't get rechecked!
12793       return SDValue(N, 0);
12794     }
12795     break;
12796   case PPCISD::VCMP:
12797     // If a VCMPo node already exists with exactly the same operands as this
12798     // node, use its result instead of this node (VCMPo computes both a CR6 and
12799     // a normal output).
12800     //
12801     if (!N->getOperand(0).hasOneUse() &&
12802         !N->getOperand(1).hasOneUse() &&
12803         !N->getOperand(2).hasOneUse()) {
12804 
12805       // Scan all of the users of the LHS, looking for VCMPo's that match.
12806       SDNode *VCMPoNode = nullptr;
12807 
12808       SDNode *LHSN = N->getOperand(0).getNode();
12809       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
12810            UI != E; ++UI)
12811         if (UI->getOpcode() == PPCISD::VCMPo &&
12812             UI->getOperand(1) == N->getOperand(1) &&
12813             UI->getOperand(2) == N->getOperand(2) &&
12814             UI->getOperand(0) == N->getOperand(0)) {
12815           VCMPoNode = *UI;
12816           break;
12817         }
12818 
12819       // If there is no VCMPo node, or if the flag value has a single use, don't
12820       // transform this.
12821       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
12822         break;
12823 
12824       // Look at the (necessarily single) use of the flag value.  If it has a
12825       // chain, this transformation is more complex.  Note that multiple things
12826       // could use the value result, which we should ignore.
12827       SDNode *FlagUser = nullptr;
12828       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
12829            FlagUser == nullptr; ++UI) {
12830         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
12831         SDNode *User = *UI;
12832         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
12833           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
12834             FlagUser = User;
12835             break;
12836           }
12837         }
12838       }
12839 
12840       // If the user is a MFOCRF instruction, we know this is safe.
12841       // Otherwise we give up for right now.
12842       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12843         return SDValue(VCMPoNode, 0);
12844     }
12845     break;
12846   case ISD::BRCOND: {
12847     SDValue Cond = N->getOperand(1);
12848     SDValue Target = N->getOperand(2);
12849 
12850     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12851         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12852           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12853 
12854       // We now need to make the intrinsic dead (it cannot be instruction
12855       // selected).
12856       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12857       assert(Cond.getNode()->hasOneUse() &&
12858              "Counter decrement has more than one use");
12859 
12860       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12861                          N->getOperand(0), Target);
12862     }
12863   }
12864   break;
12865   case ISD::BR_CC: {
12866     // If this is a branch on an altivec predicate comparison, lower this so
12867     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
12868     // lowering is done pre-legalize, because the legalizer lowers the predicate
12869     // compare down to code that is difficult to reassemble.
12870     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12871     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12872 
12873     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12874     // value. If so, pass-through the AND to get to the intrinsic.
12875     if (LHS.getOpcode() == ISD::AND &&
12876         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12877         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12878           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12879         isa<ConstantSDNode>(LHS.getOperand(1)) &&
12880         !isNullConstant(LHS.getOperand(1)))
12881       LHS = LHS.getOperand(0);
12882 
12883     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12884         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12885           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12886         isa<ConstantSDNode>(RHS)) {
12887       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12888              "Counter decrement comparison is not EQ or NE");
12889 
12890       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12891       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12892                     (CC == ISD::SETNE && !Val);
12893 
12894       // We now need to make the intrinsic dead (it cannot be instruction
12895       // selected).
12896       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12897       assert(LHS.getNode()->hasOneUse() &&
12898              "Counter decrement has more than one use");
12899 
12900       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12901                          N->getOperand(0), N->getOperand(4));
12902     }
12903 
12904     int CompareOpc;
12905     bool isDot;
12906 
12907     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12908         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12909         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12910       assert(isDot && "Can't compare against a vector result!");
12911 
12912       // If this is a comparison against something other than 0/1, then we know
12913       // that the condition is never/always true.
12914       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12915       if (Val != 0 && Val != 1) {
12916         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
12917           return N->getOperand(0);
12918         // Always !=, turn it into an unconditional branch.
12919         return DAG.getNode(ISD::BR, dl, MVT::Other,
12920                            N->getOperand(0), N->getOperand(4));
12921       }
12922 
12923       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12924 
12925       // Create the PPCISD altivec 'dot' comparison node.
12926       SDValue Ops[] = {
12927         LHS.getOperand(2),  // LHS of compare
12928         LHS.getOperand(3),  // RHS of compare
12929         DAG.getConstant(CompareOpc, dl, MVT::i32)
12930       };
12931       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12932       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12933 
12934       // Unpack the result based on how the target uses it.
12935       PPC::Predicate CompOpc;
12936       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12937       default:  // Can't happen, don't crash on invalid number though.
12938       case 0:   // Branch on the value of the EQ bit of CR6.
12939         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12940         break;
12941       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12942         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12943         break;
12944       case 2:   // Branch on the value of the LT bit of CR6.
12945         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12946         break;
12947       case 3:   // Branch on the inverted value of the LT bit of CR6.
12948         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12949         break;
12950       }
12951 
12952       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12953                          DAG.getConstant(CompOpc, dl, MVT::i32),
12954                          DAG.getRegister(PPC::CR6, MVT::i32),
12955                          N->getOperand(4), CompNode.getValue(1));
12956     }
12957     break;
12958   }
12959   case ISD::BUILD_VECTOR:
12960     return DAGCombineBuildVector(N, DCI);
12961   }
12962 
12963   return SDValue();
12964 }
12965 
12966 SDValue
12967 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12968                                   SelectionDAG &DAG,
12969                                   std::vector<SDNode *> *Created) const {
12970   // fold (sdiv X, pow2)
12971   EVT VT = N->getValueType(0);
12972   if (VT == MVT::i64 && !Subtarget.isPPC64())
12973     return SDValue();
12974   if ((VT != MVT::i32 && VT != MVT::i64) ||
12975       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12976     return SDValue();
12977 
12978   SDLoc DL(N);
12979   SDValue N0 = N->getOperand(0);
12980 
12981   bool IsNegPow2 = (-Divisor).isPowerOf2();
12982   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12983   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12984 
12985   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12986   if (Created)
12987     Created->push_back(Op.getNode());
12988 
12989   if (IsNegPow2) {
12990     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12991     if (Created)
12992       Created->push_back(Op.getNode());
12993   }
12994 
12995   return Op;
12996 }
12997 
12998 //===----------------------------------------------------------------------===//
12999 // Inline Assembly Support
13000 //===----------------------------------------------------------------------===//
13001 
13002 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13003                                                       KnownBits &Known,
13004                                                       const APInt &DemandedElts,
13005                                                       const SelectionDAG &DAG,
13006                                                       unsigned Depth) const {
13007   Known.resetAll();
13008   switch (Op.getOpcode()) {
13009   default: break;
13010   case PPCISD::LBRX: {
13011     // lhbrx is known to have the top bits cleared out.
13012     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
13013       Known.Zero = 0xFFFF0000;
13014     break;
13015   }
13016   case ISD::INTRINSIC_WO_CHAIN: {
13017     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
13018     default: break;
13019     case Intrinsic::ppc_altivec_vcmpbfp_p:
13020     case Intrinsic::ppc_altivec_vcmpeqfp_p:
13021     case Intrinsic::ppc_altivec_vcmpequb_p:
13022     case Intrinsic::ppc_altivec_vcmpequh_p:
13023     case Intrinsic::ppc_altivec_vcmpequw_p:
13024     case Intrinsic::ppc_altivec_vcmpequd_p:
13025     case Intrinsic::ppc_altivec_vcmpgefp_p:
13026     case Intrinsic::ppc_altivec_vcmpgtfp_p:
13027     case Intrinsic::ppc_altivec_vcmpgtsb_p:
13028     case Intrinsic::ppc_altivec_vcmpgtsh_p:
13029     case Intrinsic::ppc_altivec_vcmpgtsw_p:
13030     case Intrinsic::ppc_altivec_vcmpgtsd_p:
13031     case Intrinsic::ppc_altivec_vcmpgtub_p:
13032     case Intrinsic::ppc_altivec_vcmpgtuh_p:
13033     case Intrinsic::ppc_altivec_vcmpgtuw_p:
13034     case Intrinsic::ppc_altivec_vcmpgtud_p:
13035       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
13036       break;
13037     }
13038   }
13039   }
13040 }
13041 
13042 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
13043   switch (Subtarget.getDarwinDirective()) {
13044   default: break;
13045   case PPC::DIR_970:
13046   case PPC::DIR_PWR4:
13047   case PPC::DIR_PWR5:
13048   case PPC::DIR_PWR5X:
13049   case PPC::DIR_PWR6:
13050   case PPC::DIR_PWR6X:
13051   case PPC::DIR_PWR7:
13052   case PPC::DIR_PWR8:
13053   case PPC::DIR_PWR9: {
13054     if (!ML)
13055       break;
13056 
13057     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
13058 
13059     // For small loops (between 5 and 8 instructions), align to a 32-byte
13060     // boundary so that the entire loop fits in one instruction-cache line.
13061     uint64_t LoopSize = 0;
13062     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
13063       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
13064         LoopSize += TII->getInstSizeInBytes(*J);
13065         if (LoopSize > 32)
13066           break;
13067       }
13068 
13069     if (LoopSize > 16 && LoopSize <= 32)
13070       return 5;
13071 
13072     break;
13073   }
13074   }
13075 
13076   return TargetLowering::getPrefLoopAlignment(ML);
13077 }
13078 
13079 /// getConstraintType - Given a constraint, return the type of
13080 /// constraint it is for this target.
13081 PPCTargetLowering::ConstraintType
13082 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
13083   if (Constraint.size() == 1) {
13084     switch (Constraint[0]) {
13085     default: break;
13086     case 'b':
13087     case 'r':
13088     case 'f':
13089     case 'd':
13090     case 'v':
13091     case 'y':
13092       return C_RegisterClass;
13093     case 'Z':
13094       // FIXME: While Z does indicate a memory constraint, it specifically
13095       // indicates an r+r address (used in conjunction with the 'y' modifier
13096       // in the replacement string). Currently, we're forcing the base
13097       // register to be r0 in the asm printer (which is interpreted as zero)
13098       // and forming the complete address in the second register. This is
13099       // suboptimal.
13100       return C_Memory;
13101     }
13102   } else if (Constraint == "wc") { // individual CR bits.
13103     return C_RegisterClass;
13104   } else if (Constraint == "wa" || Constraint == "wd" ||
13105              Constraint == "wf" || Constraint == "ws") {
13106     return C_RegisterClass; // VSX registers.
13107   }
13108   return TargetLowering::getConstraintType(Constraint);
13109 }
13110 
13111 /// Examine constraint type and operand type and determine a weight value.
13112 /// This object must already have been set up with the operand type
13113 /// and the current alternative constraint selected.
13114 TargetLowering::ConstraintWeight
13115 PPCTargetLowering::getSingleConstraintMatchWeight(
13116     AsmOperandInfo &info, const char *constraint) const {
13117   ConstraintWeight weight = CW_Invalid;
13118   Value *CallOperandVal = info.CallOperandVal;
13119     // If we don't have a value, we can't do a match,
13120     // but allow it at the lowest weight.
13121   if (!CallOperandVal)
13122     return CW_Default;
13123   Type *type = CallOperandVal->getType();
13124 
13125   // Look at the constraint type.
13126   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
13127     return CW_Register; // an individual CR bit.
13128   else if ((StringRef(constraint) == "wa" ||
13129             StringRef(constraint) == "wd" ||
13130             StringRef(constraint) == "wf") &&
13131            type->isVectorTy())
13132     return CW_Register;
13133   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
13134     return CW_Register;
13135 
13136   switch (*constraint) {
13137   default:
13138     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13139     break;
13140   case 'b':
13141     if (type->isIntegerTy())
13142       weight = CW_Register;
13143     break;
13144   case 'f':
13145     if (type->isFloatTy())
13146       weight = CW_Register;
13147     break;
13148   case 'd':
13149     if (type->isDoubleTy())
13150       weight = CW_Register;
13151     break;
13152   case 'v':
13153     if (type->isVectorTy())
13154       weight = CW_Register;
13155     break;
13156   case 'y':
13157     weight = CW_Register;
13158     break;
13159   case 'Z':
13160     weight = CW_Memory;
13161     break;
13162   }
13163   return weight;
13164 }
13165 
13166 std::pair<unsigned, const TargetRegisterClass *>
13167 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
13168                                                 StringRef Constraint,
13169                                                 MVT VT) const {
13170   if (Constraint.size() == 1) {
13171     // GCC RS6000 Constraint Letters
13172     switch (Constraint[0]) {
13173     case 'b':   // R1-R31
13174       if (VT == MVT::i64 && Subtarget.isPPC64())
13175         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
13176       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
13177     case 'r':   // R0-R31
13178       if (VT == MVT::i64 && Subtarget.isPPC64())
13179         return std::make_pair(0U, &PPC::G8RCRegClass);
13180       return std::make_pair(0U, &PPC::GPRCRegClass);
13181     // 'd' and 'f' constraints are both defined to be "the floating point
13182     // registers", where one is for 32-bit and the other for 64-bit. We don't
13183     // really care overly much here so just give them all the same reg classes.
13184     case 'd':
13185     case 'f':
13186       if (VT == MVT::f32 || VT == MVT::i32)
13187         return std::make_pair(0U, &PPC::F4RCRegClass);
13188       if (VT == MVT::f64 || VT == MVT::i64)
13189         return std::make_pair(0U, &PPC::F8RCRegClass);
13190       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13191         return std::make_pair(0U, &PPC::QFRCRegClass);
13192       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13193         return std::make_pair(0U, &PPC::QSRCRegClass);
13194       break;
13195     case 'v':
13196       if (VT == MVT::v4f64 && Subtarget.hasQPX())
13197         return std::make_pair(0U, &PPC::QFRCRegClass);
13198       if (VT == MVT::v4f32 && Subtarget.hasQPX())
13199         return std::make_pair(0U, &PPC::QSRCRegClass);
13200       if (Subtarget.hasAltivec())
13201         return std::make_pair(0U, &PPC::VRRCRegClass);
13202       break;
13203     case 'y':   // crrc
13204       return std::make_pair(0U, &PPC::CRRCRegClass);
13205     }
13206   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
13207     // An individual CR bit.
13208     return std::make_pair(0U, &PPC::CRBITRCRegClass);
13209   } else if ((Constraint == "wa" || Constraint == "wd" ||
13210              Constraint == "wf") && Subtarget.hasVSX()) {
13211     return std::make_pair(0U, &PPC::VSRCRegClass);
13212   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
13213     if (VT == MVT::f32 && Subtarget.hasP8Vector())
13214       return std::make_pair(0U, &PPC::VSSRCRegClass);
13215     else
13216       return std::make_pair(0U, &PPC::VSFRCRegClass);
13217   }
13218 
13219   std::pair<unsigned, const TargetRegisterClass *> R =
13220       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13221 
13222   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
13223   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
13224   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
13225   // register.
13226   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
13227   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
13228   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
13229       PPC::GPRCRegClass.contains(R.first))
13230     return std::make_pair(TRI->getMatchingSuperReg(R.first,
13231                             PPC::sub_32, &PPC::G8RCRegClass),
13232                           &PPC::G8RCRegClass);
13233 
13234   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
13235   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
13236     R.first = PPC::CR0;
13237     R.second = &PPC::CRRCRegClass;
13238   }
13239 
13240   return R;
13241 }
13242 
13243 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13244 /// vector.  If it is invalid, don't add anything to Ops.
13245 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13246                                                      std::string &Constraint,
13247                                                      std::vector<SDValue>&Ops,
13248                                                      SelectionDAG &DAG) const {
13249   SDValue Result;
13250 
13251   // Only support length 1 constraints.
13252   if (Constraint.length() > 1) return;
13253 
13254   char Letter = Constraint[0];
13255   switch (Letter) {
13256   default: break;
13257   case 'I':
13258   case 'J':
13259   case 'K':
13260   case 'L':
13261   case 'M':
13262   case 'N':
13263   case 'O':
13264   case 'P': {
13265     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
13266     if (!CST) return; // Must be an immediate to match.
13267     SDLoc dl(Op);
13268     int64_t Value = CST->getSExtValue();
13269     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
13270                          // numbers are printed as such.
13271     switch (Letter) {
13272     default: llvm_unreachable("Unknown constraint letter!");
13273     case 'I':  // "I" is a signed 16-bit constant.
13274       if (isInt<16>(Value))
13275         Result = DAG.getTargetConstant(Value, dl, TCVT);
13276       break;
13277     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
13278       if (isShiftedUInt<16, 16>(Value))
13279         Result = DAG.getTargetConstant(Value, dl, TCVT);
13280       break;
13281     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
13282       if (isShiftedInt<16, 16>(Value))
13283         Result = DAG.getTargetConstant(Value, dl, TCVT);
13284       break;
13285     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
13286       if (isUInt<16>(Value))
13287         Result = DAG.getTargetConstant(Value, dl, TCVT);
13288       break;
13289     case 'M':  // "M" is a constant that is greater than 31.
13290       if (Value > 31)
13291         Result = DAG.getTargetConstant(Value, dl, TCVT);
13292       break;
13293     case 'N':  // "N" is a positive constant that is an exact power of two.
13294       if (Value > 0 && isPowerOf2_64(Value))
13295         Result = DAG.getTargetConstant(Value, dl, TCVT);
13296       break;
13297     case 'O':  // "O" is the constant zero.
13298       if (Value == 0)
13299         Result = DAG.getTargetConstant(Value, dl, TCVT);
13300       break;
13301     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
13302       if (isInt<16>(-Value))
13303         Result = DAG.getTargetConstant(Value, dl, TCVT);
13304       break;
13305     }
13306     break;
13307   }
13308   }
13309 
13310   if (Result.getNode()) {
13311     Ops.push_back(Result);
13312     return;
13313   }
13314 
13315   // Handle standard constraint letters.
13316   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13317 }
13318 
13319 // isLegalAddressingMode - Return true if the addressing mode represented
13320 // by AM is legal for this target, for a load/store of the specified type.
13321 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13322                                               const AddrMode &AM, Type *Ty,
13323                                               unsigned AS, Instruction *I) const {
13324   // PPC does not allow r+i addressing modes for vectors!
13325   if (Ty->isVectorTy() && AM.BaseOffs != 0)
13326     return false;
13327 
13328   // PPC allows a sign-extended 16-bit immediate field.
13329   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
13330     return false;
13331 
13332   // No global is ever allowed as a base.
13333   if (AM.BaseGV)
13334     return false;
13335 
13336   // PPC only support r+r,
13337   switch (AM.Scale) {
13338   case 0:  // "r+i" or just "i", depending on HasBaseReg.
13339     break;
13340   case 1:
13341     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
13342       return false;
13343     // Otherwise we have r+r or r+i.
13344     break;
13345   case 2:
13346     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
13347       return false;
13348     // Allow 2*r as r+r.
13349     break;
13350   default:
13351     // No other scales are supported.
13352     return false;
13353   }
13354 
13355   return true;
13356 }
13357 
13358 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
13359                                            SelectionDAG &DAG) const {
13360   MachineFunction &MF = DAG.getMachineFunction();
13361   MachineFrameInfo &MFI = MF.getFrameInfo();
13362   MFI.setReturnAddressIsTaken(true);
13363 
13364   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13365     return SDValue();
13366 
13367   SDLoc dl(Op);
13368   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13369 
13370   // Make sure the function does not optimize away the store of the RA to
13371   // the stack.
13372   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
13373   FuncInfo->setLRStoreRequired();
13374   bool isPPC64 = Subtarget.isPPC64();
13375   auto PtrVT = getPointerTy(MF.getDataLayout());
13376 
13377   if (Depth > 0) {
13378     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13379     SDValue Offset =
13380         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
13381                         isPPC64 ? MVT::i64 : MVT::i32);
13382     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13383                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
13384                        MachinePointerInfo());
13385   }
13386 
13387   // Just load the return address off the stack.
13388   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
13389   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
13390                      MachinePointerInfo());
13391 }
13392 
13393 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
13394                                           SelectionDAG &DAG) const {
13395   SDLoc dl(Op);
13396   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13397 
13398   MachineFunction &MF = DAG.getMachineFunction();
13399   MachineFrameInfo &MFI = MF.getFrameInfo();
13400   MFI.setFrameAddressIsTaken(true);
13401 
13402   EVT PtrVT = getPointerTy(MF.getDataLayout());
13403   bool isPPC64 = PtrVT == MVT::i64;
13404 
13405   // Naked functions never have a frame pointer, and so we use r1. For all
13406   // other functions, this decision must be delayed until during PEI.
13407   unsigned FrameReg;
13408   if (MF.getFunction().hasFnAttribute(Attribute::Naked))
13409     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
13410   else
13411     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
13412 
13413   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
13414                                          PtrVT);
13415   while (Depth--)
13416     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
13417                             FrameAddr, MachinePointerInfo());
13418   return FrameAddr;
13419 }
13420 
13421 // FIXME? Maybe this could be a TableGen attribute on some registers and
13422 // this table could be generated automatically from RegInfo.
13423 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
13424                                               SelectionDAG &DAG) const {
13425   bool isPPC64 = Subtarget.isPPC64();
13426   bool isDarwinABI = Subtarget.isDarwinABI();
13427 
13428   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
13429       (!isPPC64 && VT != MVT::i32))
13430     report_fatal_error("Invalid register global variable type");
13431 
13432   bool is64Bit = isPPC64 && VT == MVT::i64;
13433   unsigned Reg = StringSwitch<unsigned>(RegName)
13434                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
13435                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
13436                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
13437                                   (is64Bit ? PPC::X13 : PPC::R13))
13438                    .Default(0);
13439 
13440   if (Reg)
13441     return Reg;
13442   report_fatal_error("Invalid register name global variable");
13443 }
13444 
13445 bool
13446 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13447   // The PowerPC target isn't yet aware of offsets.
13448   return false;
13449 }
13450 
13451 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13452                                            const CallInst &I,
13453                                            MachineFunction &MF,
13454                                            unsigned Intrinsic) const {
13455   switch (Intrinsic) {
13456   case Intrinsic::ppc_qpx_qvlfd:
13457   case Intrinsic::ppc_qpx_qvlfs:
13458   case Intrinsic::ppc_qpx_qvlfcd:
13459   case Intrinsic::ppc_qpx_qvlfcs:
13460   case Intrinsic::ppc_qpx_qvlfiwa:
13461   case Intrinsic::ppc_qpx_qvlfiwz:
13462   case Intrinsic::ppc_altivec_lvx:
13463   case Intrinsic::ppc_altivec_lvxl:
13464   case Intrinsic::ppc_altivec_lvebx:
13465   case Intrinsic::ppc_altivec_lvehx:
13466   case Intrinsic::ppc_altivec_lvewx:
13467   case Intrinsic::ppc_vsx_lxvd2x:
13468   case Intrinsic::ppc_vsx_lxvw4x: {
13469     EVT VT;
13470     switch (Intrinsic) {
13471     case Intrinsic::ppc_altivec_lvebx:
13472       VT = MVT::i8;
13473       break;
13474     case Intrinsic::ppc_altivec_lvehx:
13475       VT = MVT::i16;
13476       break;
13477     case Intrinsic::ppc_altivec_lvewx:
13478       VT = MVT::i32;
13479       break;
13480     case Intrinsic::ppc_vsx_lxvd2x:
13481       VT = MVT::v2f64;
13482       break;
13483     case Intrinsic::ppc_qpx_qvlfd:
13484       VT = MVT::v4f64;
13485       break;
13486     case Intrinsic::ppc_qpx_qvlfs:
13487       VT = MVT::v4f32;
13488       break;
13489     case Intrinsic::ppc_qpx_qvlfcd:
13490       VT = MVT::v2f64;
13491       break;
13492     case Intrinsic::ppc_qpx_qvlfcs:
13493       VT = MVT::v2f32;
13494       break;
13495     default:
13496       VT = MVT::v4i32;
13497       break;
13498     }
13499 
13500     Info.opc = ISD::INTRINSIC_W_CHAIN;
13501     Info.memVT = VT;
13502     Info.ptrVal = I.getArgOperand(0);
13503     Info.offset = -VT.getStoreSize()+1;
13504     Info.size = 2*VT.getStoreSize()-1;
13505     Info.align = 1;
13506     Info.flags = MachineMemOperand::MOLoad;
13507     return true;
13508   }
13509   case Intrinsic::ppc_qpx_qvlfda:
13510   case Intrinsic::ppc_qpx_qvlfsa:
13511   case Intrinsic::ppc_qpx_qvlfcda:
13512   case Intrinsic::ppc_qpx_qvlfcsa:
13513   case Intrinsic::ppc_qpx_qvlfiwaa:
13514   case Intrinsic::ppc_qpx_qvlfiwza: {
13515     EVT VT;
13516     switch (Intrinsic) {
13517     case Intrinsic::ppc_qpx_qvlfda:
13518       VT = MVT::v4f64;
13519       break;
13520     case Intrinsic::ppc_qpx_qvlfsa:
13521       VT = MVT::v4f32;
13522       break;
13523     case Intrinsic::ppc_qpx_qvlfcda:
13524       VT = MVT::v2f64;
13525       break;
13526     case Intrinsic::ppc_qpx_qvlfcsa:
13527       VT = MVT::v2f32;
13528       break;
13529     default:
13530       VT = MVT::v4i32;
13531       break;
13532     }
13533 
13534     Info.opc = ISD::INTRINSIC_W_CHAIN;
13535     Info.memVT = VT;
13536     Info.ptrVal = I.getArgOperand(0);
13537     Info.offset = 0;
13538     Info.size = VT.getStoreSize();
13539     Info.align = 1;
13540     Info.flags = MachineMemOperand::MOLoad;
13541     return true;
13542   }
13543   case Intrinsic::ppc_qpx_qvstfd:
13544   case Intrinsic::ppc_qpx_qvstfs:
13545   case Intrinsic::ppc_qpx_qvstfcd:
13546   case Intrinsic::ppc_qpx_qvstfcs:
13547   case Intrinsic::ppc_qpx_qvstfiw:
13548   case Intrinsic::ppc_altivec_stvx:
13549   case Intrinsic::ppc_altivec_stvxl:
13550   case Intrinsic::ppc_altivec_stvebx:
13551   case Intrinsic::ppc_altivec_stvehx:
13552   case Intrinsic::ppc_altivec_stvewx:
13553   case Intrinsic::ppc_vsx_stxvd2x:
13554   case Intrinsic::ppc_vsx_stxvw4x: {
13555     EVT VT;
13556     switch (Intrinsic) {
13557     case Intrinsic::ppc_altivec_stvebx:
13558       VT = MVT::i8;
13559       break;
13560     case Intrinsic::ppc_altivec_stvehx:
13561       VT = MVT::i16;
13562       break;
13563     case Intrinsic::ppc_altivec_stvewx:
13564       VT = MVT::i32;
13565       break;
13566     case Intrinsic::ppc_vsx_stxvd2x:
13567       VT = MVT::v2f64;
13568       break;
13569     case Intrinsic::ppc_qpx_qvstfd:
13570       VT = MVT::v4f64;
13571       break;
13572     case Intrinsic::ppc_qpx_qvstfs:
13573       VT = MVT::v4f32;
13574       break;
13575     case Intrinsic::ppc_qpx_qvstfcd:
13576       VT = MVT::v2f64;
13577       break;
13578     case Intrinsic::ppc_qpx_qvstfcs:
13579       VT = MVT::v2f32;
13580       break;
13581     default:
13582       VT = MVT::v4i32;
13583       break;
13584     }
13585 
13586     Info.opc = ISD::INTRINSIC_VOID;
13587     Info.memVT = VT;
13588     Info.ptrVal = I.getArgOperand(1);
13589     Info.offset = -VT.getStoreSize()+1;
13590     Info.size = 2*VT.getStoreSize()-1;
13591     Info.align = 1;
13592     Info.flags = MachineMemOperand::MOStore;
13593     return true;
13594   }
13595   case Intrinsic::ppc_qpx_qvstfda:
13596   case Intrinsic::ppc_qpx_qvstfsa:
13597   case Intrinsic::ppc_qpx_qvstfcda:
13598   case Intrinsic::ppc_qpx_qvstfcsa:
13599   case Intrinsic::ppc_qpx_qvstfiwa: {
13600     EVT VT;
13601     switch (Intrinsic) {
13602     case Intrinsic::ppc_qpx_qvstfda:
13603       VT = MVT::v4f64;
13604       break;
13605     case Intrinsic::ppc_qpx_qvstfsa:
13606       VT = MVT::v4f32;
13607       break;
13608     case Intrinsic::ppc_qpx_qvstfcda:
13609       VT = MVT::v2f64;
13610       break;
13611     case Intrinsic::ppc_qpx_qvstfcsa:
13612       VT = MVT::v2f32;
13613       break;
13614     default:
13615       VT = MVT::v4i32;
13616       break;
13617     }
13618 
13619     Info.opc = ISD::INTRINSIC_VOID;
13620     Info.memVT = VT;
13621     Info.ptrVal = I.getArgOperand(1);
13622     Info.offset = 0;
13623     Info.size = VT.getStoreSize();
13624     Info.align = 1;
13625     Info.flags = MachineMemOperand::MOStore;
13626     return true;
13627   }
13628   default:
13629     break;
13630   }
13631 
13632   return false;
13633 }
13634 
13635 /// getOptimalMemOpType - Returns the target specific optimal type for load
13636 /// and store operations as a result of memset, memcpy, and memmove
13637 /// lowering. If DstAlign is zero that means it's safe to destination
13638 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
13639 /// means there isn't a need to check it against alignment requirement,
13640 /// probably because the source does not need to be loaded. If 'IsMemset' is
13641 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
13642 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
13643 /// source is constant so it does not need to be loaded.
13644 /// It returns EVT::Other if the type should be determined using generic
13645 /// target-independent logic.
13646 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
13647                                            unsigned DstAlign, unsigned SrcAlign,
13648                                            bool IsMemset, bool ZeroMemset,
13649                                            bool MemcpyStrSrc,
13650                                            MachineFunction &MF) const {
13651   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
13652     const Function &F = MF.getFunction();
13653     // When expanding a memset, require at least two QPX instructions to cover
13654     // the cost of loading the value to be stored from the constant pool.
13655     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
13656        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
13657         !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
13658       return MVT::v4f64;
13659     }
13660 
13661     // We should use Altivec/VSX loads and stores when available. For unaligned
13662     // addresses, unaligned VSX loads are only fast starting with the P8.
13663     if (Subtarget.hasAltivec() && Size >= 16 &&
13664         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
13665          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
13666       return MVT::v4i32;
13667   }
13668 
13669   if (Subtarget.isPPC64()) {
13670     return MVT::i64;
13671   }
13672 
13673   return MVT::i32;
13674 }
13675 
13676 /// Returns true if it is beneficial to convert a load of a constant
13677 /// to just the constant itself.
13678 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13679                                                           Type *Ty) const {
13680   assert(Ty->isIntegerTy());
13681 
13682   unsigned BitSize = Ty->getPrimitiveSizeInBits();
13683   return !(BitSize == 0 || BitSize > 64);
13684 }
13685 
13686 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
13687   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13688     return false;
13689   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
13690   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
13691   return NumBits1 == 64 && NumBits2 == 32;
13692 }
13693 
13694 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
13695   if (!VT1.isInteger() || !VT2.isInteger())
13696     return false;
13697   unsigned NumBits1 = VT1.getSizeInBits();
13698   unsigned NumBits2 = VT2.getSizeInBits();
13699   return NumBits1 == 64 && NumBits2 == 32;
13700 }
13701 
13702 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13703   // Generally speaking, zexts are not free, but they are free when they can be
13704   // folded with other operations.
13705   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
13706     EVT MemVT = LD->getMemoryVT();
13707     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
13708          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
13709         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
13710          LD->getExtensionType() == ISD::ZEXTLOAD))
13711       return true;
13712   }
13713 
13714   // FIXME: Add other cases...
13715   //  - 32-bit shifts with a zext to i64
13716   //  - zext after ctlz, bswap, etc.
13717   //  - zext after and by a constant mask
13718 
13719   return TargetLowering::isZExtFree(Val, VT2);
13720 }
13721 
13722 bool PPCTargetLowering::isFPExtFree(EVT DestVT, EVT SrcVT) const {
13723   assert(DestVT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
13724          "invalid fpext types");
13725   return true;
13726 }
13727 
13728 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13729   return isInt<16>(Imm) || isUInt<16>(Imm);
13730 }
13731 
13732 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13733   return isInt<16>(Imm) || isUInt<16>(Imm);
13734 }
13735 
13736 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
13737                                                        unsigned,
13738                                                        unsigned,
13739                                                        bool *Fast) const {
13740   if (DisablePPCUnaligned)
13741     return false;
13742 
13743   // PowerPC supports unaligned memory access for simple non-vector types.
13744   // Although accessing unaligned addresses is not as efficient as accessing
13745   // aligned addresses, it is generally more efficient than manual expansion,
13746   // and generally only traps for software emulation when crossing page
13747   // boundaries.
13748 
13749   if (!VT.isSimple())
13750     return false;
13751 
13752   if (VT.getSimpleVT().isVector()) {
13753     if (Subtarget.hasVSX()) {
13754       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
13755           VT != MVT::v4f32 && VT != MVT::v4i32)
13756         return false;
13757     } else {
13758       return false;
13759     }
13760   }
13761 
13762   if (VT == MVT::ppcf128)
13763     return false;
13764 
13765   if (Fast)
13766     *Fast = true;
13767 
13768   return true;
13769 }
13770 
13771 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
13772   VT = VT.getScalarType();
13773 
13774   if (!VT.isSimple())
13775     return false;
13776 
13777   switch (VT.getSimpleVT().SimpleTy) {
13778   case MVT::f32:
13779   case MVT::f64:
13780     return true;
13781   case MVT::f128:
13782     return (EnableQuadPrecision && Subtarget.hasP9Vector());
13783   default:
13784     break;
13785   }
13786 
13787   return false;
13788 }
13789 
13790 const MCPhysReg *
13791 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
13792   // LR is a callee-save register, but we must treat it as clobbered by any call
13793   // site. Hence we include LR in the scratch registers, which are in turn added
13794   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
13795   // to CTR, which is used by any indirect call.
13796   static const MCPhysReg ScratchRegs[] = {
13797     PPC::X12, PPC::LR8, PPC::CTR8, 0
13798   };
13799 
13800   return ScratchRegs;
13801 }
13802 
13803 unsigned PPCTargetLowering::getExceptionPointerRegister(
13804     const Constant *PersonalityFn) const {
13805   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
13806 }
13807 
13808 unsigned PPCTargetLowering::getExceptionSelectorRegister(
13809     const Constant *PersonalityFn) const {
13810   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
13811 }
13812 
13813 bool
13814 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
13815                      EVT VT , unsigned DefinedValues) const {
13816   if (VT == MVT::v2i64)
13817     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
13818 
13819   if (Subtarget.hasVSX() || Subtarget.hasQPX())
13820     return true;
13821 
13822   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
13823 }
13824 
13825 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
13826   if (DisableILPPref || Subtarget.enableMachineScheduler())
13827     return TargetLowering::getSchedulingPreference(N);
13828 
13829   return Sched::ILP;
13830 }
13831 
13832 // Create a fast isel object.
13833 FastISel *
13834 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13835                                   const TargetLibraryInfo *LibInfo) const {
13836   return PPC::createFastISel(FuncInfo, LibInfo);
13837 }
13838 
13839 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13840   if (Subtarget.isDarwinABI()) return;
13841   if (!Subtarget.isPPC64()) return;
13842 
13843   // Update IsSplitCSR in PPCFunctionInfo
13844   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13845   PFI->setIsSplitCSR(true);
13846 }
13847 
13848 void PPCTargetLowering::insertCopiesSplitCSR(
13849   MachineBasicBlock *Entry,
13850   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13851   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13852   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13853   if (!IStart)
13854     return;
13855 
13856   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13857   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13858   MachineBasicBlock::iterator MBBI = Entry->begin();
13859   for (const MCPhysReg *I = IStart; *I; ++I) {
13860     const TargetRegisterClass *RC = nullptr;
13861     if (PPC::G8RCRegClass.contains(*I))
13862       RC = &PPC::G8RCRegClass;
13863     else if (PPC::F8RCRegClass.contains(*I))
13864       RC = &PPC::F8RCRegClass;
13865     else if (PPC::CRRCRegClass.contains(*I))
13866       RC = &PPC::CRRCRegClass;
13867     else if (PPC::VRRCRegClass.contains(*I))
13868       RC = &PPC::VRRCRegClass;
13869     else
13870       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13871 
13872     unsigned NewVR = MRI->createVirtualRegister(RC);
13873     // Create copy from CSR to a virtual register.
13874     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13875     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13876     // nounwind. If we want to generalize this later, we may need to emit
13877     // CFI pseudo-instructions.
13878     assert(Entry->getParent()->getFunction().hasFnAttribute(
13879              Attribute::NoUnwind) &&
13880            "Function should be nounwind in insertCopiesSplitCSR!");
13881     Entry->addLiveIn(*I);
13882     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13883       .addReg(*I);
13884 
13885     // Insert the copy-back instructions right before the terminator
13886     for (auto *Exit : Exits)
13887       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13888               TII->get(TargetOpcode::COPY), *I)
13889         .addReg(NewVR);
13890   }
13891 }
13892 
13893 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13894 bool PPCTargetLowering::useLoadStackGuardNode() const {
13895   if (!Subtarget.isTargetLinux())
13896     return TargetLowering::useLoadStackGuardNode();
13897   return true;
13898 }
13899 
13900 // Override to disable global variable loading on Linux.
13901 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13902   if (!Subtarget.isTargetLinux())
13903     return TargetLowering::insertSSPDeclarations(M);
13904 }
13905 
13906 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13907   if (!VT.isSimple() || !Subtarget.hasVSX())
13908     return false;
13909 
13910   switch(VT.getSimpleVT().SimpleTy) {
13911   default:
13912     // For FP types that are currently not supported by PPC backend, return
13913     // false. Examples: f16, f80.
13914     return false;
13915   case MVT::f32:
13916   case MVT::f64:
13917   case MVT::ppcf128:
13918     return Imm.isPosZero();
13919   }
13920 }
13921 
13922 // For vector shift operation op, fold
13923 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13924 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13925                                   SelectionDAG &DAG) {
13926   SDValue N0 = N->getOperand(0);
13927   SDValue N1 = N->getOperand(1);
13928   EVT VT = N0.getValueType();
13929   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13930   unsigned Opcode = N->getOpcode();
13931   unsigned TargetOpcode;
13932 
13933   switch (Opcode) {
13934   default:
13935     llvm_unreachable("Unexpected shift operation");
13936   case ISD::SHL:
13937     TargetOpcode = PPCISD::SHL;
13938     break;
13939   case ISD::SRL:
13940     TargetOpcode = PPCISD::SRL;
13941     break;
13942   case ISD::SRA:
13943     TargetOpcode = PPCISD::SRA;
13944     break;
13945   }
13946 
13947   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13948       N1->getOpcode() == ISD::AND)
13949     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13950       if (Mask->getZExtValue() == OpSizeInBits - 1)
13951         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13952 
13953   return SDValue();
13954 }
13955 
13956 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13957   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13958     return Value;
13959 
13960   return SDValue();
13961 }
13962 
13963 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13964   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13965     return Value;
13966 
13967   return SDValue();
13968 }
13969 
13970 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13971   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13972     return Value;
13973 
13974   return SDValue();
13975 }
13976 
13977 bool PPCTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
13978   // Only duplicate to increase tail-calls for the 64bit SysV ABIs.
13979   if (!Subtarget.isSVR4ABI() || !Subtarget.isPPC64())
13980     return false;
13981 
13982   // If not a tail call then no need to proceed.
13983   if (!CI->isTailCall())
13984     return false;
13985 
13986   // If tail calls are disabled for the caller then we are done.
13987   const Function *Caller = CI->getParent()->getParent();
13988   auto Attr = Caller->getFnAttribute("disable-tail-calls");
13989   if (Attr.getValueAsString() == "true")
13990     return false;
13991 
13992   // If sibling calls have been disabled and tail-calls aren't guaranteed
13993   // there is no reason to duplicate.
13994   auto &TM = getTargetMachine();
13995   if (!TM.Options.GuaranteedTailCallOpt && DisableSCO)
13996     return false;
13997 
13998   // Can't tail call a function called indirectly, or if it has variadic args.
13999   const Function *Callee = CI->getCalledFunction();
14000   if (!Callee || Callee->isVarArg())
14001     return false;
14002 
14003   // Make sure the callee and caller calling conventions are eligible for tco.
14004   if (!areCallingConvEligibleForTCO_64SVR4(Caller->getCallingConv(),
14005                                            CI->getCallingConv()))
14006       return false;
14007 
14008   // If the function is local then we have a good chance at tail-calling it
14009   return getTargetMachine().shouldAssumeDSOLocal(*Caller->getParent(), Callee);
14010 }
14011 
14012 bool PPCTargetLowering::
14013 isMaskAndCmp0FoldingBeneficial(const Instruction &AndI) const {
14014   const Value *Mask = AndI.getOperand(1);
14015   // If the mask is suitable for andi. or andis. we should sink the and.
14016   if (const ConstantInt *CI = dyn_cast<ConstantInt>(Mask)) {
14017     // Can't handle constants wider than 64-bits.
14018     if (CI->getBitWidth() > 64)
14019       return false;
14020     int64_t ConstVal = CI->getZExtValue();
14021     return isUInt<16>(ConstVal) ||
14022       (isUInt<16>(ConstVal >> 16) && !(ConstVal & 0xFFFF));
14023   }
14024 
14025   // For non-constant masks, we can always use the record-form and.
14026   return true;
14027 }
14028