]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304222, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Target / PowerPC / PPCISelLowering.cpp
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 "MCTargetDesc/PPCPredicates.h"
15 #include "PPC.h"
16 #include "PPCCallingConv.h"
17 #include "PPCCCState.h"
18 #include "PPCFrameLowering.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCISelLowering.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/SmallPtrSet.h"
32 #include "llvm/ADT/SmallSet.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.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/MachineValueType.h"
51 #include "llvm/CodeGen/RuntimeLibcalls.h"
52 #include "llvm/CodeGen/SelectionDAG.h"
53 #include "llvm/CodeGen/SelectionDAGNodes.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/CallingConv.h"
56 #include "llvm/IR/CallSite.h"
57 #include "llvm/IR/Constant.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/Function.h"
63 #include "llvm/IR/GlobalValue.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/Module.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/Value.h"
71 #include "llvm/MC/MCExpr.h"
72 #include "llvm/MC/MCRegisterInfo.h"
73 #include "llvm/Support/AtomicOrdering.h"
74 #include "llvm/Support/BranchProbability.h"
75 #include "llvm/Support/Casting.h"
76 #include "llvm/Support/CodeGen.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/Debug.h"
80 #include "llvm/Support/ErrorHandling.h"
81 #include "llvm/Support/Format.h"
82 #include "llvm/Support/KnownBits.h"
83 #include "llvm/Support/MathExtras.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetInstrInfo.h"
86 #include "llvm/Target/TargetLowering.h"
87 #include "llvm/Target/TargetMachine.h"
88 #include "llvm/Target/TargetOptions.h"
89 #include "llvm/Target/TargetRegisterInfo.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 STATISTIC(NumTailCalls, "Number of tail calls");
115 STATISTIC(NumSiblingCalls, "Number of sibling calls");
116
117 // FIXME: Remove this once the bug has been fixed!
118 extern cl::opt<bool> ANDIGlueBug;
119
120 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM,
121                                      const PPCSubtarget &STI)
122     : TargetLowering(TM), Subtarget(STI) {
123   // Use _setjmp/_longjmp instead of setjmp/longjmp.
124   setUseUnderscoreSetJmp(true);
125   setUseUnderscoreLongJmp(true);
126
127   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
128   // arguments are at least 4/8 bytes aligned.
129   bool isPPC64 = Subtarget.isPPC64();
130   setMinStackArgumentAlignment(isPPC64 ? 8:4);
131
132   // Set up the register classes.
133   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
134   if (!useSoftFloat()) {
135     addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
136     addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
137   }
138
139   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
140   for (MVT VT : MVT::integer_valuetypes()) {
141     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
142     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
143   }
144
145   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
146
147   // PowerPC has pre-inc load and store's.
148   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
149   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
150   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
151   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
152   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
153   setIndexedLoadAction(ISD::PRE_INC, MVT::f32, Legal);
154   setIndexedLoadAction(ISD::PRE_INC, MVT::f64, Legal);
155   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
156   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
157   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
158   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
159   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
160   setIndexedStoreAction(ISD::PRE_INC, MVT::f32, Legal);
161   setIndexedStoreAction(ISD::PRE_INC, MVT::f64, Legal);
162
163   if (Subtarget.useCRBits()) {
164     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
165
166     if (isPPC64 || Subtarget.hasFPCVT()) {
167       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
168       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
169                          isPPC64 ? MVT::i64 : MVT::i32);
170       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
171       AddPromotedToType(ISD::UINT_TO_FP, MVT::i1,
172                         isPPC64 ? MVT::i64 : MVT::i32);
173     } else {
174       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
175       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
176     }
177
178     // PowerPC does not support direct load / store of condition registers
179     setOperationAction(ISD::LOAD, MVT::i1, Custom);
180     setOperationAction(ISD::STORE, MVT::i1, Custom);
181
182     // FIXME: Remove this once the ANDI glue bug is fixed:
183     if (ANDIGlueBug)
184       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
185
186     for (MVT VT : MVT::integer_valuetypes()) {
187       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
188       setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
189       setTruncStoreAction(VT, MVT::i1, Expand);
190     }
191
192     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
193   }
194
195   // This is used in the ppcf128->int sequence.  Note it has different semantics
196   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
197   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
198
199   // We do not currently implement these libm ops for PowerPC.
200   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
201   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
202   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
203   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
204   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
205   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
206
207   // PowerPC has no SREM/UREM instructions
208   setOperationAction(ISD::SREM, MVT::i32, Expand);
209   setOperationAction(ISD::UREM, MVT::i32, Expand);
210   setOperationAction(ISD::SREM, MVT::i64, Expand);
211   setOperationAction(ISD::UREM, MVT::i64, Expand);
212
213   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
214   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
215   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
216   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
217   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
218   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
219   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
220   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
221   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
222
223   // We don't support sin/cos/sqrt/fmod/pow
224   setOperationAction(ISD::FSIN , MVT::f64, Expand);
225   setOperationAction(ISD::FCOS , MVT::f64, Expand);
226   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
227   setOperationAction(ISD::FREM , MVT::f64, Expand);
228   setOperationAction(ISD::FPOW , MVT::f64, Expand);
229   setOperationAction(ISD::FMA  , MVT::f64, Legal);
230   setOperationAction(ISD::FSIN , MVT::f32, Expand);
231   setOperationAction(ISD::FCOS , MVT::f32, Expand);
232   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
233   setOperationAction(ISD::FREM , MVT::f32, Expand);
234   setOperationAction(ISD::FPOW , MVT::f32, Expand);
235   setOperationAction(ISD::FMA  , MVT::f32, Legal);
236
237   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
238
239   // If we're enabling GP optimizations, use hardware square root
240   if (!Subtarget.hasFSQRT() &&
241       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTE() &&
242         Subtarget.hasFRE()))
243     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
244
245   if (!Subtarget.hasFSQRT() &&
246       !(TM.Options.UnsafeFPMath && Subtarget.hasFRSQRTES() &&
247         Subtarget.hasFRES()))
248     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
249
250   if (Subtarget.hasFCPSGN()) {
251     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
252     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
253   } else {
254     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
255     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
256   }
257
258   if (Subtarget.hasFPRND()) {
259     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
260     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
261     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
262     setOperationAction(ISD::FROUND, MVT::f64, Legal);
263
264     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
265     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
266     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
267     setOperationAction(ISD::FROUND, MVT::f32, Legal);
268   }
269
270   // PowerPC does not have BSWAP
271   // CTPOP or CTTZ were introduced in P8/P9 respectivelly
272   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
273   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
274   if (Subtarget.isISA3_0()) {
275     setOperationAction(ISD::CTTZ , MVT::i32  , Legal);
276     setOperationAction(ISD::CTTZ , MVT::i64  , Legal);
277   } else {
278     setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
279     setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
280   }
281
282   if (Subtarget.hasPOPCNTD() == PPCSubtarget::POPCNTD_Fast) {
283     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
284     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
285   } else {
286     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
287     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
288   }
289
290   // PowerPC does not have ROTR
291   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
292   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
293
294   if (!Subtarget.useCRBits()) {
295     // PowerPC does not have Select
296     setOperationAction(ISD::SELECT, MVT::i32, Expand);
297     setOperationAction(ISD::SELECT, MVT::i64, Expand);
298     setOperationAction(ISD::SELECT, MVT::f32, Expand);
299     setOperationAction(ISD::SELECT, MVT::f64, Expand);
300   }
301
302   // PowerPC wants to turn select_cc of FP into fsel when possible.
303   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
304   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
305
306   // PowerPC wants to optimize integer setcc a bit
307   if (!Subtarget.useCRBits())
308     setOperationAction(ISD::SETCC, MVT::i32, Custom);
309
310   // PowerPC does not have BRCOND which requires SetCC
311   if (!Subtarget.useCRBits())
312     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
313
314   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
315
316   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
317   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
318
319   // PowerPC does not have [U|S]INT_TO_FP
320   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
321   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
322
323   if (Subtarget.hasDirectMove() && isPPC64) {
324     setOperationAction(ISD::BITCAST, MVT::f32, Legal);
325     setOperationAction(ISD::BITCAST, MVT::i32, Legal);
326     setOperationAction(ISD::BITCAST, MVT::i64, Legal);
327     setOperationAction(ISD::BITCAST, MVT::f64, Legal);
328   } else {
329     setOperationAction(ISD::BITCAST, MVT::f32, Expand);
330     setOperationAction(ISD::BITCAST, MVT::i32, Expand);
331     setOperationAction(ISD::BITCAST, MVT::i64, Expand);
332     setOperationAction(ISD::BITCAST, MVT::f64, Expand);
333   }
334
335   // We cannot sextinreg(i1).  Expand to shifts.
336   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
337
338   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
339   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
340   // support continuation, user-level threading, and etc.. As a result, no
341   // other SjLj exception interfaces are implemented and please don't build
342   // your own exception handling based on them.
343   // LLVM/Clang supports zero-cost DWARF exception handling.
344   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
345   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
346
347   // We want to legalize GlobalAddress and ConstantPool nodes into the
348   // appropriate instructions to materialize the address.
349   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
350   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
351   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
352   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
353   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
354   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
355   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
356   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
357   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
358   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
359
360   // TRAP is legal.
361   setOperationAction(ISD::TRAP, MVT::Other, Legal);
362
363   // TRAMPOLINE is custom lowered.
364   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
365   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
366
367   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
368   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
369
370   if (Subtarget.isSVR4ABI()) {
371     if (isPPC64) {
372       // VAARG always uses double-word chunks, so promote anything smaller.
373       setOperationAction(ISD::VAARG, MVT::i1, Promote);
374       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
375       setOperationAction(ISD::VAARG, MVT::i8, Promote);
376       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
377       setOperationAction(ISD::VAARG, MVT::i16, Promote);
378       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
379       setOperationAction(ISD::VAARG, MVT::i32, Promote);
380       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
381       setOperationAction(ISD::VAARG, MVT::Other, Expand);
382     } else {
383       // VAARG is custom lowered with the 32-bit SVR4 ABI.
384       setOperationAction(ISD::VAARG, MVT::Other, Custom);
385       setOperationAction(ISD::VAARG, MVT::i64, Custom);
386     }
387   } else
388     setOperationAction(ISD::VAARG, MVT::Other, Expand);
389
390   if (Subtarget.isSVR4ABI() && !isPPC64)
391     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
392     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
393   else
394     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
395
396   // Use the default implementation.
397   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
398   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
399   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
400   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
401   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
402   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i32, Custom);
403   setOperationAction(ISD::GET_DYNAMIC_AREA_OFFSET, MVT::i64, Custom);
404   setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
405   setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
406
407   // We want to custom lower some of our intrinsics.
408   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
409
410   // To handle counter-based loop conditions.
411   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
412
413   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
414   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
415   setOperationAction(ISD::INTRINSIC_VOID, MVT::i32, Custom);
416   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
417
418   // Comparisons that require checking two conditions.
419   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
420   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
421   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
422   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
423   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
424   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
425   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
426   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
427   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
428   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
429   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
430   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
431
432   if (Subtarget.has64BitSupport()) {
433     // They also have instructions for converting between i64 and fp.
434     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
435     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
436     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
437     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
438     // This is just the low 32 bits of a (signed) fp->i64 conversion.
439     // We cannot do this with Promote because i64 is not a legal type.
440     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
441
442     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
443       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
444   } else {
445     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
446     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
447   }
448
449   // With the instructions enabled under FPCVT, we can do everything.
450   if (Subtarget.hasFPCVT()) {
451     if (Subtarget.has64BitSupport()) {
452       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
453       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
454       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
455       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
456     }
457
458     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
459     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
460     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
461     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
462   }
463
464   if (Subtarget.use64BitRegs()) {
465     // 64-bit PowerPC implementations can support i64 types directly
466     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
467     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
468     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
469     // 64-bit PowerPC wants to expand i128 shifts itself.
470     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
471     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
472     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
473   } else {
474     // 32-bit PowerPC wants to expand i64 shifts itself.
475     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
476     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
477     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
478   }
479
480   if (Subtarget.hasAltivec()) {
481     // First set operation action for all vector types to expand. Then we
482     // will selectively turn on ones that can be effectively codegen'd.
483     for (MVT VT : MVT::vector_valuetypes()) {
484       // add/sub are legal for all supported vector VT's.
485       setOperationAction(ISD::ADD, VT, Legal);
486       setOperationAction(ISD::SUB, VT, Legal);
487
488       // Vector instructions introduced in P8
489       if (Subtarget.hasP8Altivec() && (VT.SimpleTy != MVT::v1i128)) {
490         setOperationAction(ISD::CTPOP, VT, Legal);
491         setOperationAction(ISD::CTLZ, VT, Legal);
492       }
493       else {
494         setOperationAction(ISD::CTPOP, VT, Expand);
495         setOperationAction(ISD::CTLZ, VT, Expand);
496       }
497
498       // Vector instructions introduced in P9
499       if (Subtarget.hasP9Altivec() && (VT.SimpleTy != MVT::v1i128))
500         setOperationAction(ISD::CTTZ, VT, Legal);
501       else
502         setOperationAction(ISD::CTTZ, VT, Expand);
503
504       // We promote all shuffles to v16i8.
505       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
506       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
507
508       // We promote all non-typed operations to v4i32.
509       setOperationAction(ISD::AND   , VT, Promote);
510       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
511       setOperationAction(ISD::OR    , VT, Promote);
512       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
513       setOperationAction(ISD::XOR   , VT, Promote);
514       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
515       setOperationAction(ISD::LOAD  , VT, Promote);
516       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
517       setOperationAction(ISD::SELECT, VT, Promote);
518       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
519       setOperationAction(ISD::SELECT_CC, VT, Promote);
520       AddPromotedToType (ISD::SELECT_CC, VT, MVT::v4i32);
521       setOperationAction(ISD::STORE, VT, Promote);
522       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
523
524       // No other operations are legal.
525       setOperationAction(ISD::MUL , VT, Expand);
526       setOperationAction(ISD::SDIV, VT, Expand);
527       setOperationAction(ISD::SREM, VT, Expand);
528       setOperationAction(ISD::UDIV, VT, Expand);
529       setOperationAction(ISD::UREM, VT, Expand);
530       setOperationAction(ISD::FDIV, VT, Expand);
531       setOperationAction(ISD::FREM, VT, Expand);
532       setOperationAction(ISD::FNEG, VT, Expand);
533       setOperationAction(ISD::FSQRT, VT, Expand);
534       setOperationAction(ISD::FLOG, VT, Expand);
535       setOperationAction(ISD::FLOG10, VT, Expand);
536       setOperationAction(ISD::FLOG2, VT, Expand);
537       setOperationAction(ISD::FEXP, VT, Expand);
538       setOperationAction(ISD::FEXP2, VT, Expand);
539       setOperationAction(ISD::FSIN, VT, Expand);
540       setOperationAction(ISD::FCOS, VT, Expand);
541       setOperationAction(ISD::FABS, VT, Expand);
542       setOperationAction(ISD::FFLOOR, VT, Expand);
543       setOperationAction(ISD::FCEIL,  VT, Expand);
544       setOperationAction(ISD::FTRUNC, VT, Expand);
545       setOperationAction(ISD::FRINT,  VT, Expand);
546       setOperationAction(ISD::FNEARBYINT, VT, Expand);
547       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
548       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
549       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
550       setOperationAction(ISD::MULHU, VT, Expand);
551       setOperationAction(ISD::MULHS, VT, Expand);
552       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
553       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
554       setOperationAction(ISD::UDIVREM, VT, Expand);
555       setOperationAction(ISD::SDIVREM, VT, Expand);
556       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
557       setOperationAction(ISD::FPOW, VT, Expand);
558       setOperationAction(ISD::BSWAP, VT, Expand);
559       setOperationAction(ISD::VSELECT, VT, Expand);
560       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
561       setOperationAction(ISD::ROTL, VT, Expand);
562       setOperationAction(ISD::ROTR, VT, Expand);
563
564       for (MVT InnerVT : MVT::vector_valuetypes()) {
565         setTruncStoreAction(VT, InnerVT, Expand);
566         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
567         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
568         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
569       }
570     }
571
572     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
573     // with merges, splats, etc.
574     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
575
576     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
577     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
578     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
579     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
580     setOperationAction(ISD::SELECT, MVT::v4i32,
581                        Subtarget.useCRBits() ? Legal : Expand);
582     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
583     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
584     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
585     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
586     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
587     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
588     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
589     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
590     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
591
592     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
593     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
594     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
595     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
596
597     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
598     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
599
600     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
601       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
602       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
603     }
604
605     if (Subtarget.hasP8Altivec())
606       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
607     else
608       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
609
610     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
611     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
612
613     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
614     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
615
616     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
617     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
618     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
619     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
620
621     // Altivec does not contain unordered floating-point compare instructions
622     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
623     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
624     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
625     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
626
627     if (Subtarget.hasVSX()) {
628       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
629       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
630       if (Subtarget.hasP8Vector()) {
631         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
632         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
633       }
634       if (Subtarget.hasDirectMove() && isPPC64) {
635         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
636         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
637         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
638         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
639         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
640         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
641         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
642         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
643       }
644       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
645
646       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
647       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
648       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
649       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
650       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
651
652       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
653
654       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
655       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
656
657       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
658       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
659
660       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
661       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
662       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
663       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
664       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
665
666       // Share the Altivec comparison restrictions.
667       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
668       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
669       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
670       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
671
672       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
673       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
674
675       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
676
677       if (Subtarget.hasP8Vector())
678         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
679
680       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
681
682       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
683       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
684       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
685
686       if (Subtarget.hasP8Altivec()) {
687         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
688         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
689         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
690
691         // 128 bit shifts can be accomplished via 3 instructions for SHL and
692         // SRL, but not for SRA because of the instructions available:
693         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
694         // doing
695         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
696         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
697         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
698
699         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
700       }
701       else {
702         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
703         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
704         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
705
706         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
707
708         // VSX v2i64 only supports non-arithmetic operations.
709         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
710         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
711       }
712
713       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
714       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
715       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
716       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
717
718       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
719
720       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
721       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
722       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
723       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
724
725       // Vector operation legalization checks the result type of
726       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
727       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
728       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
729       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
730       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
731
732       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
733       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
734       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
735       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
736
737       if (Subtarget.hasDirectMove())
738         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
739       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
740
741       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
742     }
743
744     if (Subtarget.hasP8Altivec()) {
745       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
746       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
747     }
748
749     if (Subtarget.hasP9Vector()) {
750       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
751       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
752
753       // 128 bit shifts can be accomplished via 3 instructions for SHL and
754       // SRL, but not for SRA because of the instructions available:
755       // VS{RL} and VS{RL}O.
756       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
757       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
758       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
759     }
760   }
761
762   if (Subtarget.hasQPX()) {
763     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
764     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
765     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
766     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
767
768     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
769     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
770
771     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
772     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
773
774     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
775     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
776
777     if (!Subtarget.useCRBits())
778       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
779     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
780
781     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
782     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
783     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
784     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
785     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
786     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
787     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
788
789     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
790     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
791
792     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
793     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
794     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
795
796     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
797     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
798     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
799     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
800     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
801     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
802     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
803     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
804     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
805     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
806
807     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
808     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
809
810     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
811     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
812
813     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
814
815     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
816     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
817     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
818     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
819
820     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
821     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
822
823     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
824     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
825
826     if (!Subtarget.useCRBits())
827       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
828     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
829
830     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
831     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
832     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
833     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
834     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
835     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
836     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
837
838     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
839     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
840
841     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
842     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
843     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
844     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
845     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
846     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
847     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
848     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
849     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
850     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
851
852     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
853     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
854
855     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
856     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
857
858     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
859
860     setOperationAction(ISD::AND , MVT::v4i1, Legal);
861     setOperationAction(ISD::OR , MVT::v4i1, Legal);
862     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
863
864     if (!Subtarget.useCRBits())
865       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
866     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
867
868     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
869     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
870
871     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
872     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
873     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
874     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
875     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
876     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
877     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
878
879     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
880     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
881
882     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
883
884     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
885     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
886     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
887     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
888
889     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
890     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
891     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
892     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
893
894     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
895     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
896
897     // These need to set FE_INEXACT, and so cannot be vectorized here.
898     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
899     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
900
901     if (TM.Options.UnsafeFPMath) {
902       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
903       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
904
905       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
906       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
907     } else {
908       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
909       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
910
911       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
912       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
913     }
914   }
915
916   if (Subtarget.has64BitSupport())
917     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
918
919   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
920
921   if (!isPPC64) {
922     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
923     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
924   }
925
926   setBooleanContents(ZeroOrOneBooleanContent);
927
928   if (Subtarget.hasAltivec()) {
929     // Altivec instructions set fields to all zeros or all ones.
930     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
931   }
932
933   if (!isPPC64) {
934     // These libcalls are not available in 32-bit.
935     setLibcallName(RTLIB::SHL_I128, nullptr);
936     setLibcallName(RTLIB::SRL_I128, nullptr);
937     setLibcallName(RTLIB::SRA_I128, nullptr);
938   }
939
940   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
941
942   // We have target-specific dag combine patterns for the following nodes:
943   setTargetDAGCombine(ISD::SHL);
944   setTargetDAGCombine(ISD::SRA);
945   setTargetDAGCombine(ISD::SRL);
946   setTargetDAGCombine(ISD::SINT_TO_FP);
947   setTargetDAGCombine(ISD::BUILD_VECTOR);
948   if (Subtarget.hasFPCVT())
949     setTargetDAGCombine(ISD::UINT_TO_FP);
950   setTargetDAGCombine(ISD::LOAD);
951   setTargetDAGCombine(ISD::STORE);
952   setTargetDAGCombine(ISD::BR_CC);
953   if (Subtarget.useCRBits())
954     setTargetDAGCombine(ISD::BRCOND);
955   setTargetDAGCombine(ISD::BSWAP);
956   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
957   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
958   setTargetDAGCombine(ISD::INTRINSIC_VOID);
959
960   setTargetDAGCombine(ISD::SIGN_EXTEND);
961   setTargetDAGCombine(ISD::ZERO_EXTEND);
962   setTargetDAGCombine(ISD::ANY_EXTEND);
963
964   if (Subtarget.useCRBits()) {
965     setTargetDAGCombine(ISD::TRUNCATE);
966     setTargetDAGCombine(ISD::SETCC);
967     setTargetDAGCombine(ISD::SELECT_CC);
968   }
969
970   // Use reciprocal estimates.
971   if (TM.Options.UnsafeFPMath) {
972     setTargetDAGCombine(ISD::FDIV);
973     setTargetDAGCombine(ISD::FSQRT);
974   }
975
976   // Darwin long double math library functions have $LDBL128 appended.
977   if (Subtarget.isDarwin()) {
978     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
979     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
980     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
981     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
982     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
983     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
984     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
985     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
986     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
987     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
988   }
989
990   // With 32 condition bits, we don't need to sink (and duplicate) compares
991   // aggressively in CodeGenPrep.
992   if (Subtarget.useCRBits()) {
993     setHasMultipleConditionRegisters();
994     setJumpIsExpensive();
995   }
996
997   setMinFunctionAlignment(2);
998   if (Subtarget.isDarwin())
999     setPrefFunctionAlignment(4);
1000
1001   switch (Subtarget.getDarwinDirective()) {
1002   default: break;
1003   case PPC::DIR_970:
1004   case PPC::DIR_A2:
1005   case PPC::DIR_E500mc:
1006   case PPC::DIR_E5500:
1007   case PPC::DIR_PWR4:
1008   case PPC::DIR_PWR5:
1009   case PPC::DIR_PWR5X:
1010   case PPC::DIR_PWR6:
1011   case PPC::DIR_PWR6X:
1012   case PPC::DIR_PWR7:
1013   case PPC::DIR_PWR8:
1014   case PPC::DIR_PWR9:
1015     setPrefFunctionAlignment(4);
1016     setPrefLoopAlignment(4);
1017     break;
1018   }
1019
1020   if (Subtarget.enableMachineScheduler())
1021     setSchedulingPreference(Sched::Source);
1022   else
1023     setSchedulingPreference(Sched::Hybrid);
1024
1025   computeRegisterProperties(STI.getRegisterInfo());
1026
1027   // The Freescale cores do better with aggressive inlining of memcpy and
1028   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1029   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1030       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1031     MaxStoresPerMemset = 32;
1032     MaxStoresPerMemsetOptSize = 16;
1033     MaxStoresPerMemcpy = 32;
1034     MaxStoresPerMemcpyOptSize = 8;
1035     MaxStoresPerMemmove = 32;
1036     MaxStoresPerMemmoveOptSize = 8;
1037   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1038     // The A2 also benefits from (very) aggressive inlining of memcpy and
1039     // friends. The overhead of a the function call, even when warm, can be
1040     // over one hundred cycles.
1041     MaxStoresPerMemset = 128;
1042     MaxStoresPerMemcpy = 128;
1043     MaxStoresPerMemmove = 128;
1044   }
1045 }
1046
1047 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1048 /// the desired ByVal argument alignment.
1049 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1050                              unsigned MaxMaxAlign) {
1051   if (MaxAlign == MaxMaxAlign)
1052     return;
1053   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1054     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1055       MaxAlign = 32;
1056     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1057       MaxAlign = 16;
1058   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1059     unsigned EltAlign = 0;
1060     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1061     if (EltAlign > MaxAlign)
1062       MaxAlign = EltAlign;
1063   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1064     for (auto *EltTy : STy->elements()) {
1065       unsigned EltAlign = 0;
1066       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1067       if (EltAlign > MaxAlign)
1068         MaxAlign = EltAlign;
1069       if (MaxAlign == MaxMaxAlign)
1070         break;
1071     }
1072   }
1073 }
1074
1075 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1076 /// function arguments in the caller parameter area.
1077 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1078                                                   const DataLayout &DL) const {
1079   // Darwin passes everything on 4 byte boundary.
1080   if (Subtarget.isDarwin())
1081     return 4;
1082
1083   // 16byte and wider vectors are passed on 16byte boundary.
1084   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1085   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1086   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1087     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1088   return Align;
1089 }
1090
1091 bool PPCTargetLowering::useSoftFloat() const {
1092   return Subtarget.useSoftFloat();
1093 }
1094
1095 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1096   switch ((PPCISD::NodeType)Opcode) {
1097   case PPCISD::FIRST_NUMBER:    break;
1098   case PPCISD::FSEL:            return "PPCISD::FSEL";
1099   case PPCISD::FCFID:           return "PPCISD::FCFID";
1100   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1101   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1102   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1103   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1104   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1105   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1106   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1107   case PPCISD::FRE:             return "PPCISD::FRE";
1108   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1109   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1110   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1111   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1112   case PPCISD::VPERM:           return "PPCISD::VPERM";
1113   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1114   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1115   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1116   case PPCISD::CMPB:            return "PPCISD::CMPB";
1117   case PPCISD::Hi:              return "PPCISD::Hi";
1118   case PPCISD::Lo:              return "PPCISD::Lo";
1119   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1120   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1121   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1122   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1123   case PPCISD::SRL:             return "PPCISD::SRL";
1124   case PPCISD::SRA:             return "PPCISD::SRA";
1125   case PPCISD::SHL:             return "PPCISD::SHL";
1126   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1127   case PPCISD::CALL:            return "PPCISD::CALL";
1128   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1129   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1130   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1131   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1132   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1133   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1134   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1135   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1136   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1137   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1138   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1139   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1140   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1141   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1142   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1143   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1144   case PPCISD::VCMP:            return "PPCISD::VCMP";
1145   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1146   case PPCISD::LBRX:            return "PPCISD::LBRX";
1147   case PPCISD::STBRX:           return "PPCISD::STBRX";
1148   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1149   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1150   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1151   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1152   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1153   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1154   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1155   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1156   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1157   case PPCISD::BDZ:             return "PPCISD::BDZ";
1158   case PPCISD::MFFS:            return "PPCISD::MFFS";
1159   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1160   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1161   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1162   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1163   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1164   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1165   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1166   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1167   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1168   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1169   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1170   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1171   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1172   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1173   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1174   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1175   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1176   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1177   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1178   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1179   case PPCISD::SC:              return "PPCISD::SC";
1180   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1181   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1182   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1183   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1184   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1185   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1186   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1187   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1188   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1189   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1190   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1191   }
1192   return nullptr;
1193 }
1194
1195 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1196                                           EVT VT) const {
1197   if (!VT.isVector())
1198     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1199
1200   if (Subtarget.hasQPX())
1201     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1202
1203   return VT.changeVectorElementTypeToInteger();
1204 }
1205
1206 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1207   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1208   return true;
1209 }
1210
1211 //===----------------------------------------------------------------------===//
1212 // Node matching predicates, for use by the tblgen matching code.
1213 //===----------------------------------------------------------------------===//
1214
1215 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1216 static bool isFloatingPointZero(SDValue Op) {
1217   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1218     return CFP->getValueAPF().isZero();
1219   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1220     // Maybe this has already been legalized into the constant pool?
1221     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1222       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1223         return CFP->getValueAPF().isZero();
1224   }
1225   return false;
1226 }
1227
1228 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1229 /// true if Op is undef or if it matches the specified value.
1230 static bool isConstantOrUndef(int Op, int Val) {
1231   return Op < 0 || Op == Val;
1232 }
1233
1234 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1235 /// VPKUHUM instruction.
1236 /// The ShuffleKind distinguishes between big-endian operations with
1237 /// two different inputs (0), either-endian operations with two identical
1238 /// inputs (1), and little-endian operations with two different inputs (2).
1239 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1240 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1241                                SelectionDAG &DAG) {
1242   bool IsLE = DAG.getDataLayout().isLittleEndian();
1243   if (ShuffleKind == 0) {
1244     if (IsLE)
1245       return false;
1246     for (unsigned i = 0; i != 16; ++i)
1247       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1248         return false;
1249   } else if (ShuffleKind == 2) {
1250     if (!IsLE)
1251       return false;
1252     for (unsigned i = 0; i != 16; ++i)
1253       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1254         return false;
1255   } else if (ShuffleKind == 1) {
1256     unsigned j = IsLE ? 0 : 1;
1257     for (unsigned i = 0; i != 8; ++i)
1258       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1259           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1260         return false;
1261   }
1262   return true;
1263 }
1264
1265 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1266 /// VPKUWUM instruction.
1267 /// The ShuffleKind distinguishes between big-endian operations with
1268 /// two different inputs (0), either-endian operations with two identical
1269 /// inputs (1), and little-endian operations with two different inputs (2).
1270 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1271 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1272                                SelectionDAG &DAG) {
1273   bool IsLE = DAG.getDataLayout().isLittleEndian();
1274   if (ShuffleKind == 0) {
1275     if (IsLE)
1276       return false;
1277     for (unsigned i = 0; i != 16; i += 2)
1278       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1279           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1280         return false;
1281   } else if (ShuffleKind == 2) {
1282     if (!IsLE)
1283       return false;
1284     for (unsigned i = 0; i != 16; i += 2)
1285       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1286           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1287         return false;
1288   } else if (ShuffleKind == 1) {
1289     unsigned j = IsLE ? 0 : 2;
1290     for (unsigned i = 0; i != 8; i += 2)
1291       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1292           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1293           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1294           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1295         return false;
1296   }
1297   return true;
1298 }
1299
1300 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1301 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1302 /// current subtarget.
1303 ///
1304 /// The ShuffleKind distinguishes between big-endian operations with
1305 /// two different inputs (0), either-endian operations with two identical
1306 /// inputs (1), and little-endian operations with two different inputs (2).
1307 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1308 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1309                                SelectionDAG &DAG) {
1310   const PPCSubtarget& Subtarget =
1311     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1312   if (!Subtarget.hasP8Vector())
1313     return false;
1314
1315   bool IsLE = DAG.getDataLayout().isLittleEndian();
1316   if (ShuffleKind == 0) {
1317     if (IsLE)
1318       return false;
1319     for (unsigned i = 0; i != 16; i += 4)
1320       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1321           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1322           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1323           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1324         return false;
1325   } else if (ShuffleKind == 2) {
1326     if (!IsLE)
1327       return false;
1328     for (unsigned i = 0; i != 16; i += 4)
1329       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1330           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1331           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1332           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1333         return false;
1334   } else if (ShuffleKind == 1) {
1335     unsigned j = IsLE ? 0 : 4;
1336     for (unsigned i = 0; i != 8; i += 4)
1337       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1338           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1339           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1340           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1341           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1342           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1343           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1344           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1345         return false;
1346   }
1347   return true;
1348 }
1349
1350 /// isVMerge - Common function, used to match vmrg* shuffles.
1351 ///
1352 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1353                      unsigned LHSStart, unsigned RHSStart) {
1354   if (N->getValueType(0) != MVT::v16i8)
1355     return false;
1356   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1357          "Unsupported merge size!");
1358
1359   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1360     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1361       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1362                              LHSStart+j+i*UnitSize) ||
1363           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1364                              RHSStart+j+i*UnitSize))
1365         return false;
1366     }
1367   return true;
1368 }
1369
1370 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1371 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1372 /// The ShuffleKind distinguishes between big-endian merges with two
1373 /// different inputs (0), either-endian merges with two identical inputs (1),
1374 /// and little-endian merges with two different inputs (2).  For the latter,
1375 /// the input operands are swapped (see PPCInstrAltivec.td).
1376 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1377                              unsigned ShuffleKind, SelectionDAG &DAG) {
1378   if (DAG.getDataLayout().isLittleEndian()) {
1379     if (ShuffleKind == 1) // unary
1380       return isVMerge(N, UnitSize, 0, 0);
1381     else if (ShuffleKind == 2) // swapped
1382       return isVMerge(N, UnitSize, 0, 16);
1383     else
1384       return false;
1385   } else {
1386     if (ShuffleKind == 1) // unary
1387       return isVMerge(N, UnitSize, 8, 8);
1388     else if (ShuffleKind == 0) // normal
1389       return isVMerge(N, UnitSize, 8, 24);
1390     else
1391       return false;
1392   }
1393 }
1394
1395 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1396 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1397 /// The ShuffleKind distinguishes between big-endian merges with two
1398 /// different inputs (0), either-endian merges with two identical inputs (1),
1399 /// and little-endian merges with two different inputs (2).  For the latter,
1400 /// the input operands are swapped (see PPCInstrAltivec.td).
1401 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1402                              unsigned ShuffleKind, SelectionDAG &DAG) {
1403   if (DAG.getDataLayout().isLittleEndian()) {
1404     if (ShuffleKind == 1) // unary
1405       return isVMerge(N, UnitSize, 8, 8);
1406     else if (ShuffleKind == 2) // swapped
1407       return isVMerge(N, UnitSize, 8, 24);
1408     else
1409       return false;
1410   } else {
1411     if (ShuffleKind == 1) // unary
1412       return isVMerge(N, UnitSize, 0, 0);
1413     else if (ShuffleKind == 0) // normal
1414       return isVMerge(N, UnitSize, 0, 16);
1415     else
1416       return false;
1417   }
1418 }
1419
1420 /**
1421  * \brief Common function used to match vmrgew and vmrgow shuffles
1422  *
1423  * The indexOffset determines whether to look for even or odd words in
1424  * the shuffle mask. This is based on the of the endianness of the target
1425  * machine.
1426  *   - Little Endian:
1427  *     - Use offset of 0 to check for odd elements
1428  *     - Use offset of 4 to check for even elements
1429  *   - Big Endian:
1430  *     - Use offset of 0 to check for even elements
1431  *     - Use offset of 4 to check for odd elements
1432  * A detailed description of the vector element ordering for little endian and
1433  * big endian can be found at
1434  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1435  * Targeting your applications - what little endian and big endian IBM XL C/C++
1436  * compiler differences mean to you
1437  *
1438  * The mask to the shuffle vector instruction specifies the indices of the
1439  * elements from the two input vectors to place in the result. The elements are
1440  * numbered in array-access order, starting with the first vector. These vectors
1441  * are always of type v16i8, thus each vector will contain 16 elements of size
1442  * 8. More info on the shuffle vector can be found in the
1443  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1444  * Language Reference.
1445  *
1446  * The RHSStartValue indicates whether the same input vectors are used (unary)
1447  * or two different input vectors are used, based on the following:
1448  *   - If the instruction uses the same vector for both inputs, the range of the
1449  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1450  *     be 0.
1451  *   - If the instruction has two different vectors then the range of the
1452  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1453  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1454  *     to 31 specify elements in the second vector).
1455  *
1456  * \param[in] N The shuffle vector SD Node to analyze
1457  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1458  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1459  * vector to the shuffle_vector instruction
1460  * \return true iff this shuffle vector represents an even or odd word merge
1461  */
1462 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1463                      unsigned RHSStartValue) {
1464   if (N->getValueType(0) != MVT::v16i8)
1465     return false;
1466
1467   for (unsigned i = 0; i < 2; ++i)
1468     for (unsigned j = 0; j < 4; ++j)
1469       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1470                              i*RHSStartValue+j+IndexOffset) ||
1471           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1472                              i*RHSStartValue+j+IndexOffset+8))
1473         return false;
1474   return true;
1475 }
1476
1477 /**
1478  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1479  * vmrgow instructions.
1480  *
1481  * \param[in] N The shuffle vector SD Node to analyze
1482  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1483  * \param[in] ShuffleKind Identify the type of merge:
1484  *   - 0 = big-endian merge with two different inputs;
1485  *   - 1 = either-endian merge with two identical inputs;
1486  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1487  *     little-endian merges).
1488  * \param[in] DAG The current SelectionDAG
1489  * \return true iff this shuffle mask
1490  */
1491 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1492                               unsigned ShuffleKind, SelectionDAG &DAG) {
1493   if (DAG.getDataLayout().isLittleEndian()) {
1494     unsigned indexOffset = CheckEven ? 4 : 0;
1495     if (ShuffleKind == 1) // Unary
1496       return isVMerge(N, indexOffset, 0);
1497     else if (ShuffleKind == 2) // swapped
1498       return isVMerge(N, indexOffset, 16);
1499     else
1500       return false;
1501   }
1502   else {
1503     unsigned indexOffset = CheckEven ? 0 : 4;
1504     if (ShuffleKind == 1) // Unary
1505       return isVMerge(N, indexOffset, 0);
1506     else if (ShuffleKind == 0) // Normal
1507       return isVMerge(N, indexOffset, 16);
1508     else
1509       return false;
1510   }
1511   return false;
1512 }
1513
1514 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1515 /// amount, otherwise return -1.
1516 /// The ShuffleKind distinguishes between big-endian operations with two
1517 /// different inputs (0), either-endian operations with two identical inputs
1518 /// (1), and little-endian operations with two different inputs (2).  For the
1519 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1520 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1521                              SelectionDAG &DAG) {
1522   if (N->getValueType(0) != MVT::v16i8)
1523     return -1;
1524
1525   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1526
1527   // Find the first non-undef value in the shuffle mask.
1528   unsigned i;
1529   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1530     /*search*/;
1531
1532   if (i == 16) return -1;  // all undef.
1533
1534   // Otherwise, check to see if the rest of the elements are consecutively
1535   // numbered from this value.
1536   unsigned ShiftAmt = SVOp->getMaskElt(i);
1537   if (ShiftAmt < i) return -1;
1538
1539   ShiftAmt -= i;
1540   bool isLE = DAG.getDataLayout().isLittleEndian();
1541
1542   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1543     // Check the rest of the elements to see if they are consecutive.
1544     for (++i; i != 16; ++i)
1545       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1546         return -1;
1547   } else if (ShuffleKind == 1) {
1548     // Check the rest of the elements to see if they are consecutive.
1549     for (++i; i != 16; ++i)
1550       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1551         return -1;
1552   } else
1553     return -1;
1554
1555   if (isLE)
1556     ShiftAmt = 16 - ShiftAmt;
1557
1558   return ShiftAmt;
1559 }
1560
1561 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1562 /// specifies a splat of a single element that is suitable for input to
1563 /// VSPLTB/VSPLTH/VSPLTW.
1564 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1565   assert(N->getValueType(0) == MVT::v16i8 &&
1566          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1567
1568   // The consecutive indices need to specify an element, not part of two
1569   // different elements.  So abandon ship early if this isn't the case.
1570   if (N->getMaskElt(0) % EltSize != 0)
1571     return false;
1572
1573   // This is a splat operation if each element of the permute is the same, and
1574   // if the value doesn't reference the second vector.
1575   unsigned ElementBase = N->getMaskElt(0);
1576
1577   // FIXME: Handle UNDEF elements too!
1578   if (ElementBase >= 16)
1579     return false;
1580
1581   // Check that the indices are consecutive, in the case of a multi-byte element
1582   // splatted with a v16i8 mask.
1583   for (unsigned i = 1; i != EltSize; ++i)
1584     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1585       return false;
1586
1587   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1588     if (N->getMaskElt(i) < 0) continue;
1589     for (unsigned j = 0; j != EltSize; ++j)
1590       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1591         return false;
1592   }
1593   return true;
1594 }
1595
1596   // Check that the mask is shuffling words
1597 static bool isWordShuffleMask(ShuffleVectorSDNode *N) {
1598   for (unsigned i = 0; i < 4; ++i) {
1599     unsigned B0 = N->getMaskElt(i*4);
1600     unsigned B1 = N->getMaskElt(i*4+1);
1601     unsigned B2 = N->getMaskElt(i*4+2);
1602     unsigned B3 = N->getMaskElt(i*4+3);
1603     if (B0 % 4)
1604       return false;
1605     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1606       return false;
1607   }
1608
1609   return true;
1610 }
1611
1612 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1613                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1614   if (!isWordShuffleMask(N))
1615     return false;
1616
1617   // Now we look at mask elements 0,4,8,12
1618   unsigned M0 = N->getMaskElt(0) / 4;
1619   unsigned M1 = N->getMaskElt(4) / 4;
1620   unsigned M2 = N->getMaskElt(8) / 4;
1621   unsigned M3 = N->getMaskElt(12) / 4;
1622   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1623   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1624
1625   // Below, let H and L be arbitrary elements of the shuffle mask
1626   // where H is in the range [4,7] and L is in the range [0,3].
1627   // H, 1, 2, 3 or L, 5, 6, 7
1628   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1629       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1630     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1631     InsertAtByte = IsLE ? 12 : 0;
1632     Swap = M0 < 4;
1633     return true;
1634   }
1635   // 0, H, 2, 3 or 4, L, 6, 7
1636   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1637       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1638     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1639     InsertAtByte = IsLE ? 8 : 4;
1640     Swap = M1 < 4;
1641     return true;
1642   }
1643   // 0, 1, H, 3 or 4, 5, L, 7
1644   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1645       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1646     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1647     InsertAtByte = IsLE ? 4 : 8;
1648     Swap = M2 < 4;
1649     return true;
1650   }
1651   // 0, 1, 2, H or 4, 5, 6, L
1652   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1653       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1654     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1655     InsertAtByte = IsLE ? 0 : 12;
1656     Swap = M3 < 4;
1657     return true;
1658   }
1659
1660   // If both vector operands for the shuffle are the same vector, the mask will
1661   // contain only elements from the first one and the second one will be undef.
1662   if (N->getOperand(1).isUndef()) {
1663     ShiftElts = 0;
1664     Swap = true;
1665     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1666     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1667       InsertAtByte = IsLE ? 12 : 0;
1668       return true;
1669     }
1670     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1671       InsertAtByte = IsLE ? 8 : 4;
1672       return true;
1673     }
1674     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1675       InsertAtByte = IsLE ? 4 : 8;
1676       return true;
1677     }
1678     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1679       InsertAtByte = IsLE ? 0 : 12;
1680       return true;
1681     }
1682   }
1683
1684   return false;
1685 }
1686
1687 bool PPC::isXXSLDWIShuffleMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1688                                bool &Swap, bool IsLE) {
1689   assert(N->getValueType(0) == MVT::v16i8 && "Shuffle vector expects v16i8");
1690   // Ensure each byte index of the word is consecutive.
1691   if (!isWordShuffleMask(N))
1692     return false;
1693
1694   // Now we look at mask elements 0,4,8,12, which are the beginning of words.
1695   unsigned M0 = N->getMaskElt(0) / 4;
1696   unsigned M1 = N->getMaskElt(4) / 4;
1697   unsigned M2 = N->getMaskElt(8) / 4;
1698   unsigned M3 = N->getMaskElt(12) / 4;
1699
1700   // If both vector operands for the shuffle are the same vector, the mask will
1701   // contain only elements from the first one and the second one will be undef.
1702   if (N->getOperand(1).isUndef()) {
1703     assert(M0 < 4 && "Indexing into an undef vector?");
1704     if (M1 != (M0 + 1) % 4 || M2 != (M1 + 1) % 4 || M3 != (M2 + 1) % 4)
1705       return false;
1706
1707     ShiftElts = IsLE ? (4 - M0) % 4 : M0;
1708     Swap = false;
1709     return true;
1710   }
1711
1712   // Ensure each word index of the ShuffleVector Mask is consecutive.
1713   if (M1 != (M0 + 1) % 8 || M2 != (M1 + 1) % 8 || M3 != (M2 + 1) % 8)
1714     return false;
1715
1716   if (IsLE) {
1717     if (M0 == 0 || M0 == 7 || M0 == 6 || M0 == 5) {
1718       // Input vectors don't need to be swapped if the leading element
1719       // of the result is one of the 3 left elements of the second vector
1720       // (or if there is no shift to be done at all).
1721       Swap = false;
1722       ShiftElts = (8 - M0) % 8;
1723     } else if (M0 == 4 || M0 == 3 || M0 == 2 || M0 == 1) {
1724       // Input vectors need to be swapped if the leading element
1725       // of the result is one of the 3 left elements of the first vector
1726       // (or if we're shifting by 4 - thereby simply swapping the vectors).
1727       Swap = true;
1728       ShiftElts = (4 - M0) % 4;
1729     }
1730
1731     return true;
1732   } else {                                          // BE
1733     if (M0 == 0 || M0 == 1 || M0 == 2 || M0 == 3) {
1734       // Input vectors don't need to be swapped if the leading element
1735       // of the result is one of the 4 elements of the first vector.
1736       Swap = false;
1737       ShiftElts = M0;
1738     } else if (M0 == 4 || M0 == 5 || M0 == 6 || M0 == 7) {
1739       // Input vectors need to be swapped if the leading element
1740       // of the result is one of the 4 elements of the right vector.
1741       Swap = true;
1742       ShiftElts = M0 - 4;
1743     }
1744
1745     return true;
1746   }
1747 }
1748
1749
1750 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1751 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1752 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1753                                 SelectionDAG &DAG) {
1754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1755   assert(isSplatShuffleMask(SVOp, EltSize));
1756   if (DAG.getDataLayout().isLittleEndian())
1757     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1758   else
1759     return SVOp->getMaskElt(0) / EltSize;
1760 }
1761
1762 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1763 /// by using a vspltis[bhw] instruction of the specified element size, return
1764 /// the constant being splatted.  The ByteSize field indicates the number of
1765 /// bytes of each element [124] -> [bhw].
1766 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1767   SDValue OpVal(nullptr, 0);
1768
1769   // If ByteSize of the splat is bigger than the element size of the
1770   // build_vector, then we have a case where we are checking for a splat where
1771   // multiple elements of the buildvector are folded together into a single
1772   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1773   unsigned EltSize = 16/N->getNumOperands();
1774   if (EltSize < ByteSize) {
1775     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1776     SDValue UniquedVals[4];
1777     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1778
1779     // See if all of the elements in the buildvector agree across.
1780     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1781       if (N->getOperand(i).isUndef()) continue;
1782       // If the element isn't a constant, bail fully out.
1783       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1784
1785       if (!UniquedVals[i&(Multiple-1)].getNode())
1786         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1787       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1788         return SDValue();  // no match.
1789     }
1790
1791     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1792     // either constant or undef values that are identical for each chunk.  See
1793     // if these chunks can form into a larger vspltis*.
1794
1795     // Check to see if all of the leading entries are either 0 or -1.  If
1796     // neither, then this won't fit into the immediate field.
1797     bool LeadingZero = true;
1798     bool LeadingOnes = true;
1799     for (unsigned i = 0; i != Multiple-1; ++i) {
1800       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1801
1802       LeadingZero &= isNullConstant(UniquedVals[i]);
1803       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1804     }
1805     // Finally, check the least significant entry.
1806     if (LeadingZero) {
1807       if (!UniquedVals[Multiple-1].getNode())
1808         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1809       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1810       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1811         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1812     }
1813     if (LeadingOnes) {
1814       if (!UniquedVals[Multiple-1].getNode())
1815         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1816       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1817       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1818         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1819     }
1820
1821     return SDValue();
1822   }
1823
1824   // Check to see if this buildvec has a single non-undef value in its elements.
1825   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1826     if (N->getOperand(i).isUndef()) continue;
1827     if (!OpVal.getNode())
1828       OpVal = N->getOperand(i);
1829     else if (OpVal != N->getOperand(i))
1830       return SDValue();
1831   }
1832
1833   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1834
1835   unsigned ValSizeInBytes = EltSize;
1836   uint64_t Value = 0;
1837   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1838     Value = CN->getZExtValue();
1839   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1840     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1841     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1842   }
1843
1844   // If the splat value is larger than the element value, then we can never do
1845   // this splat.  The only case that we could fit the replicated bits into our
1846   // immediate field for would be zero, and we prefer to use vxor for it.
1847   if (ValSizeInBytes < ByteSize) return SDValue();
1848
1849   // If the element value is larger than the splat value, check if it consists
1850   // of a repeated bit pattern of size ByteSize.
1851   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1852     return SDValue();
1853
1854   // Properly sign extend the value.
1855   int MaskVal = SignExtend32(Value, ByteSize * 8);
1856
1857   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1858   if (MaskVal == 0) return SDValue();
1859
1860   // Finally, if this value fits in a 5 bit sext field, return it
1861   if (SignExtend32<5>(MaskVal) == MaskVal)
1862     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1863   return SDValue();
1864 }
1865
1866 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1867 /// amount, otherwise return -1.
1868 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1869   EVT VT = N->getValueType(0);
1870   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1871     return -1;
1872
1873   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1874
1875   // Find the first non-undef value in the shuffle mask.
1876   unsigned i;
1877   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1878     /*search*/;
1879
1880   if (i == 4) return -1;  // all undef.
1881
1882   // Otherwise, check to see if the rest of the elements are consecutively
1883   // numbered from this value.
1884   unsigned ShiftAmt = SVOp->getMaskElt(i);
1885   if (ShiftAmt < i) return -1;
1886   ShiftAmt -= i;
1887
1888   // Check the rest of the elements to see if they are consecutive.
1889   for (++i; i != 4; ++i)
1890     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1891       return -1;
1892
1893   return ShiftAmt;
1894 }
1895
1896 //===----------------------------------------------------------------------===//
1897 //  Addressing Mode Selection
1898 //===----------------------------------------------------------------------===//
1899
1900 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1901 /// or 64-bit immediate, and if the value can be accurately represented as a
1902 /// sign extension from a 16-bit value.  If so, this returns true and the
1903 /// immediate.
1904 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1905   if (!isa<ConstantSDNode>(N))
1906     return false;
1907
1908   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1909   if (N->getValueType(0) == MVT::i32)
1910     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1911   else
1912     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1913 }
1914 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1915   return isIntS16Immediate(Op.getNode(), Imm);
1916 }
1917
1918 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1919 /// can be represented as an indexed [r+r] operation.  Returns false if it
1920 /// can be more efficiently represented with [r+imm].
1921 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1922                                             SDValue &Index,
1923                                             SelectionDAG &DAG) const {
1924   short imm = 0;
1925   if (N.getOpcode() == ISD::ADD) {
1926     if (isIntS16Immediate(N.getOperand(1), imm))
1927       return false;    // r+i
1928     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1929       return false;    // r+i
1930
1931     Base = N.getOperand(0);
1932     Index = N.getOperand(1);
1933     return true;
1934   } else if (N.getOpcode() == ISD::OR) {
1935     if (isIntS16Immediate(N.getOperand(1), imm))
1936       return false;    // r+i can fold it if we can.
1937
1938     // If this is an or of disjoint bitfields, we can codegen this as an add
1939     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1940     // disjoint.
1941     KnownBits LHSKnown, RHSKnown;
1942     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1943
1944     if (LHSKnown.Zero.getBoolValue()) {
1945       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1946       // If all of the bits are known zero on the LHS or RHS, the add won't
1947       // carry.
1948       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1949         Base = N.getOperand(0);
1950         Index = N.getOperand(1);
1951         return true;
1952       }
1953     }
1954   }
1955
1956   return false;
1957 }
1958
1959 // If we happen to be doing an i64 load or store into a stack slot that has
1960 // less than a 4-byte alignment, then the frame-index elimination may need to
1961 // use an indexed load or store instruction (because the offset may not be a
1962 // multiple of 4). The extra register needed to hold the offset comes from the
1963 // register scavenger, and it is possible that the scavenger will need to use
1964 // an emergency spill slot. As a result, we need to make sure that a spill slot
1965 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1966 // stack slot.
1967 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1968   // FIXME: This does not handle the LWA case.
1969   if (VT != MVT::i64)
1970     return;
1971
1972   // NOTE: We'll exclude negative FIs here, which come from argument
1973   // lowering, because there are no known test cases triggering this problem
1974   // using packed structures (or similar). We can remove this exclusion if
1975   // we find such a test case. The reason why this is so test-case driven is
1976   // because this entire 'fixup' is only to prevent crashes (from the
1977   // register scavenger) on not-really-valid inputs. For example, if we have:
1978   //   %a = alloca i1
1979   //   %b = bitcast i1* %a to i64*
1980   //   store i64* a, i64 b
1981   // then the store should really be marked as 'align 1', but is not. If it
1982   // were marked as 'align 1' then the indexed form would have been
1983   // instruction-selected initially, and the problem this 'fixup' is preventing
1984   // won't happen regardless.
1985   if (FrameIdx < 0)
1986     return;
1987
1988   MachineFunction &MF = DAG.getMachineFunction();
1989   MachineFrameInfo &MFI = MF.getFrameInfo();
1990
1991   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1992   if (Align >= 4)
1993     return;
1994
1995   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1996   FuncInfo->setHasNonRISpills();
1997 }
1998
1999 /// Returns true if the address N can be represented by a base register plus
2000 /// a signed 16-bit displacement [r+imm], and if it is not better
2001 /// represented as reg+reg.  If Aligned is true, only accept displacements
2002 /// suitable for STD and friends, i.e. multiples of 4.
2003 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
2004                                             SDValue &Base,
2005                                             SelectionDAG &DAG,
2006                                             bool Aligned) const {
2007   // FIXME dl should come from parent load or store, not from address
2008   SDLoc dl(N);
2009   // If this can be more profitably realized as r+r, fail.
2010   if (SelectAddressRegReg(N, Disp, Base, DAG))
2011     return false;
2012
2013   if (N.getOpcode() == ISD::ADD) {
2014     short imm = 0;
2015     if (isIntS16Immediate(N.getOperand(1), imm) &&
2016         (!Aligned || (imm & 3) == 0)) {
2017       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2018       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2019         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2020         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2021       } else {
2022         Base = N.getOperand(0);
2023       }
2024       return true; // [r+i]
2025     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
2026       // Match LOAD (ADD (X, Lo(G))).
2027       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
2028              && "Cannot handle constant offsets yet!");
2029       Disp = N.getOperand(1).getOperand(0);  // The global address.
2030       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
2031              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
2032              Disp.getOpcode() == ISD::TargetConstantPool ||
2033              Disp.getOpcode() == ISD::TargetJumpTable);
2034       Base = N.getOperand(0);
2035       return true;  // [&g+r]
2036     }
2037   } else if (N.getOpcode() == ISD::OR) {
2038     short imm = 0;
2039     if (isIntS16Immediate(N.getOperand(1), imm) &&
2040         (!Aligned || (imm & 3) == 0)) {
2041       // If this is an or of disjoint bitfields, we can codegen this as an add
2042       // (for better address arithmetic) if the LHS and RHS of the OR are
2043       // provably disjoint.
2044       KnownBits LHSKnown;
2045       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
2046
2047       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
2048         // If all of the bits are known zero on the LHS or RHS, the add won't
2049         // carry.
2050         if (FrameIndexSDNode *FI =
2051               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
2052           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2053           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2054         } else {
2055           Base = N.getOperand(0);
2056         }
2057         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
2058         return true;
2059       }
2060     }
2061   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
2062     // Loading from a constant address.
2063
2064     // If this address fits entirely in a 16-bit sext immediate field, codegen
2065     // this as "d, 0"
2066     short Imm;
2067     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
2068       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2069       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2070                              CN->getValueType(0));
2071       return true;
2072     }
2073
2074     // Handle 32-bit sext immediates with LIS + addr mode.
2075     if ((CN->getValueType(0) == MVT::i32 ||
2076          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2077         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
2078       int Addr = (int)CN->getZExtValue();
2079
2080       // Otherwise, break this down into an LIS + disp.
2081       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2082
2083       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2084                                    MVT::i32);
2085       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2086       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2087       return true;
2088     }
2089   }
2090
2091   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2092   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2093     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2094     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2095   } else
2096     Base = N;
2097   return true;      // [r+0]
2098 }
2099
2100 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2101 /// represented as an indexed [r+r] operation.
2102 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2103                                                 SDValue &Index,
2104                                                 SelectionDAG &DAG) const {
2105   // Check to see if we can easily represent this as an [r+r] address.  This
2106   // will fail if it thinks that the address is more profitably represented as
2107   // reg+imm, e.g. where imm = 0.
2108   if (SelectAddressRegReg(N, Base, Index, DAG))
2109     return true;
2110
2111   // If the operand is an addition, always emit this as [r+r], since this is
2112   // better (for code size, and execution, as the memop does the add for free)
2113   // than emitting an explicit add.
2114   if (N.getOpcode() == ISD::ADD) {
2115     Base = N.getOperand(0);
2116     Index = N.getOperand(1);
2117     return true;
2118   }
2119
2120   // Otherwise, do it the hard way, using R0 as the base register.
2121   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2122                          N.getValueType());
2123   Index = N;
2124   return true;
2125 }
2126
2127 /// getPreIndexedAddressParts - returns true by value, base pointer and
2128 /// offset pointer and addressing mode by reference if the node's address
2129 /// can be legally represented as pre-indexed load / store address.
2130 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2131                                                   SDValue &Offset,
2132                                                   ISD::MemIndexedMode &AM,
2133                                                   SelectionDAG &DAG) const {
2134   if (DisablePPCPreinc) return false;
2135
2136   bool isLoad = true;
2137   SDValue Ptr;
2138   EVT VT;
2139   unsigned Alignment;
2140   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2141     Ptr = LD->getBasePtr();
2142     VT = LD->getMemoryVT();
2143     Alignment = LD->getAlignment();
2144   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2145     Ptr = ST->getBasePtr();
2146     VT  = ST->getMemoryVT();
2147     Alignment = ST->getAlignment();
2148     isLoad = false;
2149   } else
2150     return false;
2151
2152   // PowerPC doesn't have preinc load/store instructions for vectors (except
2153   // for QPX, which does have preinc r+r forms).
2154   if (VT.isVector()) {
2155     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2156       return false;
2157     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2158       AM = ISD::PRE_INC;
2159       return true;
2160     }
2161   }
2162
2163   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2164     // Common code will reject creating a pre-inc form if the base pointer
2165     // is a frame index, or if N is a store and the base pointer is either
2166     // the same as or a predecessor of the value being stored.  Check for
2167     // those situations here, and try with swapped Base/Offset instead.
2168     bool Swap = false;
2169
2170     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2171       Swap = true;
2172     else if (!isLoad) {
2173       SDValue Val = cast<StoreSDNode>(N)->getValue();
2174       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2175         Swap = true;
2176     }
2177
2178     if (Swap)
2179       std::swap(Base, Offset);
2180
2181     AM = ISD::PRE_INC;
2182     return true;
2183   }
2184
2185   // LDU/STU can only handle immediates that are a multiple of 4.
2186   if (VT != MVT::i64) {
2187     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2188       return false;
2189   } else {
2190     // LDU/STU need an address with at least 4-byte alignment.
2191     if (Alignment < 4)
2192       return false;
2193
2194     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2195       return false;
2196   }
2197
2198   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2199     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2200     // sext i32 to i64 when addr mode is r+i.
2201     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2202         LD->getExtensionType() == ISD::SEXTLOAD &&
2203         isa<ConstantSDNode>(Offset))
2204       return false;
2205   }
2206
2207   AM = ISD::PRE_INC;
2208   return true;
2209 }
2210
2211 //===----------------------------------------------------------------------===//
2212 //  LowerOperation implementation
2213 //===----------------------------------------------------------------------===//
2214
2215 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2216 /// and LoOpFlags to the target MO flags.
2217 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2218                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2219                                const GlobalValue *GV = nullptr) {
2220   HiOpFlags = PPCII::MO_HA;
2221   LoOpFlags = PPCII::MO_LO;
2222
2223   // Don't use the pic base if not in PIC relocation model.
2224   if (IsPIC) {
2225     HiOpFlags |= PPCII::MO_PIC_FLAG;
2226     LoOpFlags |= PPCII::MO_PIC_FLAG;
2227   }
2228
2229   // If this is a reference to a global value that requires a non-lazy-ptr, make
2230   // sure that instruction lowering adds it.
2231   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2232     HiOpFlags |= PPCII::MO_NLP_FLAG;
2233     LoOpFlags |= PPCII::MO_NLP_FLAG;
2234
2235     if (GV->hasHiddenVisibility()) {
2236       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2237       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2238     }
2239   }
2240 }
2241
2242 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2243                              SelectionDAG &DAG) {
2244   SDLoc DL(HiPart);
2245   EVT PtrVT = HiPart.getValueType();
2246   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2247
2248   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2249   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2250
2251   // With PIC, the first instruction is actually "GR+hi(&G)".
2252   if (isPIC)
2253     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2254                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2255
2256   // Generate non-pic code that has direct accesses to the constant pool.
2257   // The address of the global is just (hi(&g)+lo(&g)).
2258   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2259 }
2260
2261 static void setUsesTOCBasePtr(MachineFunction &MF) {
2262   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2263   FuncInfo->setUsesTOCBasePtr();
2264 }
2265
2266 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2267   setUsesTOCBasePtr(DAG.getMachineFunction());
2268 }
2269
2270 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2271                            SDValue GA) {
2272   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2273   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2274                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2275
2276   SDValue Ops[] = { GA, Reg };
2277   return DAG.getMemIntrinsicNode(
2278       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2279       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2280       false, 0);
2281 }
2282
2283 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2284                                              SelectionDAG &DAG) const {
2285   EVT PtrVT = Op.getValueType();
2286   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2287   const Constant *C = CP->getConstVal();
2288
2289   // 64-bit SVR4 ABI code is always position-independent.
2290   // The actual address of the GlobalValue is stored in the TOC.
2291   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2292     setUsesTOCBasePtr(DAG);
2293     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2294     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2295   }
2296
2297   unsigned MOHiFlag, MOLoFlag;
2298   bool IsPIC = isPositionIndependent();
2299   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2300
2301   if (IsPIC && Subtarget.isSVR4ABI()) {
2302     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2303                                            PPCII::MO_PIC_FLAG);
2304     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2305   }
2306
2307   SDValue CPIHi =
2308     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2309   SDValue CPILo =
2310     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2311   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2312 }
2313
2314 // For 64-bit PowerPC, prefer the more compact relative encodings.
2315 // This trades 32 bits per jump table entry for one or two instructions
2316 // on the jump site.
2317 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2318   if (isJumpTableRelative())
2319     return MachineJumpTableInfo::EK_LabelDifference32;
2320
2321   return TargetLowering::getJumpTableEncoding();
2322 }
2323
2324 bool PPCTargetLowering::isJumpTableRelative() const {
2325   if (Subtarget.isPPC64())
2326     return true;
2327   return TargetLowering::isJumpTableRelative();
2328 }
2329
2330 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2331                                                     SelectionDAG &DAG) const {
2332   if (!Subtarget.isPPC64())
2333     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2334
2335   switch (getTargetMachine().getCodeModel()) {
2336   case CodeModel::Default:
2337   case CodeModel::Small:
2338   case CodeModel::Medium:
2339     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2340   default:
2341     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2342                        getPointerTy(DAG.getDataLayout()));
2343   }
2344 }
2345
2346 const MCExpr *
2347 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2348                                                 unsigned JTI,
2349                                                 MCContext &Ctx) const {
2350   if (!Subtarget.isPPC64())
2351     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2352
2353   switch (getTargetMachine().getCodeModel()) {
2354   case CodeModel::Default:
2355   case CodeModel::Small:
2356   case CodeModel::Medium:
2357     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2358   default:
2359     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2360   }
2361 }
2362
2363 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2364   EVT PtrVT = Op.getValueType();
2365   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2366
2367   // 64-bit SVR4 ABI code is always position-independent.
2368   // The actual address of the GlobalValue is stored in the TOC.
2369   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2370     setUsesTOCBasePtr(DAG);
2371     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2372     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2373   }
2374
2375   unsigned MOHiFlag, MOLoFlag;
2376   bool IsPIC = isPositionIndependent();
2377   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2378
2379   if (IsPIC && Subtarget.isSVR4ABI()) {
2380     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2381                                         PPCII::MO_PIC_FLAG);
2382     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2383   }
2384
2385   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2386   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2387   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2388 }
2389
2390 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2391                                              SelectionDAG &DAG) const {
2392   EVT PtrVT = Op.getValueType();
2393   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2394   const BlockAddress *BA = BASDN->getBlockAddress();
2395
2396   // 64-bit SVR4 ABI code is always position-independent.
2397   // The actual BlockAddress is stored in the TOC.
2398   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2399     setUsesTOCBasePtr(DAG);
2400     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2401     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2402   }
2403
2404   unsigned MOHiFlag, MOLoFlag;
2405   bool IsPIC = isPositionIndependent();
2406   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2407   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2408   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2409   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2410 }
2411
2412 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2413                                               SelectionDAG &DAG) const {
2414   // FIXME: TLS addresses currently use medium model code sequences,
2415   // which is the most useful form.  Eventually support for small and
2416   // large models could be added if users need it, at the cost of
2417   // additional complexity.
2418   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2419   if (DAG.getTarget().Options.EmulatedTLS)
2420     return LowerToTLSEmulatedModel(GA, DAG);
2421
2422   SDLoc dl(GA);
2423   const GlobalValue *GV = GA->getGlobal();
2424   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2425   bool is64bit = Subtarget.isPPC64();
2426   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2427   PICLevel::Level picLevel = M->getPICLevel();
2428
2429   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2430
2431   if (Model == TLSModel::LocalExec) {
2432     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2433                                                PPCII::MO_TPREL_HA);
2434     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2435                                                PPCII::MO_TPREL_LO);
2436     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2437                                      is64bit ? MVT::i64 : MVT::i32);
2438     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2439     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2440   }
2441
2442   if (Model == TLSModel::InitialExec) {
2443     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2444     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2445                                                 PPCII::MO_TLS);
2446     SDValue GOTPtr;
2447     if (is64bit) {
2448       setUsesTOCBasePtr(DAG);
2449       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2450       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2451                            PtrVT, GOTReg, TGA);
2452     } else
2453       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2454     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2455                                    PtrVT, TGA, GOTPtr);
2456     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2457   }
2458
2459   if (Model == TLSModel::GeneralDynamic) {
2460     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2461     SDValue GOTPtr;
2462     if (is64bit) {
2463       setUsesTOCBasePtr(DAG);
2464       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2465       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2466                                    GOTReg, TGA);
2467     } else {
2468       if (picLevel == PICLevel::SmallPIC)
2469         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2470       else
2471         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2472     }
2473     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2474                        GOTPtr, TGA, TGA);
2475   }
2476
2477   if (Model == TLSModel::LocalDynamic) {
2478     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2479     SDValue GOTPtr;
2480     if (is64bit) {
2481       setUsesTOCBasePtr(DAG);
2482       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2483       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2484                            GOTReg, TGA);
2485     } else {
2486       if (picLevel == PICLevel::SmallPIC)
2487         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2488       else
2489         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2490     }
2491     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2492                                   PtrVT, GOTPtr, TGA, TGA);
2493     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2494                                       PtrVT, TLSAddr, TGA);
2495     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2496   }
2497
2498   llvm_unreachable("Unknown TLS model!");
2499 }
2500
2501 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2502                                               SelectionDAG &DAG) const {
2503   EVT PtrVT = Op.getValueType();
2504   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2505   SDLoc DL(GSDN);
2506   const GlobalValue *GV = GSDN->getGlobal();
2507
2508   // 64-bit SVR4 ABI code is always position-independent.
2509   // The actual address of the GlobalValue is stored in the TOC.
2510   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2511     setUsesTOCBasePtr(DAG);
2512     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2513     return getTOCEntry(DAG, DL, true, GA);
2514   }
2515
2516   unsigned MOHiFlag, MOLoFlag;
2517   bool IsPIC = isPositionIndependent();
2518   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2519
2520   if (IsPIC && Subtarget.isSVR4ABI()) {
2521     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2522                                             GSDN->getOffset(),
2523                                             PPCII::MO_PIC_FLAG);
2524     return getTOCEntry(DAG, DL, false, GA);
2525   }
2526
2527   SDValue GAHi =
2528     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2529   SDValue GALo =
2530     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2531
2532   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2533
2534   // If the global reference is actually to a non-lazy-pointer, we have to do an
2535   // extra load to get the address of the global.
2536   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2537     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2538   return Ptr;
2539 }
2540
2541 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2542   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2543   SDLoc dl(Op);
2544
2545   if (Op.getValueType() == MVT::v2i64) {
2546     // When the operands themselves are v2i64 values, we need to do something
2547     // special because VSX has no underlying comparison operations for these.
2548     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2549       // Equality can be handled by casting to the legal type for Altivec
2550       // comparisons, everything else needs to be expanded.
2551       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2552         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2553                  DAG.getSetCC(dl, MVT::v4i32,
2554                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2555                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2556                    CC));
2557       }
2558
2559       return SDValue();
2560     }
2561
2562     // We handle most of these in the usual way.
2563     return Op;
2564   }
2565
2566   // If we're comparing for equality to zero, expose the fact that this is
2567   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2568   // fold the new nodes.
2569   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2570     return V;
2571
2572   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2573     // Leave comparisons against 0 and -1 alone for now, since they're usually
2574     // optimized.  FIXME: revisit this when we can custom lower all setcc
2575     // optimizations.
2576     if (C->isAllOnesValue() || C->isNullValue())
2577       return SDValue();
2578   }
2579
2580   // If we have an integer seteq/setne, turn it into a compare against zero
2581   // by xor'ing the rhs with the lhs, which is faster than setting a
2582   // condition register, reading it back out, and masking the correct bit.  The
2583   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2584   // the result to other bit-twiddling opportunities.
2585   EVT LHSVT = Op.getOperand(0).getValueType();
2586   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2587     EVT VT = Op.getValueType();
2588     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2589                                 Op.getOperand(1));
2590     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2591   }
2592   return SDValue();
2593 }
2594
2595 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2596   SDNode *Node = Op.getNode();
2597   EVT VT = Node->getValueType(0);
2598   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2599   SDValue InChain = Node->getOperand(0);
2600   SDValue VAListPtr = Node->getOperand(1);
2601   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2602   SDLoc dl(Node);
2603
2604   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2605
2606   // gpr_index
2607   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2608                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2609   InChain = GprIndex.getValue(1);
2610
2611   if (VT == MVT::i64) {
2612     // Check if GprIndex is even
2613     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2614                                  DAG.getConstant(1, dl, MVT::i32));
2615     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2616                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2617     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2618                                           DAG.getConstant(1, dl, MVT::i32));
2619     // Align GprIndex to be even if it isn't
2620     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2621                            GprIndex);
2622   }
2623
2624   // fpr index is 1 byte after gpr
2625   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2626                                DAG.getConstant(1, dl, MVT::i32));
2627
2628   // fpr
2629   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2630                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2631   InChain = FprIndex.getValue(1);
2632
2633   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2634                                        DAG.getConstant(8, dl, MVT::i32));
2635
2636   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2637                                         DAG.getConstant(4, dl, MVT::i32));
2638
2639   // areas
2640   SDValue OverflowArea =
2641       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2642   InChain = OverflowArea.getValue(1);
2643
2644   SDValue RegSaveArea =
2645       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2646   InChain = RegSaveArea.getValue(1);
2647
2648   // select overflow_area if index > 8
2649   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2650                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2651
2652   // adjustment constant gpr_index * 4/8
2653   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2654                                     VT.isInteger() ? GprIndex : FprIndex,
2655                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2656                                                     MVT::i32));
2657
2658   // OurReg = RegSaveArea + RegConstant
2659   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2660                                RegConstant);
2661
2662   // Floating types are 32 bytes into RegSaveArea
2663   if (VT.isFloatingPoint())
2664     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2665                          DAG.getConstant(32, dl, MVT::i32));
2666
2667   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2668   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2669                                    VT.isInteger() ? GprIndex : FprIndex,
2670                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2671                                                    MVT::i32));
2672
2673   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2674                               VT.isInteger() ? VAListPtr : FprPtr,
2675                               MachinePointerInfo(SV), MVT::i8);
2676
2677   // determine if we should load from reg_save_area or overflow_area
2678   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2679
2680   // increase overflow_area by 4/8 if gpr/fpr > 8
2681   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2682                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2683                                           dl, MVT::i32));
2684
2685   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2686                              OverflowAreaPlusN);
2687
2688   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2689                               MachinePointerInfo(), MVT::i32);
2690
2691   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2692 }
2693
2694 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2695   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2696
2697   // We have to copy the entire va_list struct:
2698   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2699   return DAG.getMemcpy(Op.getOperand(0), Op,
2700                        Op.getOperand(1), Op.getOperand(2),
2701                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2702                        false, MachinePointerInfo(), MachinePointerInfo());
2703 }
2704
2705 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2706                                                   SelectionDAG &DAG) const {
2707   return Op.getOperand(0);
2708 }
2709
2710 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2711                                                 SelectionDAG &DAG) const {
2712   SDValue Chain = Op.getOperand(0);
2713   SDValue Trmp = Op.getOperand(1); // trampoline
2714   SDValue FPtr = Op.getOperand(2); // nested function
2715   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2716   SDLoc dl(Op);
2717
2718   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2719   bool isPPC64 = (PtrVT == MVT::i64);
2720   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2721
2722   TargetLowering::ArgListTy Args;
2723   TargetLowering::ArgListEntry Entry;
2724
2725   Entry.Ty = IntPtrTy;
2726   Entry.Node = Trmp; Args.push_back(Entry);
2727
2728   // TrampSize == (isPPC64 ? 48 : 40);
2729   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2730                                isPPC64 ? MVT::i64 : MVT::i32);
2731   Args.push_back(Entry);
2732
2733   Entry.Node = FPtr; Args.push_back(Entry);
2734   Entry.Node = Nest; Args.push_back(Entry);
2735
2736   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2737   TargetLowering::CallLoweringInfo CLI(DAG);
2738   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2739       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2740       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2741
2742   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2743   return CallResult.second;
2744 }
2745
2746 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2747   MachineFunction &MF = DAG.getMachineFunction();
2748   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2749   EVT PtrVT = getPointerTy(MF.getDataLayout());
2750
2751   SDLoc dl(Op);
2752
2753   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2754     // vastart just stores the address of the VarArgsFrameIndex slot into the
2755     // memory location argument.
2756     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2757     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2758     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2759                         MachinePointerInfo(SV));
2760   }
2761
2762   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2763   // We suppose the given va_list is already allocated.
2764   //
2765   // typedef struct {
2766   //  char gpr;     /* index into the array of 8 GPRs
2767   //                 * stored in the register save area
2768   //                 * gpr=0 corresponds to r3,
2769   //                 * gpr=1 to r4, etc.
2770   //                 */
2771   //  char fpr;     /* index into the array of 8 FPRs
2772   //                 * stored in the register save area
2773   //                 * fpr=0 corresponds to f1,
2774   //                 * fpr=1 to f2, etc.
2775   //                 */
2776   //  char *overflow_arg_area;
2777   //                /* location on stack that holds
2778   //                 * the next overflow argument
2779   //                 */
2780   //  char *reg_save_area;
2781   //               /* where r3:r10 and f1:f8 (if saved)
2782   //                * are stored
2783   //                */
2784   // } va_list[1];
2785
2786   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2787   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2788   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2789                                             PtrVT);
2790   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2791                                  PtrVT);
2792
2793   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2794   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2795
2796   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2797   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2798
2799   uint64_t FPROffset = 1;
2800   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2801
2802   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2803
2804   // Store first byte : number of int regs
2805   SDValue firstStore =
2806       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2807                         MachinePointerInfo(SV), MVT::i8);
2808   uint64_t nextOffset = FPROffset;
2809   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2810                                   ConstFPROffset);
2811
2812   // Store second byte : number of float regs
2813   SDValue secondStore =
2814       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2815                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2816   nextOffset += StackOffset;
2817   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2818
2819   // Store second word : arguments given on stack
2820   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2821                                     MachinePointerInfo(SV, nextOffset));
2822   nextOffset += FrameOffset;
2823   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2824
2825   // Store third word : arguments given in registers
2826   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2827                       MachinePointerInfo(SV, nextOffset));
2828 }
2829
2830 #include "PPCGenCallingConv.inc"
2831
2832 // Function whose sole purpose is to kill compiler warnings
2833 // stemming from unused functions included from PPCGenCallingConv.inc.
2834 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2835   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2836 }
2837
2838 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2839                                       CCValAssign::LocInfo &LocInfo,
2840                                       ISD::ArgFlagsTy &ArgFlags,
2841                                       CCState &State) {
2842   return true;
2843 }
2844
2845 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2846                                              MVT &LocVT,
2847                                              CCValAssign::LocInfo &LocInfo,
2848                                              ISD::ArgFlagsTy &ArgFlags,
2849                                              CCState &State) {
2850   static const MCPhysReg ArgRegs[] = {
2851     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2852     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2853   };
2854   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2855
2856   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2857
2858   // Skip one register if the first unallocated register has an even register
2859   // number and there are still argument registers available which have not been
2860   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2861   // need to skip a register if RegNum is odd.
2862   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2863     State.AllocateReg(ArgRegs[RegNum]);
2864   }
2865
2866   // Always return false here, as this function only makes sure that the first
2867   // unallocated register has an odd register number and does not actually
2868   // allocate a register for the current argument.
2869   return false;
2870 }
2871
2872 bool
2873 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2874                                                   MVT &LocVT,
2875                                                   CCValAssign::LocInfo &LocInfo,
2876                                                   ISD::ArgFlagsTy &ArgFlags,
2877                                                   CCState &State) {
2878   static const MCPhysReg ArgRegs[] = {
2879     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2880     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2881   };
2882   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2883
2884   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2885   int RegsLeft = NumArgRegs - RegNum;
2886
2887   // Skip if there is not enough registers left for long double type (4 gpr regs
2888   // in soft float mode) and put long double argument on the stack.
2889   if (RegNum != NumArgRegs && RegsLeft < 4) {
2890     for (int i = 0; i < RegsLeft; i++) {
2891       State.AllocateReg(ArgRegs[RegNum + i]);
2892     }
2893   }
2894
2895   return false;
2896 }
2897
2898 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2899                                                MVT &LocVT,
2900                                                CCValAssign::LocInfo &LocInfo,
2901                                                ISD::ArgFlagsTy &ArgFlags,
2902                                                CCState &State) {
2903   static const MCPhysReg ArgRegs[] = {
2904     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2905     PPC::F8
2906   };
2907
2908   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2909
2910   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2911
2912   // If there is only one Floating-point register left we need to put both f64
2913   // values of a split ppc_fp128 value on the stack.
2914   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2915     State.AllocateReg(ArgRegs[RegNum]);
2916   }
2917
2918   // Always return false here, as this function only makes sure that the two f64
2919   // values a ppc_fp128 value is split into are both passed in registers or both
2920   // passed on the stack and does not actually allocate a register for the
2921   // current argument.
2922   return false;
2923 }
2924
2925 /// FPR - The set of FP registers that should be allocated for arguments,
2926 /// on Darwin.
2927 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2928                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2929                                 PPC::F11, PPC::F12, PPC::F13};
2930
2931 /// QFPR - The set of QPX registers that should be allocated for arguments.
2932 static const MCPhysReg QFPR[] = {
2933     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2934     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2935
2936 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2937 /// the stack.
2938 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2939                                        unsigned PtrByteSize) {
2940   unsigned ArgSize = ArgVT.getStoreSize();
2941   if (Flags.isByVal())
2942     ArgSize = Flags.getByValSize();
2943
2944   // Round up to multiples of the pointer size, except for array members,
2945   // which are always packed.
2946   if (!Flags.isInConsecutiveRegs())
2947     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2948
2949   return ArgSize;
2950 }
2951
2952 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2953 /// on the stack.
2954 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2955                                             ISD::ArgFlagsTy Flags,
2956                                             unsigned PtrByteSize) {
2957   unsigned Align = PtrByteSize;
2958
2959   // Altivec parameters are padded to a 16 byte boundary.
2960   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2961       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2962       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2963       ArgVT == MVT::v1i128)
2964     Align = 16;
2965   // QPX vector types stored in double-precision are padded to a 32 byte
2966   // boundary.
2967   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2968     Align = 32;
2969
2970   // ByVal parameters are aligned as requested.
2971   if (Flags.isByVal()) {
2972     unsigned BVAlign = Flags.getByValAlign();
2973     if (BVAlign > PtrByteSize) {
2974       if (BVAlign % PtrByteSize != 0)
2975           llvm_unreachable(
2976             "ByVal alignment is not a multiple of the pointer size");
2977
2978       Align = BVAlign;
2979     }
2980   }
2981
2982   // Array members are always packed to their original alignment.
2983   if (Flags.isInConsecutiveRegs()) {
2984     // If the array member was split into multiple registers, the first
2985     // needs to be aligned to the size of the full type.  (Except for
2986     // ppcf128, which is only aligned as its f64 components.)
2987     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2988       Align = OrigVT.getStoreSize();
2989     else
2990       Align = ArgVT.getStoreSize();
2991   }
2992
2993   return Align;
2994 }
2995
2996 /// CalculateStackSlotUsed - Return whether this argument will use its
2997 /// stack slot (instead of being passed in registers).  ArgOffset,
2998 /// AvailableFPRs, and AvailableVRs must hold the current argument
2999 /// position, and will be updated to account for this argument.
3000 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
3001                                    ISD::ArgFlagsTy Flags,
3002                                    unsigned PtrByteSize,
3003                                    unsigned LinkageSize,
3004                                    unsigned ParamAreaSize,
3005                                    unsigned &ArgOffset,
3006                                    unsigned &AvailableFPRs,
3007                                    unsigned &AvailableVRs, bool HasQPX) {
3008   bool UseMemory = false;
3009
3010   // Respect alignment of argument on the stack.
3011   unsigned Align =
3012     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
3013   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3014   // If there's no space left in the argument save area, we must
3015   // use memory (this check also catches zero-sized arguments).
3016   if (ArgOffset >= LinkageSize + ParamAreaSize)
3017     UseMemory = true;
3018
3019   // Allocate argument on the stack.
3020   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
3021   if (Flags.isInConsecutiveRegsLast())
3022     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3023   // If we overran the argument save area, we must use memory
3024   // (this check catches arguments passed partially in memory)
3025   if (ArgOffset > LinkageSize + ParamAreaSize)
3026     UseMemory = true;
3027
3028   // However, if the argument is actually passed in an FPR or a VR,
3029   // we don't use memory after all.
3030   if (!Flags.isByVal()) {
3031     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
3032         // QPX registers overlap with the scalar FP registers.
3033         (HasQPX && (ArgVT == MVT::v4f32 ||
3034                     ArgVT == MVT::v4f64 ||
3035                     ArgVT == MVT::v4i1)))
3036       if (AvailableFPRs > 0) {
3037         --AvailableFPRs;
3038         return false;
3039       }
3040     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
3041         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
3042         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
3043         ArgVT == MVT::v1i128)
3044       if (AvailableVRs > 0) {
3045         --AvailableVRs;
3046         return false;
3047       }
3048   }
3049
3050   return UseMemory;
3051 }
3052
3053 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
3054 /// ensure minimum alignment required for target.
3055 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
3056                                      unsigned NumBytes) {
3057   unsigned TargetAlign = Lowering->getStackAlignment();
3058   unsigned AlignMask = TargetAlign - 1;
3059   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
3060   return NumBytes;
3061 }
3062
3063 SDValue PPCTargetLowering::LowerFormalArguments(
3064     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3065     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3066     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3067   if (Subtarget.isSVR4ABI()) {
3068     if (Subtarget.isPPC64())
3069       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3070                                          dl, DAG, InVals);
3071     else
3072       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3073                                          dl, DAG, InVals);
3074   } else {
3075     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3076                                        dl, DAG, InVals);
3077   }
3078 }
3079
3080 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3081     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3082     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3083     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3084
3085   // 32-bit SVR4 ABI Stack Frame Layout:
3086   //              +-----------------------------------+
3087   //        +-->  |            Back chain             |
3088   //        |     +-----------------------------------+
3089   //        |     | Floating-point register save area |
3090   //        |     +-----------------------------------+
3091   //        |     |    General register save area     |
3092   //        |     +-----------------------------------+
3093   //        |     |          CR save word             |
3094   //        |     +-----------------------------------+
3095   //        |     |         VRSAVE save word          |
3096   //        |     +-----------------------------------+
3097   //        |     |         Alignment padding         |
3098   //        |     +-----------------------------------+
3099   //        |     |     Vector register save area     |
3100   //        |     +-----------------------------------+
3101   //        |     |       Local variable space        |
3102   //        |     +-----------------------------------+
3103   //        |     |        Parameter list area        |
3104   //        |     +-----------------------------------+
3105   //        |     |           LR save word            |
3106   //        |     +-----------------------------------+
3107   // SP-->  +---  |            Back chain             |
3108   //              +-----------------------------------+
3109   //
3110   // Specifications:
3111   //   System V Application Binary Interface PowerPC Processor Supplement
3112   //   AltiVec Technology Programming Interface Manual
3113
3114   MachineFunction &MF = DAG.getMachineFunction();
3115   MachineFrameInfo &MFI = MF.getFrameInfo();
3116   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3117
3118   EVT PtrVT = getPointerTy(MF.getDataLayout());
3119   // Potential tail calls could cause overwriting of argument stack slots.
3120   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3121                        (CallConv == CallingConv::Fast));
3122   unsigned PtrByteSize = 4;
3123
3124   // Assign locations to all of the incoming arguments.
3125   SmallVector<CCValAssign, 16> ArgLocs;
3126   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3127                  *DAG.getContext());
3128
3129   // Reserve space for the linkage area on the stack.
3130   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3131   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3132   if (useSoftFloat())
3133     CCInfo.PreAnalyzeFormalArguments(Ins);
3134
3135   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3136   CCInfo.clearWasPPCF128();
3137
3138   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3139     CCValAssign &VA = ArgLocs[i];
3140
3141     // Arguments stored in registers.
3142     if (VA.isRegLoc()) {
3143       const TargetRegisterClass *RC;
3144       EVT ValVT = VA.getValVT();
3145
3146       switch (ValVT.getSimpleVT().SimpleTy) {
3147         default:
3148           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3149         case MVT::i1:
3150         case MVT::i32:
3151           RC = &PPC::GPRCRegClass;
3152           break;
3153         case MVT::f32:
3154           if (Subtarget.hasP8Vector())
3155             RC = &PPC::VSSRCRegClass;
3156           else
3157             RC = &PPC::F4RCRegClass;
3158           break;
3159         case MVT::f64:
3160           if (Subtarget.hasVSX())
3161             RC = &PPC::VSFRCRegClass;
3162           else
3163             RC = &PPC::F8RCRegClass;
3164           break;
3165         case MVT::v16i8:
3166         case MVT::v8i16:
3167         case MVT::v4i32:
3168           RC = &PPC::VRRCRegClass;
3169           break;
3170         case MVT::v4f32:
3171           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3172           break;
3173         case MVT::v2f64:
3174         case MVT::v2i64:
3175           RC = &PPC::VRRCRegClass;
3176           break;
3177         case MVT::v4f64:
3178           RC = &PPC::QFRCRegClass;
3179           break;
3180         case MVT::v4i1:
3181           RC = &PPC::QBRCRegClass;
3182           break;
3183       }
3184
3185       // Transform the arguments stored in physical registers into virtual ones.
3186       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3187       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3188                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3189
3190       if (ValVT == MVT::i1)
3191         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3192
3193       InVals.push_back(ArgValue);
3194     } else {
3195       // Argument stored in memory.
3196       assert(VA.isMemLoc());
3197
3198       unsigned ArgSize = VA.getLocVT().getStoreSize();
3199       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3200                                      isImmutable);
3201
3202       // Create load nodes to retrieve arguments from the stack.
3203       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3204       InVals.push_back(
3205           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3206     }
3207   }
3208
3209   // Assign locations to all of the incoming aggregate by value arguments.
3210   // Aggregates passed by value are stored in the local variable space of the
3211   // caller's stack frame, right above the parameter list area.
3212   SmallVector<CCValAssign, 16> ByValArgLocs;
3213   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3214                       ByValArgLocs, *DAG.getContext());
3215
3216   // Reserve stack space for the allocations in CCInfo.
3217   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3218
3219   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3220
3221   // Area that is at least reserved in the caller of this function.
3222   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3223   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3224
3225   // Set the size that is at least reserved in caller of this function.  Tail
3226   // call optimized function's reserved stack space needs to be aligned so that
3227   // taking the difference between two stack areas will result in an aligned
3228   // stack.
3229   MinReservedArea =
3230       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3231   FuncInfo->setMinReservedArea(MinReservedArea);
3232
3233   SmallVector<SDValue, 8> MemOps;
3234
3235   // If the function takes variable number of arguments, make a frame index for
3236   // the start of the first vararg value... for expansion of llvm.va_start.
3237   if (isVarArg) {
3238     static const MCPhysReg GPArgRegs[] = {
3239       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3240       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3241     };
3242     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3243
3244     static const MCPhysReg FPArgRegs[] = {
3245       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3246       PPC::F8
3247     };
3248     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3249
3250     if (useSoftFloat())
3251        NumFPArgRegs = 0;
3252
3253     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3254     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3255
3256     // Make room for NumGPArgRegs and NumFPArgRegs.
3257     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3258                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3259
3260     FuncInfo->setVarArgsStackOffset(
3261       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3262                             CCInfo.getNextStackOffset(), true));
3263
3264     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3265     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3266
3267     // The fixed integer arguments of a variadic function are stored to the
3268     // VarArgsFrameIndex on the stack so that they may be loaded by
3269     // dereferencing the result of va_next.
3270     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3271       // Get an existing live-in vreg, or add a new one.
3272       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3273       if (!VReg)
3274         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3275
3276       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3277       SDValue Store =
3278           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3279       MemOps.push_back(Store);
3280       // Increment the address by four for the next argument to store
3281       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3282       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3283     }
3284
3285     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3286     // is set.
3287     // The double arguments are stored to the VarArgsFrameIndex
3288     // on the stack.
3289     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3290       // Get an existing live-in vreg, or add a new one.
3291       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3292       if (!VReg)
3293         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3294
3295       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3296       SDValue Store =
3297           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3298       MemOps.push_back(Store);
3299       // Increment the address by eight for the next argument to store
3300       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3301                                          PtrVT);
3302       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3303     }
3304   }
3305
3306   if (!MemOps.empty())
3307     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3308
3309   return Chain;
3310 }
3311
3312 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3313 // value to MVT::i64 and then truncate to the correct register size.
3314 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3315                                              EVT ObjectVT, SelectionDAG &DAG,
3316                                              SDValue ArgVal,
3317                                              const SDLoc &dl) const {
3318   if (Flags.isSExt())
3319     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3320                          DAG.getValueType(ObjectVT));
3321   else if (Flags.isZExt())
3322     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3323                          DAG.getValueType(ObjectVT));
3324
3325   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3326 }
3327
3328 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3329     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3330     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3331     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3332   // TODO: add description of PPC stack frame format, or at least some docs.
3333   //
3334   bool isELFv2ABI = Subtarget.isELFv2ABI();
3335   bool isLittleEndian = Subtarget.isLittleEndian();
3336   MachineFunction &MF = DAG.getMachineFunction();
3337   MachineFrameInfo &MFI = MF.getFrameInfo();
3338   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3339
3340   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3341          "fastcc not supported on varargs functions");
3342
3343   EVT PtrVT = getPointerTy(MF.getDataLayout());
3344   // Potential tail calls could cause overwriting of argument stack slots.
3345   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3346                        (CallConv == CallingConv::Fast));
3347   unsigned PtrByteSize = 8;
3348   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3349
3350   static const MCPhysReg GPR[] = {
3351     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3352     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3353   };
3354   static const MCPhysReg VR[] = {
3355     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3356     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3357   };
3358
3359   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3360   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3361   const unsigned Num_VR_Regs  = array_lengthof(VR);
3362   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3363
3364   // Do a first pass over the arguments to determine whether the ABI
3365   // guarantees that our caller has allocated the parameter save area
3366   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3367   // in the ELFv2 ABI, it is true if this is a vararg function or if
3368   // any parameter is located in a stack slot.
3369
3370   bool HasParameterArea = !isELFv2ABI || isVarArg;
3371   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3372   unsigned NumBytes = LinkageSize;
3373   unsigned AvailableFPRs = Num_FPR_Regs;
3374   unsigned AvailableVRs = Num_VR_Regs;
3375   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3376     if (Ins[i].Flags.isNest())
3377       continue;
3378
3379     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3380                                PtrByteSize, LinkageSize, ParamAreaSize,
3381                                NumBytes, AvailableFPRs, AvailableVRs,
3382                                Subtarget.hasQPX()))
3383       HasParameterArea = true;
3384   }
3385
3386   // Add DAG nodes to load the arguments or copy them out of registers.  On
3387   // entry to a function on PPC, the arguments start after the linkage area,
3388   // although the first ones are often in registers.
3389
3390   unsigned ArgOffset = LinkageSize;
3391   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3392   unsigned &QFPR_idx = FPR_idx;
3393   SmallVector<SDValue, 8> MemOps;
3394   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3395   unsigned CurArgIdx = 0;
3396   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3397     SDValue ArgVal;
3398     bool needsLoad = false;
3399     EVT ObjectVT = Ins[ArgNo].VT;
3400     EVT OrigVT = Ins[ArgNo].ArgVT;
3401     unsigned ObjSize = ObjectVT.getStoreSize();
3402     unsigned ArgSize = ObjSize;
3403     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3404     if (Ins[ArgNo].isOrigArg()) {
3405       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3406       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3407     }
3408     // We re-align the argument offset for each argument, except when using the
3409     // fast calling convention, when we need to make sure we do that only when
3410     // we'll actually use a stack slot.
3411     unsigned CurArgOffset, Align;
3412     auto ComputeArgOffset = [&]() {
3413       /* Respect alignment of argument on the stack.  */
3414       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3415       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3416       CurArgOffset = ArgOffset;
3417     };
3418
3419     if (CallConv != CallingConv::Fast) {
3420       ComputeArgOffset();
3421
3422       /* Compute GPR index associated with argument offset.  */
3423       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3424       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3425     }
3426
3427     // FIXME the codegen can be much improved in some cases.
3428     // We do not have to keep everything in memory.
3429     if (Flags.isByVal()) {
3430       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3431
3432       if (CallConv == CallingConv::Fast)
3433         ComputeArgOffset();
3434
3435       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3436       ObjSize = Flags.getByValSize();
3437       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3438       // Empty aggregate parameters do not take up registers.  Examples:
3439       //   struct { } a;
3440       //   union  { } b;
3441       //   int c[0];
3442       // etc.  However, we have to provide a place-holder in InVals, so
3443       // pretend we have an 8-byte item at the current address for that
3444       // purpose.
3445       if (!ObjSize) {
3446         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3447         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3448         InVals.push_back(FIN);
3449         continue;
3450       }
3451
3452       // Create a stack object covering all stack doublewords occupied
3453       // by the argument.  If the argument is (fully or partially) on
3454       // the stack, or if the argument is fully in registers but the
3455       // caller has allocated the parameter save anyway, we can refer
3456       // directly to the caller's stack frame.  Otherwise, create a
3457       // local copy in our own frame.
3458       int FI;
3459       if (HasParameterArea ||
3460           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3461         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3462       else
3463         FI = MFI.CreateStackObject(ArgSize, Align, false);
3464       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3465
3466       // Handle aggregates smaller than 8 bytes.
3467       if (ObjSize < PtrByteSize) {
3468         // The value of the object is its address, which differs from the
3469         // address of the enclosing doubleword on big-endian systems.
3470         SDValue Arg = FIN;
3471         if (!isLittleEndian) {
3472           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3473           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3474         }
3475         InVals.push_back(Arg);
3476
3477         if (GPR_idx != Num_GPR_Regs) {
3478           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3479           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3480           SDValue Store;
3481
3482           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3483             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3484                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3485             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3486                                       MachinePointerInfo(&*FuncArg), ObjType);
3487           } else {
3488             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3489             // store the whole register as-is to the parameter save area
3490             // slot.
3491             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3492                                  MachinePointerInfo(&*FuncArg));
3493           }
3494
3495           MemOps.push_back(Store);
3496         }
3497         // Whether we copied from a register or not, advance the offset
3498         // into the parameter save area by a full doubleword.
3499         ArgOffset += PtrByteSize;
3500         continue;
3501       }
3502
3503       // The value of the object is its address, which is the address of
3504       // its first stack doubleword.
3505       InVals.push_back(FIN);
3506
3507       // Store whatever pieces of the object are in registers to memory.
3508       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3509         if (GPR_idx == Num_GPR_Regs)
3510           break;
3511
3512         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3513         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3514         SDValue Addr = FIN;
3515         if (j) {
3516           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3517           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3518         }
3519         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3520                                      MachinePointerInfo(&*FuncArg, j));
3521         MemOps.push_back(Store);
3522         ++GPR_idx;
3523       }
3524       ArgOffset += ArgSize;
3525       continue;
3526     }
3527
3528     switch (ObjectVT.getSimpleVT().SimpleTy) {
3529     default: llvm_unreachable("Unhandled argument type!");
3530     case MVT::i1:
3531     case MVT::i32:
3532     case MVT::i64:
3533       if (Flags.isNest()) {
3534         // The 'nest' parameter, if any, is passed in R11.
3535         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3536         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3537
3538         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3539           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3540
3541         break;
3542       }
3543
3544       // These can be scalar arguments or elements of an integer array type
3545       // passed directly.  Clang may use those instead of "byval" aggregate
3546       // types to avoid forcing arguments to memory unnecessarily.
3547       if (GPR_idx != Num_GPR_Regs) {
3548         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3549         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3550
3551         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3552           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3553           // value to MVT::i64 and then truncate to the correct register size.
3554           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3555       } else {
3556         if (CallConv == CallingConv::Fast)
3557           ComputeArgOffset();
3558
3559         needsLoad = true;
3560         ArgSize = PtrByteSize;
3561       }
3562       if (CallConv != CallingConv::Fast || needsLoad)
3563         ArgOffset += 8;
3564       break;
3565
3566     case MVT::f32:
3567     case MVT::f64:
3568       // These can be scalar arguments or elements of a float array type
3569       // passed directly.  The latter are used to implement ELFv2 homogenous
3570       // float aggregates.
3571       if (FPR_idx != Num_FPR_Regs) {
3572         unsigned VReg;
3573
3574         if (ObjectVT == MVT::f32)
3575           VReg = MF.addLiveIn(FPR[FPR_idx],
3576                               Subtarget.hasP8Vector()
3577                                   ? &PPC::VSSRCRegClass
3578                                   : &PPC::F4RCRegClass);
3579         else
3580           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3581                                                 ? &PPC::VSFRCRegClass
3582                                                 : &PPC::F8RCRegClass);
3583
3584         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3585         ++FPR_idx;
3586       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3587         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3588         // once we support fp <-> gpr moves.
3589
3590         // This can only ever happen in the presence of f32 array types,
3591         // since otherwise we never run out of FPRs before running out
3592         // of GPRs.
3593         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3594         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3595
3596         if (ObjectVT == MVT::f32) {
3597           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3598             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3599                                  DAG.getConstant(32, dl, MVT::i32));
3600           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3601         }
3602
3603         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3604       } else {
3605         if (CallConv == CallingConv::Fast)
3606           ComputeArgOffset();
3607
3608         needsLoad = true;
3609       }
3610
3611       // When passing an array of floats, the array occupies consecutive
3612       // space in the argument area; only round up to the next doubleword
3613       // at the end of the array.  Otherwise, each float takes 8 bytes.
3614       if (CallConv != CallingConv::Fast || needsLoad) {
3615         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3616         ArgOffset += ArgSize;
3617         if (Flags.isInConsecutiveRegsLast())
3618           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3619       }
3620       break;
3621     case MVT::v4f32:
3622     case MVT::v4i32:
3623     case MVT::v8i16:
3624     case MVT::v16i8:
3625     case MVT::v2f64:
3626     case MVT::v2i64:
3627     case MVT::v1i128:
3628       if (!Subtarget.hasQPX()) {
3629       // These can be scalar arguments or elements of a vector array type
3630       // passed directly.  The latter are used to implement ELFv2 homogenous
3631       // vector aggregates.
3632       if (VR_idx != Num_VR_Regs) {
3633         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3634         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3635         ++VR_idx;
3636       } else {
3637         if (CallConv == CallingConv::Fast)
3638           ComputeArgOffset();
3639
3640         needsLoad = true;
3641       }
3642       if (CallConv != CallingConv::Fast || needsLoad)
3643         ArgOffset += 16;
3644       break;
3645       } // not QPX
3646
3647       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3648              "Invalid QPX parameter type");
3649       /* fall through */
3650
3651     case MVT::v4f64:
3652     case MVT::v4i1:
3653       // QPX vectors are treated like their scalar floating-point subregisters
3654       // (except that they're larger).
3655       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3656       if (QFPR_idx != Num_QFPR_Regs) {
3657         const TargetRegisterClass *RC;
3658         switch (ObjectVT.getSimpleVT().SimpleTy) {
3659         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3660         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3661         default:         RC = &PPC::QBRCRegClass; break;
3662         }
3663
3664         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3665         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3666         ++QFPR_idx;
3667       } else {
3668         if (CallConv == CallingConv::Fast)
3669           ComputeArgOffset();
3670         needsLoad = true;
3671       }
3672       if (CallConv != CallingConv::Fast || needsLoad)
3673         ArgOffset += Sz;
3674       break;
3675     }
3676
3677     // We need to load the argument to a virtual register if we determined
3678     // above that we ran out of physical registers of the appropriate type.
3679     if (needsLoad) {
3680       if (ObjSize < ArgSize && !isLittleEndian)
3681         CurArgOffset += ArgSize - ObjSize;
3682       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3683       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3684       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3685     }
3686
3687     InVals.push_back(ArgVal);
3688   }
3689
3690   // Area that is at least reserved in the caller of this function.
3691   unsigned MinReservedArea;
3692   if (HasParameterArea)
3693     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3694   else
3695     MinReservedArea = LinkageSize;
3696
3697   // Set the size that is at least reserved in caller of this function.  Tail
3698   // call optimized functions' reserved stack space needs to be aligned so that
3699   // taking the difference between two stack areas will result in an aligned
3700   // stack.
3701   MinReservedArea =
3702       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3703   FuncInfo->setMinReservedArea(MinReservedArea);
3704
3705   // If the function takes variable number of arguments, make a frame index for
3706   // the start of the first vararg value... for expansion of llvm.va_start.
3707   if (isVarArg) {
3708     int Depth = ArgOffset;
3709
3710     FuncInfo->setVarArgsFrameIndex(
3711       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3712     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3713
3714     // If this function is vararg, store any remaining integer argument regs
3715     // to their spots on the stack so that they may be loaded by dereferencing
3716     // the result of va_next.
3717     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3718          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3719       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3720       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3721       SDValue Store =
3722           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3723       MemOps.push_back(Store);
3724       // Increment the address by four for the next argument to store
3725       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3726       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3727     }
3728   }
3729
3730   if (!MemOps.empty())
3731     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3732
3733   return Chain;
3734 }
3735
3736 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3737     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3738     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3739     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3740   // TODO: add description of PPC stack frame format, or at least some docs.
3741   //
3742   MachineFunction &MF = DAG.getMachineFunction();
3743   MachineFrameInfo &MFI = MF.getFrameInfo();
3744   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3745
3746   EVT PtrVT = getPointerTy(MF.getDataLayout());
3747   bool isPPC64 = PtrVT == MVT::i64;
3748   // Potential tail calls could cause overwriting of argument stack slots.
3749   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3750                        (CallConv == CallingConv::Fast));
3751   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3752   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3753   unsigned ArgOffset = LinkageSize;
3754   // Area that is at least reserved in caller of this function.
3755   unsigned MinReservedArea = ArgOffset;
3756
3757   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3758     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3759     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3760   };
3761   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3762     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3763     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3764   };
3765   static const MCPhysReg VR[] = {
3766     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3767     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3768   };
3769
3770   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3771   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3772   const unsigned Num_VR_Regs  = array_lengthof( VR);
3773
3774   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3775
3776   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3777
3778   // In 32-bit non-varargs functions, the stack space for vectors is after the
3779   // stack space for non-vectors.  We do not use this space unless we have
3780   // too many vectors to fit in registers, something that only occurs in
3781   // constructed examples:), but we have to walk the arglist to figure
3782   // that out...for the pathological case, compute VecArgOffset as the
3783   // start of the vector parameter area.  Computing VecArgOffset is the
3784   // entire point of the following loop.
3785   unsigned VecArgOffset = ArgOffset;
3786   if (!isVarArg && !isPPC64) {
3787     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3788          ++ArgNo) {
3789       EVT ObjectVT = Ins[ArgNo].VT;
3790       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3791
3792       if (Flags.isByVal()) {
3793         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3794         unsigned ObjSize = Flags.getByValSize();
3795         unsigned ArgSize =
3796                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3797         VecArgOffset += ArgSize;
3798         continue;
3799       }
3800
3801       switch(ObjectVT.getSimpleVT().SimpleTy) {
3802       default: llvm_unreachable("Unhandled argument type!");
3803       case MVT::i1:
3804       case MVT::i32:
3805       case MVT::f32:
3806         VecArgOffset += 4;
3807         break;
3808       case MVT::i64:  // PPC64
3809       case MVT::f64:
3810         // FIXME: We are guaranteed to be !isPPC64 at this point.
3811         // Does MVT::i64 apply?
3812         VecArgOffset += 8;
3813         break;
3814       case MVT::v4f32:
3815       case MVT::v4i32:
3816       case MVT::v8i16:
3817       case MVT::v16i8:
3818         // Nothing to do, we're only looking at Nonvector args here.
3819         break;
3820       }
3821     }
3822   }
3823   // We've found where the vector parameter area in memory is.  Skip the
3824   // first 12 parameters; these don't use that memory.
3825   VecArgOffset = ((VecArgOffset+15)/16)*16;
3826   VecArgOffset += 12*16;
3827
3828   // Add DAG nodes to load the arguments or copy them out of registers.  On
3829   // entry to a function on PPC, the arguments start after the linkage area,
3830   // although the first ones are often in registers.
3831
3832   SmallVector<SDValue, 8> MemOps;
3833   unsigned nAltivecParamsAtEnd = 0;
3834   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3835   unsigned CurArgIdx = 0;
3836   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3837     SDValue ArgVal;
3838     bool needsLoad = false;
3839     EVT ObjectVT = Ins[ArgNo].VT;
3840     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3841     unsigned ArgSize = ObjSize;
3842     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3843     if (Ins[ArgNo].isOrigArg()) {
3844       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3845       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3846     }
3847     unsigned CurArgOffset = ArgOffset;
3848
3849     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3850     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3851         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3852       if (isVarArg || isPPC64) {
3853         MinReservedArea = ((MinReservedArea+15)/16)*16;
3854         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3855                                                   Flags,
3856                                                   PtrByteSize);
3857       } else  nAltivecParamsAtEnd++;
3858     } else
3859       // Calculate min reserved area.
3860       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3861                                                 Flags,
3862                                                 PtrByteSize);
3863
3864     // FIXME the codegen can be much improved in some cases.
3865     // We do not have to keep everything in memory.
3866     if (Flags.isByVal()) {
3867       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3868
3869       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3870       ObjSize = Flags.getByValSize();
3871       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3872       // Objects of size 1 and 2 are right justified, everything else is
3873       // left justified.  This means the memory address is adjusted forwards.
3874       if (ObjSize==1 || ObjSize==2) {
3875         CurArgOffset = CurArgOffset + (4 - ObjSize);
3876       }
3877       // The value of the object is its address.
3878       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3879       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3880       InVals.push_back(FIN);
3881       if (ObjSize==1 || ObjSize==2) {
3882         if (GPR_idx != Num_GPR_Regs) {
3883           unsigned VReg;
3884           if (isPPC64)
3885             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3886           else
3887             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3888           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3889           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3890           SDValue Store =
3891               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3892                                 MachinePointerInfo(&*FuncArg), ObjType);
3893           MemOps.push_back(Store);
3894           ++GPR_idx;
3895         }
3896
3897         ArgOffset += PtrByteSize;
3898
3899         continue;
3900       }
3901       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3902         // Store whatever pieces of the object are in registers
3903         // to memory.  ArgOffset will be the address of the beginning
3904         // of the object.
3905         if (GPR_idx != Num_GPR_Regs) {
3906           unsigned VReg;
3907           if (isPPC64)
3908             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3909           else
3910             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3911           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3912           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3913           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3914           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3915                                        MachinePointerInfo(&*FuncArg, j));
3916           MemOps.push_back(Store);
3917           ++GPR_idx;
3918           ArgOffset += PtrByteSize;
3919         } else {
3920           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3921           break;
3922         }
3923       }
3924       continue;
3925     }
3926
3927     switch (ObjectVT.getSimpleVT().SimpleTy) {
3928     default: llvm_unreachable("Unhandled argument type!");
3929     case MVT::i1:
3930     case MVT::i32:
3931       if (!isPPC64) {
3932         if (GPR_idx != Num_GPR_Regs) {
3933           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3934           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3935
3936           if (ObjectVT == MVT::i1)
3937             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3938
3939           ++GPR_idx;
3940         } else {
3941           needsLoad = true;
3942           ArgSize = PtrByteSize;
3943         }
3944         // All int arguments reserve stack space in the Darwin ABI.
3945         ArgOffset += PtrByteSize;
3946         break;
3947       }
3948       LLVM_FALLTHROUGH;
3949     case MVT::i64:  // PPC64
3950       if (GPR_idx != Num_GPR_Regs) {
3951         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3952         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3953
3954         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3955           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3956           // value to MVT::i64 and then truncate to the correct register size.
3957           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3958
3959         ++GPR_idx;
3960       } else {
3961         needsLoad = true;
3962         ArgSize = PtrByteSize;
3963       }
3964       // All int arguments reserve stack space in the Darwin ABI.
3965       ArgOffset += 8;
3966       break;
3967
3968     case MVT::f32:
3969     case MVT::f64:
3970       // Every 4 bytes of argument space consumes one of the GPRs available for
3971       // argument passing.
3972       if (GPR_idx != Num_GPR_Regs) {
3973         ++GPR_idx;
3974         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3975           ++GPR_idx;
3976       }
3977       if (FPR_idx != Num_FPR_Regs) {
3978         unsigned VReg;
3979
3980         if (ObjectVT == MVT::f32)
3981           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3982         else
3983           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3984
3985         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3986         ++FPR_idx;
3987       } else {
3988         needsLoad = true;
3989       }
3990
3991       // All FP arguments reserve stack space in the Darwin ABI.
3992       ArgOffset += isPPC64 ? 8 : ObjSize;
3993       break;
3994     case MVT::v4f32:
3995     case MVT::v4i32:
3996     case MVT::v8i16:
3997     case MVT::v16i8:
3998       // Note that vector arguments in registers don't reserve stack space,
3999       // except in varargs functions.
4000       if (VR_idx != Num_VR_Regs) {
4001         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
4002         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
4003         if (isVarArg) {
4004           while ((ArgOffset % 16) != 0) {
4005             ArgOffset += PtrByteSize;
4006             if (GPR_idx != Num_GPR_Regs)
4007               GPR_idx++;
4008           }
4009           ArgOffset += 16;
4010           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
4011         }
4012         ++VR_idx;
4013       } else {
4014         if (!isVarArg && !isPPC64) {
4015           // Vectors go after all the nonvectors.
4016           CurArgOffset = VecArgOffset;
4017           VecArgOffset += 16;
4018         } else {
4019           // Vectors are aligned.
4020           ArgOffset = ((ArgOffset+15)/16)*16;
4021           CurArgOffset = ArgOffset;
4022           ArgOffset += 16;
4023         }
4024         needsLoad = true;
4025       }
4026       break;
4027     }
4028
4029     // We need to load the argument to a virtual register if we determined above
4030     // that we ran out of physical registers of the appropriate type.
4031     if (needsLoad) {
4032       int FI = MFI.CreateFixedObject(ObjSize,
4033                                      CurArgOffset + (ArgSize - ObjSize),
4034                                      isImmutable);
4035       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
4036       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
4037     }
4038
4039     InVals.push_back(ArgVal);
4040   }
4041
4042   // Allow for Altivec parameters at the end, if needed.
4043   if (nAltivecParamsAtEnd) {
4044     MinReservedArea = ((MinReservedArea+15)/16)*16;
4045     MinReservedArea += 16*nAltivecParamsAtEnd;
4046   }
4047
4048   // Area that is at least reserved in the caller of this function.
4049   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
4050
4051   // Set the size that is at least reserved in caller of this function.  Tail
4052   // call optimized functions' reserved stack space needs to be aligned so that
4053   // taking the difference between two stack areas will result in an aligned
4054   // stack.
4055   MinReservedArea =
4056       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
4057   FuncInfo->setMinReservedArea(MinReservedArea);
4058
4059   // If the function takes variable number of arguments, make a frame index for
4060   // the start of the first vararg value... for expansion of llvm.va_start.
4061   if (isVarArg) {
4062     int Depth = ArgOffset;
4063
4064     FuncInfo->setVarArgsFrameIndex(
4065       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
4066                             Depth, true));
4067     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4068
4069     // If this function is vararg, store any remaining integer argument regs
4070     // to their spots on the stack so that they may be loaded by dereferencing
4071     // the result of va_next.
4072     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4073       unsigned VReg;
4074
4075       if (isPPC64)
4076         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4077       else
4078         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4079
4080       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4081       SDValue Store =
4082           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4083       MemOps.push_back(Store);
4084       // Increment the address by four for the next argument to store
4085       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4086       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4087     }
4088   }
4089
4090   if (!MemOps.empty())
4091     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4092
4093   return Chain;
4094 }
4095
4096 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4097 /// adjusted to accommodate the arguments for the tailcall.
4098 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4099                                    unsigned ParamSize) {
4100
4101   if (!isTailCall) return 0;
4102
4103   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4104   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4105   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4106   // Remember only if the new adjustement is bigger.
4107   if (SPDiff < FI->getTailCallSPDelta())
4108     FI->setTailCallSPDelta(SPDiff);
4109
4110   return SPDiff;
4111 }
4112
4113 static bool isFunctionGlobalAddress(SDValue Callee);
4114
4115 static bool
4116 resideInSameSection(const Function *Caller, SDValue Callee,
4117                     const TargetMachine &TM) {
4118   // If !G, Callee can be an external symbol.
4119   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4120   if (!G)
4121     return false;
4122
4123   const GlobalValue *GV = G->getGlobal();
4124   if (!GV->isStrongDefinitionForLinker())
4125     return false;
4126
4127   // Any explicitly-specified sections and section prefixes must also match.
4128   // Also, if we're using -ffunction-sections, then each function is always in
4129   // a different section (the same is true for COMDAT functions).
4130   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4131       GV->getSection() != Caller->getSection())
4132     return false;
4133   if (const auto *F = dyn_cast<Function>(GV)) {
4134     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4135       return false;
4136   }
4137
4138   // If the callee might be interposed, then we can't assume the ultimate call
4139   // target will be in the same section. Even in cases where we can assume that
4140   // interposition won't happen, in any case where the linker might insert a
4141   // stub to allow for interposition, we must generate code as though
4142   // interposition might occur. To understand why this matters, consider a
4143   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4144   // in the same section, but a is in a different module (i.e. has a different
4145   // TOC base pointer). If the linker allows for interposition between b and c,
4146   // then it will generate a stub for the call edge between b and c which will
4147   // save the TOC pointer into the designated stack slot allocated by b. If we
4148   // return true here, and therefore allow a tail call between b and c, that
4149   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4150   // pointer into the stack slot allocated by a (where the a -> b stub saved
4151   // a's TOC base pointer). If we're not considering a tail call, but rather,
4152   // whether a nop is needed after the call instruction in b, because the linker
4153   // will insert a stub, it might complain about a missing nop if we omit it
4154   // (although many don't complain in this case).
4155   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4156     return false;
4157
4158   return true;
4159 }
4160
4161 static bool
4162 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4163                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4164   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4165
4166   const unsigned PtrByteSize = 8;
4167   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4168
4169   static const MCPhysReg GPR[] = {
4170     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4171     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4172   };
4173   static const MCPhysReg VR[] = {
4174     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4175     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4176   };
4177
4178   const unsigned NumGPRs = array_lengthof(GPR);
4179   const unsigned NumFPRs = 13;
4180   const unsigned NumVRs = array_lengthof(VR);
4181   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4182
4183   unsigned NumBytes = LinkageSize;
4184   unsigned AvailableFPRs = NumFPRs;
4185   unsigned AvailableVRs = NumVRs;
4186
4187   for (const ISD::OutputArg& Param : Outs) {
4188     if (Param.Flags.isNest()) continue;
4189
4190     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4191                                PtrByteSize, LinkageSize, ParamAreaSize,
4192                                NumBytes, AvailableFPRs, AvailableVRs,
4193                                Subtarget.hasQPX()))
4194       return true;
4195   }
4196   return false;
4197 }
4198
4199 static bool
4200 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4201   if (CS->arg_size() != CallerFn->arg_size())
4202     return false;
4203
4204   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4205   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4206   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4207
4208   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4209     const Value* CalleeArg = *CalleeArgIter;
4210     const Value* CallerArg = &(*CallerArgIter);
4211     if (CalleeArg == CallerArg)
4212       continue;
4213
4214     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4215     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4216     //      }
4217     // 1st argument of callee is undef and has the same type as caller.
4218     if (CalleeArg->getType() == CallerArg->getType() &&
4219         isa<UndefValue>(CalleeArg))
4220       continue;
4221
4222     return false;
4223   }
4224
4225   return true;
4226 }
4227
4228 bool
4229 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4230                                     SDValue Callee,
4231                                     CallingConv::ID CalleeCC,
4232                                     ImmutableCallSite *CS,
4233                                     bool isVarArg,
4234                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4235                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4236                                     SelectionDAG& DAG) const {
4237   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4238
4239   if (DisableSCO && !TailCallOpt) return false;
4240
4241   // Variadic argument functions are not supported.
4242   if (isVarArg) return false;
4243
4244   MachineFunction &MF = DAG.getMachineFunction();
4245   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4246
4247   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4248   // the same calling convention
4249   if (CallerCC != CalleeCC) return false;
4250
4251   // SCO support C calling convention
4252   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4253     return false;
4254
4255   // Caller contains any byval parameter is not supported.
4256   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4257     return false;
4258
4259   // Callee contains any byval parameter is not supported, too.
4260   // Note: This is a quick work around, because in some cases, e.g.
4261   // caller's stack size > callee's stack size, we are still able to apply
4262   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4263   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4264     return false;
4265
4266   // No TCO/SCO on indirect call because Caller have to restore its TOC
4267   if (!isFunctionGlobalAddress(Callee) &&
4268       !isa<ExternalSymbolSDNode>(Callee))
4269     return false;
4270
4271   // Check if Callee resides in the same section, because for now, PPC64 SVR4
4272   // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4273   // section.
4274   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4275   if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4276     return false;
4277
4278   // TCO allows altering callee ABI, so we don't have to check further.
4279   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4280     return true;
4281
4282   if (DisableSCO) return false;
4283
4284   // If callee use the same argument list that caller is using, then we can
4285   // apply SCO on this case. If it is not, then we need to check if callee needs
4286   // stack for passing arguments.
4287   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4288       needStackSlotPassParameters(Subtarget, Outs)) {
4289     return false;
4290   }
4291
4292   return true;
4293 }
4294
4295 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4296 /// for tail call optimization. Targets which want to do tail call
4297 /// optimization should implement this function.
4298 bool
4299 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4300                                                      CallingConv::ID CalleeCC,
4301                                                      bool isVarArg,
4302                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4303                                                      SelectionDAG& DAG) const {
4304   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4305     return false;
4306
4307   // Variable argument functions are not supported.
4308   if (isVarArg)
4309     return false;
4310
4311   MachineFunction &MF = DAG.getMachineFunction();
4312   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4313   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4314     // Functions containing by val parameters are not supported.
4315     for (unsigned i = 0; i != Ins.size(); i++) {
4316        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4317        if (Flags.isByVal()) return false;
4318     }
4319
4320     // Non-PIC/GOT tail calls are supported.
4321     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4322       return true;
4323
4324     // At the moment we can only do local tail calls (in same module, hidden
4325     // or protected) if we are generating PIC.
4326     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4327       return G->getGlobal()->hasHiddenVisibility()
4328           || G->getGlobal()->hasProtectedVisibility();
4329   }
4330
4331   return false;
4332 }
4333
4334 /// isCallCompatibleAddress - Return the immediate to use if the specified
4335 /// 32-bit value is representable in the immediate field of a BxA instruction.
4336 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4337   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4338   if (!C) return nullptr;
4339
4340   int Addr = C->getZExtValue();
4341   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4342       SignExtend32<26>(Addr) != Addr)
4343     return nullptr;  // Top 6 bits have to be sext of immediate.
4344
4345   return DAG
4346       .getConstant(
4347           (int)C->getZExtValue() >> 2, SDLoc(Op),
4348           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4349       .getNode();
4350 }
4351
4352 namespace {
4353
4354 struct TailCallArgumentInfo {
4355   SDValue Arg;
4356   SDValue FrameIdxOp;
4357   int FrameIdx = 0;
4358
4359   TailCallArgumentInfo() = default;
4360 };
4361
4362 } // end anonymous namespace
4363
4364 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4365 static void StoreTailCallArgumentsToStackSlot(
4366     SelectionDAG &DAG, SDValue Chain,
4367     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4368     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4369   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4370     SDValue Arg = TailCallArgs[i].Arg;
4371     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4372     int FI = TailCallArgs[i].FrameIdx;
4373     // Store relative to framepointer.
4374     MemOpChains.push_back(DAG.getStore(
4375         Chain, dl, Arg, FIN,
4376         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4377   }
4378 }
4379
4380 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4381 /// the appropriate stack slot for the tail call optimized function call.
4382 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4383                                              SDValue OldRetAddr, SDValue OldFP,
4384                                              int SPDiff, const SDLoc &dl) {
4385   if (SPDiff) {
4386     // Calculate the new stack slot for the return address.
4387     MachineFunction &MF = DAG.getMachineFunction();
4388     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4389     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4390     bool isPPC64 = Subtarget.isPPC64();
4391     int SlotSize = isPPC64 ? 8 : 4;
4392     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4393     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4394                                                          NewRetAddrLoc, true);
4395     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4396     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4397     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4398                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4399
4400     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4401     // slot as the FP is never overwritten.
4402     if (Subtarget.isDarwinABI()) {
4403       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4404       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4405                                                          true);
4406       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4407       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4408                            MachinePointerInfo::getFixedStack(
4409                                DAG.getMachineFunction(), NewFPIdx));
4410     }
4411   }
4412   return Chain;
4413 }
4414
4415 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4416 /// the position of the argument.
4417 static void
4418 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4419                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4420                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4421   int Offset = ArgOffset + SPDiff;
4422   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4423   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4424   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4425   SDValue FIN = DAG.getFrameIndex(FI, VT);
4426   TailCallArgumentInfo Info;
4427   Info.Arg = Arg;
4428   Info.FrameIdxOp = FIN;
4429   Info.FrameIdx = FI;
4430   TailCallArguments.push_back(Info);
4431 }
4432
4433 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4434 /// stack slot. Returns the chain as result and the loaded frame pointers in
4435 /// LROpOut/FPOpout. Used when tail calling.
4436 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4437     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4438     SDValue &FPOpOut, const SDLoc &dl) const {
4439   if (SPDiff) {
4440     // Load the LR and FP stack slot for later adjusting.
4441     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4442     LROpOut = getReturnAddrFrameIndex(DAG);
4443     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4444     Chain = SDValue(LROpOut.getNode(), 1);
4445
4446     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4447     // slot as the FP is never overwritten.
4448     if (Subtarget.isDarwinABI()) {
4449       FPOpOut = getFramePointerFrameIndex(DAG);
4450       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4451       Chain = SDValue(FPOpOut.getNode(), 1);
4452     }
4453   }
4454   return Chain;
4455 }
4456
4457 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4458 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4459 /// specified by the specific parameter attribute. The copy will be passed as
4460 /// a byval function parameter.
4461 /// Sometimes what we are copying is the end of a larger object, the part that
4462 /// does not fit in registers.
4463 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4464                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4465                                          SelectionDAG &DAG, const SDLoc &dl) {
4466   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4467   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4468                        false, false, false, MachinePointerInfo(),
4469                        MachinePointerInfo());
4470 }
4471
4472 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4473 /// tail calls.
4474 static void LowerMemOpCallTo(
4475     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4476     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4477     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4478     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4479   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4480   if (!isTailCall) {
4481     if (isVector) {
4482       SDValue StackPtr;
4483       if (isPPC64)
4484         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4485       else
4486         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4487       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4488                            DAG.getConstant(ArgOffset, dl, PtrVT));
4489     }
4490     MemOpChains.push_back(
4491         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4492     // Calculate and remember argument location.
4493   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4494                                   TailCallArguments);
4495 }
4496
4497 static void
4498 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4499                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4500                 SDValue FPOp,
4501                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4502   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4503   // might overwrite each other in case of tail call optimization.
4504   SmallVector<SDValue, 8> MemOpChains2;
4505   // Do not flag preceding copytoreg stuff together with the following stuff.
4506   InFlag = SDValue();
4507   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4508                                     MemOpChains2, dl);
4509   if (!MemOpChains2.empty())
4510     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4511
4512   // Store the return address to the appropriate stack slot.
4513   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4514
4515   // Emit callseq_end just before tailcall node.
4516   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4517                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4518   InFlag = Chain.getValue(1);
4519 }
4520
4521 // Is this global address that of a function that can be called by name? (as
4522 // opposed to something that must hold a descriptor for an indirect call).
4523 static bool isFunctionGlobalAddress(SDValue Callee) {
4524   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4525     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4526         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4527       return false;
4528
4529     return G->getGlobal()->getValueType()->isFunctionTy();
4530   }
4531
4532   return false;
4533 }
4534
4535 static unsigned
4536 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4537             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4538             bool isPatchPoint, bool hasNest,
4539             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4540             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4541             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4542   bool isPPC64 = Subtarget.isPPC64();
4543   bool isSVR4ABI = Subtarget.isSVR4ABI();
4544   bool isELFv2ABI = Subtarget.isELFv2ABI();
4545
4546   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4547   NodeTys.push_back(MVT::Other);   // Returns a chain
4548   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4549
4550   unsigned CallOpc = PPCISD::CALL;
4551
4552   bool needIndirectCall = true;
4553   if (!isSVR4ABI || !isPPC64)
4554     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4555       // If this is an absolute destination address, use the munged value.
4556       Callee = SDValue(Dest, 0);
4557       needIndirectCall = false;
4558     }
4559
4560   // PC-relative references to external symbols should go through $stub, unless
4561   // we're building with the leopard linker or later, which automatically
4562   // synthesizes these stubs.
4563   const TargetMachine &TM = DAG.getTarget();
4564   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4565   const GlobalValue *GV = nullptr;
4566   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4567     GV = G->getGlobal();
4568   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4569   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4570
4571   if (isFunctionGlobalAddress(Callee)) {
4572     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4573     // A call to a TLS address is actually an indirect call to a
4574     // thread-specific pointer.
4575     unsigned OpFlags = 0;
4576     if (UsePlt)
4577       OpFlags = PPCII::MO_PLT;
4578
4579     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4580     // every direct call is) turn it into a TargetGlobalAddress /
4581     // TargetExternalSymbol node so that legalize doesn't hack it.
4582     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4583                                         Callee.getValueType(), 0, OpFlags);
4584     needIndirectCall = false;
4585   }
4586
4587   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4588     unsigned char OpFlags = 0;
4589
4590     if (UsePlt)
4591       OpFlags = PPCII::MO_PLT;
4592
4593     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4594                                          OpFlags);
4595     needIndirectCall = false;
4596   }
4597
4598   if (isPatchPoint) {
4599     // We'll form an invalid direct call when lowering a patchpoint; the full
4600     // sequence for an indirect call is complicated, and many of the
4601     // instructions introduced might have side effects (and, thus, can't be
4602     // removed later). The call itself will be removed as soon as the
4603     // argument/return lowering is complete, so the fact that it has the wrong
4604     // kind of operands should not really matter.
4605     needIndirectCall = false;
4606   }
4607
4608   if (needIndirectCall) {
4609     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4610     // to do the call, we can't use PPCISD::CALL.
4611     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4612
4613     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4614       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4615       // entry point, but to the function descriptor (the function entry point
4616       // address is part of the function descriptor though).
4617       // The function descriptor is a three doubleword structure with the
4618       // following fields: function entry point, TOC base address and
4619       // environment pointer.
4620       // Thus for a call through a function pointer, the following actions need
4621       // to be performed:
4622       //   1. Save the TOC of the caller in the TOC save area of its stack
4623       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4624       //   2. Load the address of the function entry point from the function
4625       //      descriptor.
4626       //   3. Load the TOC of the callee from the function descriptor into r2.
4627       //   4. Load the environment pointer from the function descriptor into
4628       //      r11.
4629       //   5. Branch to the function entry point address.
4630       //   6. On return of the callee, the TOC of the caller needs to be
4631       //      restored (this is done in FinishCall()).
4632       //
4633       // The loads are scheduled at the beginning of the call sequence, and the
4634       // register copies are flagged together to ensure that no other
4635       // operations can be scheduled in between. E.g. without flagging the
4636       // copies together, a TOC access in the caller could be scheduled between
4637       // the assignment of the callee TOC and the branch to the callee, which
4638       // results in the TOC access going through the TOC of the callee instead
4639       // of going through the TOC of the caller, which leads to incorrect code.
4640
4641       // Load the address of the function entry point from the function
4642       // descriptor.
4643       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4644       if (LDChain.getValueType() == MVT::Glue)
4645         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4646
4647       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4648                           ? (MachineMemOperand::MODereferenceable |
4649                              MachineMemOperand::MOInvariant)
4650                           : MachineMemOperand::MONone;
4651
4652       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4653       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4654                                         /* Alignment = */ 8, MMOFlags);
4655
4656       // Load environment pointer into r11.
4657       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4658       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4659       SDValue LoadEnvPtr =
4660           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4661                       /* Alignment = */ 8, MMOFlags);
4662
4663       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4664       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4665       SDValue TOCPtr =
4666           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4667                       /* Alignment = */ 8, MMOFlags);
4668
4669       setUsesTOCBasePtr(DAG);
4670       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4671                                         InFlag);
4672       Chain = TOCVal.getValue(0);
4673       InFlag = TOCVal.getValue(1);
4674
4675       // If the function call has an explicit 'nest' parameter, it takes the
4676       // place of the environment pointer.
4677       if (!hasNest) {
4678         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4679                                           InFlag);
4680
4681         Chain = EnvVal.getValue(0);
4682         InFlag = EnvVal.getValue(1);
4683       }
4684
4685       MTCTROps[0] = Chain;
4686       MTCTROps[1] = LoadFuncPtr;
4687       MTCTROps[2] = InFlag;
4688     }
4689
4690     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4691                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4692     InFlag = Chain.getValue(1);
4693
4694     NodeTys.clear();
4695     NodeTys.push_back(MVT::Other);
4696     NodeTys.push_back(MVT::Glue);
4697     Ops.push_back(Chain);
4698     CallOpc = PPCISD::BCTRL;
4699     Callee.setNode(nullptr);
4700     // Add use of X11 (holding environment pointer)
4701     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4702       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4703     // Add CTR register as callee so a bctr can be emitted later.
4704     if (isTailCall)
4705       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4706   }
4707
4708   // If this is a direct call, pass the chain and the callee.
4709   if (Callee.getNode()) {
4710     Ops.push_back(Chain);
4711     Ops.push_back(Callee);
4712   }
4713   // If this is a tail call add stack pointer delta.
4714   if (isTailCall)
4715     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4716
4717   // Add argument registers to the end of the list so that they are known live
4718   // into the call.
4719   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4720     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4721                                   RegsToPass[i].second.getValueType()));
4722
4723   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4724   // into the call.
4725   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4726     setUsesTOCBasePtr(DAG);
4727     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4728   }
4729
4730   return CallOpc;
4731 }
4732
4733 SDValue PPCTargetLowering::LowerCallResult(
4734     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4735     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4736     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4737   SmallVector<CCValAssign, 16> RVLocs;
4738   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4739                     *DAG.getContext());
4740   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4741
4742   // Copy all of the result registers out of their specified physreg.
4743   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4744     CCValAssign &VA = RVLocs[i];
4745     assert(VA.isRegLoc() && "Can only return in registers!");
4746
4747     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4748                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4749     Chain = Val.getValue(1);
4750     InFlag = Val.getValue(2);
4751
4752     switch (VA.getLocInfo()) {
4753     default: llvm_unreachable("Unknown loc info!");
4754     case CCValAssign::Full: break;
4755     case CCValAssign::AExt:
4756       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4757       break;
4758     case CCValAssign::ZExt:
4759       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4760                         DAG.getValueType(VA.getValVT()));
4761       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4762       break;
4763     case CCValAssign::SExt:
4764       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4765                         DAG.getValueType(VA.getValVT()));
4766       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4767       break;
4768     }
4769
4770     InVals.push_back(Val);
4771   }
4772
4773   return Chain;
4774 }
4775
4776 SDValue PPCTargetLowering::FinishCall(
4777     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4778     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4779     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4780     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4781     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4782     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4783   std::vector<EVT> NodeTys;
4784   SmallVector<SDValue, 8> Ops;
4785   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4786                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4787                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4788
4789   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4790   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4791     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4792
4793   // When performing tail call optimization the callee pops its arguments off
4794   // the stack. Account for this here so these bytes can be pushed back on in
4795   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4796   int BytesCalleePops =
4797     (CallConv == CallingConv::Fast &&
4798      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4799
4800   // Add a register mask operand representing the call-preserved registers.
4801   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4802   const uint32_t *Mask =
4803       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4804   assert(Mask && "Missing call preserved mask for calling convention");
4805   Ops.push_back(DAG.getRegisterMask(Mask));
4806
4807   if (InFlag.getNode())
4808     Ops.push_back(InFlag);
4809
4810   // Emit tail call.
4811   if (isTailCall) {
4812     assert(((Callee.getOpcode() == ISD::Register &&
4813              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4814             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4815             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4816             isa<ConstantSDNode>(Callee)) &&
4817     "Expecting an global address, external symbol, absolute value or register");
4818
4819     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4820     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4821   }
4822
4823   // Add a NOP immediately after the branch instruction when using the 64-bit
4824   // SVR4 ABI. At link time, if caller and callee are in a different module and
4825   // thus have a different TOC, the call will be replaced with a call to a stub
4826   // function which saves the current TOC, loads the TOC of the callee and
4827   // branches to the callee. The NOP will be replaced with a load instruction
4828   // which restores the TOC of the caller from the TOC save slot of the current
4829   // stack frame. If caller and callee belong to the same module (and have the
4830   // same TOC), the NOP will remain unchanged.
4831
4832   MachineFunction &MF = DAG.getMachineFunction();
4833   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4834       !isPatchPoint) {
4835     if (CallOpc == PPCISD::BCTRL) {
4836       // This is a call through a function pointer.
4837       // Restore the caller TOC from the save area into R2.
4838       // See PrepareCall() for more information about calls through function
4839       // pointers in the 64-bit SVR4 ABI.
4840       // We are using a target-specific load with r2 hard coded, because the
4841       // result of a target-independent load would never go directly into r2,
4842       // since r2 is a reserved register (which prevents the register allocator
4843       // from allocating it), resulting in an additional register being
4844       // allocated and an unnecessary move instruction being generated.
4845       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4846
4847       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4848       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4849       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4850       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4851       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4852
4853       // The address needs to go after the chain input but before the flag (or
4854       // any other variadic arguments).
4855       Ops.insert(std::next(Ops.begin()), AddTOC);
4856     } else if (CallOpc == PPCISD::CALL &&
4857       !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4858       // Otherwise insert NOP for non-local calls.
4859       CallOpc = PPCISD::CALL_NOP;
4860     }
4861   }
4862
4863   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4864   InFlag = Chain.getValue(1);
4865
4866   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4867                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4868                              InFlag, dl);
4869   if (!Ins.empty())
4870     InFlag = Chain.getValue(1);
4871
4872   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4873                          Ins, dl, DAG, InVals);
4874 }
4875
4876 SDValue
4877 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4878                              SmallVectorImpl<SDValue> &InVals) const {
4879   SelectionDAG &DAG                     = CLI.DAG;
4880   SDLoc &dl                             = CLI.DL;
4881   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4882   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4883   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4884   SDValue Chain                         = CLI.Chain;
4885   SDValue Callee                        = CLI.Callee;
4886   bool &isTailCall                      = CLI.IsTailCall;
4887   CallingConv::ID CallConv              = CLI.CallConv;
4888   bool isVarArg                         = CLI.IsVarArg;
4889   bool isPatchPoint                     = CLI.IsPatchPoint;
4890   ImmutableCallSite *CS                 = CLI.CS;
4891
4892   if (isTailCall) {
4893     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4894       isTailCall = false;
4895     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4896       isTailCall =
4897         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4898                                                  isVarArg, Outs, Ins, DAG);
4899     else
4900       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4901                                                      Ins, DAG);
4902     if (isTailCall) {
4903       ++NumTailCalls;
4904       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4905         ++NumSiblingCalls;
4906
4907       assert(isa<GlobalAddressSDNode>(Callee) &&
4908              "Callee should be an llvm::Function object.");
4909       DEBUG(
4910         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4911         const unsigned Width = 80 - strlen("TCO caller: ")
4912                                   - strlen(", callee linkage: 0, 0");
4913         dbgs() << "TCO caller: "
4914                << left_justify(DAG.getMachineFunction().getName(), Width)
4915                << ", callee linkage: "
4916                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4917       );
4918     }
4919   }
4920
4921   if (!isTailCall && CS && CS->isMustTailCall())
4922     report_fatal_error("failed to perform tail call elimination on a call "
4923                        "site marked musttail");
4924
4925   // When long calls (i.e. indirect calls) are always used, calls are always
4926   // made via function pointer. If we have a function name, first translate it
4927   // into a pointer.
4928   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4929       !isTailCall)
4930     Callee = LowerGlobalAddress(Callee, DAG);
4931
4932   if (Subtarget.isSVR4ABI()) {
4933     if (Subtarget.isPPC64())
4934       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4935                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4936                               dl, DAG, InVals, CS);
4937     else
4938       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4939                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4940                               dl, DAG, InVals, CS);
4941   }
4942
4943   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4944                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4945                           dl, DAG, InVals, CS);
4946 }
4947
4948 SDValue PPCTargetLowering::LowerCall_32SVR4(
4949     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4950     bool isTailCall, bool isPatchPoint,
4951     const SmallVectorImpl<ISD::OutputArg> &Outs,
4952     const SmallVectorImpl<SDValue> &OutVals,
4953     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4954     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4955     ImmutableCallSite *CS) const {
4956   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4957   // of the 32-bit SVR4 ABI stack frame layout.
4958
4959   assert((CallConv == CallingConv::C ||
4960           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4961
4962   unsigned PtrByteSize = 4;
4963
4964   MachineFunction &MF = DAG.getMachineFunction();
4965
4966   // Mark this function as potentially containing a function that contains a
4967   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4968   // and restoring the callers stack pointer in this functions epilog. This is
4969   // done because by tail calling the called function might overwrite the value
4970   // in this function's (MF) stack pointer stack slot 0(SP).
4971   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4972       CallConv == CallingConv::Fast)
4973     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4974
4975   // Count how many bytes are to be pushed on the stack, including the linkage
4976   // area, parameter list area and the part of the local variable space which
4977   // contains copies of aggregates which are passed by value.
4978
4979   // Assign locations to all of the outgoing arguments.
4980   SmallVector<CCValAssign, 16> ArgLocs;
4981   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4982
4983   // Reserve space for the linkage area on the stack.
4984   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4985                        PtrByteSize);
4986   if (useSoftFloat())
4987     CCInfo.PreAnalyzeCallOperands(Outs);
4988
4989   if (isVarArg) {
4990     // Handle fixed and variable vector arguments differently.
4991     // Fixed vector arguments go into registers as long as registers are
4992     // available. Variable vector arguments always go into memory.
4993     unsigned NumArgs = Outs.size();
4994
4995     for (unsigned i = 0; i != NumArgs; ++i) {
4996       MVT ArgVT = Outs[i].VT;
4997       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4998       bool Result;
4999
5000       if (Outs[i].IsFixed) {
5001         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
5002                                CCInfo);
5003       } else {
5004         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
5005                                       ArgFlags, CCInfo);
5006       }
5007
5008       if (Result) {
5009 #ifndef NDEBUG
5010         errs() << "Call operand #" << i << " has unhandled type "
5011              << EVT(ArgVT).getEVTString() << "\n";
5012 #endif
5013         llvm_unreachable(nullptr);
5014       }
5015     }
5016   } else {
5017     // All arguments are treated the same.
5018     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
5019   }
5020   CCInfo.clearWasPPCF128();
5021
5022   // Assign locations to all of the outgoing aggregate by value arguments.
5023   SmallVector<CCValAssign, 16> ByValArgLocs;
5024   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
5025
5026   // Reserve stack space for the allocations in CCInfo.
5027   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
5028
5029   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
5030
5031   // Size of the linkage area, parameter list area and the part of the local
5032   // space variable where copies of aggregates which are passed by value are
5033   // stored.
5034   unsigned NumBytes = CCByValInfo.getNextStackOffset();
5035
5036   // Calculate by how many bytes the stack has to be adjusted in case of tail
5037   // call optimization.
5038   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5039
5040   // Adjust the stack pointer for the new arguments...
5041   // These operations are automatically eliminated by the prolog/epilog pass
5042   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5043   SDValue CallSeqStart = Chain;
5044
5045   // Load the return address and frame pointer so it can be moved somewhere else
5046   // later.
5047   SDValue LROp, FPOp;
5048   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5049
5050   // Set up a copy of the stack pointer for use loading and storing any
5051   // arguments that may not fit in the registers available for argument
5052   // passing.
5053   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5054
5055   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5056   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5057   SmallVector<SDValue, 8> MemOpChains;
5058
5059   bool seenFloatArg = false;
5060   // Walk the register/memloc assignments, inserting copies/loads.
5061   for (unsigned i = 0, j = 0, e = ArgLocs.size();
5062        i != e;
5063        ++i) {
5064     CCValAssign &VA = ArgLocs[i];
5065     SDValue Arg = OutVals[i];
5066     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5067
5068     if (Flags.isByVal()) {
5069       // Argument is an aggregate which is passed by value, thus we need to
5070       // create a copy of it in the local variable space of the current stack
5071       // frame (which is the stack frame of the caller) and pass the address of
5072       // this copy to the callee.
5073       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5074       CCValAssign &ByValVA = ByValArgLocs[j++];
5075       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5076
5077       // Memory reserved in the local variable space of the callers stack frame.
5078       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5079
5080       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5081       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5082                            StackPtr, PtrOff);
5083
5084       // Create a copy of the argument in the local area of the current
5085       // stack frame.
5086       SDValue MemcpyCall =
5087         CreateCopyOfByValArgument(Arg, PtrOff,
5088                                   CallSeqStart.getNode()->getOperand(0),
5089                                   Flags, DAG, dl);
5090
5091       // This must go outside the CALLSEQ_START..END.
5092       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5093                                                      SDLoc(MemcpyCall));
5094       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5095                              NewCallSeqStart.getNode());
5096       Chain = CallSeqStart = NewCallSeqStart;
5097
5098       // Pass the address of the aggregate copy on the stack either in a
5099       // physical register or in the parameter list area of the current stack
5100       // frame to the callee.
5101       Arg = PtrOff;
5102     }
5103
5104     if (VA.isRegLoc()) {
5105       if (Arg.getValueType() == MVT::i1)
5106         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5107
5108       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5109       // Put argument in a physical register.
5110       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5111     } else {
5112       // Put argument in the parameter list area of the current stack frame.
5113       assert(VA.isMemLoc());
5114       unsigned LocMemOffset = VA.getLocMemOffset();
5115
5116       if (!isTailCall) {
5117         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5118         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5119                              StackPtr, PtrOff);
5120
5121         MemOpChains.push_back(
5122             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5123       } else {
5124         // Calculate and remember argument location.
5125         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5126                                  TailCallArguments);
5127       }
5128     }
5129   }
5130
5131   if (!MemOpChains.empty())
5132     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5133
5134   // Build a sequence of copy-to-reg nodes chained together with token chain
5135   // and flag operands which copy the outgoing args into the appropriate regs.
5136   SDValue InFlag;
5137   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5138     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5139                              RegsToPass[i].second, InFlag);
5140     InFlag = Chain.getValue(1);
5141   }
5142
5143   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5144   // registers.
5145   if (isVarArg) {
5146     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5147     SDValue Ops[] = { Chain, InFlag };
5148
5149     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5150                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5151
5152     InFlag = Chain.getValue(1);
5153   }
5154
5155   if (isTailCall)
5156     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5157                     TailCallArguments);
5158
5159   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5160                     /* unused except on PPC64 ELFv1 */ false, DAG,
5161                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5162                     NumBytes, Ins, InVals, CS);
5163 }
5164
5165 // Copy an argument into memory, being careful to do this outside the
5166 // call sequence for the call to which the argument belongs.
5167 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5168     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5169     SelectionDAG &DAG, const SDLoc &dl) const {
5170   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5171                         CallSeqStart.getNode()->getOperand(0),
5172                         Flags, DAG, dl);
5173   // The MEMCPY must go outside the CALLSEQ_START..END.
5174   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5175   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5176                                                  SDLoc(MemcpyCall));
5177   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5178                          NewCallSeqStart.getNode());
5179   return NewCallSeqStart;
5180 }
5181
5182 SDValue PPCTargetLowering::LowerCall_64SVR4(
5183     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5184     bool isTailCall, bool isPatchPoint,
5185     const SmallVectorImpl<ISD::OutputArg> &Outs,
5186     const SmallVectorImpl<SDValue> &OutVals,
5187     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5188     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5189     ImmutableCallSite *CS) const {
5190   bool isELFv2ABI = Subtarget.isELFv2ABI();
5191   bool isLittleEndian = Subtarget.isLittleEndian();
5192   unsigned NumOps = Outs.size();
5193   bool hasNest = false;
5194   bool IsSibCall = false;
5195
5196   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5197   unsigned PtrByteSize = 8;
5198
5199   MachineFunction &MF = DAG.getMachineFunction();
5200
5201   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5202     IsSibCall = true;
5203
5204   // Mark this function as potentially containing a function that contains a
5205   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5206   // and restoring the callers stack pointer in this functions epilog. This is
5207   // done because by tail calling the called function might overwrite the value
5208   // in this function's (MF) stack pointer stack slot 0(SP).
5209   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5210       CallConv == CallingConv::Fast)
5211     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5212
5213   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5214          "fastcc not supported on varargs functions");
5215
5216   // Count how many bytes are to be pushed on the stack, including the linkage
5217   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5218   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5219   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5220   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5221   unsigned NumBytes = LinkageSize;
5222   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5223   unsigned &QFPR_idx = FPR_idx;
5224
5225   static const MCPhysReg GPR[] = {
5226     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5227     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5228   };
5229   static const MCPhysReg VR[] = {
5230     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5231     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5232   };
5233
5234   const unsigned NumGPRs = array_lengthof(GPR);
5235   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5236   const unsigned NumVRs  = array_lengthof(VR);
5237   const unsigned NumQFPRs = NumFPRs;
5238
5239   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5240   // can be passed to the callee in registers.
5241   // For the fast calling convention, there is another check below.
5242   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5243   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5244   if (!HasParameterArea) {
5245     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5246     unsigned AvailableFPRs = NumFPRs;
5247     unsigned AvailableVRs = NumVRs;
5248     unsigned NumBytesTmp = NumBytes;
5249     for (unsigned i = 0; i != NumOps; ++i) {
5250       if (Outs[i].Flags.isNest()) continue;
5251       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5252                                 PtrByteSize, LinkageSize, ParamAreaSize,
5253                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5254                                 Subtarget.hasQPX()))
5255         HasParameterArea = true;
5256     }
5257   }
5258
5259   // When using the fast calling convention, we don't provide backing for
5260   // arguments that will be in registers.
5261   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5262
5263   // Add up all the space actually used.
5264   for (unsigned i = 0; i != NumOps; ++i) {
5265     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5266     EVT ArgVT = Outs[i].VT;
5267     EVT OrigVT = Outs[i].ArgVT;
5268
5269     if (Flags.isNest())
5270       continue;
5271
5272     if (CallConv == CallingConv::Fast) {
5273       if (Flags.isByVal())
5274         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5275       else
5276         switch (ArgVT.getSimpleVT().SimpleTy) {
5277         default: llvm_unreachable("Unexpected ValueType for argument!");
5278         case MVT::i1:
5279         case MVT::i32:
5280         case MVT::i64:
5281           if (++NumGPRsUsed <= NumGPRs)
5282             continue;
5283           break;
5284         case MVT::v4i32:
5285         case MVT::v8i16:
5286         case MVT::v16i8:
5287         case MVT::v2f64:
5288         case MVT::v2i64:
5289         case MVT::v1i128:
5290           if (++NumVRsUsed <= NumVRs)
5291             continue;
5292           break;
5293         case MVT::v4f32:
5294           // When using QPX, this is handled like a FP register, otherwise, it
5295           // is an Altivec register.
5296           if (Subtarget.hasQPX()) {
5297             if (++NumFPRsUsed <= NumFPRs)
5298               continue;
5299           } else {
5300             if (++NumVRsUsed <= NumVRs)
5301               continue;
5302           }
5303           break;
5304         case MVT::f32:
5305         case MVT::f64:
5306         case MVT::v4f64: // QPX
5307         case MVT::v4i1:  // QPX
5308           if (++NumFPRsUsed <= NumFPRs)
5309             continue;
5310           break;
5311         }
5312     }
5313
5314     /* Respect alignment of argument on the stack.  */
5315     unsigned Align =
5316       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5317     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5318
5319     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5320     if (Flags.isInConsecutiveRegsLast())
5321       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5322   }
5323
5324   unsigned NumBytesActuallyUsed = NumBytes;
5325
5326   // In the old ELFv1 ABI,
5327   // the prolog code of the callee may store up to 8 GPR argument registers to
5328   // the stack, allowing va_start to index over them in memory if its varargs.
5329   // Because we cannot tell if this is needed on the caller side, we have to
5330   // conservatively assume that it is needed.  As such, make sure we have at
5331   // least enough stack space for the caller to store the 8 GPRs.
5332   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5333   // really requires memory operands, e.g. a vararg function.
5334   if (HasParameterArea)
5335     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5336   else
5337     NumBytes = LinkageSize;
5338
5339   // Tail call needs the stack to be aligned.
5340   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5341       CallConv == CallingConv::Fast)
5342     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5343
5344   int SPDiff = 0;
5345
5346   // Calculate by how many bytes the stack has to be adjusted in case of tail
5347   // call optimization.
5348   if (!IsSibCall)
5349     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5350
5351   // To protect arguments on the stack from being clobbered in a tail call,
5352   // force all the loads to happen before doing any other lowering.
5353   if (isTailCall)
5354     Chain = DAG.getStackArgumentTokenFactor(Chain);
5355
5356   // Adjust the stack pointer for the new arguments...
5357   // These operations are automatically eliminated by the prolog/epilog pass
5358   if (!IsSibCall)
5359     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5360   SDValue CallSeqStart = Chain;
5361
5362   // Load the return address and frame pointer so it can be move somewhere else
5363   // later.
5364   SDValue LROp, FPOp;
5365   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5366
5367   // Set up a copy of the stack pointer for use loading and storing any
5368   // arguments that may not fit in the registers available for argument
5369   // passing.
5370   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5371
5372   // Figure out which arguments are going to go in registers, and which in
5373   // memory.  Also, if this is a vararg function, floating point operations
5374   // must be stored to our stack, and loaded into integer regs as well, if
5375   // any integer regs are available for argument passing.
5376   unsigned ArgOffset = LinkageSize;
5377
5378   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5379   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5380
5381   SmallVector<SDValue, 8> MemOpChains;
5382   for (unsigned i = 0; i != NumOps; ++i) {
5383     SDValue Arg = OutVals[i];
5384     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5385     EVT ArgVT = Outs[i].VT;
5386     EVT OrigVT = Outs[i].ArgVT;
5387
5388     // PtrOff will be used to store the current argument to the stack if a
5389     // register cannot be found for it.
5390     SDValue PtrOff;
5391
5392     // We re-align the argument offset for each argument, except when using the
5393     // fast calling convention, when we need to make sure we do that only when
5394     // we'll actually use a stack slot.
5395     auto ComputePtrOff = [&]() {
5396       /* Respect alignment of argument on the stack.  */
5397       unsigned Align =
5398         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5399       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5400
5401       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5402
5403       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5404     };
5405
5406     if (CallConv != CallingConv::Fast) {
5407       ComputePtrOff();
5408
5409       /* Compute GPR index associated with argument offset.  */
5410       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5411       GPR_idx = std::min(GPR_idx, NumGPRs);
5412     }
5413
5414     // Promote integers to 64-bit values.
5415     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5416       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5417       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5418       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5419     }
5420
5421     // FIXME memcpy is used way more than necessary.  Correctness first.
5422     // Note: "by value" is code for passing a structure by value, not
5423     // basic types.
5424     if (Flags.isByVal()) {
5425       // Note: Size includes alignment padding, so
5426       //   struct x { short a; char b; }
5427       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5428       // These are the proper values we need for right-justifying the
5429       // aggregate in a parameter register.
5430       unsigned Size = Flags.getByValSize();
5431
5432       // An empty aggregate parameter takes up no storage and no
5433       // registers.
5434       if (Size == 0)
5435         continue;
5436
5437       if (CallConv == CallingConv::Fast)
5438         ComputePtrOff();
5439
5440       // All aggregates smaller than 8 bytes must be passed right-justified.
5441       if (Size==1 || Size==2 || Size==4) {
5442         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5443         if (GPR_idx != NumGPRs) {
5444           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5445                                         MachinePointerInfo(), VT);
5446           MemOpChains.push_back(Load.getValue(1));
5447           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5448
5449           ArgOffset += PtrByteSize;
5450           continue;
5451         }
5452       }
5453
5454       if (GPR_idx == NumGPRs && Size < 8) {
5455         SDValue AddPtr = PtrOff;
5456         if (!isLittleEndian) {
5457           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5458                                           PtrOff.getValueType());
5459           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5460         }
5461         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5462                                                           CallSeqStart,
5463                                                           Flags, DAG, dl);
5464         ArgOffset += PtrByteSize;
5465         continue;
5466       }
5467       // Copy entire object into memory.  There are cases where gcc-generated
5468       // code assumes it is there, even if it could be put entirely into
5469       // registers.  (This is not what the doc says.)
5470
5471       // FIXME: The above statement is likely due to a misunderstanding of the
5472       // documents.  All arguments must be copied into the parameter area BY
5473       // THE CALLEE in the event that the callee takes the address of any
5474       // formal argument.  That has not yet been implemented.  However, it is
5475       // reasonable to use the stack area as a staging area for the register
5476       // load.
5477
5478       // Skip this for small aggregates, as we will use the same slot for a
5479       // right-justified copy, below.
5480       if (Size >= 8)
5481         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5482                                                           CallSeqStart,
5483                                                           Flags, DAG, dl);
5484
5485       // When a register is available, pass a small aggregate right-justified.
5486       if (Size < 8 && GPR_idx != NumGPRs) {
5487         // The easiest way to get this right-justified in a register
5488         // is to copy the structure into the rightmost portion of a
5489         // local variable slot, then load the whole slot into the
5490         // register.
5491         // FIXME: The memcpy seems to produce pretty awful code for
5492         // small aggregates, particularly for packed ones.
5493         // FIXME: It would be preferable to use the slot in the
5494         // parameter save area instead of a new local variable.
5495         SDValue AddPtr = PtrOff;
5496         if (!isLittleEndian) {
5497           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5498           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5499         }
5500         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5501                                                           CallSeqStart,
5502                                                           Flags, DAG, dl);
5503
5504         // Load the slot into the register.
5505         SDValue Load =
5506             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5507         MemOpChains.push_back(Load.getValue(1));
5508         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5509
5510         // Done with this argument.
5511         ArgOffset += PtrByteSize;
5512         continue;
5513       }
5514
5515       // For aggregates larger than PtrByteSize, copy the pieces of the
5516       // object that fit into registers from the parameter save area.
5517       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5518         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5519         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5520         if (GPR_idx != NumGPRs) {
5521           SDValue Load =
5522               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5523           MemOpChains.push_back(Load.getValue(1));
5524           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5525           ArgOffset += PtrByteSize;
5526         } else {
5527           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5528           break;
5529         }
5530       }
5531       continue;
5532     }
5533
5534     switch (Arg.getSimpleValueType().SimpleTy) {
5535     default: llvm_unreachable("Unexpected ValueType for argument!");
5536     case MVT::i1:
5537     case MVT::i32:
5538     case MVT::i64:
5539       if (Flags.isNest()) {
5540         // The 'nest' parameter, if any, is passed in R11.
5541         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5542         hasNest = true;
5543         break;
5544       }
5545
5546       // These can be scalar arguments or elements of an integer array type
5547       // passed directly.  Clang may use those instead of "byval" aggregate
5548       // types to avoid forcing arguments to memory unnecessarily.
5549       if (GPR_idx != NumGPRs) {
5550         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5551       } else {
5552         if (CallConv == CallingConv::Fast)
5553           ComputePtrOff();
5554
5555         assert(HasParameterArea &&
5556                "Parameter area must exist to pass an argument in memory.");
5557         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5558                          true, isTailCall, false, MemOpChains,
5559                          TailCallArguments, dl);
5560         if (CallConv == CallingConv::Fast)
5561           ArgOffset += PtrByteSize;
5562       }
5563       if (CallConv != CallingConv::Fast)
5564         ArgOffset += PtrByteSize;
5565       break;
5566     case MVT::f32:
5567     case MVT::f64: {
5568       // These can be scalar arguments or elements of a float array type
5569       // passed directly.  The latter are used to implement ELFv2 homogenous
5570       // float aggregates.
5571
5572       // Named arguments go into FPRs first, and once they overflow, the
5573       // remaining arguments go into GPRs and then the parameter save area.
5574       // Unnamed arguments for vararg functions always go to GPRs and
5575       // then the parameter save area.  For now, put all arguments to vararg
5576       // routines always in both locations (FPR *and* GPR or stack slot).
5577       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5578       bool NeededLoad = false;
5579
5580       // First load the argument into the next available FPR.
5581       if (FPR_idx != NumFPRs)
5582         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5583
5584       // Next, load the argument into GPR or stack slot if needed.
5585       if (!NeedGPROrStack)
5586         ;
5587       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5588         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5589         // once we support fp <-> gpr moves.
5590
5591         // In the non-vararg case, this can only ever happen in the
5592         // presence of f32 array types, since otherwise we never run
5593         // out of FPRs before running out of GPRs.
5594         SDValue ArgVal;
5595
5596         // Double values are always passed in a single GPR.
5597         if (Arg.getValueType() != MVT::f32) {
5598           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5599
5600         // Non-array float values are extended and passed in a GPR.
5601         } else if (!Flags.isInConsecutiveRegs()) {
5602           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5603           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5604
5605         // If we have an array of floats, we collect every odd element
5606         // together with its predecessor into one GPR.
5607         } else if (ArgOffset % PtrByteSize != 0) {
5608           SDValue Lo, Hi;
5609           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5610           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5611           if (!isLittleEndian)
5612             std::swap(Lo, Hi);
5613           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5614
5615         // The final element, if even, goes into the first half of a GPR.
5616         } else if (Flags.isInConsecutiveRegsLast()) {
5617           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5618           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5619           if (!isLittleEndian)
5620             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5621                                  DAG.getConstant(32, dl, MVT::i32));
5622
5623         // Non-final even elements are skipped; they will be handled
5624         // together the with subsequent argument on the next go-around.
5625         } else
5626           ArgVal = SDValue();
5627
5628         if (ArgVal.getNode())
5629           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5630       } else {
5631         if (CallConv == CallingConv::Fast)
5632           ComputePtrOff();
5633
5634         // Single-precision floating-point values are mapped to the
5635         // second (rightmost) word of the stack doubleword.
5636         if (Arg.getValueType() == MVT::f32 &&
5637             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5638           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5639           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5640         }
5641
5642         assert(HasParameterArea &&
5643                "Parameter area must exist to pass an argument in memory.");
5644         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5645                          true, isTailCall, false, MemOpChains,
5646                          TailCallArguments, dl);
5647
5648         NeededLoad = true;
5649       }
5650       // When passing an array of floats, the array occupies consecutive
5651       // space in the argument area; only round up to the next doubleword
5652       // at the end of the array.  Otherwise, each float takes 8 bytes.
5653       if (CallConv != CallingConv::Fast || NeededLoad) {
5654         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5655                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5656         if (Flags.isInConsecutiveRegsLast())
5657           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5658       }
5659       break;
5660     }
5661     case MVT::v4f32:
5662     case MVT::v4i32:
5663     case MVT::v8i16:
5664     case MVT::v16i8:
5665     case MVT::v2f64:
5666     case MVT::v2i64:
5667     case MVT::v1i128:
5668       if (!Subtarget.hasQPX()) {
5669       // These can be scalar arguments or elements of a vector array type
5670       // passed directly.  The latter are used to implement ELFv2 homogenous
5671       // vector aggregates.
5672
5673       // For a varargs call, named arguments go into VRs or on the stack as
5674       // usual; unnamed arguments always go to the stack or the corresponding
5675       // GPRs when within range.  For now, we always put the value in both
5676       // locations (or even all three).
5677       if (isVarArg) {
5678         assert(HasParameterArea &&
5679                "Parameter area must exist if we have a varargs call.");
5680         // We could elide this store in the case where the object fits
5681         // entirely in R registers.  Maybe later.
5682         SDValue Store =
5683             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5684         MemOpChains.push_back(Store);
5685         if (VR_idx != NumVRs) {
5686           SDValue Load =
5687               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5688           MemOpChains.push_back(Load.getValue(1));
5689           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5690         }
5691         ArgOffset += 16;
5692         for (unsigned i=0; i<16; i+=PtrByteSize) {
5693           if (GPR_idx == NumGPRs)
5694             break;
5695           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5696                                    DAG.getConstant(i, dl, PtrVT));
5697           SDValue Load =
5698               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5699           MemOpChains.push_back(Load.getValue(1));
5700           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5701         }
5702         break;
5703       }
5704
5705       // Non-varargs Altivec params go into VRs or on the stack.
5706       if (VR_idx != NumVRs) {
5707         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5708       } else {
5709         if (CallConv == CallingConv::Fast)
5710           ComputePtrOff();
5711
5712         assert(HasParameterArea &&
5713                "Parameter area must exist to pass an argument in memory.");
5714         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5715                          true, isTailCall, true, MemOpChains,
5716                          TailCallArguments, dl);
5717         if (CallConv == CallingConv::Fast)
5718           ArgOffset += 16;
5719       }
5720
5721       if (CallConv != CallingConv::Fast)
5722         ArgOffset += 16;
5723       break;
5724       } // not QPX
5725
5726       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5727              "Invalid QPX parameter type");
5728
5729       /* fall through */
5730     case MVT::v4f64:
5731     case MVT::v4i1: {
5732       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5733       if (isVarArg) {
5734         assert(HasParameterArea &&
5735                "Parameter area must exist if we have a varargs call.");
5736         // We could elide this store in the case where the object fits
5737         // entirely in R registers.  Maybe later.
5738         SDValue Store =
5739             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5740         MemOpChains.push_back(Store);
5741         if (QFPR_idx != NumQFPRs) {
5742           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5743                                      PtrOff, MachinePointerInfo());
5744           MemOpChains.push_back(Load.getValue(1));
5745           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5746         }
5747         ArgOffset += (IsF32 ? 16 : 32);
5748         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5749           if (GPR_idx == NumGPRs)
5750             break;
5751           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5752                                    DAG.getConstant(i, dl, PtrVT));
5753           SDValue Load =
5754               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5755           MemOpChains.push_back(Load.getValue(1));
5756           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5757         }
5758         break;
5759       }
5760
5761       // Non-varargs QPX params go into registers or on the stack.
5762       if (QFPR_idx != NumQFPRs) {
5763         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5764       } else {
5765         if (CallConv == CallingConv::Fast)
5766           ComputePtrOff();
5767
5768         assert(HasParameterArea &&
5769                "Parameter area must exist to pass an argument in memory.");
5770         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5771                          true, isTailCall, true, MemOpChains,
5772                          TailCallArguments, dl);
5773         if (CallConv == CallingConv::Fast)
5774           ArgOffset += (IsF32 ? 16 : 32);
5775       }
5776
5777       if (CallConv != CallingConv::Fast)
5778         ArgOffset += (IsF32 ? 16 : 32);
5779       break;
5780       }
5781     }
5782   }
5783
5784   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5785          "mismatch in size of parameter area");
5786   (void)NumBytesActuallyUsed;
5787
5788   if (!MemOpChains.empty())
5789     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5790
5791   // Check if this is an indirect call (MTCTR/BCTRL).
5792   // See PrepareCall() for more information about calls through function
5793   // pointers in the 64-bit SVR4 ABI.
5794   if (!isTailCall && !isPatchPoint &&
5795       !isFunctionGlobalAddress(Callee) &&
5796       !isa<ExternalSymbolSDNode>(Callee)) {
5797     // Load r2 into a virtual register and store it to the TOC save area.
5798     setUsesTOCBasePtr(DAG);
5799     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5800     // TOC save area offset.
5801     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5802     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5803     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5804     Chain = DAG.getStore(
5805         Val.getValue(1), dl, Val, AddPtr,
5806         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5807     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5808     // This does not mean the MTCTR instruction must use R12; it's easier
5809     // to model this as an extra parameter, so do that.
5810     if (isELFv2ABI && !isPatchPoint)
5811       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5812   }
5813
5814   // Build a sequence of copy-to-reg nodes chained together with token chain
5815   // and flag operands which copy the outgoing args into the appropriate regs.
5816   SDValue InFlag;
5817   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5818     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5819                              RegsToPass[i].second, InFlag);
5820     InFlag = Chain.getValue(1);
5821   }
5822
5823   if (isTailCall && !IsSibCall)
5824     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5825                     TailCallArguments);
5826
5827   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5828                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5829                     SPDiff, NumBytes, Ins, InVals, CS);
5830 }
5831
5832 SDValue PPCTargetLowering::LowerCall_Darwin(
5833     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5834     bool isTailCall, bool isPatchPoint,
5835     const SmallVectorImpl<ISD::OutputArg> &Outs,
5836     const SmallVectorImpl<SDValue> &OutVals,
5837     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5838     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5839     ImmutableCallSite *CS) const {
5840   unsigned NumOps = Outs.size();
5841
5842   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5843   bool isPPC64 = PtrVT == MVT::i64;
5844   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5845
5846   MachineFunction &MF = DAG.getMachineFunction();
5847
5848   // Mark this function as potentially containing a function that contains a
5849   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5850   // and restoring the callers stack pointer in this functions epilog. This is
5851   // done because by tail calling the called function might overwrite the value
5852   // in this function's (MF) stack pointer stack slot 0(SP).
5853   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5854       CallConv == CallingConv::Fast)
5855     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5856
5857   // Count how many bytes are to be pushed on the stack, including the linkage
5858   // area, and parameter passing area.  We start with 24/48 bytes, which is
5859   // prereserved space for [SP][CR][LR][3 x unused].
5860   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5861   unsigned NumBytes = LinkageSize;
5862
5863   // Add up all the space actually used.
5864   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5865   // they all go in registers, but we must reserve stack space for them for
5866   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5867   // assigned stack space in order, with padding so Altivec parameters are
5868   // 16-byte aligned.
5869   unsigned nAltivecParamsAtEnd = 0;
5870   for (unsigned i = 0; i != NumOps; ++i) {
5871     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5872     EVT ArgVT = Outs[i].VT;
5873     // Varargs Altivec parameters are padded to a 16 byte boundary.
5874     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5875         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5876         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5877       if (!isVarArg && !isPPC64) {
5878         // Non-varargs Altivec parameters go after all the non-Altivec
5879         // parameters; handle those later so we know how much padding we need.
5880         nAltivecParamsAtEnd++;
5881         continue;
5882       }
5883       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5884       NumBytes = ((NumBytes+15)/16)*16;
5885     }
5886     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5887   }
5888
5889   // Allow for Altivec parameters at the end, if needed.
5890   if (nAltivecParamsAtEnd) {
5891     NumBytes = ((NumBytes+15)/16)*16;
5892     NumBytes += 16*nAltivecParamsAtEnd;
5893   }
5894
5895   // The prolog code of the callee may store up to 8 GPR argument registers to
5896   // the stack, allowing va_start to index over them in memory if its varargs.
5897   // Because we cannot tell if this is needed on the caller side, we have to
5898   // conservatively assume that it is needed.  As such, make sure we have at
5899   // least enough stack space for the caller to store the 8 GPRs.
5900   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5901
5902   // Tail call needs the stack to be aligned.
5903   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5904       CallConv == CallingConv::Fast)
5905     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5906
5907   // Calculate by how many bytes the stack has to be adjusted in case of tail
5908   // call optimization.
5909   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5910
5911   // To protect arguments on the stack from being clobbered in a tail call,
5912   // force all the loads to happen before doing any other lowering.
5913   if (isTailCall)
5914     Chain = DAG.getStackArgumentTokenFactor(Chain);
5915
5916   // Adjust the stack pointer for the new arguments...
5917   // These operations are automatically eliminated by the prolog/epilog pass
5918   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5919   SDValue CallSeqStart = Chain;
5920
5921   // Load the return address and frame pointer so it can be move somewhere else
5922   // later.
5923   SDValue LROp, FPOp;
5924   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5925
5926   // Set up a copy of the stack pointer for use loading and storing any
5927   // arguments that may not fit in the registers available for argument
5928   // passing.
5929   SDValue StackPtr;
5930   if (isPPC64)
5931     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5932   else
5933     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5934
5935   // Figure out which arguments are going to go in registers, and which in
5936   // memory.  Also, if this is a vararg function, floating point operations
5937   // must be stored to our stack, and loaded into integer regs as well, if
5938   // any integer regs are available for argument passing.
5939   unsigned ArgOffset = LinkageSize;
5940   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5941
5942   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5943     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5944     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5945   };
5946   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5947     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5948     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5949   };
5950   static const MCPhysReg VR[] = {
5951     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5952     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5953   };
5954   const unsigned NumGPRs = array_lengthof(GPR_32);
5955   const unsigned NumFPRs = 13;
5956   const unsigned NumVRs  = array_lengthof(VR);
5957
5958   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5959
5960   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5961   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5962
5963   SmallVector<SDValue, 8> MemOpChains;
5964   for (unsigned i = 0; i != NumOps; ++i) {
5965     SDValue Arg = OutVals[i];
5966     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5967
5968     // PtrOff will be used to store the current argument to the stack if a
5969     // register cannot be found for it.
5970     SDValue PtrOff;
5971
5972     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5973
5974     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5975
5976     // On PPC64, promote integers to 64-bit values.
5977     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5978       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5979       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5980       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5981     }
5982
5983     // FIXME memcpy is used way more than necessary.  Correctness first.
5984     // Note: "by value" is code for passing a structure by value, not
5985     // basic types.
5986     if (Flags.isByVal()) {
5987       unsigned Size = Flags.getByValSize();
5988       // Very small objects are passed right-justified.  Everything else is
5989       // passed left-justified.
5990       if (Size==1 || Size==2) {
5991         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5992         if (GPR_idx != NumGPRs) {
5993           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5994                                         MachinePointerInfo(), VT);
5995           MemOpChains.push_back(Load.getValue(1));
5996           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5997
5998           ArgOffset += PtrByteSize;
5999         } else {
6000           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
6001                                           PtrOff.getValueType());
6002           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
6003           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
6004                                                             CallSeqStart,
6005                                                             Flags, DAG, dl);
6006           ArgOffset += PtrByteSize;
6007         }
6008         continue;
6009       }
6010       // Copy entire object into memory.  There are cases where gcc-generated
6011       // code assumes it is there, even if it could be put entirely into
6012       // registers.  (This is not what the doc says.)
6013       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
6014                                                         CallSeqStart,
6015                                                         Flags, DAG, dl);
6016
6017       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
6018       // copy the pieces of the object that fit into registers from the
6019       // parameter save area.
6020       for (unsigned j=0; j<Size; j+=PtrByteSize) {
6021         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
6022         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
6023         if (GPR_idx != NumGPRs) {
6024           SDValue Load =
6025               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
6026           MemOpChains.push_back(Load.getValue(1));
6027           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6028           ArgOffset += PtrByteSize;
6029         } else {
6030           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
6031           break;
6032         }
6033       }
6034       continue;
6035     }
6036
6037     switch (Arg.getSimpleValueType().SimpleTy) {
6038     default: llvm_unreachable("Unexpected ValueType for argument!");
6039     case MVT::i1:
6040     case MVT::i32:
6041     case MVT::i64:
6042       if (GPR_idx != NumGPRs) {
6043         if (Arg.getValueType() == MVT::i1)
6044           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
6045
6046         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
6047       } else {
6048         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6049                          isPPC64, isTailCall, false, MemOpChains,
6050                          TailCallArguments, dl);
6051       }
6052       ArgOffset += PtrByteSize;
6053       break;
6054     case MVT::f32:
6055     case MVT::f64:
6056       if (FPR_idx != NumFPRs) {
6057         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
6058
6059         if (isVarArg) {
6060           SDValue Store =
6061               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6062           MemOpChains.push_back(Store);
6063
6064           // Float varargs are always shadowed in available integer registers
6065           if (GPR_idx != NumGPRs) {
6066             SDValue Load =
6067                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6068             MemOpChains.push_back(Load.getValue(1));
6069             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6070           }
6071           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6072             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6073             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6074             SDValue Load =
6075                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6076             MemOpChains.push_back(Load.getValue(1));
6077             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6078           }
6079         } else {
6080           // If we have any FPRs remaining, we may also have GPRs remaining.
6081           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6082           // GPRs.
6083           if (GPR_idx != NumGPRs)
6084             ++GPR_idx;
6085           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6086               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6087             ++GPR_idx;
6088         }
6089       } else
6090         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6091                          isPPC64, isTailCall, false, MemOpChains,
6092                          TailCallArguments, dl);
6093       if (isPPC64)
6094         ArgOffset += 8;
6095       else
6096         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6097       break;
6098     case MVT::v4f32:
6099     case MVT::v4i32:
6100     case MVT::v8i16:
6101     case MVT::v16i8:
6102       if (isVarArg) {
6103         // These go aligned on the stack, or in the corresponding R registers
6104         // when within range.  The Darwin PPC ABI doc claims they also go in
6105         // V registers; in fact gcc does this only for arguments that are
6106         // prototyped, not for those that match the ...  We do it for all
6107         // arguments, seems to work.
6108         while (ArgOffset % 16 !=0) {
6109           ArgOffset += PtrByteSize;
6110           if (GPR_idx != NumGPRs)
6111             GPR_idx++;
6112         }
6113         // We could elide this store in the case where the object fits
6114         // entirely in R registers.  Maybe later.
6115         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6116                              DAG.getConstant(ArgOffset, dl, PtrVT));
6117         SDValue Store =
6118             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6119         MemOpChains.push_back(Store);
6120         if (VR_idx != NumVRs) {
6121           SDValue Load =
6122               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6123           MemOpChains.push_back(Load.getValue(1));
6124           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6125         }
6126         ArgOffset += 16;
6127         for (unsigned i=0; i<16; i+=PtrByteSize) {
6128           if (GPR_idx == NumGPRs)
6129             break;
6130           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6131                                    DAG.getConstant(i, dl, PtrVT));
6132           SDValue Load =
6133               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6134           MemOpChains.push_back(Load.getValue(1));
6135           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6136         }
6137         break;
6138       }
6139
6140       // Non-varargs Altivec params generally go in registers, but have
6141       // stack space allocated at the end.
6142       if (VR_idx != NumVRs) {
6143         // Doesn't have GPR space allocated.
6144         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6145       } else if (nAltivecParamsAtEnd==0) {
6146         // We are emitting Altivec params in order.
6147         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6148                          isPPC64, isTailCall, true, MemOpChains,
6149                          TailCallArguments, dl);
6150         ArgOffset += 16;
6151       }
6152       break;
6153     }
6154   }
6155   // If all Altivec parameters fit in registers, as they usually do,
6156   // they get stack space following the non-Altivec parameters.  We
6157   // don't track this here because nobody below needs it.
6158   // If there are more Altivec parameters than fit in registers emit
6159   // the stores here.
6160   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6161     unsigned j = 0;
6162     // Offset is aligned; skip 1st 12 params which go in V registers.
6163     ArgOffset = ((ArgOffset+15)/16)*16;
6164     ArgOffset += 12*16;
6165     for (unsigned i = 0; i != NumOps; ++i) {
6166       SDValue Arg = OutVals[i];
6167       EVT ArgType = Outs[i].VT;
6168       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6169           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6170         if (++j > NumVRs) {
6171           SDValue PtrOff;
6172           // We are emitting Altivec params in order.
6173           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6174                            isPPC64, isTailCall, true, MemOpChains,
6175                            TailCallArguments, dl);
6176           ArgOffset += 16;
6177         }
6178       }
6179     }
6180   }
6181
6182   if (!MemOpChains.empty())
6183     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6184
6185   // On Darwin, R12 must contain the address of an indirect callee.  This does
6186   // not mean the MTCTR instruction must use R12; it's easier to model this as
6187   // an extra parameter, so do that.
6188   if (!isTailCall &&
6189       !isFunctionGlobalAddress(Callee) &&
6190       !isa<ExternalSymbolSDNode>(Callee) &&
6191       !isBLACompatibleAddress(Callee, DAG))
6192     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6193                                                    PPC::R12), Callee));
6194
6195   // Build a sequence of copy-to-reg nodes chained together with token chain
6196   // and flag operands which copy the outgoing args into the appropriate regs.
6197   SDValue InFlag;
6198   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6199     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6200                              RegsToPass[i].second, InFlag);
6201     InFlag = Chain.getValue(1);
6202   }
6203
6204   if (isTailCall)
6205     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6206                     TailCallArguments);
6207
6208   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6209                     /* unused except on PPC64 ELFv1 */ false, DAG,
6210                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6211                     NumBytes, Ins, InVals, CS);
6212 }
6213
6214 bool
6215 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6216                                   MachineFunction &MF, bool isVarArg,
6217                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6218                                   LLVMContext &Context) const {
6219   SmallVector<CCValAssign, 16> RVLocs;
6220   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6221   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6222 }
6223
6224 SDValue
6225 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6226                                bool isVarArg,
6227                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6228                                const SmallVectorImpl<SDValue> &OutVals,
6229                                const SDLoc &dl, SelectionDAG &DAG) const {
6230   SmallVector<CCValAssign, 16> RVLocs;
6231   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6232                  *DAG.getContext());
6233   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6234
6235   SDValue Flag;
6236   SmallVector<SDValue, 4> RetOps(1, Chain);
6237
6238   // Copy the result values into the output registers.
6239   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6240     CCValAssign &VA = RVLocs[i];
6241     assert(VA.isRegLoc() && "Can only return in registers!");
6242
6243     SDValue Arg = OutVals[i];
6244
6245     switch (VA.getLocInfo()) {
6246     default: llvm_unreachable("Unknown loc info!");
6247     case CCValAssign::Full: break;
6248     case CCValAssign::AExt:
6249       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6250       break;
6251     case CCValAssign::ZExt:
6252       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6253       break;
6254     case CCValAssign::SExt:
6255       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6256       break;
6257     }
6258
6259     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6260     Flag = Chain.getValue(1);
6261     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6262   }
6263
6264   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6265   const MCPhysReg *I =
6266     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6267   if (I) {
6268     for (; *I; ++I) {
6269
6270       if (PPC::G8RCRegClass.contains(*I))
6271         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6272       else if (PPC::F8RCRegClass.contains(*I))
6273         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6274       else if (PPC::CRRCRegClass.contains(*I))
6275         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6276       else if (PPC::VRRCRegClass.contains(*I))
6277         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6278       else
6279         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6280     }
6281   }
6282
6283   RetOps[0] = Chain;  // Update chain.
6284
6285   // Add the flag if we have it.
6286   if (Flag.getNode())
6287     RetOps.push_back(Flag);
6288
6289   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6290 }
6291
6292 SDValue
6293 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6294                                                 SelectionDAG &DAG) const {
6295   SDLoc dl(Op);
6296
6297   // Get the corect type for integers.
6298   EVT IntVT = Op.getValueType();
6299
6300   // Get the inputs.
6301   SDValue Chain = Op.getOperand(0);
6302   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6303   // Build a DYNAREAOFFSET node.
6304   SDValue Ops[2] = {Chain, FPSIdx};
6305   SDVTList VTs = DAG.getVTList(IntVT);
6306   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6307 }
6308
6309 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6310                                              SelectionDAG &DAG) const {
6311   // When we pop the dynamic allocation we need to restore the SP link.
6312   SDLoc dl(Op);
6313
6314   // Get the corect type for pointers.
6315   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6316
6317   // Construct the stack pointer operand.
6318   bool isPPC64 = Subtarget.isPPC64();
6319   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6320   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6321
6322   // Get the operands for the STACKRESTORE.
6323   SDValue Chain = Op.getOperand(0);
6324   SDValue SaveSP = Op.getOperand(1);
6325
6326   // Load the old link SP.
6327   SDValue LoadLinkSP =
6328       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6329
6330   // Restore the stack pointer.
6331   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6332
6333   // Store the old link SP.
6334   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6335 }
6336
6337 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6338   MachineFunction &MF = DAG.getMachineFunction();
6339   bool isPPC64 = Subtarget.isPPC64();
6340   EVT PtrVT = getPointerTy(MF.getDataLayout());
6341
6342   // Get current frame pointer save index.  The users of this index will be
6343   // primarily DYNALLOC instructions.
6344   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6345   int RASI = FI->getReturnAddrSaveIndex();
6346
6347   // If the frame pointer save index hasn't been defined yet.
6348   if (!RASI) {
6349     // Find out what the fix offset of the frame pointer save area.
6350     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6351     // Allocate the frame index for frame pointer save area.
6352     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6353     // Save the result.
6354     FI->setReturnAddrSaveIndex(RASI);
6355   }
6356   return DAG.getFrameIndex(RASI, PtrVT);
6357 }
6358
6359 SDValue
6360 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6361   MachineFunction &MF = DAG.getMachineFunction();
6362   bool isPPC64 = Subtarget.isPPC64();
6363   EVT PtrVT = getPointerTy(MF.getDataLayout());
6364
6365   // Get current frame pointer save index.  The users of this index will be
6366   // primarily DYNALLOC instructions.
6367   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6368   int FPSI = FI->getFramePointerSaveIndex();
6369
6370   // If the frame pointer save index hasn't been defined yet.
6371   if (!FPSI) {
6372     // Find out what the fix offset of the frame pointer save area.
6373     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6374     // Allocate the frame index for frame pointer save area.
6375     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6376     // Save the result.
6377     FI->setFramePointerSaveIndex(FPSI);
6378   }
6379   return DAG.getFrameIndex(FPSI, PtrVT);
6380 }
6381
6382 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6383                                                    SelectionDAG &DAG) const {
6384   // Get the inputs.
6385   SDValue Chain = Op.getOperand(0);
6386   SDValue Size  = Op.getOperand(1);
6387   SDLoc dl(Op);
6388
6389   // Get the corect type for pointers.
6390   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6391   // Negate the size.
6392   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6393                                 DAG.getConstant(0, dl, PtrVT), Size);
6394   // Construct a node for the frame pointer save index.
6395   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6396   // Build a DYNALLOC node.
6397   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6398   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6399   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6400 }
6401
6402 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6403                                                      SelectionDAG &DAG) const {
6404   MachineFunction &MF = DAG.getMachineFunction();
6405
6406   bool isPPC64 = Subtarget.isPPC64();
6407   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6408
6409   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6410   return DAG.getFrameIndex(FI, PtrVT);
6411 }
6412
6413 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6414                                                SelectionDAG &DAG) const {
6415   SDLoc DL(Op);
6416   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6417                      DAG.getVTList(MVT::i32, MVT::Other),
6418                      Op.getOperand(0), Op.getOperand(1));
6419 }
6420
6421 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6422                                                 SelectionDAG &DAG) const {
6423   SDLoc DL(Op);
6424   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6425                      Op.getOperand(0), Op.getOperand(1));
6426 }
6427
6428 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6429   if (Op.getValueType().isVector())
6430     return LowerVectorLoad(Op, DAG);
6431
6432   assert(Op.getValueType() == MVT::i1 &&
6433          "Custom lowering only for i1 loads");
6434
6435   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6436
6437   SDLoc dl(Op);
6438   LoadSDNode *LD = cast<LoadSDNode>(Op);
6439
6440   SDValue Chain = LD->getChain();
6441   SDValue BasePtr = LD->getBasePtr();
6442   MachineMemOperand *MMO = LD->getMemOperand();
6443
6444   SDValue NewLD =
6445       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6446                      BasePtr, MVT::i8, MMO);
6447   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6448
6449   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6450   return DAG.getMergeValues(Ops, dl);
6451 }
6452
6453 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6454   if (Op.getOperand(1).getValueType().isVector())
6455     return LowerVectorStore(Op, DAG);
6456
6457   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6458          "Custom lowering only for i1 stores");
6459
6460   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6461
6462   SDLoc dl(Op);
6463   StoreSDNode *ST = cast<StoreSDNode>(Op);
6464
6465   SDValue Chain = ST->getChain();
6466   SDValue BasePtr = ST->getBasePtr();
6467   SDValue Value = ST->getValue();
6468   MachineMemOperand *MMO = ST->getMemOperand();
6469
6470   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6471                       Value);
6472   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6473 }
6474
6475 // FIXME: Remove this once the ANDI glue bug is fixed:
6476 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6477   assert(Op.getValueType() == MVT::i1 &&
6478          "Custom lowering only for i1 results");
6479
6480   SDLoc DL(Op);
6481   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6482                      Op.getOperand(0));
6483 }
6484
6485 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6486 /// possible.
6487 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6488   // Not FP? Not a fsel.
6489   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6490       !Op.getOperand(2).getValueType().isFloatingPoint())
6491     return Op;
6492
6493   // We might be able to do better than this under some circumstances, but in
6494   // general, fsel-based lowering of select is a finite-math-only optimization.
6495   // For more information, see section F.3 of the 2.06 ISA specification.
6496   if (!DAG.getTarget().Options.NoInfsFPMath ||
6497       !DAG.getTarget().Options.NoNaNsFPMath)
6498     return Op;
6499   // TODO: Propagate flags from the select rather than global settings.
6500   SDNodeFlags Flags;
6501   Flags.setNoInfs(true);
6502   Flags.setNoNaNs(true);
6503
6504   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6505
6506   EVT ResVT = Op.getValueType();
6507   EVT CmpVT = Op.getOperand(0).getValueType();
6508   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6509   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6510   SDLoc dl(Op);
6511
6512   // If the RHS of the comparison is a 0.0, we don't need to do the
6513   // subtraction at all.
6514   SDValue Sel1;
6515   if (isFloatingPointZero(RHS))
6516     switch (CC) {
6517     default: break;       // SETUO etc aren't handled by fsel.
6518     case ISD::SETNE:
6519       std::swap(TV, FV);
6520     case ISD::SETEQ:
6521       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6522         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6523       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6524       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6525         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6526       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6527                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6528     case ISD::SETULT:
6529     case ISD::SETLT:
6530       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6531     case ISD::SETOGE:
6532     case ISD::SETGE:
6533       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6534         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6535       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6536     case ISD::SETUGT:
6537     case ISD::SETGT:
6538       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6539     case ISD::SETOLE:
6540     case ISD::SETLE:
6541       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6542         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6543       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6544                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6545     }
6546
6547   SDValue Cmp;
6548   switch (CC) {
6549   default: break;       // SETUO etc aren't handled by fsel.
6550   case ISD::SETNE:
6551     std::swap(TV, FV);
6552   case ISD::SETEQ:
6553     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6554     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6555       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6556     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6557     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6558       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6559     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6560                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6561   case ISD::SETULT:
6562   case ISD::SETLT:
6563     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6564     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6565       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6566     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6567   case ISD::SETOGE:
6568   case ISD::SETGE:
6569     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6570     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6571       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6572     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6573   case ISD::SETUGT:
6574   case ISD::SETGT:
6575     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6576     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6577       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6578     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6579   case ISD::SETOLE:
6580   case ISD::SETLE:
6581     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6582     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6583       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6584     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6585   }
6586   return Op;
6587 }
6588
6589 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6590                                                SelectionDAG &DAG,
6591                                                const SDLoc &dl) const {
6592   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6593   SDValue Src = Op.getOperand(0);
6594   if (Src.getValueType() == MVT::f32)
6595     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6596
6597   SDValue Tmp;
6598   switch (Op.getSimpleValueType().SimpleTy) {
6599   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6600   case MVT::i32:
6601     Tmp = DAG.getNode(
6602         Op.getOpcode() == ISD::FP_TO_SINT
6603             ? PPCISD::FCTIWZ
6604             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6605         dl, MVT::f64, Src);
6606     break;
6607   case MVT::i64:
6608     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6609            "i64 FP_TO_UINT is supported only with FPCVT");
6610     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6611                                                         PPCISD::FCTIDUZ,
6612                       dl, MVT::f64, Src);
6613     break;
6614   }
6615
6616   // Convert the FP value to an int value through memory.
6617   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6618     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6619   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6620   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6621   MachinePointerInfo MPI =
6622       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6623
6624   // Emit a store to the stack slot.
6625   SDValue Chain;
6626   if (i32Stack) {
6627     MachineFunction &MF = DAG.getMachineFunction();
6628     MachineMemOperand *MMO =
6629       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6630     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6631     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6632               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6633   } else
6634     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6635
6636   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6637   // add in a bias on big endian.
6638   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6639     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6640                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6641     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6642   }
6643
6644   RLI.Chain = Chain;
6645   RLI.Ptr = FIPtr;
6646   RLI.MPI = MPI;
6647 }
6648
6649 /// \brief Custom lowers floating point to integer conversions to use
6650 /// the direct move instructions available in ISA 2.07 to avoid the
6651 /// need for load/store combinations.
6652 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6653                                                     SelectionDAG &DAG,
6654                                                     const SDLoc &dl) const {
6655   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6656   SDValue Src = Op.getOperand(0);
6657
6658   if (Src.getValueType() == MVT::f32)
6659     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6660
6661   SDValue Tmp;
6662   switch (Op.getSimpleValueType().SimpleTy) {
6663   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6664   case MVT::i32:
6665     Tmp = DAG.getNode(
6666         Op.getOpcode() == ISD::FP_TO_SINT
6667             ? PPCISD::FCTIWZ
6668             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6669         dl, MVT::f64, Src);
6670     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6671     break;
6672   case MVT::i64:
6673     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6674            "i64 FP_TO_UINT is supported only with FPCVT");
6675     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6676                                                         PPCISD::FCTIDUZ,
6677                       dl, MVT::f64, Src);
6678     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6679     break;
6680   }
6681   return Tmp;
6682 }
6683
6684 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6685                                           const SDLoc &dl) const {
6686   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6687     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6688
6689   ReuseLoadInfo RLI;
6690   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6691
6692   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6693                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6694 }
6695
6696 // We're trying to insert a regular store, S, and then a load, L. If the
6697 // incoming value, O, is a load, we might just be able to have our load use the
6698 // address used by O. However, we don't know if anything else will store to
6699 // that address before we can load from it. To prevent this situation, we need
6700 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6701 // the same chain operand as O, we create a token factor from the chain results
6702 // of O and L, and we replace all uses of O's chain result with that token
6703 // factor (see spliceIntoChain below for this last part).
6704 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6705                                             ReuseLoadInfo &RLI,
6706                                             SelectionDAG &DAG,
6707                                             ISD::LoadExtType ET) const {
6708   SDLoc dl(Op);
6709   if (ET == ISD::NON_EXTLOAD &&
6710       (Op.getOpcode() == ISD::FP_TO_UINT ||
6711        Op.getOpcode() == ISD::FP_TO_SINT) &&
6712       isOperationLegalOrCustom(Op.getOpcode(),
6713                                Op.getOperand(0).getValueType())) {
6714
6715     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6716     return true;
6717   }
6718
6719   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6720   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6721       LD->isNonTemporal())
6722     return false;
6723   if (LD->getMemoryVT() != MemVT)
6724     return false;
6725
6726   RLI.Ptr = LD->getBasePtr();
6727   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6728     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6729            "Non-pre-inc AM on PPC?");
6730     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6731                           LD->getOffset());
6732   }
6733
6734   RLI.Chain = LD->getChain();
6735   RLI.MPI = LD->getPointerInfo();
6736   RLI.IsDereferenceable = LD->isDereferenceable();
6737   RLI.IsInvariant = LD->isInvariant();
6738   RLI.Alignment = LD->getAlignment();
6739   RLI.AAInfo = LD->getAAInfo();
6740   RLI.Ranges = LD->getRanges();
6741
6742   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6743   return true;
6744 }
6745
6746 // Given the head of the old chain, ResChain, insert a token factor containing
6747 // it and NewResChain, and make users of ResChain now be users of that token
6748 // factor.
6749 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6750                                         SDValue NewResChain,
6751                                         SelectionDAG &DAG) const {
6752   if (!ResChain)
6753     return;
6754
6755   SDLoc dl(NewResChain);
6756
6757   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6758                            NewResChain, DAG.getUNDEF(MVT::Other));
6759   assert(TF.getNode() != NewResChain.getNode() &&
6760          "A new TF really is required here");
6761
6762   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6763   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6764 }
6765
6766 /// \brief Analyze profitability of direct move
6767 /// prefer float load to int load plus direct move
6768 /// when there is no integer use of int load
6769 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6770   SDNode *Origin = Op.getOperand(0).getNode();
6771   if (Origin->getOpcode() != ISD::LOAD)
6772     return true;
6773
6774   // If there is no LXSIBZX/LXSIHZX, like Power8,
6775   // prefer direct move if the memory size is 1 or 2 bytes.
6776   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6777   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6778     return true;
6779
6780   for (SDNode::use_iterator UI = Origin->use_begin(),
6781                             UE = Origin->use_end();
6782        UI != UE; ++UI) {
6783
6784     // Only look at the users of the loaded value.
6785     if (UI.getUse().get().getResNo() != 0)
6786       continue;
6787
6788     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6789         UI->getOpcode() != ISD::UINT_TO_FP)
6790       return true;
6791   }
6792
6793   return false;
6794 }
6795
6796 /// \brief Custom lowers integer to floating point conversions to use
6797 /// the direct move instructions available in ISA 2.07 to avoid the
6798 /// need for load/store combinations.
6799 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6800                                                     SelectionDAG &DAG,
6801                                                     const SDLoc &dl) const {
6802   assert((Op.getValueType() == MVT::f32 ||
6803           Op.getValueType() == MVT::f64) &&
6804          "Invalid floating point type as target of conversion");
6805   assert(Subtarget.hasFPCVT() &&
6806          "Int to FP conversions with direct moves require FPCVT");
6807   SDValue FP;
6808   SDValue Src = Op.getOperand(0);
6809   bool SinglePrec = Op.getValueType() == MVT::f32;
6810   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6811   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6812   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6813                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6814
6815   if (WordInt) {
6816     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6817                      dl, MVT::f64, Src);
6818     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6819   }
6820   else {
6821     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6822     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6823   }
6824
6825   return FP;
6826 }
6827
6828 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6829                                           SelectionDAG &DAG) const {
6830   SDLoc dl(Op);
6831
6832   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6833     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6834       return SDValue();
6835
6836     SDValue Value = Op.getOperand(0);
6837     // The values are now known to be -1 (false) or 1 (true). To convert this
6838     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6839     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6840     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6841
6842     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6843
6844     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6845
6846     if (Op.getValueType() != MVT::v4f64)
6847       Value = DAG.getNode(ISD::FP_ROUND, dl,
6848                           Op.getValueType(), Value,
6849                           DAG.getIntPtrConstant(1, dl));
6850     return Value;
6851   }
6852
6853   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6854   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6855     return SDValue();
6856
6857   if (Op.getOperand(0).getValueType() == MVT::i1)
6858     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6859                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6860                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6861
6862   // If we have direct moves, we can do all the conversion, skip the store/load
6863   // however, without FPCVT we can't do most conversions.
6864   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6865       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6866     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6867
6868   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6869          "UINT_TO_FP is supported only with FPCVT");
6870
6871   // If we have FCFIDS, then use it when converting to single-precision.
6872   // Otherwise, convert to double-precision and then round.
6873   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6874                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6875                                                             : PPCISD::FCFIDS)
6876                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6877                                                             : PPCISD::FCFID);
6878   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6879                   ? MVT::f32
6880                   : MVT::f64;
6881
6882   if (Op.getOperand(0).getValueType() == MVT::i64) {
6883     SDValue SINT = Op.getOperand(0);
6884     // When converting to single-precision, we actually need to convert
6885     // to double-precision first and then round to single-precision.
6886     // To avoid double-rounding effects during that operation, we have
6887     // to prepare the input operand.  Bits that might be truncated when
6888     // converting to double-precision are replaced by a bit that won't
6889     // be lost at this stage, but is below the single-precision rounding
6890     // position.
6891     //
6892     // However, if -enable-unsafe-fp-math is in effect, accept double
6893     // rounding to avoid the extra overhead.
6894     if (Op.getValueType() == MVT::f32 &&
6895         !Subtarget.hasFPCVT() &&
6896         !DAG.getTarget().Options.UnsafeFPMath) {
6897
6898       // Twiddle input to make sure the low 11 bits are zero.  (If this
6899       // is the case, we are guaranteed the value will fit into the 53 bit
6900       // mantissa of an IEEE double-precision value without rounding.)
6901       // If any of those low 11 bits were not zero originally, make sure
6902       // bit 12 (value 2048) is set instead, so that the final rounding
6903       // to single-precision gets the correct result.
6904       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6905                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6906       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6907                           Round, DAG.getConstant(2047, dl, MVT::i64));
6908       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6909       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6910                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6911
6912       // However, we cannot use that value unconditionally: if the magnitude
6913       // of the input value is small, the bit-twiddling we did above might
6914       // end up visibly changing the output.  Fortunately, in that case, we
6915       // don't need to twiddle bits since the original input will convert
6916       // exactly to double-precision floating-point already.  Therefore,
6917       // construct a conditional to use the original value if the top 11
6918       // bits are all sign-bit copies, and use the rounded value computed
6919       // above otherwise.
6920       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6921                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6922       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6923                          Cond, DAG.getConstant(1, dl, MVT::i64));
6924       Cond = DAG.getSetCC(dl, MVT::i32,
6925                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6926
6927       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6928     }
6929
6930     ReuseLoadInfo RLI;
6931     SDValue Bits;
6932
6933     MachineFunction &MF = DAG.getMachineFunction();
6934     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6935       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6936                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6937       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6938     } else if (Subtarget.hasLFIWAX() &&
6939                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6940       MachineMemOperand *MMO =
6941         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6942                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6943       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6944       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6945                                      DAG.getVTList(MVT::f64, MVT::Other),
6946                                      Ops, MVT::i32, MMO);
6947       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6948     } else if (Subtarget.hasFPCVT() &&
6949                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6950       MachineMemOperand *MMO =
6951         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6952                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6953       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6954       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6955                                      DAG.getVTList(MVT::f64, MVT::Other),
6956                                      Ops, MVT::i32, MMO);
6957       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6958     } else if (((Subtarget.hasLFIWAX() &&
6959                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6960                 (Subtarget.hasFPCVT() &&
6961                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6962                SINT.getOperand(0).getValueType() == MVT::i32) {
6963       MachineFrameInfo &MFI = MF.getFrameInfo();
6964       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6965
6966       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6967       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6968
6969       SDValue Store =
6970           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6971                        MachinePointerInfo::getFixedStack(
6972                            DAG.getMachineFunction(), FrameIdx));
6973
6974       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6975              "Expected an i32 store");
6976
6977       RLI.Ptr = FIdx;
6978       RLI.Chain = Store;
6979       RLI.MPI =
6980           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6981       RLI.Alignment = 4;
6982
6983       MachineMemOperand *MMO =
6984         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6985                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6986       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6987       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6988                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6989                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6990                                      Ops, MVT::i32, MMO);
6991     } else
6992       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6993
6994     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6995
6996     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6997       FP = DAG.getNode(ISD::FP_ROUND, dl,
6998                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6999     return FP;
7000   }
7001
7002   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
7003          "Unhandled INT_TO_FP type in custom expander!");
7004   // Since we only generate this in 64-bit mode, we can take advantage of
7005   // 64-bit registers.  In particular, sign extend the input value into the
7006   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
7007   // then lfd it and fcfid it.
7008   MachineFunction &MF = DAG.getMachineFunction();
7009   MachineFrameInfo &MFI = MF.getFrameInfo();
7010   EVT PtrVT = getPointerTy(MF.getDataLayout());
7011
7012   SDValue Ld;
7013   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
7014     ReuseLoadInfo RLI;
7015     bool ReusingLoad;
7016     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
7017                                             DAG))) {
7018       int FrameIdx = MFI.CreateStackObject(4, 4, false);
7019       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7020
7021       SDValue Store =
7022           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
7023                        MachinePointerInfo::getFixedStack(
7024                            DAG.getMachineFunction(), FrameIdx));
7025
7026       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
7027              "Expected an i32 store");
7028
7029       RLI.Ptr = FIdx;
7030       RLI.Chain = Store;
7031       RLI.MPI =
7032           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7033       RLI.Alignment = 4;
7034     }
7035
7036     MachineMemOperand *MMO =
7037       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
7038                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
7039     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
7040     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
7041                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
7042                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
7043                                  Ops, MVT::i32, MMO);
7044     if (ReusingLoad)
7045       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
7046   } else {
7047     assert(Subtarget.isPPC64() &&
7048            "i32->FP without LFIWAX supported only on PPC64");
7049
7050     int FrameIdx = MFI.CreateStackObject(8, 8, false);
7051     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7052
7053     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
7054                                 Op.getOperand(0));
7055
7056     // STD the extended value into the stack slot.
7057     SDValue Store = DAG.getStore(
7058         DAG.getEntryNode(), dl, Ext64, FIdx,
7059         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7060
7061     // Load the value as a double.
7062     Ld = DAG.getLoad(
7063         MVT::f64, dl, Store, FIdx,
7064         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
7065   }
7066
7067   // FCFID it and return it.
7068   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7069   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7070     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7071                      DAG.getIntPtrConstant(0, dl));
7072   return FP;
7073 }
7074
7075 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7076                                             SelectionDAG &DAG) const {
7077   SDLoc dl(Op);
7078   /*
7079    The rounding mode is in bits 30:31 of FPSR, and has the following
7080    settings:
7081      00 Round to nearest
7082      01 Round to 0
7083      10 Round to +inf
7084      11 Round to -inf
7085
7086   FLT_ROUNDS, on the other hand, expects the following:
7087     -1 Undefined
7088      0 Round to 0
7089      1 Round to nearest
7090      2 Round to +inf
7091      3 Round to -inf
7092
7093   To perform the conversion, we do:
7094     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7095   */
7096
7097   MachineFunction &MF = DAG.getMachineFunction();
7098   EVT VT = Op.getValueType();
7099   EVT PtrVT = getPointerTy(MF.getDataLayout());
7100
7101   // Save FP Control Word to register
7102   EVT NodeTys[] = {
7103     MVT::f64,    // return register
7104     MVT::Glue    // unused in this context
7105   };
7106   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7107
7108   // Save FP register to stack slot
7109   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7110   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7111   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7112                                MachinePointerInfo());
7113
7114   // Load FP Control Word from low 32 bits of stack slot.
7115   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7116   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7117   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7118
7119   // Transform as necessary
7120   SDValue CWD1 =
7121     DAG.getNode(ISD::AND, dl, MVT::i32,
7122                 CWD, DAG.getConstant(3, dl, MVT::i32));
7123   SDValue CWD2 =
7124     DAG.getNode(ISD::SRL, dl, MVT::i32,
7125                 DAG.getNode(ISD::AND, dl, MVT::i32,
7126                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7127                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7128                             DAG.getConstant(3, dl, MVT::i32)),
7129                 DAG.getConstant(1, dl, MVT::i32));
7130
7131   SDValue RetVal =
7132     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7133
7134   return DAG.getNode((VT.getSizeInBits() < 16 ?
7135                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7136 }
7137
7138 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7139   EVT VT = Op.getValueType();
7140   unsigned BitWidth = VT.getSizeInBits();
7141   SDLoc dl(Op);
7142   assert(Op.getNumOperands() == 3 &&
7143          VT == Op.getOperand(1).getValueType() &&
7144          "Unexpected SHL!");
7145
7146   // Expand into a bunch of logical ops.  Note that these ops
7147   // depend on the PPC behavior for oversized shift amounts.
7148   SDValue Lo = Op.getOperand(0);
7149   SDValue Hi = Op.getOperand(1);
7150   SDValue Amt = Op.getOperand(2);
7151   EVT AmtVT = Amt.getValueType();
7152
7153   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7154                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7155   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7156   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7157   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7158   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7159                              DAG.getConstant(-BitWidth, dl, AmtVT));
7160   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7161   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7162   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7163   SDValue OutOps[] = { OutLo, OutHi };
7164   return DAG.getMergeValues(OutOps, dl);
7165 }
7166
7167 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7168   EVT VT = Op.getValueType();
7169   SDLoc dl(Op);
7170   unsigned BitWidth = VT.getSizeInBits();
7171   assert(Op.getNumOperands() == 3 &&
7172          VT == Op.getOperand(1).getValueType() &&
7173          "Unexpected SRL!");
7174
7175   // Expand into a bunch of logical ops.  Note that these ops
7176   // depend on the PPC behavior for oversized shift amounts.
7177   SDValue Lo = Op.getOperand(0);
7178   SDValue Hi = Op.getOperand(1);
7179   SDValue Amt = Op.getOperand(2);
7180   EVT AmtVT = Amt.getValueType();
7181
7182   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7183                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7184   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7185   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7186   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7187   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7188                              DAG.getConstant(-BitWidth, dl, AmtVT));
7189   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7190   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7191   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7192   SDValue OutOps[] = { OutLo, OutHi };
7193   return DAG.getMergeValues(OutOps, dl);
7194 }
7195
7196 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7197   SDLoc dl(Op);
7198   EVT VT = Op.getValueType();
7199   unsigned BitWidth = VT.getSizeInBits();
7200   assert(Op.getNumOperands() == 3 &&
7201          VT == Op.getOperand(1).getValueType() &&
7202          "Unexpected SRA!");
7203
7204   // Expand into a bunch of logical ops, followed by a select_cc.
7205   SDValue Lo = Op.getOperand(0);
7206   SDValue Hi = Op.getOperand(1);
7207   SDValue Amt = Op.getOperand(2);
7208   EVT AmtVT = Amt.getValueType();
7209
7210   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7211                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7212   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7213   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7214   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7215   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7216                              DAG.getConstant(-BitWidth, dl, AmtVT));
7217   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7218   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7219   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7220                                   Tmp4, Tmp6, ISD::SETLE);
7221   SDValue OutOps[] = { OutLo, OutHi };
7222   return DAG.getMergeValues(OutOps, dl);
7223 }
7224
7225 //===----------------------------------------------------------------------===//
7226 // Vector related lowering.
7227 //
7228
7229 /// BuildSplatI - Build a canonical splati of Val with an element size of
7230 /// SplatSize.  Cast the result to VT.
7231 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7232                            SelectionDAG &DAG, const SDLoc &dl) {
7233   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7234
7235   static const MVT VTys[] = { // canonical VT to use for each size.
7236     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7237   };
7238
7239   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7240
7241   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7242   if (Val == -1)
7243     SplatSize = 1;
7244
7245   EVT CanonicalVT = VTys[SplatSize-1];
7246
7247   // Build a canonical splat for this value.
7248   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7249 }
7250
7251 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7252 /// specified intrinsic ID.
7253 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7254                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7255   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7256   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7257                      DAG.getConstant(IID, dl, MVT::i32), Op);
7258 }
7259
7260 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7261 /// specified intrinsic ID.
7262 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7263                                 SelectionDAG &DAG, const SDLoc &dl,
7264                                 EVT DestVT = MVT::Other) {
7265   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7266   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7267                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7268 }
7269
7270 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7271 /// specified intrinsic ID.
7272 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7273                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7274                                 EVT DestVT = MVT::Other) {
7275   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7276   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7277                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7278 }
7279
7280 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7281 /// amount.  The result has the specified value type.
7282 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7283                            SelectionDAG &DAG, const SDLoc &dl) {
7284   // Force LHS/RHS to be the right type.
7285   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7286   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7287
7288   int Ops[16];
7289   for (unsigned i = 0; i != 16; ++i)
7290     Ops[i] = i + Amt;
7291   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7292   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7293 }
7294
7295 /// Do we have an efficient pattern in a .td file for this node?
7296 ///
7297 /// \param V - pointer to the BuildVectorSDNode being matched
7298 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7299 ///
7300 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7301 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7302 /// the opposite is true (expansion is beneficial) are:
7303 /// - The node builds a vector out of integers that are not 32 or 64-bits
7304 /// - The node builds a vector out of constants
7305 /// - The node is a "load-and-splat"
7306 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7307 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7308                                             bool HasDirectMove) {
7309   EVT VecVT = V->getValueType(0);
7310   bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7311     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7312   if (!RightType)
7313     return false;
7314
7315   bool IsSplat = true;
7316   bool IsLoad = false;
7317   SDValue Op0 = V->getOperand(0);
7318
7319   // This function is called in a block that confirms the node is not a constant
7320   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7321   // different constants.
7322   if (V->isConstant())
7323     return false;
7324   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7325     if (V->getOperand(i).isUndef())
7326       return false;
7327     // We want to expand nodes that represent load-and-splat even if the
7328     // loaded value is a floating point truncation or conversion to int.
7329     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7330         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7331          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7332         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7333          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7334         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7335          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7336       IsLoad = true;
7337     // If the operands are different or the input is not a load and has more
7338     // uses than just this BV node, then it isn't a splat.
7339     if (V->getOperand(i) != Op0 ||
7340         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7341       IsSplat = false;
7342   }
7343   return !(IsSplat && IsLoad);
7344 }
7345
7346 // If this is a case we can't handle, return null and let the default
7347 // expansion code take care of it.  If we CAN select this case, and if it
7348 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7349 // this case more efficiently than a constant pool load, lower it to the
7350 // sequence of ops that should be used.
7351 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7352                                              SelectionDAG &DAG) const {
7353   SDLoc dl(Op);
7354   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7355   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7356
7357   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7358     // We first build an i32 vector, load it into a QPX register,
7359     // then convert it to a floating-point vector and compare it
7360     // to a zero vector to get the boolean result.
7361     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7362     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7363     MachinePointerInfo PtrInfo =
7364         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7365     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7366     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7367
7368     assert(BVN->getNumOperands() == 4 &&
7369       "BUILD_VECTOR for v4i1 does not have 4 operands");
7370
7371     bool IsConst = true;
7372     for (unsigned i = 0; i < 4; ++i) {
7373       if (BVN->getOperand(i).isUndef()) continue;
7374       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7375         IsConst = false;
7376         break;
7377       }
7378     }
7379
7380     if (IsConst) {
7381       Constant *One =
7382         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7383       Constant *NegOne =
7384         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7385
7386       Constant *CV[4];
7387       for (unsigned i = 0; i < 4; ++i) {
7388         if (BVN->getOperand(i).isUndef())
7389           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7390         else if (isNullConstant(BVN->getOperand(i)))
7391           CV[i] = NegOne;
7392         else
7393           CV[i] = One;
7394       }
7395
7396       Constant *CP = ConstantVector::get(CV);
7397       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7398                                           16 /* alignment */);
7399
7400       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7401       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7402       return DAG.getMemIntrinsicNode(
7403           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7404           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7405     }
7406
7407     SmallVector<SDValue, 4> Stores;
7408     for (unsigned i = 0; i < 4; ++i) {
7409       if (BVN->getOperand(i).isUndef()) continue;
7410
7411       unsigned Offset = 4*i;
7412       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7413       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7414
7415       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7416       if (StoreSize > 4) {
7417         Stores.push_back(
7418             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7419                               PtrInfo.getWithOffset(Offset), MVT::i32));
7420       } else {
7421         SDValue StoreValue = BVN->getOperand(i);
7422         if (StoreSize < 4)
7423           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7424
7425         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7426                                       PtrInfo.getWithOffset(Offset)));
7427       }
7428     }
7429
7430     SDValue StoreChain;
7431     if (!Stores.empty())
7432       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7433     else
7434       StoreChain = DAG.getEntryNode();
7435
7436     // Now load from v4i32 into the QPX register; this will extend it to
7437     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7438     // is typed as v4f64 because the QPX register integer states are not
7439     // explicitly represented.
7440
7441     SDValue Ops[] = {StoreChain,
7442                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7443                      FIdx};
7444     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7445
7446     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7447       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7448     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7449       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7450       LoadedVect);
7451
7452     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7453
7454     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7455   }
7456
7457   // All other QPX vectors are handled by generic code.
7458   if (Subtarget.hasQPX())
7459     return SDValue();
7460
7461   // Check if this is a splat of a constant value.
7462   APInt APSplatBits, APSplatUndef;
7463   unsigned SplatBitSize;
7464   bool HasAnyUndefs;
7465   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7466                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7467       SplatBitSize > 32) {
7468     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7469     // lowered to VSX instructions under certain conditions.
7470     // Without VSX, there is no pattern more efficient than expanding the node.
7471     if (Subtarget.hasVSX() &&
7472         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7473       return Op;
7474     return SDValue();
7475   }
7476
7477   unsigned SplatBits = APSplatBits.getZExtValue();
7478   unsigned SplatUndef = APSplatUndef.getZExtValue();
7479   unsigned SplatSize = SplatBitSize / 8;
7480
7481   // First, handle single instruction cases.
7482
7483   // All zeros?
7484   if (SplatBits == 0) {
7485     // Canonicalize all zero vectors to be v4i32.
7486     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7487       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7488       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7489     }
7490     return Op;
7491   }
7492
7493   // We have XXSPLTIB for constant splats one byte wide
7494   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7495     // This is a splat of 1-byte elements with some elements potentially undef.
7496     // Rather than trying to match undef in the SDAG patterns, ensure that all
7497     // elements are the same constant.
7498     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7499       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7500                                                        dl, MVT::i32));
7501       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7502       if (Op.getValueType() != MVT::v16i8)
7503         return DAG.getBitcast(Op.getValueType(), NewBV);
7504       return NewBV;
7505     }
7506     return Op;
7507   }
7508
7509   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7510   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7511                     (32-SplatBitSize));
7512   if (SextVal >= -16 && SextVal <= 15)
7513     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7514
7515   // Two instruction sequences.
7516
7517   // If this value is in the range [-32,30] and is even, use:
7518   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7519   // If this value is in the range [17,31] and is odd, use:
7520   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7521   // If this value is in the range [-31,-17] and is odd, use:
7522   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7523   // Note the last two are three-instruction sequences.
7524   if (SextVal >= -32 && SextVal <= 31) {
7525     // To avoid having these optimizations undone by constant folding,
7526     // we convert to a pseudo that will be expanded later into one of
7527     // the above forms.
7528     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7529     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7530               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7531     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7532     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7533     if (VT == Op.getValueType())
7534       return RetVal;
7535     else
7536       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7537   }
7538
7539   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7540   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7541   // for fneg/fabs.
7542   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7543     // Make -1 and vspltisw -1:
7544     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7545
7546     // Make the VSLW intrinsic, computing 0x8000_0000.
7547     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7548                                    OnesV, DAG, dl);
7549
7550     // xor by OnesV to invert it.
7551     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7552     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7553   }
7554
7555   // Check to see if this is a wide variety of vsplti*, binop self cases.
7556   static const signed char SplatCsts[] = {
7557     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7558     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7559   };
7560
7561   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7562     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7563     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7564     int i = SplatCsts[idx];
7565
7566     // Figure out what shift amount will be used by altivec if shifted by i in
7567     // this splat size.
7568     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7569
7570     // vsplti + shl self.
7571     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7572       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7573       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7574         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7575         Intrinsic::ppc_altivec_vslw
7576       };
7577       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7578       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7579     }
7580
7581     // vsplti + srl self.
7582     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7583       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7584       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7585         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7586         Intrinsic::ppc_altivec_vsrw
7587       };
7588       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7589       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7590     }
7591
7592     // vsplti + sra self.
7593     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7594       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7595       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7596         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7597         Intrinsic::ppc_altivec_vsraw
7598       };
7599       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7600       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7601     }
7602
7603     // vsplti + rol self.
7604     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7605                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7606       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7607       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7608         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7609         Intrinsic::ppc_altivec_vrlw
7610       };
7611       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7612       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7613     }
7614
7615     // t = vsplti c, result = vsldoi t, t, 1
7616     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7617       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7618       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7619       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7620     }
7621     // t = vsplti c, result = vsldoi t, t, 2
7622     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7623       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7624       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7625       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7626     }
7627     // t = vsplti c, result = vsldoi t, t, 3
7628     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7629       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7630       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7631       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7632     }
7633   }
7634
7635   return SDValue();
7636 }
7637
7638 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7639 /// the specified operations to build the shuffle.
7640 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7641                                       SDValue RHS, SelectionDAG &DAG,
7642                                       const SDLoc &dl) {
7643   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7644   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7645   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7646
7647   enum {
7648     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7649     OP_VMRGHW,
7650     OP_VMRGLW,
7651     OP_VSPLTISW0,
7652     OP_VSPLTISW1,
7653     OP_VSPLTISW2,
7654     OP_VSPLTISW3,
7655     OP_VSLDOI4,
7656     OP_VSLDOI8,
7657     OP_VSLDOI12
7658   };
7659
7660   if (OpNum == OP_COPY) {
7661     if (LHSID == (1*9+2)*9+3) return LHS;
7662     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7663     return RHS;
7664   }
7665
7666   SDValue OpLHS, OpRHS;
7667   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7668   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7669
7670   int ShufIdxs[16];
7671   switch (OpNum) {
7672   default: llvm_unreachable("Unknown i32 permute!");
7673   case OP_VMRGHW:
7674     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7675     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7676     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7677     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7678     break;
7679   case OP_VMRGLW:
7680     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7681     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7682     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7683     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7684     break;
7685   case OP_VSPLTISW0:
7686     for (unsigned i = 0; i != 16; ++i)
7687       ShufIdxs[i] = (i&3)+0;
7688     break;
7689   case OP_VSPLTISW1:
7690     for (unsigned i = 0; i != 16; ++i)
7691       ShufIdxs[i] = (i&3)+4;
7692     break;
7693   case OP_VSPLTISW2:
7694     for (unsigned i = 0; i != 16; ++i)
7695       ShufIdxs[i] = (i&3)+8;
7696     break;
7697   case OP_VSPLTISW3:
7698     for (unsigned i = 0; i != 16; ++i)
7699       ShufIdxs[i] = (i&3)+12;
7700     break;
7701   case OP_VSLDOI4:
7702     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7703   case OP_VSLDOI8:
7704     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7705   case OP_VSLDOI12:
7706     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7707   }
7708   EVT VT = OpLHS.getValueType();
7709   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7710   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7711   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7712   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7713 }
7714
7715 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7716 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7717 /// return the code it can be lowered into.  Worst case, it can always be
7718 /// lowered into a vperm.
7719 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7720                                                SelectionDAG &DAG) const {
7721   SDLoc dl(Op);
7722   SDValue V1 = Op.getOperand(0);
7723   SDValue V2 = Op.getOperand(1);
7724   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7725   EVT VT = Op.getValueType();
7726   bool isLittleEndian = Subtarget.isLittleEndian();
7727
7728   unsigned ShiftElts, InsertAtByte;
7729   bool Swap;
7730   if (Subtarget.hasP9Vector() &&
7731       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7732                            isLittleEndian)) {
7733     if (Swap)
7734       std::swap(V1, V2);
7735     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7736     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7737     if (ShiftElts) {
7738       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7739                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7740       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7741                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7742       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7743     }
7744     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7745                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7746     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7747   }
7748
7749
7750   if (Subtarget.hasVSX() &&
7751       PPC::isXXSLDWIShuffleMask(SVOp, ShiftElts, Swap, isLittleEndian)) {
7752     if (Swap)
7753       std::swap(V1, V2);
7754     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7755     SDValue Conv2 =
7756         DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2.isUndef() ? V1 : V2);
7757
7758     SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv1, Conv2,
7759                               DAG.getConstant(ShiftElts, dl, MVT::i32));
7760     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Shl);
7761   }
7762
7763   if (Subtarget.hasVSX()) {
7764     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7765       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7766
7767       // If the source for the shuffle is a scalar_to_vector that came from a
7768       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7769       if (Subtarget.hasP9Vector() &&
7770           ((isLittleEndian && SplatIdx == 3) ||
7771            (!isLittleEndian && SplatIdx == 0))) {
7772         SDValue Src = V1.getOperand(0);
7773         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7774             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7775             Src.getOperand(0).hasOneUse())
7776           return V1;
7777       }
7778       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7779       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7780                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7781       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7782     }
7783
7784     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7785     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7786       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7787       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7788       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7789     }
7790   }
7791
7792   if (Subtarget.hasQPX()) {
7793     if (VT.getVectorNumElements() != 4)
7794       return SDValue();
7795
7796     if (V2.isUndef()) V2 = V1;
7797
7798     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7799     if (AlignIdx != -1) {
7800       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7801                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7802     } else if (SVOp->isSplat()) {
7803       int SplatIdx = SVOp->getSplatIndex();
7804       if (SplatIdx >= 4) {
7805         std::swap(V1, V2);
7806         SplatIdx -= 4;
7807       }
7808
7809       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7810                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7811     }
7812
7813     // Lower this into a qvgpci/qvfperm pair.
7814
7815     // Compute the qvgpci literal
7816     unsigned idx = 0;
7817     for (unsigned i = 0; i < 4; ++i) {
7818       int m = SVOp->getMaskElt(i);
7819       unsigned mm = m >= 0 ? (unsigned) m : i;
7820       idx |= mm << (3-i)*3;
7821     }
7822
7823     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7824                              DAG.getConstant(idx, dl, MVT::i32));
7825     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7826   }
7827
7828   // Cases that are handled by instructions that take permute immediates
7829   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7830   // selected by the instruction selector.
7831   if (V2.isUndef()) {
7832     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7833         PPC::isSplatShuffleMask(SVOp, 2) ||
7834         PPC::isSplatShuffleMask(SVOp, 4) ||
7835         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7836         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7837         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7838         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7839         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7840         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7841         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7842         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7843         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7844         (Subtarget.hasP8Altivec() && (
7845          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7846          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7847          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7848       return Op;
7849     }
7850   }
7851
7852   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7853   // and produce a fixed permutation.  If any of these match, do not lower to
7854   // VPERM.
7855   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7856   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7857       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7858       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7859       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7860       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7861       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7862       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7863       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7864       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7865       (Subtarget.hasP8Altivec() && (
7866        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7867        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7868        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7869     return Op;
7870
7871   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7872   // perfect shuffle table to emit an optimal matching sequence.
7873   ArrayRef<int> PermMask = SVOp->getMask();
7874
7875   unsigned PFIndexes[4];
7876   bool isFourElementShuffle = true;
7877   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7878     unsigned EltNo = 8;   // Start out undef.
7879     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7880       if (PermMask[i*4+j] < 0)
7881         continue;   // Undef, ignore it.
7882
7883       unsigned ByteSource = PermMask[i*4+j];
7884       if ((ByteSource & 3) != j) {
7885         isFourElementShuffle = false;
7886         break;
7887       }
7888
7889       if (EltNo == 8) {
7890         EltNo = ByteSource/4;
7891       } else if (EltNo != ByteSource/4) {
7892         isFourElementShuffle = false;
7893         break;
7894       }
7895     }
7896     PFIndexes[i] = EltNo;
7897   }
7898
7899   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7900   // perfect shuffle vector to determine if it is cost effective to do this as
7901   // discrete instructions, or whether we should use a vperm.
7902   // For now, we skip this for little endian until such time as we have a
7903   // little-endian perfect shuffle table.
7904   if (isFourElementShuffle && !isLittleEndian) {
7905     // Compute the index in the perfect shuffle table.
7906     unsigned PFTableIndex =
7907       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7908
7909     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7910     unsigned Cost  = (PFEntry >> 30);
7911
7912     // Determining when to avoid vperm is tricky.  Many things affect the cost
7913     // of vperm, particularly how many times the perm mask needs to be computed.
7914     // For example, if the perm mask can be hoisted out of a loop or is already
7915     // used (perhaps because there are multiple permutes with the same shuffle
7916     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7917     // the loop requires an extra register.
7918     //
7919     // As a compromise, we only emit discrete instructions if the shuffle can be
7920     // generated in 3 or fewer operations.  When we have loop information
7921     // available, if this block is within a loop, we should avoid using vperm
7922     // for 3-operation perms and use a constant pool load instead.
7923     if (Cost < 3)
7924       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7925   }
7926
7927   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7928   // vector that will get spilled to the constant pool.
7929   if (V2.isUndef()) V2 = V1;
7930
7931   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7932   // that it is in input element units, not in bytes.  Convert now.
7933
7934   // For little endian, the order of the input vectors is reversed, and
7935   // the permutation mask is complemented with respect to 31.  This is
7936   // necessary to produce proper semantics with the big-endian-biased vperm
7937   // instruction.
7938   EVT EltVT = V1.getValueType().getVectorElementType();
7939   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7940
7941   SmallVector<SDValue, 16> ResultMask;
7942   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7943     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7944
7945     for (unsigned j = 0; j != BytesPerElement; ++j)
7946       if (isLittleEndian)
7947         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7948                                              dl, MVT::i32));
7949       else
7950         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7951                                              MVT::i32));
7952   }
7953
7954   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7955   if (isLittleEndian)
7956     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7957                        V2, V1, VPermMask);
7958   else
7959     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7960                        V1, V2, VPermMask);
7961 }
7962
7963 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7964 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7965 /// information about the intrinsic.
7966 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7967                                  bool &isDot, const PPCSubtarget &Subtarget) {
7968   unsigned IntrinsicID =
7969       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7970   CompareOpc = -1;
7971   isDot = false;
7972   switch (IntrinsicID) {
7973   default:
7974     return false;
7975   // Comparison predicates.
7976   case Intrinsic::ppc_altivec_vcmpbfp_p:
7977     CompareOpc = 966;
7978     isDot = true;
7979     break;
7980   case Intrinsic::ppc_altivec_vcmpeqfp_p:
7981     CompareOpc = 198;
7982     isDot = true;
7983     break;
7984   case Intrinsic::ppc_altivec_vcmpequb_p:
7985     CompareOpc = 6;
7986     isDot = true;
7987     break;
7988   case Intrinsic::ppc_altivec_vcmpequh_p:
7989     CompareOpc = 70;
7990     isDot = true;
7991     break;
7992   case Intrinsic::ppc_altivec_vcmpequw_p:
7993     CompareOpc = 134;
7994     isDot = true;
7995     break;
7996   case Intrinsic::ppc_altivec_vcmpequd_p:
7997     if (Subtarget.hasP8Altivec()) {
7998       CompareOpc = 199;
7999       isDot = true;
8000     } else
8001       return false;
8002     break;
8003   case Intrinsic::ppc_altivec_vcmpneb_p:
8004   case Intrinsic::ppc_altivec_vcmpneh_p:
8005   case Intrinsic::ppc_altivec_vcmpnew_p:
8006   case Intrinsic::ppc_altivec_vcmpnezb_p:
8007   case Intrinsic::ppc_altivec_vcmpnezh_p:
8008   case Intrinsic::ppc_altivec_vcmpnezw_p:
8009     if (Subtarget.hasP9Altivec()) {
8010       switch (IntrinsicID) {
8011       default:
8012         llvm_unreachable("Unknown comparison intrinsic.");
8013       case Intrinsic::ppc_altivec_vcmpneb_p:
8014         CompareOpc = 7;
8015         break;
8016       case Intrinsic::ppc_altivec_vcmpneh_p:
8017         CompareOpc = 71;
8018         break;
8019       case Intrinsic::ppc_altivec_vcmpnew_p:
8020         CompareOpc = 135;
8021         break;
8022       case Intrinsic::ppc_altivec_vcmpnezb_p:
8023         CompareOpc = 263;
8024         break;
8025       case Intrinsic::ppc_altivec_vcmpnezh_p:
8026         CompareOpc = 327;
8027         break;
8028       case Intrinsic::ppc_altivec_vcmpnezw_p:
8029         CompareOpc = 391;
8030         break;
8031       }
8032       isDot = true;
8033     } else
8034       return false;
8035     break;
8036   case Intrinsic::ppc_altivec_vcmpgefp_p:
8037     CompareOpc = 454;
8038     isDot = true;
8039     break;
8040   case Intrinsic::ppc_altivec_vcmpgtfp_p:
8041     CompareOpc = 710;
8042     isDot = true;
8043     break;
8044   case Intrinsic::ppc_altivec_vcmpgtsb_p:
8045     CompareOpc = 774;
8046     isDot = true;
8047     break;
8048   case Intrinsic::ppc_altivec_vcmpgtsh_p:
8049     CompareOpc = 838;
8050     isDot = true;
8051     break;
8052   case Intrinsic::ppc_altivec_vcmpgtsw_p:
8053     CompareOpc = 902;
8054     isDot = true;
8055     break;
8056   case Intrinsic::ppc_altivec_vcmpgtsd_p:
8057     if (Subtarget.hasP8Altivec()) {
8058       CompareOpc = 967;
8059       isDot = true;
8060     } else
8061       return false;
8062     break;
8063   case Intrinsic::ppc_altivec_vcmpgtub_p:
8064     CompareOpc = 518;
8065     isDot = true;
8066     break;
8067   case Intrinsic::ppc_altivec_vcmpgtuh_p:
8068     CompareOpc = 582;
8069     isDot = true;
8070     break;
8071   case Intrinsic::ppc_altivec_vcmpgtuw_p:
8072     CompareOpc = 646;
8073     isDot = true;
8074     break;
8075   case Intrinsic::ppc_altivec_vcmpgtud_p:
8076     if (Subtarget.hasP8Altivec()) {
8077       CompareOpc = 711;
8078       isDot = true;
8079     } else
8080       return false;
8081     break;
8082
8083   // VSX predicate comparisons use the same infrastructure
8084   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8085   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8086   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8087   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8088   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8089   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8090     if (Subtarget.hasVSX()) {
8091       switch (IntrinsicID) {
8092       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8093         CompareOpc = 99;
8094         break;
8095       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8096         CompareOpc = 115;
8097         break;
8098       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8099         CompareOpc = 107;
8100         break;
8101       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8102         CompareOpc = 67;
8103         break;
8104       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8105         CompareOpc = 83;
8106         break;
8107       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8108         CompareOpc = 75;
8109         break;
8110       }
8111       isDot = true;
8112     } else
8113       return false;
8114     break;
8115
8116   // Normal Comparisons.
8117   case Intrinsic::ppc_altivec_vcmpbfp:
8118     CompareOpc = 966;
8119     break;
8120   case Intrinsic::ppc_altivec_vcmpeqfp:
8121     CompareOpc = 198;
8122     break;
8123   case Intrinsic::ppc_altivec_vcmpequb:
8124     CompareOpc = 6;
8125     break;
8126   case Intrinsic::ppc_altivec_vcmpequh:
8127     CompareOpc = 70;
8128     break;
8129   case Intrinsic::ppc_altivec_vcmpequw:
8130     CompareOpc = 134;
8131     break;
8132   case Intrinsic::ppc_altivec_vcmpequd:
8133     if (Subtarget.hasP8Altivec())
8134       CompareOpc = 199;
8135     else
8136       return false;
8137     break;
8138   case Intrinsic::ppc_altivec_vcmpneb:
8139   case Intrinsic::ppc_altivec_vcmpneh:
8140   case Intrinsic::ppc_altivec_vcmpnew:
8141   case Intrinsic::ppc_altivec_vcmpnezb:
8142   case Intrinsic::ppc_altivec_vcmpnezh:
8143   case Intrinsic::ppc_altivec_vcmpnezw:
8144     if (Subtarget.hasP9Altivec())
8145       switch (IntrinsicID) {
8146       default:
8147         llvm_unreachable("Unknown comparison intrinsic.");
8148       case Intrinsic::ppc_altivec_vcmpneb:
8149         CompareOpc = 7;
8150         break;
8151       case Intrinsic::ppc_altivec_vcmpneh:
8152         CompareOpc = 71;
8153         break;
8154       case Intrinsic::ppc_altivec_vcmpnew:
8155         CompareOpc = 135;
8156         break;
8157       case Intrinsic::ppc_altivec_vcmpnezb:
8158         CompareOpc = 263;
8159         break;
8160       case Intrinsic::ppc_altivec_vcmpnezh:
8161         CompareOpc = 327;
8162         break;
8163       case Intrinsic::ppc_altivec_vcmpnezw:
8164         CompareOpc = 391;
8165         break;
8166       }
8167     else
8168       return false;
8169     break;
8170   case Intrinsic::ppc_altivec_vcmpgefp:
8171     CompareOpc = 454;
8172     break;
8173   case Intrinsic::ppc_altivec_vcmpgtfp:
8174     CompareOpc = 710;
8175     break;
8176   case Intrinsic::ppc_altivec_vcmpgtsb:
8177     CompareOpc = 774;
8178     break;
8179   case Intrinsic::ppc_altivec_vcmpgtsh:
8180     CompareOpc = 838;
8181     break;
8182   case Intrinsic::ppc_altivec_vcmpgtsw:
8183     CompareOpc = 902;
8184     break;
8185   case Intrinsic::ppc_altivec_vcmpgtsd:
8186     if (Subtarget.hasP8Altivec())
8187       CompareOpc = 967;
8188     else
8189       return false;
8190     break;
8191   case Intrinsic::ppc_altivec_vcmpgtub:
8192     CompareOpc = 518;
8193     break;
8194   case Intrinsic::ppc_altivec_vcmpgtuh:
8195     CompareOpc = 582;
8196     break;
8197   case Intrinsic::ppc_altivec_vcmpgtuw:
8198     CompareOpc = 646;
8199     break;
8200   case Intrinsic::ppc_altivec_vcmpgtud:
8201     if (Subtarget.hasP8Altivec())
8202       CompareOpc = 711;
8203     else
8204       return false;
8205     break;
8206   }
8207   return true;
8208 }
8209
8210 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8211 /// lower, do it, otherwise return null.
8212 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8213                                                    SelectionDAG &DAG) const {
8214   unsigned IntrinsicID =
8215     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8216
8217   if (IntrinsicID == Intrinsic::thread_pointer) {
8218     // Reads the thread pointer register, used for __builtin_thread_pointer.
8219     bool is64bit = Subtarget.isPPC64();
8220     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8221                            is64bit ? MVT::i64 : MVT::i32);
8222   }
8223
8224   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8225   // opcode number of the comparison.
8226   SDLoc dl(Op);
8227   int CompareOpc;
8228   bool isDot;
8229   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8230     return SDValue();    // Don't custom lower most intrinsics.
8231
8232   // If this is a non-dot comparison, make the VCMP node and we are done.
8233   if (!isDot) {
8234     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8235                               Op.getOperand(1), Op.getOperand(2),
8236                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8237     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8238   }
8239
8240   // Create the PPCISD altivec 'dot' comparison node.
8241   SDValue Ops[] = {
8242     Op.getOperand(2),  // LHS
8243     Op.getOperand(3),  // RHS
8244     DAG.getConstant(CompareOpc, dl, MVT::i32)
8245   };
8246   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8247   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8248
8249   // Now that we have the comparison, emit a copy from the CR to a GPR.
8250   // This is flagged to the above dot comparison.
8251   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8252                                 DAG.getRegister(PPC::CR6, MVT::i32),
8253                                 CompNode.getValue(1));
8254
8255   // Unpack the result based on how the target uses it.
8256   unsigned BitNo;   // Bit # of CR6.
8257   bool InvertBit;   // Invert result?
8258   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8259   default:  // Can't happen, don't crash on invalid number though.
8260   case 0:   // Return the value of the EQ bit of CR6.
8261     BitNo = 0; InvertBit = false;
8262     break;
8263   case 1:   // Return the inverted value of the EQ bit of CR6.
8264     BitNo = 0; InvertBit = true;
8265     break;
8266   case 2:   // Return the value of the LT bit of CR6.
8267     BitNo = 2; InvertBit = false;
8268     break;
8269   case 3:   // Return the inverted value of the LT bit of CR6.
8270     BitNo = 2; InvertBit = true;
8271     break;
8272   }
8273
8274   // Shift the bit into the low position.
8275   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8276                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8277   // Isolate the bit.
8278   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8279                       DAG.getConstant(1, dl, MVT::i32));
8280
8281   // If we are supposed to, toggle the bit.
8282   if (InvertBit)
8283     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8284                         DAG.getConstant(1, dl, MVT::i32));
8285   return Flags;
8286 }
8287
8288 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8289                                                SelectionDAG &DAG) const {
8290   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8291   // the beginning of the argument list.
8292   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8293   SDLoc DL(Op);
8294   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8295   case Intrinsic::ppc_cfence: {
8296     assert(ArgStart == 1 && "llvm.ppc.cfence must carry a chain argument.");
8297     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8298     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8299                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8300                                                   Op.getOperand(ArgStart + 1)),
8301                                       Op.getOperand(0)),
8302                    0);
8303   }
8304   default:
8305     break;
8306   }
8307   return SDValue();
8308 }
8309
8310 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8311                                                   SelectionDAG &DAG) const {
8312   SDLoc dl(Op);
8313   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8314   // instructions), but for smaller types, we need to first extend up to v2i32
8315   // before doing going farther.
8316   if (Op.getValueType() == MVT::v2i64) {
8317     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8318     if (ExtVT != MVT::v2i32) {
8319       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8320       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8321                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8322                                         ExtVT.getVectorElementType(), 4)));
8323       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8324       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8325                        DAG.getValueType(MVT::v2i32));
8326     }
8327
8328     return Op;
8329   }
8330
8331   return SDValue();
8332 }
8333
8334 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8335                                                  SelectionDAG &DAG) const {
8336   SDLoc dl(Op);
8337   // Create a stack slot that is 16-byte aligned.
8338   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8339   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8340   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8341   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8342
8343   // Store the input value into Value#0 of the stack slot.
8344   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8345                                MachinePointerInfo());
8346   // Load it out.
8347   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8348 }
8349
8350 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8351                                                   SelectionDAG &DAG) const {
8352   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8353          "Should only be called for ISD::INSERT_VECTOR_ELT");
8354   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8355   // We have legal lowering for constant indices but not for variable ones.
8356   if (C)
8357     return Op;
8358   return SDValue();
8359 }
8360
8361 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8362                                                    SelectionDAG &DAG) const {
8363   SDLoc dl(Op);
8364   SDNode *N = Op.getNode();
8365
8366   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8367          "Unknown extract_vector_elt type");
8368
8369   SDValue Value = N->getOperand(0);
8370
8371   // The first part of this is like the store lowering except that we don't
8372   // need to track the chain.
8373
8374   // The values are now known to be -1 (false) or 1 (true). To convert this
8375   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8376   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8377   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8378
8379   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8380   // understand how to form the extending load.
8381   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8382
8383   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8384
8385   // Now convert to an integer and store.
8386   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8387     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8388     Value);
8389
8390   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8391   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8392   MachinePointerInfo PtrInfo =
8393       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8394   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8395   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8396
8397   SDValue StoreChain = DAG.getEntryNode();
8398   SDValue Ops[] = {StoreChain,
8399                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8400                    Value, FIdx};
8401   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8402
8403   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8404     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8405
8406   // Extract the value requested.
8407   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8408   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8409   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8410
8411   SDValue IntVal =
8412       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8413
8414   if (!Subtarget.useCRBits())
8415     return IntVal;
8416
8417   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8418 }
8419
8420 /// Lowering for QPX v4i1 loads
8421 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8422                                            SelectionDAG &DAG) const {
8423   SDLoc dl(Op);
8424   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8425   SDValue LoadChain = LN->getChain();
8426   SDValue BasePtr = LN->getBasePtr();
8427
8428   if (Op.getValueType() == MVT::v4f64 ||
8429       Op.getValueType() == MVT::v4f32) {
8430     EVT MemVT = LN->getMemoryVT();
8431     unsigned Alignment = LN->getAlignment();
8432
8433     // If this load is properly aligned, then it is legal.
8434     if (Alignment >= MemVT.getStoreSize())
8435       return Op;
8436
8437     EVT ScalarVT = Op.getValueType().getScalarType(),
8438         ScalarMemVT = MemVT.getScalarType();
8439     unsigned Stride = ScalarMemVT.getStoreSize();
8440
8441     SDValue Vals[4], LoadChains[4];
8442     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8443       SDValue Load;
8444       if (ScalarVT != ScalarMemVT)
8445         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8446                               BasePtr,
8447                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8448                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8449                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8450       else
8451         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8452                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8453                            MinAlign(Alignment, Idx * Stride),
8454                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8455
8456       if (Idx == 0 && LN->isIndexed()) {
8457         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8458                "Unknown addressing mode on vector load");
8459         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8460                                   LN->getAddressingMode());
8461       }
8462
8463       Vals[Idx] = Load;
8464       LoadChains[Idx] = Load.getValue(1);
8465
8466       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8467                             DAG.getConstant(Stride, dl,
8468                                             BasePtr.getValueType()));
8469     }
8470
8471     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8472     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8473
8474     if (LN->isIndexed()) {
8475       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8476       return DAG.getMergeValues(RetOps, dl);
8477     }
8478
8479     SDValue RetOps[] = { Value, TF };
8480     return DAG.getMergeValues(RetOps, dl);
8481   }
8482
8483   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8484   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8485
8486   // To lower v4i1 from a byte array, we load the byte elements of the
8487   // vector and then reuse the BUILD_VECTOR logic.
8488
8489   SDValue VectElmts[4], VectElmtChains[4];
8490   for (unsigned i = 0; i < 4; ++i) {
8491     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8492     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8493
8494     VectElmts[i] = DAG.getExtLoad(
8495         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8496         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8497         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8498     VectElmtChains[i] = VectElmts[i].getValue(1);
8499   }
8500
8501   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8502   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8503
8504   SDValue RVals[] = { Value, LoadChain };
8505   return DAG.getMergeValues(RVals, dl);
8506 }
8507
8508 /// Lowering for QPX v4i1 stores
8509 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8510                                             SelectionDAG &DAG) const {
8511   SDLoc dl(Op);
8512   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8513   SDValue StoreChain = SN->getChain();
8514   SDValue BasePtr = SN->getBasePtr();
8515   SDValue Value = SN->getValue();
8516
8517   if (Value.getValueType() == MVT::v4f64 ||
8518       Value.getValueType() == MVT::v4f32) {
8519     EVT MemVT = SN->getMemoryVT();
8520     unsigned Alignment = SN->getAlignment();
8521
8522     // If this store is properly aligned, then it is legal.
8523     if (Alignment >= MemVT.getStoreSize())
8524       return Op;
8525
8526     EVT ScalarVT = Value.getValueType().getScalarType(),
8527         ScalarMemVT = MemVT.getScalarType();
8528     unsigned Stride = ScalarMemVT.getStoreSize();
8529
8530     SDValue Stores[4];
8531     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8532       SDValue Ex = DAG.getNode(
8533           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8534           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8535       SDValue Store;
8536       if (ScalarVT != ScalarMemVT)
8537         Store =
8538             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8539                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8540                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8541                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8542       else
8543         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8544                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8545                              MinAlign(Alignment, Idx * Stride),
8546                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8547
8548       if (Idx == 0 && SN->isIndexed()) {
8549         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8550                "Unknown addressing mode on vector store");
8551         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8552                                     SN->getAddressingMode());
8553       }
8554
8555       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8556                             DAG.getConstant(Stride, dl,
8557                                             BasePtr.getValueType()));
8558       Stores[Idx] = Store;
8559     }
8560
8561     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8562
8563     if (SN->isIndexed()) {
8564       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8565       return DAG.getMergeValues(RetOps, dl);
8566     }
8567
8568     return TF;
8569   }
8570
8571   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8572   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8573
8574   // The values are now known to be -1 (false) or 1 (true). To convert this
8575   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8576   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8577   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8578
8579   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8580   // understand how to form the extending load.
8581   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8582
8583   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8584
8585   // Now convert to an integer and store.
8586   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8587     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8588     Value);
8589
8590   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8591   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8592   MachinePointerInfo PtrInfo =
8593       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8594   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8595   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8596
8597   SDValue Ops[] = {StoreChain,
8598                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8599                    Value, FIdx};
8600   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8601
8602   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8603     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8604
8605   // Move data into the byte array.
8606   SDValue Loads[4], LoadChains[4];
8607   for (unsigned i = 0; i < 4; ++i) {
8608     unsigned Offset = 4*i;
8609     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8610     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8611
8612     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8613                            PtrInfo.getWithOffset(Offset));
8614     LoadChains[i] = Loads[i].getValue(1);
8615   }
8616
8617   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8618
8619   SDValue Stores[4];
8620   for (unsigned i = 0; i < 4; ++i) {
8621     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8622     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8623
8624     Stores[i] = DAG.getTruncStore(
8625         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8626         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8627         SN->getAAInfo());
8628   }
8629
8630   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8631
8632   return StoreChain;
8633 }
8634
8635 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8636   SDLoc dl(Op);
8637   if (Op.getValueType() == MVT::v4i32) {
8638     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8639
8640     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8641     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8642
8643     SDValue RHSSwap =   // = vrlw RHS, 16
8644       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8645
8646     // Shrinkify inputs to v8i16.
8647     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8648     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8649     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8650
8651     // Low parts multiplied together, generating 32-bit results (we ignore the
8652     // top parts).
8653     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8654                                         LHS, RHS, DAG, dl, MVT::v4i32);
8655
8656     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8657                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8658     // Shift the high parts up 16 bits.
8659     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8660                               Neg16, DAG, dl);
8661     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8662   } else if (Op.getValueType() == MVT::v8i16) {
8663     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8664
8665     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8666
8667     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8668                             LHS, RHS, Zero, DAG, dl);
8669   } else if (Op.getValueType() == MVT::v16i8) {
8670     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8671     bool isLittleEndian = Subtarget.isLittleEndian();
8672
8673     // Multiply the even 8-bit parts, producing 16-bit sums.
8674     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8675                                            LHS, RHS, DAG, dl, MVT::v8i16);
8676     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8677
8678     // Multiply the odd 8-bit parts, producing 16-bit sums.
8679     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8680                                           LHS, RHS, DAG, dl, MVT::v8i16);
8681     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8682
8683     // Merge the results together.  Because vmuleub and vmuloub are
8684     // instructions with a big-endian bias, we must reverse the
8685     // element numbering and reverse the meaning of "odd" and "even"
8686     // when generating little endian code.
8687     int Ops[16];
8688     for (unsigned i = 0; i != 8; ++i) {
8689       if (isLittleEndian) {
8690         Ops[i*2  ] = 2*i;
8691         Ops[i*2+1] = 2*i+16;
8692       } else {
8693         Ops[i*2  ] = 2*i+1;
8694         Ops[i*2+1] = 2*i+1+16;
8695       }
8696     }
8697     if (isLittleEndian)
8698       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8699     else
8700       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8701   } else {
8702     llvm_unreachable("Unknown mul to lower!");
8703   }
8704 }
8705
8706 /// LowerOperation - Provide custom lowering hooks for some operations.
8707 ///
8708 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8709   switch (Op.getOpcode()) {
8710   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8711   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8712   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8713   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8714   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8715   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8716   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8717   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8718   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8719   case ISD::VASTART:
8720     return LowerVASTART(Op, DAG);
8721
8722   case ISD::VAARG:
8723     return LowerVAARG(Op, DAG);
8724
8725   case ISD::VACOPY:
8726     return LowerVACOPY(Op, DAG);
8727
8728   case ISD::STACKRESTORE:
8729     return LowerSTACKRESTORE(Op, DAG);
8730
8731   case ISD::DYNAMIC_STACKALLOC:
8732     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8733
8734   case ISD::GET_DYNAMIC_AREA_OFFSET:
8735     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8736
8737   case ISD::EH_DWARF_CFA:
8738     return LowerEH_DWARF_CFA(Op, DAG);
8739
8740   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8741   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8742
8743   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8744   case ISD::STORE:              return LowerSTORE(Op, DAG);
8745   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8746   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8747   case ISD::FP_TO_UINT:
8748   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8749                                                       SDLoc(Op));
8750   case ISD::UINT_TO_FP:
8751   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8752   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8753
8754   // Lower 64-bit shifts.
8755   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8756   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8757   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8758
8759   // Vector-related lowering.
8760   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8761   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8762   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8763   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8764   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8765   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8766   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8767   case ISD::MUL:                return LowerMUL(Op, DAG);
8768
8769   // For counter-based loop handling.
8770   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8771
8772   // Frame & Return address.
8773   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8774   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8775
8776   case ISD::INTRINSIC_VOID:
8777     return LowerINTRINSIC_VOID(Op, DAG);
8778   }
8779 }
8780
8781 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8782                                            SmallVectorImpl<SDValue>&Results,
8783                                            SelectionDAG &DAG) const {
8784   SDLoc dl(N);
8785   switch (N->getOpcode()) {
8786   default:
8787     llvm_unreachable("Do not know how to custom type legalize this operation!");
8788   case ISD::READCYCLECOUNTER: {
8789     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8790     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8791
8792     Results.push_back(RTB);
8793     Results.push_back(RTB.getValue(1));
8794     Results.push_back(RTB.getValue(2));
8795     break;
8796   }
8797   case ISD::INTRINSIC_W_CHAIN: {
8798     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8799         Intrinsic::ppc_is_decremented_ctr_nonzero)
8800       break;
8801
8802     assert(N->getValueType(0) == MVT::i1 &&
8803            "Unexpected result type for CTR decrement intrinsic");
8804     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8805                                  N->getValueType(0));
8806     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8807     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8808                                  N->getOperand(1));
8809
8810     Results.push_back(NewInt);
8811     Results.push_back(NewInt.getValue(1));
8812     break;
8813   }
8814   case ISD::VAARG: {
8815     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8816       return;
8817
8818     EVT VT = N->getValueType(0);
8819
8820     if (VT == MVT::i64) {
8821       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8822
8823       Results.push_back(NewNode);
8824       Results.push_back(NewNode.getValue(1));
8825     }
8826     return;
8827   }
8828   case ISD::FP_ROUND_INREG: {
8829     assert(N->getValueType(0) == MVT::ppcf128);
8830     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8831     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8832                              MVT::f64, N->getOperand(0),
8833                              DAG.getIntPtrConstant(0, dl));
8834     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8835                              MVT::f64, N->getOperand(0),
8836                              DAG.getIntPtrConstant(1, dl));
8837
8838     // Add the two halves of the long double in round-to-zero mode.
8839     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8840
8841     // We know the low half is about to be thrown away, so just use something
8842     // convenient.
8843     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8844                                 FPreg, FPreg));
8845     return;
8846   }
8847   case ISD::FP_TO_SINT:
8848   case ISD::FP_TO_UINT:
8849     // LowerFP_TO_INT() can only handle f32 and f64.
8850     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8851       return;
8852     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8853     return;
8854   }
8855 }
8856
8857 //===----------------------------------------------------------------------===//
8858 //  Other Lowering Code
8859 //===----------------------------------------------------------------------===//
8860
8861 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8862   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8863   Function *Func = Intrinsic::getDeclaration(M, Id);
8864   return Builder.CreateCall(Func, {});
8865 }
8866
8867 // The mappings for emitLeading/TrailingFence is taken from
8868 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8869 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8870                                                  Instruction *Inst,
8871                                                  AtomicOrdering Ord) const {
8872   if (Ord == AtomicOrdering::SequentiallyConsistent)
8873     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8874   if (isReleaseOrStronger(Ord))
8875     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8876   return nullptr;
8877 }
8878
8879 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8880                                                   Instruction *Inst,
8881                                                   AtomicOrdering Ord) const {
8882   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
8883     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8884     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8885     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8886     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
8887       return Builder.CreateCall(
8888           Intrinsic::getDeclaration(
8889               Builder.GetInsertBlock()->getParent()->getParent(),
8890               Intrinsic::ppc_cfence, {Inst->getType()}),
8891           {Inst});
8892     // FIXME: Can use isync for rmw operation.
8893     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8894   }
8895   return nullptr;
8896 }
8897
8898 MachineBasicBlock *
8899 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8900                                     unsigned AtomicSize,
8901                                     unsigned BinOpcode,
8902                                     unsigned CmpOpcode,
8903                                     unsigned CmpPred) const {
8904   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8905   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8906
8907   auto LoadMnemonic = PPC::LDARX;
8908   auto StoreMnemonic = PPC::STDCX;
8909   switch (AtomicSize) {
8910   default:
8911     llvm_unreachable("Unexpected size of atomic entity");
8912   case 1:
8913     LoadMnemonic = PPC::LBARX;
8914     StoreMnemonic = PPC::STBCX;
8915     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8916     break;
8917   case 2:
8918     LoadMnemonic = PPC::LHARX;
8919     StoreMnemonic = PPC::STHCX;
8920     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8921     break;
8922   case 4:
8923     LoadMnemonic = PPC::LWARX;
8924     StoreMnemonic = PPC::STWCX;
8925     break;
8926   case 8:
8927     LoadMnemonic = PPC::LDARX;
8928     StoreMnemonic = PPC::STDCX;
8929     break;
8930   }
8931
8932   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8933   MachineFunction *F = BB->getParent();
8934   MachineFunction::iterator It = ++BB->getIterator();
8935
8936   unsigned dest = MI.getOperand(0).getReg();
8937   unsigned ptrA = MI.getOperand(1).getReg();
8938   unsigned ptrB = MI.getOperand(2).getReg();
8939   unsigned incr = MI.getOperand(3).getReg();
8940   DebugLoc dl = MI.getDebugLoc();
8941
8942   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8943   MachineBasicBlock *loop2MBB =
8944     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8945   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8946   F->insert(It, loopMBB);
8947   if (CmpOpcode)
8948     F->insert(It, loop2MBB);
8949   F->insert(It, exitMBB);
8950   exitMBB->splice(exitMBB->begin(), BB,
8951                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8952   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8953
8954   MachineRegisterInfo &RegInfo = F->getRegInfo();
8955   unsigned TmpReg = (!BinOpcode) ? incr :
8956     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8957                                            : &PPC::GPRCRegClass);
8958
8959   //  thisMBB:
8960   //   ...
8961   //   fallthrough --> loopMBB
8962   BB->addSuccessor(loopMBB);
8963
8964   //  loopMBB:
8965   //   l[wd]arx dest, ptr
8966   //   add r0, dest, incr
8967   //   st[wd]cx. r0, ptr
8968   //   bne- loopMBB
8969   //   fallthrough --> exitMBB
8970
8971   // For max/min...
8972   //  loopMBB:
8973   //   l[wd]arx dest, ptr
8974   //   cmpl?[wd] incr, dest
8975   //   bgt exitMBB
8976   //  loop2MBB:
8977   //   st[wd]cx. dest, ptr
8978   //   bne- loopMBB
8979   //   fallthrough --> exitMBB
8980
8981   BB = loopMBB;
8982   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8983     .addReg(ptrA).addReg(ptrB);
8984   if (BinOpcode)
8985     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8986   if (CmpOpcode) {
8987     // Signed comparisons of byte or halfword values must be sign-extended.
8988     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8989       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8990       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8991               ExtReg).addReg(dest);
8992       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8993         .addReg(incr).addReg(ExtReg);
8994     } else
8995       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8996         .addReg(incr).addReg(dest);
8997
8998     BuildMI(BB, dl, TII->get(PPC::BCC))
8999       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9000     BB->addSuccessor(loop2MBB);
9001     BB->addSuccessor(exitMBB);
9002     BB = loop2MBB;
9003   }
9004   BuildMI(BB, dl, TII->get(StoreMnemonic))
9005     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
9006   BuildMI(BB, dl, TII->get(PPC::BCC))
9007     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9008   BB->addSuccessor(loopMBB);
9009   BB->addSuccessor(exitMBB);
9010
9011   //  exitMBB:
9012   //   ...
9013   BB = exitMBB;
9014   return BB;
9015 }
9016
9017 MachineBasicBlock *
9018 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
9019                                             MachineBasicBlock *BB,
9020                                             bool is8bit, // operation
9021                                             unsigned BinOpcode,
9022                                             unsigned CmpOpcode,
9023                                             unsigned CmpPred) const {
9024   // If we support part-word atomic mnemonics, just use them
9025   if (Subtarget.hasPartwordAtomics())
9026     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
9027                             CmpOpcode, CmpPred);
9028
9029   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
9030   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9031   // In 64 bit mode we have to use 64 bits for addresses, even though the
9032   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
9033   // registers without caring whether they're 32 or 64, but here we're
9034   // doing actual arithmetic on the addresses.
9035   bool is64bit = Subtarget.isPPC64();
9036   bool isLittleEndian = Subtarget.isLittleEndian();
9037   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9038
9039   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9040   MachineFunction *F = BB->getParent();
9041   MachineFunction::iterator It = ++BB->getIterator();
9042
9043   unsigned dest = MI.getOperand(0).getReg();
9044   unsigned ptrA = MI.getOperand(1).getReg();
9045   unsigned ptrB = MI.getOperand(2).getReg();
9046   unsigned incr = MI.getOperand(3).getReg();
9047   DebugLoc dl = MI.getDebugLoc();
9048
9049   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
9050   MachineBasicBlock *loop2MBB =
9051     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
9052   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9053   F->insert(It, loopMBB);
9054   if (CmpOpcode)
9055     F->insert(It, loop2MBB);
9056   F->insert(It, exitMBB);
9057   exitMBB->splice(exitMBB->begin(), BB,
9058                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9059   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9060
9061   MachineRegisterInfo &RegInfo = F->getRegInfo();
9062   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9063                                           : &PPC::GPRCRegClass;
9064   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9065   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9066   unsigned ShiftReg =
9067     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9068   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
9069   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9070   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9071   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9072   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9073   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
9074   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9075   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9076   unsigned Ptr1Reg;
9077   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
9078
9079   //  thisMBB:
9080   //   ...
9081   //   fallthrough --> loopMBB
9082   BB->addSuccessor(loopMBB);
9083
9084   // The 4-byte load must be aligned, while a char or short may be
9085   // anywhere in the word.  Hence all this nasty bookkeeping code.
9086   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9087   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9088   //   xori shift, shift1, 24 [16]
9089   //   rlwinm ptr, ptr1, 0, 0, 29
9090   //   slw incr2, incr, shift
9091   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9092   //   slw mask, mask2, shift
9093   //  loopMBB:
9094   //   lwarx tmpDest, ptr
9095   //   add tmp, tmpDest, incr2
9096   //   andc tmp2, tmpDest, mask
9097   //   and tmp3, tmp, mask
9098   //   or tmp4, tmp3, tmp2
9099   //   stwcx. tmp4, ptr
9100   //   bne- loopMBB
9101   //   fallthrough --> exitMBB
9102   //   srw dest, tmpDest, shift
9103   if (ptrA != ZeroReg) {
9104     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9105     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9106       .addReg(ptrA).addReg(ptrB);
9107   } else {
9108     Ptr1Reg = ptrB;
9109   }
9110   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9111       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9112   if (!isLittleEndian)
9113     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9114         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9115   if (is64bit)
9116     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9117       .addReg(Ptr1Reg).addImm(0).addImm(61);
9118   else
9119     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9120       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9121   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9122       .addReg(incr).addReg(ShiftReg);
9123   if (is8bit)
9124     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9125   else {
9126     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9127     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9128   }
9129   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9130       .addReg(Mask2Reg).addReg(ShiftReg);
9131
9132   BB = loopMBB;
9133   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9134     .addReg(ZeroReg).addReg(PtrReg);
9135   if (BinOpcode)
9136     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9137       .addReg(Incr2Reg).addReg(TmpDestReg);
9138   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9139     .addReg(TmpDestReg).addReg(MaskReg);
9140   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9141     .addReg(TmpReg).addReg(MaskReg);
9142   if (CmpOpcode) {
9143     // For unsigned comparisons, we can directly compare the shifted values.
9144     // For signed comparisons we shift and sign extend.
9145     unsigned SReg = RegInfo.createVirtualRegister(RC);
9146     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9147       .addReg(TmpDestReg).addReg(MaskReg);
9148     unsigned ValueReg = SReg;
9149     unsigned CmpReg = Incr2Reg;
9150     if (CmpOpcode == PPC::CMPW) {
9151       ValueReg = RegInfo.createVirtualRegister(RC);
9152       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9153         .addReg(SReg).addReg(ShiftReg);
9154       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9155       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9156         .addReg(ValueReg);
9157       ValueReg = ValueSReg;
9158       CmpReg = incr;
9159     }
9160     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9161       .addReg(CmpReg).addReg(ValueReg);
9162     BuildMI(BB, dl, TII->get(PPC::BCC))
9163       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9164     BB->addSuccessor(loop2MBB);
9165     BB->addSuccessor(exitMBB);
9166     BB = loop2MBB;
9167   }
9168   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9169     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9170   BuildMI(BB, dl, TII->get(PPC::STWCX))
9171     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9172   BuildMI(BB, dl, TII->get(PPC::BCC))
9173     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9174   BB->addSuccessor(loopMBB);
9175   BB->addSuccessor(exitMBB);
9176
9177   //  exitMBB:
9178   //   ...
9179   BB = exitMBB;
9180   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9181     .addReg(ShiftReg);
9182   return BB;
9183 }
9184
9185 llvm::MachineBasicBlock *
9186 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9187                                     MachineBasicBlock *MBB) const {
9188   DebugLoc DL = MI.getDebugLoc();
9189   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9190   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9191
9192   MachineFunction *MF = MBB->getParent();
9193   MachineRegisterInfo &MRI = MF->getRegInfo();
9194
9195   const BasicBlock *BB = MBB->getBasicBlock();
9196   MachineFunction::iterator I = ++MBB->getIterator();
9197
9198   // Memory Reference
9199   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9200   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9201
9202   unsigned DstReg = MI.getOperand(0).getReg();
9203   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9204   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9205   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9206   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9207
9208   MVT PVT = getPointerTy(MF->getDataLayout());
9209   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9210          "Invalid Pointer Size!");
9211   // For v = setjmp(buf), we generate
9212   //
9213   // thisMBB:
9214   //  SjLjSetup mainMBB
9215   //  bl mainMBB
9216   //  v_restore = 1
9217   //  b sinkMBB
9218   //
9219   // mainMBB:
9220   //  buf[LabelOffset] = LR
9221   //  v_main = 0
9222   //
9223   // sinkMBB:
9224   //  v = phi(main, restore)
9225   //
9226
9227   MachineBasicBlock *thisMBB = MBB;
9228   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9229   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9230   MF->insert(I, mainMBB);
9231   MF->insert(I, sinkMBB);
9232
9233   MachineInstrBuilder MIB;
9234
9235   // Transfer the remainder of BB and its successor edges to sinkMBB.
9236   sinkMBB->splice(sinkMBB->begin(), MBB,
9237                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9238   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9239
9240   // Note that the structure of the jmp_buf used here is not compatible
9241   // with that used by libc, and is not designed to be. Specifically, it
9242   // stores only those 'reserved' registers that LLVM does not otherwise
9243   // understand how to spill. Also, by convention, by the time this
9244   // intrinsic is called, Clang has already stored the frame address in the
9245   // first slot of the buffer and stack address in the third. Following the
9246   // X86 target code, we'll store the jump address in the second slot. We also
9247   // need to save the TOC pointer (R2) to handle jumps between shared
9248   // libraries, and that will be stored in the fourth slot. The thread
9249   // identifier (R13) is not affected.
9250
9251   // thisMBB:
9252   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9253   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9254   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9255
9256   // Prepare IP either in reg.
9257   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9258   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9259   unsigned BufReg = MI.getOperand(1).getReg();
9260
9261   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9262     setUsesTOCBasePtr(*MBB->getParent());
9263     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9264             .addReg(PPC::X2)
9265             .addImm(TOCOffset)
9266             .addReg(BufReg);
9267     MIB.setMemRefs(MMOBegin, MMOEnd);
9268   }
9269
9270   // Naked functions never have a base pointer, and so we use r1. For all
9271   // other functions, this decision must be delayed until during PEI.
9272   unsigned BaseReg;
9273   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9274     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9275   else
9276     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9277
9278   MIB = BuildMI(*thisMBB, MI, DL,
9279                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9280             .addReg(BaseReg)
9281             .addImm(BPOffset)
9282             .addReg(BufReg);
9283   MIB.setMemRefs(MMOBegin, MMOEnd);
9284
9285   // Setup
9286   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9287   MIB.addRegMask(TRI->getNoPreservedMask());
9288
9289   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9290
9291   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9292           .addMBB(mainMBB);
9293   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9294
9295   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9296   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9297
9298   // mainMBB:
9299   //  mainDstReg = 0
9300   MIB =
9301       BuildMI(mainMBB, DL,
9302               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9303
9304   // Store IP
9305   if (Subtarget.isPPC64()) {
9306     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9307             .addReg(LabelReg)
9308             .addImm(LabelOffset)
9309             .addReg(BufReg);
9310   } else {
9311     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9312             .addReg(LabelReg)
9313             .addImm(LabelOffset)
9314             .addReg(BufReg);
9315   }
9316
9317   MIB.setMemRefs(MMOBegin, MMOEnd);
9318
9319   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9320   mainMBB->addSuccessor(sinkMBB);
9321
9322   // sinkMBB:
9323   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9324           TII->get(PPC::PHI), DstReg)
9325     .addReg(mainDstReg).addMBB(mainMBB)
9326     .addReg(restoreDstReg).addMBB(thisMBB);
9327
9328   MI.eraseFromParent();
9329   return sinkMBB;
9330 }
9331
9332 MachineBasicBlock *
9333 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9334                                      MachineBasicBlock *MBB) const {
9335   DebugLoc DL = MI.getDebugLoc();
9336   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9337
9338   MachineFunction *MF = MBB->getParent();
9339   MachineRegisterInfo &MRI = MF->getRegInfo();
9340
9341   // Memory Reference
9342   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9343   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9344
9345   MVT PVT = getPointerTy(MF->getDataLayout());
9346   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9347          "Invalid Pointer Size!");
9348
9349   const TargetRegisterClass *RC =
9350     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9351   unsigned Tmp = MRI.createVirtualRegister(RC);
9352   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9353   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9354   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9355   unsigned BP =
9356       (PVT == MVT::i64)
9357           ? PPC::X30
9358           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9359                                                               : PPC::R30);
9360
9361   MachineInstrBuilder MIB;
9362
9363   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9364   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9365   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9366   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9367
9368   unsigned BufReg = MI.getOperand(0).getReg();
9369
9370   // Reload FP (the jumped-to function may not have had a
9371   // frame pointer, and if so, then its r31 will be restored
9372   // as necessary).
9373   if (PVT == MVT::i64) {
9374     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9375             .addImm(0)
9376             .addReg(BufReg);
9377   } else {
9378     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9379             .addImm(0)
9380             .addReg(BufReg);
9381   }
9382   MIB.setMemRefs(MMOBegin, MMOEnd);
9383
9384   // Reload IP
9385   if (PVT == MVT::i64) {
9386     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9387             .addImm(LabelOffset)
9388             .addReg(BufReg);
9389   } else {
9390     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9391             .addImm(LabelOffset)
9392             .addReg(BufReg);
9393   }
9394   MIB.setMemRefs(MMOBegin, MMOEnd);
9395
9396   // Reload SP
9397   if (PVT == MVT::i64) {
9398     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9399             .addImm(SPOffset)
9400             .addReg(BufReg);
9401   } else {
9402     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9403             .addImm(SPOffset)
9404             .addReg(BufReg);
9405   }
9406   MIB.setMemRefs(MMOBegin, MMOEnd);
9407
9408   // Reload BP
9409   if (PVT == MVT::i64) {
9410     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9411             .addImm(BPOffset)
9412             .addReg(BufReg);
9413   } else {
9414     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9415             .addImm(BPOffset)
9416             .addReg(BufReg);
9417   }
9418   MIB.setMemRefs(MMOBegin, MMOEnd);
9419
9420   // Reload TOC
9421   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9422     setUsesTOCBasePtr(*MBB->getParent());
9423     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9424             .addImm(TOCOffset)
9425             .addReg(BufReg);
9426
9427     MIB.setMemRefs(MMOBegin, MMOEnd);
9428   }
9429
9430   // Jump
9431   BuildMI(*MBB, MI, DL,
9432           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9433   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9434
9435   MI.eraseFromParent();
9436   return MBB;
9437 }
9438
9439 MachineBasicBlock *
9440 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9441                                                MachineBasicBlock *BB) const {
9442   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9443       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9444     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9445         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9446       // Call lowering should have added an r2 operand to indicate a dependence
9447       // on the TOC base pointer value. It can't however, because there is no
9448       // way to mark the dependence as implicit there, and so the stackmap code
9449       // will confuse it with a regular operand. Instead, add the dependence
9450       // here.
9451       setUsesTOCBasePtr(*BB->getParent());
9452       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9453     }
9454
9455     return emitPatchPoint(MI, BB);
9456   }
9457
9458   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9459       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9460     return emitEHSjLjSetJmp(MI, BB);
9461   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9462              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9463     return emitEHSjLjLongJmp(MI, BB);
9464   }
9465
9466   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9467
9468   // To "insert" these instructions we actually have to insert their
9469   // control-flow patterns.
9470   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9471   MachineFunction::iterator It = ++BB->getIterator();
9472
9473   MachineFunction *F = BB->getParent();
9474
9475   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9476        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9477        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9478     SmallVector<MachineOperand, 2> Cond;
9479     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9480         MI.getOpcode() == PPC::SELECT_CC_I8)
9481       Cond.push_back(MI.getOperand(4));
9482     else
9483       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9484     Cond.push_back(MI.getOperand(1));
9485
9486     DebugLoc dl = MI.getDebugLoc();
9487     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9488                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9489   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9490              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9491              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9492              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9493              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9494              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9495              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9496              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9497              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9498              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9499              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9500              MI.getOpcode() == PPC::SELECT_I4 ||
9501              MI.getOpcode() == PPC::SELECT_I8 ||
9502              MI.getOpcode() == PPC::SELECT_F4 ||
9503              MI.getOpcode() == PPC::SELECT_F8 ||
9504              MI.getOpcode() == PPC::SELECT_QFRC ||
9505              MI.getOpcode() == PPC::SELECT_QSRC ||
9506              MI.getOpcode() == PPC::SELECT_QBRC ||
9507              MI.getOpcode() == PPC::SELECT_VRRC ||
9508              MI.getOpcode() == PPC::SELECT_VSFRC ||
9509              MI.getOpcode() == PPC::SELECT_VSSRC ||
9510              MI.getOpcode() == PPC::SELECT_VSRC) {
9511     // The incoming instruction knows the destination vreg to set, the
9512     // condition code register to branch on, the true/false values to
9513     // select between, and a branch opcode to use.
9514
9515     //  thisMBB:
9516     //  ...
9517     //   TrueVal = ...
9518     //   cmpTY ccX, r1, r2
9519     //   bCC copy1MBB
9520     //   fallthrough --> copy0MBB
9521     MachineBasicBlock *thisMBB = BB;
9522     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9523     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9524     DebugLoc dl = MI.getDebugLoc();
9525     F->insert(It, copy0MBB);
9526     F->insert(It, sinkMBB);
9527
9528     // Transfer the remainder of BB and its successor edges to sinkMBB.
9529     sinkMBB->splice(sinkMBB->begin(), BB,
9530                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9531     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9532
9533     // Next, add the true and fallthrough blocks as its successors.
9534     BB->addSuccessor(copy0MBB);
9535     BB->addSuccessor(sinkMBB);
9536
9537     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9538         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9539         MI.getOpcode() == PPC::SELECT_QFRC ||
9540         MI.getOpcode() == PPC::SELECT_QSRC ||
9541         MI.getOpcode() == PPC::SELECT_QBRC ||
9542         MI.getOpcode() == PPC::SELECT_VRRC ||
9543         MI.getOpcode() == PPC::SELECT_VSFRC ||
9544         MI.getOpcode() == PPC::SELECT_VSSRC ||
9545         MI.getOpcode() == PPC::SELECT_VSRC) {
9546       BuildMI(BB, dl, TII->get(PPC::BC))
9547           .addReg(MI.getOperand(1).getReg())
9548           .addMBB(sinkMBB);
9549     } else {
9550       unsigned SelectPred = MI.getOperand(4).getImm();
9551       BuildMI(BB, dl, TII->get(PPC::BCC))
9552           .addImm(SelectPred)
9553           .addReg(MI.getOperand(1).getReg())
9554           .addMBB(sinkMBB);
9555     }
9556
9557     //  copy0MBB:
9558     //   %FalseValue = ...
9559     //   # fallthrough to sinkMBB
9560     BB = copy0MBB;
9561
9562     // Update machine-CFG edges
9563     BB->addSuccessor(sinkMBB);
9564
9565     //  sinkMBB:
9566     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9567     //  ...
9568     BB = sinkMBB;
9569     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9570         .addReg(MI.getOperand(3).getReg())
9571         .addMBB(copy0MBB)
9572         .addReg(MI.getOperand(2).getReg())
9573         .addMBB(thisMBB);
9574   } else if (MI.getOpcode() == PPC::ReadTB) {
9575     // To read the 64-bit time-base register on a 32-bit target, we read the
9576     // two halves. Should the counter have wrapped while it was being read, we
9577     // need to try again.
9578     // ...
9579     // readLoop:
9580     // mfspr Rx,TBU # load from TBU
9581     // mfspr Ry,TB  # load from TB
9582     // mfspr Rz,TBU # load from TBU
9583     // cmpw crX,Rx,Rz # check if 'old'='new'
9584     // bne readLoop   # branch if they're not equal
9585     // ...
9586
9587     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9588     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9589     DebugLoc dl = MI.getDebugLoc();
9590     F->insert(It, readMBB);
9591     F->insert(It, sinkMBB);
9592
9593     // Transfer the remainder of BB and its successor edges to sinkMBB.
9594     sinkMBB->splice(sinkMBB->begin(), BB,
9595                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9596     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9597
9598     BB->addSuccessor(readMBB);
9599     BB = readMBB;
9600
9601     MachineRegisterInfo &RegInfo = F->getRegInfo();
9602     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9603     unsigned LoReg = MI.getOperand(0).getReg();
9604     unsigned HiReg = MI.getOperand(1).getReg();
9605
9606     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9607     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9608     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9609
9610     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9611
9612     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9613       .addReg(HiReg).addReg(ReadAgainReg);
9614     BuildMI(BB, dl, TII->get(PPC::BCC))
9615       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9616
9617     BB->addSuccessor(readMBB);
9618     BB->addSuccessor(sinkMBB);
9619   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9620     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9621   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9622     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9623   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9624     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9625   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9626     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9627
9628   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9629     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9630   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9631     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9632   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9633     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9634   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9635     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9636
9637   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9638     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9639   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9640     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9641   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9642     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9643   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9644     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9645
9646   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9647     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9648   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9649     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9650   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9651     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9652   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9653     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9654
9655   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9656     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9657   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9658     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9659   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9660     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9661   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9662     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9663
9664   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9665     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9666   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9667     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9668   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9669     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9670   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9671     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9672
9673   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9674     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9675   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9676     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9677   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9678     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9679   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9680     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9681
9682   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9683     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9684   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9685     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9686   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9687     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9688   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9689     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9690
9691   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9692     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9693   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9694     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9695   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9696     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9697   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9698     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9699
9700   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9701     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9702   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9703     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9704   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9705     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9706   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9707     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9708
9709   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9710     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9711   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9712     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9713   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9714     BB = EmitAtomicBinary(MI, BB, 4, 0);
9715   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9716     BB = EmitAtomicBinary(MI, BB, 8, 0);
9717   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9718            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9719            (Subtarget.hasPartwordAtomics() &&
9720             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9721            (Subtarget.hasPartwordAtomics() &&
9722             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9723     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9724
9725     auto LoadMnemonic = PPC::LDARX;
9726     auto StoreMnemonic = PPC::STDCX;
9727     switch (MI.getOpcode()) {
9728     default:
9729       llvm_unreachable("Compare and swap of unknown size");
9730     case PPC::ATOMIC_CMP_SWAP_I8:
9731       LoadMnemonic = PPC::LBARX;
9732       StoreMnemonic = PPC::STBCX;
9733       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9734       break;
9735     case PPC::ATOMIC_CMP_SWAP_I16:
9736       LoadMnemonic = PPC::LHARX;
9737       StoreMnemonic = PPC::STHCX;
9738       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9739       break;
9740     case PPC::ATOMIC_CMP_SWAP_I32:
9741       LoadMnemonic = PPC::LWARX;
9742       StoreMnemonic = PPC::STWCX;
9743       break;
9744     case PPC::ATOMIC_CMP_SWAP_I64:
9745       LoadMnemonic = PPC::LDARX;
9746       StoreMnemonic = PPC::STDCX;
9747       break;
9748     }
9749     unsigned dest = MI.getOperand(0).getReg();
9750     unsigned ptrA = MI.getOperand(1).getReg();
9751     unsigned ptrB = MI.getOperand(2).getReg();
9752     unsigned oldval = MI.getOperand(3).getReg();
9753     unsigned newval = MI.getOperand(4).getReg();
9754     DebugLoc dl = MI.getDebugLoc();
9755
9756     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9757     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9758     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9759     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9760     F->insert(It, loop1MBB);
9761     F->insert(It, loop2MBB);
9762     F->insert(It, midMBB);
9763     F->insert(It, exitMBB);
9764     exitMBB->splice(exitMBB->begin(), BB,
9765                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9766     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9767
9768     //  thisMBB:
9769     //   ...
9770     //   fallthrough --> loopMBB
9771     BB->addSuccessor(loop1MBB);
9772
9773     // loop1MBB:
9774     //   l[bhwd]arx dest, ptr
9775     //   cmp[wd] dest, oldval
9776     //   bne- midMBB
9777     // loop2MBB:
9778     //   st[bhwd]cx. newval, ptr
9779     //   bne- loopMBB
9780     //   b exitBB
9781     // midMBB:
9782     //   st[bhwd]cx. dest, ptr
9783     // exitBB:
9784     BB = loop1MBB;
9785     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9786       .addReg(ptrA).addReg(ptrB);
9787     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9788       .addReg(oldval).addReg(dest);
9789     BuildMI(BB, dl, TII->get(PPC::BCC))
9790       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9791     BB->addSuccessor(loop2MBB);
9792     BB->addSuccessor(midMBB);
9793
9794     BB = loop2MBB;
9795     BuildMI(BB, dl, TII->get(StoreMnemonic))
9796       .addReg(newval).addReg(ptrA).addReg(ptrB);
9797     BuildMI(BB, dl, TII->get(PPC::BCC))
9798       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9799     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9800     BB->addSuccessor(loop1MBB);
9801     BB->addSuccessor(exitMBB);
9802
9803     BB = midMBB;
9804     BuildMI(BB, dl, TII->get(StoreMnemonic))
9805       .addReg(dest).addReg(ptrA).addReg(ptrB);
9806     BB->addSuccessor(exitMBB);
9807
9808     //  exitMBB:
9809     //   ...
9810     BB = exitMBB;
9811   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9812              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9813     // We must use 64-bit registers for addresses when targeting 64-bit,
9814     // since we're actually doing arithmetic on them.  Other registers
9815     // can be 32-bit.
9816     bool is64bit = Subtarget.isPPC64();
9817     bool isLittleEndian = Subtarget.isLittleEndian();
9818     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9819
9820     unsigned dest = MI.getOperand(0).getReg();
9821     unsigned ptrA = MI.getOperand(1).getReg();
9822     unsigned ptrB = MI.getOperand(2).getReg();
9823     unsigned oldval = MI.getOperand(3).getReg();
9824     unsigned newval = MI.getOperand(4).getReg();
9825     DebugLoc dl = MI.getDebugLoc();
9826
9827     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9828     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9829     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9830     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9831     F->insert(It, loop1MBB);
9832     F->insert(It, loop2MBB);
9833     F->insert(It, midMBB);
9834     F->insert(It, exitMBB);
9835     exitMBB->splice(exitMBB->begin(), BB,
9836                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9837     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9838
9839     MachineRegisterInfo &RegInfo = F->getRegInfo();
9840     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9841                                             : &PPC::GPRCRegClass;
9842     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9843     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9844     unsigned ShiftReg =
9845       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9846     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9847     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9848     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9849     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9850     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9851     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9852     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9853     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9854     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9855     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9856     unsigned Ptr1Reg;
9857     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9858     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9859     //  thisMBB:
9860     //   ...
9861     //   fallthrough --> loopMBB
9862     BB->addSuccessor(loop1MBB);
9863
9864     // The 4-byte load must be aligned, while a char or short may be
9865     // anywhere in the word.  Hence all this nasty bookkeeping code.
9866     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9867     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9868     //   xori shift, shift1, 24 [16]
9869     //   rlwinm ptr, ptr1, 0, 0, 29
9870     //   slw newval2, newval, shift
9871     //   slw oldval2, oldval,shift
9872     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9873     //   slw mask, mask2, shift
9874     //   and newval3, newval2, mask
9875     //   and oldval3, oldval2, mask
9876     // loop1MBB:
9877     //   lwarx tmpDest, ptr
9878     //   and tmp, tmpDest, mask
9879     //   cmpw tmp, oldval3
9880     //   bne- midMBB
9881     // loop2MBB:
9882     //   andc tmp2, tmpDest, mask
9883     //   or tmp4, tmp2, newval3
9884     //   stwcx. tmp4, ptr
9885     //   bne- loop1MBB
9886     //   b exitBB
9887     // midMBB:
9888     //   stwcx. tmpDest, ptr
9889     // exitBB:
9890     //   srw dest, tmpDest, shift
9891     if (ptrA != ZeroReg) {
9892       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9893       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9894         .addReg(ptrA).addReg(ptrB);
9895     } else {
9896       Ptr1Reg = ptrB;
9897     }
9898     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9899         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9900     if (!isLittleEndian)
9901       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9902           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9903     if (is64bit)
9904       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9905         .addReg(Ptr1Reg).addImm(0).addImm(61);
9906     else
9907       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9908         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9909     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9910         .addReg(newval).addReg(ShiftReg);
9911     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9912         .addReg(oldval).addReg(ShiftReg);
9913     if (is8bit)
9914       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9915     else {
9916       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9917       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9918         .addReg(Mask3Reg).addImm(65535);
9919     }
9920     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9921         .addReg(Mask2Reg).addReg(ShiftReg);
9922     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9923         .addReg(NewVal2Reg).addReg(MaskReg);
9924     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9925         .addReg(OldVal2Reg).addReg(MaskReg);
9926
9927     BB = loop1MBB;
9928     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9929         .addReg(ZeroReg).addReg(PtrReg);
9930     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9931         .addReg(TmpDestReg).addReg(MaskReg);
9932     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9933         .addReg(TmpReg).addReg(OldVal3Reg);
9934     BuildMI(BB, dl, TII->get(PPC::BCC))
9935         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9936     BB->addSuccessor(loop2MBB);
9937     BB->addSuccessor(midMBB);
9938
9939     BB = loop2MBB;
9940     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9941         .addReg(TmpDestReg).addReg(MaskReg);
9942     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9943         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9944     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9945         .addReg(ZeroReg).addReg(PtrReg);
9946     BuildMI(BB, dl, TII->get(PPC::BCC))
9947       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9948     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9949     BB->addSuccessor(loop1MBB);
9950     BB->addSuccessor(exitMBB);
9951
9952     BB = midMBB;
9953     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9954       .addReg(ZeroReg).addReg(PtrReg);
9955     BB->addSuccessor(exitMBB);
9956
9957     //  exitMBB:
9958     //   ...
9959     BB = exitMBB;
9960     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9961       .addReg(ShiftReg);
9962   } else if (MI.getOpcode() == PPC::FADDrtz) {
9963     // This pseudo performs an FADD with rounding mode temporarily forced
9964     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9965     // is not modeled at the SelectionDAG level.
9966     unsigned Dest = MI.getOperand(0).getReg();
9967     unsigned Src1 = MI.getOperand(1).getReg();
9968     unsigned Src2 = MI.getOperand(2).getReg();
9969     DebugLoc dl = MI.getDebugLoc();
9970
9971     MachineRegisterInfo &RegInfo = F->getRegInfo();
9972     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9973
9974     // Save FPSCR value.
9975     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9976
9977     // Set rounding mode to round-to-zero.
9978     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9979     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9980
9981     // Perform addition.
9982     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9983
9984     // Restore FPSCR value.
9985     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9986   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9987              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9988              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9989              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9990     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9991                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9992                           ? PPC::ANDIo8
9993                           : PPC::ANDIo;
9994     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9995                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9996
9997     MachineRegisterInfo &RegInfo = F->getRegInfo();
9998     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9999                                                   &PPC::GPRCRegClass :
10000                                                   &PPC::G8RCRegClass);
10001
10002     DebugLoc dl = MI.getDebugLoc();
10003     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
10004         .addReg(MI.getOperand(1).getReg())
10005         .addImm(1);
10006     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
10007             MI.getOperand(0).getReg())
10008         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
10009   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
10010     DebugLoc Dl = MI.getDebugLoc();
10011     MachineRegisterInfo &RegInfo = F->getRegInfo();
10012     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
10013     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
10014     return BB;
10015   } else {
10016     llvm_unreachable("Unexpected instr type to insert");
10017   }
10018
10019   MI.eraseFromParent(); // The pseudo instruction is gone now.
10020   return BB;
10021 }
10022
10023 //===----------------------------------------------------------------------===//
10024 // Target Optimization Hooks
10025 //===----------------------------------------------------------------------===//
10026
10027 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
10028   // For the estimates, convergence is quadratic, so we essentially double the
10029   // number of digits correct after every iteration. For both FRE and FRSQRTE,
10030   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
10031   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
10032   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
10033   if (VT.getScalarType() == MVT::f64)
10034     RefinementSteps++;
10035   return RefinementSteps;
10036 }
10037
10038 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
10039                                            int Enabled, int &RefinementSteps,
10040                                            bool &UseOneConstNR,
10041                                            bool Reciprocal) const {
10042   EVT VT = Operand.getValueType();
10043   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
10044       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
10045       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10046       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10047       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10048       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10049     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10050       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10051
10052     UseOneConstNR = true;
10053     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
10054   }
10055   return SDValue();
10056 }
10057
10058 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
10059                                             int Enabled,
10060                                             int &RefinementSteps) const {
10061   EVT VT = Operand.getValueType();
10062   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
10063       (VT == MVT::f64 && Subtarget.hasFRE()) ||
10064       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
10065       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
10066       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
10067       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
10068     if (RefinementSteps == ReciprocalEstimate::Unspecified)
10069       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
10070     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
10071   }
10072   return SDValue();
10073 }
10074
10075 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
10076   // Note: This functionality is used only when unsafe-fp-math is enabled, and
10077   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
10078   // enabled for division), this functionality is redundant with the default
10079   // combiner logic (once the division -> reciprocal/multiply transformation
10080   // has taken place). As a result, this matters more for older cores than for
10081   // newer ones.
10082
10083   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10084   // reciprocal if there are two or more FDIVs (for embedded cores with only
10085   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10086   switch (Subtarget.getDarwinDirective()) {
10087   default:
10088     return 3;
10089   case PPC::DIR_440:
10090   case PPC::DIR_A2:
10091   case PPC::DIR_E500mc:
10092   case PPC::DIR_E5500:
10093     return 2;
10094   }
10095 }
10096
10097 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10098 // collapsed, and so we need to look through chains of them.
10099 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10100                                      int64_t& Offset, SelectionDAG &DAG) {
10101   if (DAG.isBaseWithConstantOffset(Loc)) {
10102     Base = Loc.getOperand(0);
10103     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10104
10105     // The base might itself be a base plus an offset, and if so, accumulate
10106     // that as well.
10107     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10108   }
10109 }
10110
10111 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10112                             unsigned Bytes, int Dist,
10113                             SelectionDAG &DAG) {
10114   if (VT.getSizeInBits() / 8 != Bytes)
10115     return false;
10116
10117   SDValue BaseLoc = Base->getBasePtr();
10118   if (Loc.getOpcode() == ISD::FrameIndex) {
10119     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10120       return false;
10121     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10122     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10123     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10124     int FS  = MFI.getObjectSize(FI);
10125     int BFS = MFI.getObjectSize(BFI);
10126     if (FS != BFS || FS != (int)Bytes) return false;
10127     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10128   }
10129
10130   SDValue Base1 = Loc, Base2 = BaseLoc;
10131   int64_t Offset1 = 0, Offset2 = 0;
10132   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10133   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10134   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10135     return true;
10136
10137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10138   const GlobalValue *GV1 = nullptr;
10139   const GlobalValue *GV2 = nullptr;
10140   Offset1 = 0;
10141   Offset2 = 0;
10142   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10143   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10144   if (isGA1 && isGA2 && GV1 == GV2)
10145     return Offset1 == (Offset2 + Dist*Bytes);
10146   return false;
10147 }
10148
10149 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10150 // not enforce equality of the chain operands.
10151 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10152                             unsigned Bytes, int Dist,
10153                             SelectionDAG &DAG) {
10154   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10155     EVT VT = LS->getMemoryVT();
10156     SDValue Loc = LS->getBasePtr();
10157     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10158   }
10159
10160   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10161     EVT VT;
10162     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10163     default: return false;
10164     case Intrinsic::ppc_qpx_qvlfd:
10165     case Intrinsic::ppc_qpx_qvlfda:
10166       VT = MVT::v4f64;
10167       break;
10168     case Intrinsic::ppc_qpx_qvlfs:
10169     case Intrinsic::ppc_qpx_qvlfsa:
10170       VT = MVT::v4f32;
10171       break;
10172     case Intrinsic::ppc_qpx_qvlfcd:
10173     case Intrinsic::ppc_qpx_qvlfcda:
10174       VT = MVT::v2f64;
10175       break;
10176     case Intrinsic::ppc_qpx_qvlfcs:
10177     case Intrinsic::ppc_qpx_qvlfcsa:
10178       VT = MVT::v2f32;
10179       break;
10180     case Intrinsic::ppc_qpx_qvlfiwa:
10181     case Intrinsic::ppc_qpx_qvlfiwz:
10182     case Intrinsic::ppc_altivec_lvx:
10183     case Intrinsic::ppc_altivec_lvxl:
10184     case Intrinsic::ppc_vsx_lxvw4x:
10185     case Intrinsic::ppc_vsx_lxvw4x_be:
10186       VT = MVT::v4i32;
10187       break;
10188     case Intrinsic::ppc_vsx_lxvd2x:
10189     case Intrinsic::ppc_vsx_lxvd2x_be:
10190       VT = MVT::v2f64;
10191       break;
10192     case Intrinsic::ppc_altivec_lvebx:
10193       VT = MVT::i8;
10194       break;
10195     case Intrinsic::ppc_altivec_lvehx:
10196       VT = MVT::i16;
10197       break;
10198     case Intrinsic::ppc_altivec_lvewx:
10199       VT = MVT::i32;
10200       break;
10201     }
10202
10203     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10204   }
10205
10206   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10207     EVT VT;
10208     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10209     default: return false;
10210     case Intrinsic::ppc_qpx_qvstfd:
10211     case Intrinsic::ppc_qpx_qvstfda:
10212       VT = MVT::v4f64;
10213       break;
10214     case Intrinsic::ppc_qpx_qvstfs:
10215     case Intrinsic::ppc_qpx_qvstfsa:
10216       VT = MVT::v4f32;
10217       break;
10218     case Intrinsic::ppc_qpx_qvstfcd:
10219     case Intrinsic::ppc_qpx_qvstfcda:
10220       VT = MVT::v2f64;
10221       break;
10222     case Intrinsic::ppc_qpx_qvstfcs:
10223     case Intrinsic::ppc_qpx_qvstfcsa:
10224       VT = MVT::v2f32;
10225       break;
10226     case Intrinsic::ppc_qpx_qvstfiw:
10227     case Intrinsic::ppc_qpx_qvstfiwa:
10228     case Intrinsic::ppc_altivec_stvx:
10229     case Intrinsic::ppc_altivec_stvxl:
10230     case Intrinsic::ppc_vsx_stxvw4x:
10231       VT = MVT::v4i32;
10232       break;
10233     case Intrinsic::ppc_vsx_stxvd2x:
10234       VT = MVT::v2f64;
10235       break;
10236     case Intrinsic::ppc_vsx_stxvw4x_be:
10237       VT = MVT::v4i32;
10238       break;
10239     case Intrinsic::ppc_vsx_stxvd2x_be:
10240       VT = MVT::v2f64;
10241       break;
10242     case Intrinsic::ppc_altivec_stvebx:
10243       VT = MVT::i8;
10244       break;
10245     case Intrinsic::ppc_altivec_stvehx:
10246       VT = MVT::i16;
10247       break;
10248     case Intrinsic::ppc_altivec_stvewx:
10249       VT = MVT::i32;
10250       break;
10251     }
10252
10253     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10254   }
10255
10256   return false;
10257 }
10258
10259 // Return true is there is a nearyby consecutive load to the one provided
10260 // (regardless of alignment). We search up and down the chain, looking though
10261 // token factors and other loads (but nothing else). As a result, a true result
10262 // indicates that it is safe to create a new consecutive load adjacent to the
10263 // load provided.
10264 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10265   SDValue Chain = LD->getChain();
10266   EVT VT = LD->getMemoryVT();
10267
10268   SmallSet<SDNode *, 16> LoadRoots;
10269   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10270   SmallSet<SDNode *, 16> Visited;
10271
10272   // First, search up the chain, branching to follow all token-factor operands.
10273   // If we find a consecutive load, then we're done, otherwise, record all
10274   // nodes just above the top-level loads and token factors.
10275   while (!Queue.empty()) {
10276     SDNode *ChainNext = Queue.pop_back_val();
10277     if (!Visited.insert(ChainNext).second)
10278       continue;
10279
10280     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10281       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10282         return true;
10283
10284       if (!Visited.count(ChainLD->getChain().getNode()))
10285         Queue.push_back(ChainLD->getChain().getNode());
10286     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10287       for (const SDUse &O : ChainNext->ops())
10288         if (!Visited.count(O.getNode()))
10289           Queue.push_back(O.getNode());
10290     } else
10291       LoadRoots.insert(ChainNext);
10292   }
10293
10294   // Second, search down the chain, starting from the top-level nodes recorded
10295   // in the first phase. These top-level nodes are the nodes just above all
10296   // loads and token factors. Starting with their uses, recursively look though
10297   // all loads (just the chain uses) and token factors to find a consecutive
10298   // load.
10299   Visited.clear();
10300   Queue.clear();
10301
10302   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10303        IE = LoadRoots.end(); I != IE; ++I) {
10304     Queue.push_back(*I);
10305
10306     while (!Queue.empty()) {
10307       SDNode *LoadRoot = Queue.pop_back_val();
10308       if (!Visited.insert(LoadRoot).second)
10309         continue;
10310
10311       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10312         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10313           return true;
10314
10315       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10316            UE = LoadRoot->use_end(); UI != UE; ++UI)
10317         if (((isa<MemSDNode>(*UI) &&
10318             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10319             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10320           Queue.push_back(*UI);
10321     }
10322   }
10323
10324   return false;
10325 }
10326
10327 /// This function is called when we have proved that a SETCC node can be replaced
10328 /// by subtraction (and other supporting instructions) so that the result of
10329 /// comparison is kept in a GPR instead of CR. This function is purely for
10330 /// codegen purposes and has some flags to guide the codegen process.
10331 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10332                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10333   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10334
10335   // Zero extend the operands to the largest legal integer. Originally, they
10336   // must be of a strictly smaller size.
10337   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10338                          DAG.getConstant(Size, DL, MVT::i32));
10339   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10340                          DAG.getConstant(Size, DL, MVT::i32));
10341
10342   // Swap if needed. Depends on the condition code.
10343   if (Swap)
10344     std::swap(Op0, Op1);
10345
10346   // Subtract extended integers.
10347   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10348
10349   // Move the sign bit to the least significant position and zero out the rest.
10350   // Now the least significant bit carries the result of original comparison.
10351   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10352                              DAG.getConstant(Size - 1, DL, MVT::i32));
10353   auto Final = Shifted;
10354
10355   // Complement the result if needed. Based on the condition code.
10356   if (Complement)
10357     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10358                         DAG.getConstant(1, DL, MVT::i64));
10359
10360   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10361 }
10362
10363 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10364                                                   DAGCombinerInfo &DCI) const {
10365   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10366
10367   SelectionDAG &DAG = DCI.DAG;
10368   SDLoc DL(N);
10369
10370   // Size of integers being compared has a critical role in the following
10371   // analysis, so we prefer to do this when all types are legal.
10372   if (!DCI.isAfterLegalizeVectorOps())
10373     return SDValue();
10374
10375   // If all users of SETCC extend its value to a legal integer type
10376   // then we replace SETCC with a subtraction
10377   for (SDNode::use_iterator UI = N->use_begin(),
10378        UE = N->use_end(); UI != UE; ++UI) {
10379     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10380       return SDValue();
10381   }
10382
10383   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10384   auto OpSize = N->getOperand(0).getValueSizeInBits();
10385
10386   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10387
10388   if (OpSize < Size) {
10389     switch (CC) {
10390     default: break;
10391     case ISD::SETULT:
10392       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10393     case ISD::SETULE:
10394       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10395     case ISD::SETUGT:
10396       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10397     case ISD::SETUGE:
10398       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10399     }
10400   }
10401
10402   return SDValue();
10403 }
10404
10405 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10406                                                   DAGCombinerInfo &DCI) const {
10407   SelectionDAG &DAG = DCI.DAG;
10408   SDLoc dl(N);
10409
10410   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10411   // If we're tracking CR bits, we need to be careful that we don't have:
10412   //   trunc(binary-ops(zext(x), zext(y)))
10413   // or
10414   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10415   // such that we're unnecessarily moving things into GPRs when it would be
10416   // better to keep them in CR bits.
10417
10418   // Note that trunc here can be an actual i1 trunc, or can be the effective
10419   // truncation that comes from a setcc or select_cc.
10420   if (N->getOpcode() == ISD::TRUNCATE &&
10421       N->getValueType(0) != MVT::i1)
10422     return SDValue();
10423
10424   if (N->getOperand(0).getValueType() != MVT::i32 &&
10425       N->getOperand(0).getValueType() != MVT::i64)
10426     return SDValue();
10427
10428   if (N->getOpcode() == ISD::SETCC ||
10429       N->getOpcode() == ISD::SELECT_CC) {
10430     // If we're looking at a comparison, then we need to make sure that the
10431     // high bits (all except for the first) don't matter the result.
10432     ISD::CondCode CC =
10433       cast<CondCodeSDNode>(N->getOperand(
10434         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10435     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10436
10437     if (ISD::isSignedIntSetCC(CC)) {
10438       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10439           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10440         return SDValue();
10441     } else if (ISD::isUnsignedIntSetCC(CC)) {
10442       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10443                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10444           !DAG.MaskedValueIsZero(N->getOperand(1),
10445                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10446         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10447                                              : SDValue());
10448     } else {
10449       // This is neither a signed nor an unsigned comparison, just make sure
10450       // that the high bits are equal.
10451       KnownBits Op1Known, Op2Known;
10452       DAG.computeKnownBits(N->getOperand(0), Op1Known);
10453       DAG.computeKnownBits(N->getOperand(1), Op2Known);
10454
10455       // We don't really care about what is known about the first bit (if
10456       // anything), so clear it in all masks prior to comparing them.
10457       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10458       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10459
10460       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10461         return SDValue();
10462     }
10463   }
10464
10465   // We now know that the higher-order bits are irrelevant, we just need to
10466   // make sure that all of the intermediate operations are bit operations, and
10467   // all inputs are extensions.
10468   if (N->getOperand(0).getOpcode() != ISD::AND &&
10469       N->getOperand(0).getOpcode() != ISD::OR  &&
10470       N->getOperand(0).getOpcode() != ISD::XOR &&
10471       N->getOperand(0).getOpcode() != ISD::SELECT &&
10472       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10473       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10474       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10475       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10476       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10477     return SDValue();
10478
10479   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10480       N->getOperand(1).getOpcode() != ISD::AND &&
10481       N->getOperand(1).getOpcode() != ISD::OR  &&
10482       N->getOperand(1).getOpcode() != ISD::XOR &&
10483       N->getOperand(1).getOpcode() != ISD::SELECT &&
10484       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10485       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10486       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10487       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10488       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10489     return SDValue();
10490
10491   SmallVector<SDValue, 4> Inputs;
10492   SmallVector<SDValue, 8> BinOps, PromOps;
10493   SmallPtrSet<SDNode *, 16> Visited;
10494
10495   for (unsigned i = 0; i < 2; ++i) {
10496     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10497           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10498           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10499           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10500         isa<ConstantSDNode>(N->getOperand(i)))
10501       Inputs.push_back(N->getOperand(i));
10502     else
10503       BinOps.push_back(N->getOperand(i));
10504
10505     if (N->getOpcode() == ISD::TRUNCATE)
10506       break;
10507   }
10508
10509   // Visit all inputs, collect all binary operations (and, or, xor and
10510   // select) that are all fed by extensions.
10511   while (!BinOps.empty()) {
10512     SDValue BinOp = BinOps.back();
10513     BinOps.pop_back();
10514
10515     if (!Visited.insert(BinOp.getNode()).second)
10516       continue;
10517
10518     PromOps.push_back(BinOp);
10519
10520     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10521       // The condition of the select is not promoted.
10522       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10523         continue;
10524       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10525         continue;
10526
10527       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10528             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10529             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10530            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10531           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10532         Inputs.push_back(BinOp.getOperand(i));
10533       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10534                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10535                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10536                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10537                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10538                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10539                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10540                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10541                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10542         BinOps.push_back(BinOp.getOperand(i));
10543       } else {
10544         // We have an input that is not an extension or another binary
10545         // operation; we'll abort this transformation.
10546         return SDValue();
10547       }
10548     }
10549   }
10550
10551   // Make sure that this is a self-contained cluster of operations (which
10552   // is not quite the same thing as saying that everything has only one
10553   // use).
10554   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10555     if (isa<ConstantSDNode>(Inputs[i]))
10556       continue;
10557
10558     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10559                               UE = Inputs[i].getNode()->use_end();
10560          UI != UE; ++UI) {
10561       SDNode *User = *UI;
10562       if (User != N && !Visited.count(User))
10563         return SDValue();
10564
10565       // Make sure that we're not going to promote the non-output-value
10566       // operand(s) or SELECT or SELECT_CC.
10567       // FIXME: Although we could sometimes handle this, and it does occur in
10568       // practice that one of the condition inputs to the select is also one of
10569       // the outputs, we currently can't deal with this.
10570       if (User->getOpcode() == ISD::SELECT) {
10571         if (User->getOperand(0) == Inputs[i])
10572           return SDValue();
10573       } else if (User->getOpcode() == ISD::SELECT_CC) {
10574         if (User->getOperand(0) == Inputs[i] ||
10575             User->getOperand(1) == Inputs[i])
10576           return SDValue();
10577       }
10578     }
10579   }
10580
10581   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10582     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10583                               UE = PromOps[i].getNode()->use_end();
10584          UI != UE; ++UI) {
10585       SDNode *User = *UI;
10586       if (User != N && !Visited.count(User))
10587         return SDValue();
10588
10589       // Make sure that we're not going to promote the non-output-value
10590       // operand(s) or SELECT or SELECT_CC.
10591       // FIXME: Although we could sometimes handle this, and it does occur in
10592       // practice that one of the condition inputs to the select is also one of
10593       // the outputs, we currently can't deal with this.
10594       if (User->getOpcode() == ISD::SELECT) {
10595         if (User->getOperand(0) == PromOps[i])
10596           return SDValue();
10597       } else if (User->getOpcode() == ISD::SELECT_CC) {
10598         if (User->getOperand(0) == PromOps[i] ||
10599             User->getOperand(1) == PromOps[i])
10600           return SDValue();
10601       }
10602     }
10603   }
10604
10605   // Replace all inputs with the extension operand.
10606   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10607     // Constants may have users outside the cluster of to-be-promoted nodes,
10608     // and so we need to replace those as we do the promotions.
10609     if (isa<ConstantSDNode>(Inputs[i]))
10610       continue;
10611     else
10612       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10613   }
10614
10615   std::list<HandleSDNode> PromOpHandles;
10616   for (auto &PromOp : PromOps)
10617     PromOpHandles.emplace_back(PromOp);
10618
10619   // Replace all operations (these are all the same, but have a different
10620   // (i1) return type). DAG.getNode will validate that the types of
10621   // a binary operator match, so go through the list in reverse so that
10622   // we've likely promoted both operands first. Any intermediate truncations or
10623   // extensions disappear.
10624   while (!PromOpHandles.empty()) {
10625     SDValue PromOp = PromOpHandles.back().getValue();
10626     PromOpHandles.pop_back();
10627
10628     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10629         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10630         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10631         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10632       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10633           PromOp.getOperand(0).getValueType() != MVT::i1) {
10634         // The operand is not yet ready (see comment below).
10635         PromOpHandles.emplace_front(PromOp);
10636         continue;
10637       }
10638
10639       SDValue RepValue = PromOp.getOperand(0);
10640       if (isa<ConstantSDNode>(RepValue))
10641         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10642
10643       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10644       continue;
10645     }
10646
10647     unsigned C;
10648     switch (PromOp.getOpcode()) {
10649     default:             C = 0; break;
10650     case ISD::SELECT:    C = 1; break;
10651     case ISD::SELECT_CC: C = 2; break;
10652     }
10653
10654     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10655          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10656         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10657          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10658       // The to-be-promoted operands of this node have not yet been
10659       // promoted (this should be rare because we're going through the
10660       // list backward, but if one of the operands has several users in
10661       // this cluster of to-be-promoted nodes, it is possible).
10662       PromOpHandles.emplace_front(PromOp);
10663       continue;
10664     }
10665
10666     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10667                                 PromOp.getNode()->op_end());
10668
10669     // If there are any constant inputs, make sure they're replaced now.
10670     for (unsigned i = 0; i < 2; ++i)
10671       if (isa<ConstantSDNode>(Ops[C+i]))
10672         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10673
10674     DAG.ReplaceAllUsesOfValueWith(PromOp,
10675       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10676   }
10677
10678   // Now we're left with the initial truncation itself.
10679   if (N->getOpcode() == ISD::TRUNCATE)
10680     return N->getOperand(0);
10681
10682   // Otherwise, this is a comparison. The operands to be compared have just
10683   // changed type (to i1), but everything else is the same.
10684   return SDValue(N, 0);
10685 }
10686
10687 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10688                                                   DAGCombinerInfo &DCI) const {
10689   SelectionDAG &DAG = DCI.DAG;
10690   SDLoc dl(N);
10691
10692   // If we're tracking CR bits, we need to be careful that we don't have:
10693   //   zext(binary-ops(trunc(x), trunc(y)))
10694   // or
10695   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10696   // such that we're unnecessarily moving things into CR bits that can more
10697   // efficiently stay in GPRs. Note that if we're not certain that the high
10698   // bits are set as required by the final extension, we still may need to do
10699   // some masking to get the proper behavior.
10700
10701   // This same functionality is important on PPC64 when dealing with
10702   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10703   // the return values of functions. Because it is so similar, it is handled
10704   // here as well.
10705
10706   if (N->getValueType(0) != MVT::i32 &&
10707       N->getValueType(0) != MVT::i64)
10708     return SDValue();
10709
10710   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10711         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10712     return SDValue();
10713
10714   if (N->getOperand(0).getOpcode() != ISD::AND &&
10715       N->getOperand(0).getOpcode() != ISD::OR  &&
10716       N->getOperand(0).getOpcode() != ISD::XOR &&
10717       N->getOperand(0).getOpcode() != ISD::SELECT &&
10718       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10719     return SDValue();
10720
10721   SmallVector<SDValue, 4> Inputs;
10722   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10723   SmallPtrSet<SDNode *, 16> Visited;
10724
10725   // Visit all inputs, collect all binary operations (and, or, xor and
10726   // select) that are all fed by truncations.
10727   while (!BinOps.empty()) {
10728     SDValue BinOp = BinOps.back();
10729     BinOps.pop_back();
10730
10731     if (!Visited.insert(BinOp.getNode()).second)
10732       continue;
10733
10734     PromOps.push_back(BinOp);
10735
10736     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10737       // The condition of the select is not promoted.
10738       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10739         continue;
10740       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10741         continue;
10742
10743       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10744           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10745         Inputs.push_back(BinOp.getOperand(i));
10746       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10747                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10748                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10749                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10750                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10751         BinOps.push_back(BinOp.getOperand(i));
10752       } else {
10753         // We have an input that is not a truncation or another binary
10754         // operation; we'll abort this transformation.
10755         return SDValue();
10756       }
10757     }
10758   }
10759
10760   // The operands of a select that must be truncated when the select is
10761   // promoted because the operand is actually part of the to-be-promoted set.
10762   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10763
10764   // Make sure that this is a self-contained cluster of operations (which
10765   // is not quite the same thing as saying that everything has only one
10766   // use).
10767   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10768     if (isa<ConstantSDNode>(Inputs[i]))
10769       continue;
10770
10771     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10772                               UE = Inputs[i].getNode()->use_end();
10773          UI != UE; ++UI) {
10774       SDNode *User = *UI;
10775       if (User != N && !Visited.count(User))
10776         return SDValue();
10777
10778       // If we're going to promote the non-output-value operand(s) or SELECT or
10779       // SELECT_CC, record them for truncation.
10780       if (User->getOpcode() == ISD::SELECT) {
10781         if (User->getOperand(0) == Inputs[i])
10782           SelectTruncOp[0].insert(std::make_pair(User,
10783                                     User->getOperand(0).getValueType()));
10784       } else if (User->getOpcode() == ISD::SELECT_CC) {
10785         if (User->getOperand(0) == Inputs[i])
10786           SelectTruncOp[0].insert(std::make_pair(User,
10787                                     User->getOperand(0).getValueType()));
10788         if (User->getOperand(1) == Inputs[i])
10789           SelectTruncOp[1].insert(std::make_pair(User,
10790                                     User->getOperand(1).getValueType()));
10791       }
10792     }
10793   }
10794
10795   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10796     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10797                               UE = PromOps[i].getNode()->use_end();
10798          UI != UE; ++UI) {
10799       SDNode *User = *UI;
10800       if (User != N && !Visited.count(User))
10801         return SDValue();
10802
10803       // If we're going to promote the non-output-value operand(s) or SELECT or
10804       // SELECT_CC, record them for truncation.
10805       if (User->getOpcode() == ISD::SELECT) {
10806         if (User->getOperand(0) == PromOps[i])
10807           SelectTruncOp[0].insert(std::make_pair(User,
10808                                     User->getOperand(0).getValueType()));
10809       } else if (User->getOpcode() == ISD::SELECT_CC) {
10810         if (User->getOperand(0) == PromOps[i])
10811           SelectTruncOp[0].insert(std::make_pair(User,
10812                                     User->getOperand(0).getValueType()));
10813         if (User->getOperand(1) == PromOps[i])
10814           SelectTruncOp[1].insert(std::make_pair(User,
10815                                     User->getOperand(1).getValueType()));
10816       }
10817     }
10818   }
10819
10820   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10821   bool ReallyNeedsExt = false;
10822   if (N->getOpcode() != ISD::ANY_EXTEND) {
10823     // If all of the inputs are not already sign/zero extended, then
10824     // we'll still need to do that at the end.
10825     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10826       if (isa<ConstantSDNode>(Inputs[i]))
10827         continue;
10828
10829       unsigned OpBits =
10830         Inputs[i].getOperand(0).getValueSizeInBits();
10831       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10832
10833       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10834            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10835                                   APInt::getHighBitsSet(OpBits,
10836                                                         OpBits-PromBits))) ||
10837           (N->getOpcode() == ISD::SIGN_EXTEND &&
10838            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10839              (OpBits-(PromBits-1)))) {
10840         ReallyNeedsExt = true;
10841         break;
10842       }
10843     }
10844   }
10845
10846   // Replace all inputs, either with the truncation operand, or a
10847   // truncation or extension to the final output type.
10848   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10849     // Constant inputs need to be replaced with the to-be-promoted nodes that
10850     // use them because they might have users outside of the cluster of
10851     // promoted nodes.
10852     if (isa<ConstantSDNode>(Inputs[i]))
10853       continue;
10854
10855     SDValue InSrc = Inputs[i].getOperand(0);
10856     if (Inputs[i].getValueType() == N->getValueType(0))
10857       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10858     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10859       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10860         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10861     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10862       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10863         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10864     else
10865       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10866         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10867   }
10868
10869   std::list<HandleSDNode> PromOpHandles;
10870   for (auto &PromOp : PromOps)
10871     PromOpHandles.emplace_back(PromOp);
10872
10873   // Replace all operations (these are all the same, but have a different
10874   // (promoted) return type). DAG.getNode will validate that the types of
10875   // a binary operator match, so go through the list in reverse so that
10876   // we've likely promoted both operands first.
10877   while (!PromOpHandles.empty()) {
10878     SDValue PromOp = PromOpHandles.back().getValue();
10879     PromOpHandles.pop_back();
10880
10881     unsigned C;
10882     switch (PromOp.getOpcode()) {
10883     default:             C = 0; break;
10884     case ISD::SELECT:    C = 1; break;
10885     case ISD::SELECT_CC: C = 2; break;
10886     }
10887
10888     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10889          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10890         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10891          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10892       // The to-be-promoted operands of this node have not yet been
10893       // promoted (this should be rare because we're going through the
10894       // list backward, but if one of the operands has several users in
10895       // this cluster of to-be-promoted nodes, it is possible).
10896       PromOpHandles.emplace_front(PromOp);
10897       continue;
10898     }
10899
10900     // For SELECT and SELECT_CC nodes, we do a similar check for any
10901     // to-be-promoted comparison inputs.
10902     if (PromOp.getOpcode() == ISD::SELECT ||
10903         PromOp.getOpcode() == ISD::SELECT_CC) {
10904       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10905            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10906           (SelectTruncOp[1].count(PromOp.getNode()) &&
10907            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10908         PromOpHandles.emplace_front(PromOp);
10909         continue;
10910       }
10911     }
10912
10913     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10914                                 PromOp.getNode()->op_end());
10915
10916     // If this node has constant inputs, then they'll need to be promoted here.
10917     for (unsigned i = 0; i < 2; ++i) {
10918       if (!isa<ConstantSDNode>(Ops[C+i]))
10919         continue;
10920       if (Ops[C+i].getValueType() == N->getValueType(0))
10921         continue;
10922
10923       if (N->getOpcode() == ISD::SIGN_EXTEND)
10924         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10925       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10926         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10927       else
10928         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10929     }
10930
10931     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10932     // truncate them again to the original value type.
10933     if (PromOp.getOpcode() == ISD::SELECT ||
10934         PromOp.getOpcode() == ISD::SELECT_CC) {
10935       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10936       if (SI0 != SelectTruncOp[0].end())
10937         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10938       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10939       if (SI1 != SelectTruncOp[1].end())
10940         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10941     }
10942
10943     DAG.ReplaceAllUsesOfValueWith(PromOp,
10944       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10945   }
10946
10947   // Now we're left with the initial extension itself.
10948   if (!ReallyNeedsExt)
10949     return N->getOperand(0);
10950
10951   // To zero extend, just mask off everything except for the first bit (in the
10952   // i1 case).
10953   if (N->getOpcode() == ISD::ZERO_EXTEND)
10954     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10955                        DAG.getConstant(APInt::getLowBitsSet(
10956                                          N->getValueSizeInBits(0), PromBits),
10957                                        dl, N->getValueType(0)));
10958
10959   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10960          "Invalid extension type");
10961   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10962   SDValue ShiftCst =
10963       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10964   return DAG.getNode(
10965       ISD::SRA, dl, N->getValueType(0),
10966       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10967       ShiftCst);
10968 }
10969
10970 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10971 ///
10972 /// If this vector is built out of floating to integer conversions,
10973 /// transform it to a vector built out of floating point values followed by a
10974 /// single floating to integer conversion of the vector.
10975 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
10976 /// becomes (fptosi (build_vector ($A, $B, ...)))
10977 SDValue PPCTargetLowering::
10978 combineElementTruncationToVectorTruncation(SDNode *N,
10979                                            DAGCombinerInfo &DCI) const {
10980   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10981          "Should be called with a BUILD_VECTOR node");
10982
10983   SelectionDAG &DAG = DCI.DAG;
10984   SDLoc dl(N);
10985
10986   SDValue FirstInput = N->getOperand(0);
10987   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10988          "The input operand must be an fp-to-int conversion.");
10989
10990   // This combine happens after legalization so the fp_to_[su]i nodes are
10991   // already converted to PPCSISD nodes.
10992   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10993   if (FirstConversion == PPCISD::FCTIDZ ||
10994       FirstConversion == PPCISD::FCTIDUZ ||
10995       FirstConversion == PPCISD::FCTIWZ ||
10996       FirstConversion == PPCISD::FCTIWUZ) {
10997     bool IsSplat = true;
10998     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10999       FirstConversion == PPCISD::FCTIWUZ;
11000     EVT SrcVT = FirstInput.getOperand(0).getValueType();
11001     SmallVector<SDValue, 4> Ops;
11002     EVT TargetVT = N->getValueType(0);
11003     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11004       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
11005         return SDValue();
11006       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
11007       if (NextConversion != FirstConversion)
11008         return SDValue();
11009       if (N->getOperand(i) != FirstInput)
11010         IsSplat = false;
11011     }
11012
11013     // If this is a splat, we leave it as-is since there will be only a single
11014     // fp-to-int conversion followed by a splat of the integer. This is better
11015     // for 32-bit and smaller ints and neutral for 64-bit ints.
11016     if (IsSplat)
11017       return SDValue();
11018
11019     // Now that we know we have the right type of node, get its operands
11020     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
11021       SDValue In = N->getOperand(i).getOperand(0);
11022       // For 32-bit values, we need to add an FP_ROUND node.
11023       if (Is32Bit) {
11024         if (In.isUndef())
11025           Ops.push_back(DAG.getUNDEF(SrcVT));
11026         else {
11027           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
11028                                       MVT::f32, In.getOperand(0),
11029                                       DAG.getIntPtrConstant(1, dl));
11030           Ops.push_back(Trunc);
11031         }
11032       } else
11033         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
11034     }
11035
11036     unsigned Opcode;
11037     if (FirstConversion == PPCISD::FCTIDZ ||
11038         FirstConversion == PPCISD::FCTIWZ)
11039       Opcode = ISD::FP_TO_SINT;
11040     else
11041       Opcode = ISD::FP_TO_UINT;
11042
11043     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
11044     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
11045     return DAG.getNode(Opcode, dl, TargetVT, BV);
11046   }
11047   return SDValue();
11048 }
11049
11050 /// \brief Reduce the number of loads when building a vector.
11051 ///
11052 /// Building a vector out of multiple loads can be converted to a load
11053 /// of the vector type if the loads are consecutive. If the loads are
11054 /// consecutive but in descending order, a shuffle is added at the end
11055 /// to reorder the vector.
11056 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
11057   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11058          "Should be called with a BUILD_VECTOR node");
11059
11060   SDLoc dl(N);
11061   bool InputsAreConsecutiveLoads = true;
11062   bool InputsAreReverseConsecutive = true;
11063   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
11064   SDValue FirstInput = N->getOperand(0);
11065   bool IsRoundOfExtLoad = false;
11066
11067   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
11068       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
11069     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
11070     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
11071   }
11072   // Not a build vector of (possibly fp_rounded) loads.
11073   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
11074     return SDValue();
11075
11076   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
11077     // If any inputs are fp_round(extload), they all must be.
11078     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
11079       return SDValue();
11080
11081     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
11082       N->getOperand(i);
11083     if (NextInput.getOpcode() != ISD::LOAD)
11084       return SDValue();
11085
11086     SDValue PreviousInput =
11087       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11088     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11089     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11090
11091     // If any inputs are fp_round(extload), they all must be.
11092     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11093       return SDValue();
11094
11095     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11096       InputsAreConsecutiveLoads = false;
11097     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11098       InputsAreReverseConsecutive = false;
11099
11100     // Exit early if the loads are neither consecutive nor reverse consecutive.
11101     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11102       return SDValue();
11103   }
11104
11105   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11106          "The loads cannot be both consecutive and reverse consecutive.");
11107
11108   SDValue FirstLoadOp =
11109     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11110   SDValue LastLoadOp =
11111     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11112                        N->getOperand(N->getNumOperands()-1);
11113
11114   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11115   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11116   if (InputsAreConsecutiveLoads) {
11117     assert(LD1 && "Input needs to be a LoadSDNode.");
11118     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11119                        LD1->getBasePtr(), LD1->getPointerInfo(),
11120                        LD1->getAlignment());
11121   }
11122   if (InputsAreReverseConsecutive) {
11123     assert(LDL && "Input needs to be a LoadSDNode.");
11124     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11125                                LDL->getBasePtr(), LDL->getPointerInfo(),
11126                                LDL->getAlignment());
11127     SmallVector<int, 16> Ops;
11128     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11129       Ops.push_back(i);
11130
11131     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11132                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11133   }
11134   return SDValue();
11135 }
11136
11137 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11138                                                  DAGCombinerInfo &DCI) const {
11139   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11140          "Should be called with a BUILD_VECTOR node");
11141
11142   SelectionDAG &DAG = DCI.DAG;
11143   SDLoc dl(N);
11144
11145   if (!Subtarget.hasVSX())
11146     return SDValue();
11147
11148   // The target independent DAG combiner will leave a build_vector of
11149   // float-to-int conversions intact. We can generate MUCH better code for
11150   // a float-to-int conversion of a vector of floats.
11151   SDValue FirstInput = N->getOperand(0);
11152   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11153     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11154     if (Reduced)
11155       return Reduced;
11156   }
11157
11158   // If we're building a vector out of consecutive loads, just load that
11159   // vector type.
11160   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11161   if (Reduced)
11162     return Reduced;
11163
11164   if (N->getValueType(0) != MVT::v2f64)
11165     return SDValue();
11166
11167   // Looking for:
11168   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11169   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11170       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11171     return SDValue();
11172   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11173       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11174     return SDValue();
11175   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11176     return SDValue();
11177
11178   SDValue Ext1 = FirstInput.getOperand(0);
11179   SDValue Ext2 = N->getOperand(1).getOperand(0);
11180   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11181      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11182     return SDValue();
11183
11184   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11185   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11186   if (!Ext1Op || !Ext2Op)
11187     return SDValue();
11188   if (Ext1.getValueType() != MVT::i32 ||
11189       Ext2.getValueType() != MVT::i32)
11190   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11191     return SDValue();
11192
11193   int FirstElem = Ext1Op->getZExtValue();
11194   int SecondElem = Ext2Op->getZExtValue();
11195   int SubvecIdx;
11196   if (FirstElem == 0 && SecondElem == 1)
11197     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11198   else if (FirstElem == 2 && SecondElem == 3)
11199     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11200   else
11201     return SDValue();
11202
11203   SDValue SrcVec = Ext1.getOperand(0);
11204   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11205     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11206   return DAG.getNode(NodeType, dl, MVT::v2f64,
11207                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11208 }
11209
11210 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11211                                               DAGCombinerInfo &DCI) const {
11212   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11213           N->getOpcode() == ISD::UINT_TO_FP) &&
11214          "Need an int -> FP conversion node here");
11215
11216   if (useSoftFloat() || !Subtarget.has64BitSupport())
11217     return SDValue();
11218
11219   SelectionDAG &DAG = DCI.DAG;
11220   SDLoc dl(N);
11221   SDValue Op(N, 0);
11222
11223   SDValue FirstOperand(Op.getOperand(0));
11224   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11225     (FirstOperand.getValueType() == MVT::i8 ||
11226      FirstOperand.getValueType() == MVT::i16);
11227   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11228     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11229     bool DstDouble = Op.getValueType() == MVT::f64;
11230     unsigned ConvOp = Signed ?
11231       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11232       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11233     SDValue WidthConst =
11234       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11235                             dl, false);
11236     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11237     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11238     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11239                                          DAG.getVTList(MVT::f64, MVT::Other),
11240                                          Ops, MVT::i8, LDN->getMemOperand());
11241
11242     // For signed conversion, we need to sign-extend the value in the VSR
11243     if (Signed) {
11244       SDValue ExtOps[] = { Ld, WidthConst };
11245       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11246       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11247     } else
11248       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11249   }
11250
11251   // Don't handle ppc_fp128 here or i1 conversions.
11252   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11253     return SDValue();
11254   if (Op.getOperand(0).getValueType() == MVT::i1)
11255     return SDValue();
11256
11257   // For i32 intermediate values, unfortunately, the conversion functions
11258   // leave the upper 32 bits of the value are undefined. Within the set of
11259   // scalar instructions, we have no method for zero- or sign-extending the
11260   // value. Thus, we cannot handle i32 intermediate values here.
11261   if (Op.getOperand(0).getValueType() == MVT::i32)
11262     return SDValue();
11263
11264   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11265          "UINT_TO_FP is supported only with FPCVT");
11266
11267   // If we have FCFIDS, then use it when converting to single-precision.
11268   // Otherwise, convert to double-precision and then round.
11269   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11270                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11271                                                             : PPCISD::FCFIDS)
11272                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11273                                                             : PPCISD::FCFID);
11274   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11275                   ? MVT::f32
11276                   : MVT::f64;
11277
11278   // If we're converting from a float, to an int, and back to a float again,
11279   // then we don't need the store/load pair at all.
11280   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11281        Subtarget.hasFPCVT()) ||
11282       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11283     SDValue Src = Op.getOperand(0).getOperand(0);
11284     if (Src.getValueType() == MVT::f32) {
11285       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11286       DCI.AddToWorklist(Src.getNode());
11287     } else if (Src.getValueType() != MVT::f64) {
11288       // Make sure that we don't pick up a ppc_fp128 source value.
11289       return SDValue();
11290     }
11291
11292     unsigned FCTOp =
11293       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11294                                                         PPCISD::FCTIDUZ;
11295
11296     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11297     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11298
11299     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11300       FP = DAG.getNode(ISD::FP_ROUND, dl,
11301                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11302       DCI.AddToWorklist(FP.getNode());
11303     }
11304
11305     return FP;
11306   }
11307
11308   return SDValue();
11309 }
11310
11311 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11312 // builtins) into loads with swaps.
11313 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11314                                               DAGCombinerInfo &DCI) const {
11315   SelectionDAG &DAG = DCI.DAG;
11316   SDLoc dl(N);
11317   SDValue Chain;
11318   SDValue Base;
11319   MachineMemOperand *MMO;
11320
11321   switch (N->getOpcode()) {
11322   default:
11323     llvm_unreachable("Unexpected opcode for little endian VSX load");
11324   case ISD::LOAD: {
11325     LoadSDNode *LD = cast<LoadSDNode>(N);
11326     Chain = LD->getChain();
11327     Base = LD->getBasePtr();
11328     MMO = LD->getMemOperand();
11329     // If the MMO suggests this isn't a load of a full vector, leave
11330     // things alone.  For a built-in, we have to make the change for
11331     // correctness, so if there is a size problem that will be a bug.
11332     if (MMO->getSize() < 16)
11333       return SDValue();
11334     break;
11335   }
11336   case ISD::INTRINSIC_W_CHAIN: {
11337     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11338     Chain = Intrin->getChain();
11339     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11340     // us what we want. Get operand 2 instead.
11341     Base = Intrin->getOperand(2);
11342     MMO = Intrin->getMemOperand();
11343     break;
11344   }
11345   }
11346
11347   MVT VecTy = N->getValueType(0).getSimpleVT();
11348
11349   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11350   // aligned and the type is a vector with elements up to 4 bytes
11351   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11352       && VecTy.getScalarSizeInBits() <= 32 ) {
11353     return SDValue();
11354   }
11355
11356   SDValue LoadOps[] = { Chain, Base };
11357   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11358                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11359                                          LoadOps, MVT::v2f64, MMO);
11360
11361   DCI.AddToWorklist(Load.getNode());
11362   Chain = Load.getValue(1);
11363   SDValue Swap = DAG.getNode(
11364       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11365   DCI.AddToWorklist(Swap.getNode());
11366
11367   // Add a bitcast if the resulting load type doesn't match v2f64.
11368   if (VecTy != MVT::v2f64) {
11369     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11370     DCI.AddToWorklist(N.getNode());
11371     // Package {bitcast value, swap's chain} to match Load's shape.
11372     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11373                        N, Swap.getValue(1));
11374   }
11375
11376   return Swap;
11377 }
11378
11379 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11380 // builtins) into stores with swaps.
11381 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11382                                                DAGCombinerInfo &DCI) const {
11383   SelectionDAG &DAG = DCI.DAG;
11384   SDLoc dl(N);
11385   SDValue Chain;
11386   SDValue Base;
11387   unsigned SrcOpnd;
11388   MachineMemOperand *MMO;
11389
11390   switch (N->getOpcode()) {
11391   default:
11392     llvm_unreachable("Unexpected opcode for little endian VSX store");
11393   case ISD::STORE: {
11394     StoreSDNode *ST = cast<StoreSDNode>(N);
11395     Chain = ST->getChain();
11396     Base = ST->getBasePtr();
11397     MMO = ST->getMemOperand();
11398     SrcOpnd = 1;
11399     // If the MMO suggests this isn't a store of a full vector, leave
11400     // things alone.  For a built-in, we have to make the change for
11401     // correctness, so if there is a size problem that will be a bug.
11402     if (MMO->getSize() < 16)
11403       return SDValue();
11404     break;
11405   }
11406   case ISD::INTRINSIC_VOID: {
11407     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11408     Chain = Intrin->getChain();
11409     // Intrin->getBasePtr() oddly does not get what we want.
11410     Base = Intrin->getOperand(3);
11411     MMO = Intrin->getMemOperand();
11412     SrcOpnd = 2;
11413     break;
11414   }
11415   }
11416
11417   SDValue Src = N->getOperand(SrcOpnd);
11418   MVT VecTy = Src.getValueType().getSimpleVT();
11419
11420   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11421   // aligned and the type is a vector with elements up to 4 bytes
11422   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11423       && VecTy.getScalarSizeInBits() <= 32 ) {
11424     return SDValue();
11425   }
11426
11427   // All stores are done as v2f64 and possible bit cast.
11428   if (VecTy != MVT::v2f64) {
11429     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11430     DCI.AddToWorklist(Src.getNode());
11431   }
11432
11433   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11434                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11435   DCI.AddToWorklist(Swap.getNode());
11436   Chain = Swap.getValue(1);
11437   SDValue StoreOps[] = { Chain, Swap, Base };
11438   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11439                                           DAG.getVTList(MVT::Other),
11440                                           StoreOps, VecTy, MMO);
11441   DCI.AddToWorklist(Store.getNode());
11442   return Store;
11443 }
11444
11445 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11446                                              DAGCombinerInfo &DCI) const {
11447   SelectionDAG &DAG = DCI.DAG;
11448   SDLoc dl(N);
11449   switch (N->getOpcode()) {
11450   default: break;
11451   case ISD::SHL:
11452     return combineSHL(N, DCI);
11453   case ISD::SRA:
11454     return combineSRA(N, DCI);
11455   case ISD::SRL:
11456     return combineSRL(N, DCI);
11457   case PPCISD::SHL:
11458     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11459         return N->getOperand(0);
11460     break;
11461   case PPCISD::SRL:
11462     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11463         return N->getOperand(0);
11464     break;
11465   case PPCISD::SRA:
11466     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11467       if (C->isNullValue() ||   //  0 >>s V -> 0.
11468           C->isAllOnesValue())    // -1 >>s V -> -1.
11469         return N->getOperand(0);
11470     }
11471     break;
11472   case ISD::SIGN_EXTEND:
11473   case ISD::ZERO_EXTEND:
11474   case ISD::ANY_EXTEND:
11475     return DAGCombineExtBoolTrunc(N, DCI);
11476   case ISD::TRUNCATE:
11477   case ISD::SETCC:
11478   case ISD::SELECT_CC:
11479     return DAGCombineTruncBoolExt(N, DCI);
11480   case ISD::SINT_TO_FP:
11481   case ISD::UINT_TO_FP:
11482     return combineFPToIntToFP(N, DCI);
11483   case ISD::STORE: {
11484     EVT Op1VT = N->getOperand(1).getValueType();
11485     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11486       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11487
11488     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11489     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11490         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11491         ValidTypeForStoreFltAsInt &&
11492         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11493       SDValue Val = N->getOperand(1).getOperand(0);
11494       if (Val.getValueType() == MVT::f32) {
11495         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11496         DCI.AddToWorklist(Val.getNode());
11497       }
11498       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11499       DCI.AddToWorklist(Val.getNode());
11500
11501       if (Op1VT == MVT::i32) {
11502         SDValue Ops[] = {
11503           N->getOperand(0), Val, N->getOperand(2),
11504           DAG.getValueType(N->getOperand(1).getValueType())
11505         };
11506
11507         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11508                 DAG.getVTList(MVT::Other), Ops,
11509                 cast<StoreSDNode>(N)->getMemoryVT(),
11510                 cast<StoreSDNode>(N)->getMemOperand());
11511       } else {
11512         unsigned WidthInBytes =
11513           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11514         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11515
11516         SDValue Ops[] = {
11517           N->getOperand(0), Val, N->getOperand(2), WidthConst,
11518           DAG.getValueType(N->getOperand(1).getValueType())
11519         };
11520         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11521                                       DAG.getVTList(MVT::Other), Ops,
11522                                       cast<StoreSDNode>(N)->getMemoryVT(),
11523                                       cast<StoreSDNode>(N)->getMemOperand());
11524       }
11525
11526       DCI.AddToWorklist(Val.getNode());
11527       return Val;
11528     }
11529
11530     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11531     if (cast<StoreSDNode>(N)->isUnindexed() &&
11532         N->getOperand(1).getOpcode() == ISD::BSWAP &&
11533         N->getOperand(1).getNode()->hasOneUse() &&
11534         (N->getOperand(1).getValueType() == MVT::i32 ||
11535          N->getOperand(1).getValueType() == MVT::i16 ||
11536          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11537           N->getOperand(1).getValueType() == MVT::i64))) {
11538       SDValue BSwapOp = N->getOperand(1).getOperand(0);
11539       // Do an any-extend to 32-bits if this is a half-word input.
11540       if (BSwapOp.getValueType() == MVT::i16)
11541         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11542
11543       // If the type of BSWAP operand is wider than stored memory width
11544       // it need to be shifted to the right side before STBRX.
11545       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11546       if (Op1VT.bitsGT(mVT)) {
11547         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11548         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11549                               DAG.getConstant(Shift, dl, MVT::i32));
11550         // Need to truncate if this is a bswap of i64 stored as i32/i16.
11551         if (Op1VT == MVT::i64)
11552           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11553       }
11554
11555       SDValue Ops[] = {
11556         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11557       };
11558       return
11559         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11560                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11561                                 cast<StoreSDNode>(N)->getMemOperand());
11562     }
11563
11564     // For little endian, VSX stores require generating xxswapd/lxvd2x.
11565     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11566     EVT VT = N->getOperand(1).getValueType();
11567     if (VT.isSimple()) {
11568       MVT StoreVT = VT.getSimpleVT();
11569       if (Subtarget.needsSwapsForVSXMemOps() &&
11570           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11571            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11572         return expandVSXStoreForLE(N, DCI);
11573     }
11574     break;
11575   }
11576   case ISD::LOAD: {
11577     LoadSDNode *LD = cast<LoadSDNode>(N);
11578     EVT VT = LD->getValueType(0);
11579
11580     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11581     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11582     if (VT.isSimple()) {
11583       MVT LoadVT = VT.getSimpleVT();
11584       if (Subtarget.needsSwapsForVSXMemOps() &&
11585           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11586            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11587         return expandVSXLoadForLE(N, DCI);
11588     }
11589
11590     // We sometimes end up with a 64-bit integer load, from which we extract
11591     // two single-precision floating-point numbers. This happens with
11592     // std::complex<float>, and other similar structures, because of the way we
11593     // canonicalize structure copies. However, if we lack direct moves,
11594     // then the final bitcasts from the extracted integer values to the
11595     // floating-point numbers turn into store/load pairs. Even with direct moves,
11596     // just loading the two floating-point numbers is likely better.
11597     auto ReplaceTwoFloatLoad = [&]() {
11598       if (VT != MVT::i64)
11599         return false;
11600
11601       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11602           LD->isVolatile())
11603         return false;
11604
11605       //  We're looking for a sequence like this:
11606       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11607       //      t16: i64 = srl t13, Constant:i32<32>
11608       //    t17: i32 = truncate t16
11609       //  t18: f32 = bitcast t17
11610       //    t19: i32 = truncate t13
11611       //  t20: f32 = bitcast t19
11612
11613       if (!LD->hasNUsesOfValue(2, 0))
11614         return false;
11615
11616       auto UI = LD->use_begin();
11617       while (UI.getUse().getResNo() != 0) ++UI;
11618       SDNode *Trunc = *UI++;
11619       while (UI.getUse().getResNo() != 0) ++UI;
11620       SDNode *RightShift = *UI;
11621       if (Trunc->getOpcode() != ISD::TRUNCATE)
11622         std::swap(Trunc, RightShift);
11623
11624       if (Trunc->getOpcode() != ISD::TRUNCATE ||
11625           Trunc->getValueType(0) != MVT::i32 ||
11626           !Trunc->hasOneUse())
11627         return false;
11628       if (RightShift->getOpcode() != ISD::SRL ||
11629           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11630           RightShift->getConstantOperandVal(1) != 32 ||
11631           !RightShift->hasOneUse())
11632         return false;
11633
11634       SDNode *Trunc2 = *RightShift->use_begin();
11635       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11636           Trunc2->getValueType(0) != MVT::i32 ||
11637           !Trunc2->hasOneUse())
11638         return false;
11639
11640       SDNode *Bitcast = *Trunc->use_begin();
11641       SDNode *Bitcast2 = *Trunc2->use_begin();
11642
11643       if (Bitcast->getOpcode() != ISD::BITCAST ||
11644           Bitcast->getValueType(0) != MVT::f32)
11645         return false;
11646       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11647           Bitcast2->getValueType(0) != MVT::f32)
11648         return false;
11649
11650       if (Subtarget.isLittleEndian())
11651         std::swap(Bitcast, Bitcast2);
11652
11653       // Bitcast has the second float (in memory-layout order) and Bitcast2
11654       // has the first one.
11655
11656       SDValue BasePtr = LD->getBasePtr();
11657       if (LD->isIndexed()) {
11658         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11659                "Non-pre-inc AM on PPC?");
11660         BasePtr =
11661           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11662                       LD->getOffset());
11663       }
11664
11665       auto MMOFlags =
11666           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11667       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11668                                       LD->getPointerInfo(), LD->getAlignment(),
11669                                       MMOFlags, LD->getAAInfo());
11670       SDValue AddPtr =
11671         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11672                     BasePtr, DAG.getIntPtrConstant(4, dl));
11673       SDValue FloatLoad2 = DAG.getLoad(
11674           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11675           LD->getPointerInfo().getWithOffset(4),
11676           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11677
11678       if (LD->isIndexed()) {
11679         // Note that DAGCombine should re-form any pre-increment load(s) from
11680         // what is produced here if that makes sense.
11681         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11682       }
11683
11684       DCI.CombineTo(Bitcast2, FloatLoad);
11685       DCI.CombineTo(Bitcast, FloatLoad2);
11686
11687       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11688                                     SDValue(FloatLoad2.getNode(), 1));
11689       return true;
11690     };
11691
11692     if (ReplaceTwoFloatLoad())
11693       return SDValue(N, 0);
11694
11695     EVT MemVT = LD->getMemoryVT();
11696     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11697     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11698     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11699     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11700     if (LD->isUnindexed() && VT.isVector() &&
11701         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11702           // P8 and later hardware should just use LOAD.
11703           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11704                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11705          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11706           LD->getAlignment() >= ScalarABIAlignment)) &&
11707         LD->getAlignment() < ABIAlignment) {
11708       // This is a type-legal unaligned Altivec or QPX load.
11709       SDValue Chain = LD->getChain();
11710       SDValue Ptr = LD->getBasePtr();
11711       bool isLittleEndian = Subtarget.isLittleEndian();
11712
11713       // This implements the loading of unaligned vectors as described in
11714       // the venerable Apple Velocity Engine overview. Specifically:
11715       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11716       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11717       //
11718       // The general idea is to expand a sequence of one or more unaligned
11719       // loads into an alignment-based permutation-control instruction (lvsl
11720       // or lvsr), a series of regular vector loads (which always truncate
11721       // their input address to an aligned address), and a series of
11722       // permutations.  The results of these permutations are the requested
11723       // loaded values.  The trick is that the last "extra" load is not taken
11724       // from the address you might suspect (sizeof(vector) bytes after the
11725       // last requested load), but rather sizeof(vector) - 1 bytes after the
11726       // last requested vector. The point of this is to avoid a page fault if
11727       // the base address happened to be aligned. This works because if the
11728       // base address is aligned, then adding less than a full vector length
11729       // will cause the last vector in the sequence to be (re)loaded.
11730       // Otherwise, the next vector will be fetched as you might suspect was
11731       // necessary.
11732
11733       // We might be able to reuse the permutation generation from
11734       // a different base address offset from this one by an aligned amount.
11735       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11736       // optimization later.
11737       Intrinsic::ID Intr, IntrLD, IntrPerm;
11738       MVT PermCntlTy, PermTy, LDTy;
11739       if (Subtarget.hasAltivec()) {
11740         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11741                                  Intrinsic::ppc_altivec_lvsl;
11742         IntrLD = Intrinsic::ppc_altivec_lvx;
11743         IntrPerm = Intrinsic::ppc_altivec_vperm;
11744         PermCntlTy = MVT::v16i8;
11745         PermTy = MVT::v4i32;
11746         LDTy = MVT::v4i32;
11747       } else {
11748         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11749                                        Intrinsic::ppc_qpx_qvlpcls;
11750         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11751                                        Intrinsic::ppc_qpx_qvlfs;
11752         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11753         PermCntlTy = MVT::v4f64;
11754         PermTy = MVT::v4f64;
11755         LDTy = MemVT.getSimpleVT();
11756       }
11757
11758       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11759
11760       // Create the new MMO for the new base load. It is like the original MMO,
11761       // but represents an area in memory almost twice the vector size centered
11762       // on the original address. If the address is unaligned, we might start
11763       // reading up to (sizeof(vector)-1) bytes below the address of the
11764       // original unaligned load.
11765       MachineFunction &MF = DAG.getMachineFunction();
11766       MachineMemOperand *BaseMMO =
11767         MF.getMachineMemOperand(LD->getMemOperand(),
11768                                 -(long)MemVT.getStoreSize()+1,
11769                                 2*MemVT.getStoreSize()-1);
11770
11771       // Create the new base load.
11772       SDValue LDXIntID =
11773           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11774       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11775       SDValue BaseLoad =
11776         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11777                                 DAG.getVTList(PermTy, MVT::Other),
11778                                 BaseLoadOps, LDTy, BaseMMO);
11779
11780       // Note that the value of IncOffset (which is provided to the next
11781       // load's pointer info offset value, and thus used to calculate the
11782       // alignment), and the value of IncValue (which is actually used to
11783       // increment the pointer value) are different! This is because we
11784       // require the next load to appear to be aligned, even though it
11785       // is actually offset from the base pointer by a lesser amount.
11786       int IncOffset = VT.getSizeInBits() / 8;
11787       int IncValue = IncOffset;
11788
11789       // Walk (both up and down) the chain looking for another load at the real
11790       // (aligned) offset (the alignment of the other load does not matter in
11791       // this case). If found, then do not use the offset reduction trick, as
11792       // that will prevent the loads from being later combined (as they would
11793       // otherwise be duplicates).
11794       if (!findConsecutiveLoad(LD, DAG))
11795         --IncValue;
11796
11797       SDValue Increment =
11798           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11799       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11800
11801       MachineMemOperand *ExtraMMO =
11802         MF.getMachineMemOperand(LD->getMemOperand(),
11803                                 1, 2*MemVT.getStoreSize()-1);
11804       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11805       SDValue ExtraLoad =
11806         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11807                                 DAG.getVTList(PermTy, MVT::Other),
11808                                 ExtraLoadOps, LDTy, ExtraMMO);
11809
11810       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11811         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11812
11813       // Because vperm has a big-endian bias, we must reverse the order
11814       // of the input vectors and complement the permute control vector
11815       // when generating little endian code.  We have already handled the
11816       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11817       // and ExtraLoad here.
11818       SDValue Perm;
11819       if (isLittleEndian)
11820         Perm = BuildIntrinsicOp(IntrPerm,
11821                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11822       else
11823         Perm = BuildIntrinsicOp(IntrPerm,
11824                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11825
11826       if (VT != PermTy)
11827         Perm = Subtarget.hasAltivec() ?
11828                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11829                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11830                                DAG.getTargetConstant(1, dl, MVT::i64));
11831                                // second argument is 1 because this rounding
11832                                // is always exact.
11833
11834       // The output of the permutation is our loaded result, the TokenFactor is
11835       // our new chain.
11836       DCI.CombineTo(N, Perm, TF);
11837       return SDValue(N, 0);
11838     }
11839     }
11840     break;
11841     case ISD::INTRINSIC_WO_CHAIN: {
11842       bool isLittleEndian = Subtarget.isLittleEndian();
11843       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11844       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11845                                            : Intrinsic::ppc_altivec_lvsl);
11846       if ((IID == Intr ||
11847            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11848            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11849         N->getOperand(1)->getOpcode() == ISD::ADD) {
11850         SDValue Add = N->getOperand(1);
11851
11852         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11853                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11854
11855         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11856                                   APInt::getAllOnesValue(Bits /* alignment */)
11857                                       .zext(Add.getScalarValueSizeInBits()))) {
11858           SDNode *BasePtr = Add->getOperand(0).getNode();
11859           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11860                                     UE = BasePtr->use_end();
11861                UI != UE; ++UI) {
11862             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11863                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11864               // We've found another LVSL/LVSR, and this address is an aligned
11865               // multiple of that one. The results will be the same, so use the
11866               // one we've just found instead.
11867
11868               return SDValue(*UI, 0);
11869             }
11870           }
11871         }
11872
11873         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11874           SDNode *BasePtr = Add->getOperand(0).getNode();
11875           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11876                UE = BasePtr->use_end(); UI != UE; ++UI) {
11877             if (UI->getOpcode() == ISD::ADD &&
11878                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11879                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11880                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11881                 (1ULL << Bits) == 0) {
11882               SDNode *OtherAdd = *UI;
11883               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11884                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11885                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11886                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11887                   return SDValue(*VI, 0);
11888                 }
11889               }
11890             }
11891           }
11892         }
11893       }
11894     }
11895
11896     break;
11897   case ISD::INTRINSIC_W_CHAIN:
11898     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11899     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11900     if (Subtarget.needsSwapsForVSXMemOps()) {
11901       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11902       default:
11903         break;
11904       case Intrinsic::ppc_vsx_lxvw4x:
11905       case Intrinsic::ppc_vsx_lxvd2x:
11906         return expandVSXLoadForLE(N, DCI);
11907       }
11908     }
11909     break;
11910   case ISD::INTRINSIC_VOID:
11911     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11912     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11913     if (Subtarget.needsSwapsForVSXMemOps()) {
11914       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11915       default:
11916         break;
11917       case Intrinsic::ppc_vsx_stxvw4x:
11918       case Intrinsic::ppc_vsx_stxvd2x:
11919         return expandVSXStoreForLE(N, DCI);
11920       }
11921     }
11922     break;
11923   case ISD::BSWAP:
11924     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11925     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11926         N->getOperand(0).hasOneUse() &&
11927         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11928          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11929           N->getValueType(0) == MVT::i64))) {
11930       SDValue Load = N->getOperand(0);
11931       LoadSDNode *LD = cast<LoadSDNode>(Load);
11932       // Create the byte-swapping load.
11933       SDValue Ops[] = {
11934         LD->getChain(),    // Chain
11935         LD->getBasePtr(),  // Ptr
11936         DAG.getValueType(N->getValueType(0)) // VT
11937       };
11938       SDValue BSLoad =
11939         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11940                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11941                                               MVT::i64 : MVT::i32, MVT::Other),
11942                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11943
11944       // If this is an i16 load, insert the truncate.
11945       SDValue ResVal = BSLoad;
11946       if (N->getValueType(0) == MVT::i16)
11947         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11948
11949       // First, combine the bswap away.  This makes the value produced by the
11950       // load dead.
11951       DCI.CombineTo(N, ResVal);
11952
11953       // Next, combine the load away, we give it a bogus result value but a real
11954       // chain result.  The result value is dead because the bswap is dead.
11955       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11956
11957       // Return N so it doesn't get rechecked!
11958       return SDValue(N, 0);
11959     }
11960     break;
11961   case PPCISD::VCMP:
11962     // If a VCMPo node already exists with exactly the same operands as this
11963     // node, use its result instead of this node (VCMPo computes both a CR6 and
11964     // a normal output).
11965     //
11966     if (!N->getOperand(0).hasOneUse() &&
11967         !N->getOperand(1).hasOneUse() &&
11968         !N->getOperand(2).hasOneUse()) {
11969
11970       // Scan all of the users of the LHS, looking for VCMPo's that match.
11971       SDNode *VCMPoNode = nullptr;
11972
11973       SDNode *LHSN = N->getOperand(0).getNode();
11974       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11975            UI != E; ++UI)
11976         if (UI->getOpcode() == PPCISD::VCMPo &&
11977             UI->getOperand(1) == N->getOperand(1) &&
11978             UI->getOperand(2) == N->getOperand(2) &&
11979             UI->getOperand(0) == N->getOperand(0)) {
11980           VCMPoNode = *UI;
11981           break;
11982         }
11983
11984       // If there is no VCMPo node, or if the flag value has a single use, don't
11985       // transform this.
11986       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11987         break;
11988
11989       // Look at the (necessarily single) use of the flag value.  If it has a
11990       // chain, this transformation is more complex.  Note that multiple things
11991       // could use the value result, which we should ignore.
11992       SDNode *FlagUser = nullptr;
11993       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11994            FlagUser == nullptr; ++UI) {
11995         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11996         SDNode *User = *UI;
11997         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11998           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11999             FlagUser = User;
12000             break;
12001           }
12002         }
12003       }
12004
12005       // If the user is a MFOCRF instruction, we know this is safe.
12006       // Otherwise we give up for right now.
12007       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
12008         return SDValue(VCMPoNode, 0);
12009     }
12010     break;
12011   case ISD::BRCOND: {
12012     SDValue Cond = N->getOperand(1);
12013     SDValue Target = N->getOperand(2);
12014
12015     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12016         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
12017           Intrinsic::ppc_is_decremented_ctr_nonzero) {
12018
12019       // We now need to make the intrinsic dead (it cannot be instruction
12020       // selected).
12021       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
12022       assert(Cond.getNode()->hasOneUse() &&
12023              "Counter decrement has more than one use");
12024
12025       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
12026                          N->getOperand(0), Target);
12027     }
12028   }
12029   break;
12030   case ISD::BR_CC: {
12031     // If this is a branch on an altivec predicate comparison, lower this so
12032     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
12033     // lowering is done pre-legalize, because the legalizer lowers the predicate
12034     // compare down to code that is difficult to reassemble.
12035     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
12036     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
12037
12038     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
12039     // value. If so, pass-through the AND to get to the intrinsic.
12040     if (LHS.getOpcode() == ISD::AND &&
12041         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12042         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
12043           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12044         isa<ConstantSDNode>(LHS.getOperand(1)) &&
12045         !isNullConstant(LHS.getOperand(1)))
12046       LHS = LHS.getOperand(0);
12047
12048     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
12049         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
12050           Intrinsic::ppc_is_decremented_ctr_nonzero &&
12051         isa<ConstantSDNode>(RHS)) {
12052       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
12053              "Counter decrement comparison is not EQ or NE");
12054
12055       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12056       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
12057                     (CC == ISD::SETNE && !Val);
12058
12059       // We now need to make the intrinsic dead (it cannot be instruction
12060       // selected).
12061       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
12062       assert(LHS.getNode()->hasOneUse() &&
12063              "Counter decrement has more than one use");
12064
12065       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
12066                          N->getOperand(0), N->getOperand(4));
12067     }
12068
12069     int CompareOpc;
12070     bool isDot;
12071
12072     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
12073         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
12074         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
12075       assert(isDot && "Can't compare against a vector result!");
12076
12077       // If this is a comparison against something other than 0/1, then we know
12078       // that the condition is never/always true.
12079       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
12080       if (Val != 0 && Val != 1) {
12081         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
12082           return N->getOperand(0);
12083         // Always !=, turn it into an unconditional branch.
12084         return DAG.getNode(ISD::BR, dl, MVT::Other,
12085                            N->getOperand(0), N->getOperand(4));
12086       }
12087
12088       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12089
12090       // Create the PPCISD altivec 'dot' comparison node.
12091       SDValue Ops[] = {
12092         LHS.getOperand(2),  // LHS of compare
12093         LHS.getOperand(3),  // RHS of compare
12094         DAG.getConstant(CompareOpc, dl, MVT::i32)
12095       };
12096       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12097       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12098
12099       // Unpack the result based on how the target uses it.
12100       PPC::Predicate CompOpc;
12101       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12102       default:  // Can't happen, don't crash on invalid number though.
12103       case 0:   // Branch on the value of the EQ bit of CR6.
12104         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12105         break;
12106       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12107         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12108         break;
12109       case 2:   // Branch on the value of the LT bit of CR6.
12110         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12111         break;
12112       case 3:   // Branch on the inverted value of the LT bit of CR6.
12113         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12114         break;
12115       }
12116
12117       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12118                          DAG.getConstant(CompOpc, dl, MVT::i32),
12119                          DAG.getRegister(PPC::CR6, MVT::i32),
12120                          N->getOperand(4), CompNode.getValue(1));
12121     }
12122     break;
12123   }
12124   case ISD::BUILD_VECTOR:
12125     return DAGCombineBuildVector(N, DCI);
12126   }
12127
12128   return SDValue();
12129 }
12130
12131 SDValue
12132 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12133                                   SelectionDAG &DAG,
12134                                   std::vector<SDNode *> *Created) const {
12135   // fold (sdiv X, pow2)
12136   EVT VT = N->getValueType(0);
12137   if (VT == MVT::i64 && !Subtarget.isPPC64())
12138     return SDValue();
12139   if ((VT != MVT::i32 && VT != MVT::i64) ||
12140       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12141     return SDValue();
12142
12143   SDLoc DL(N);
12144   SDValue N0 = N->getOperand(0);
12145
12146   bool IsNegPow2 = (-Divisor).isPowerOf2();
12147   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12148   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12149
12150   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12151   if (Created)
12152     Created->push_back(Op.getNode());
12153
12154   if (IsNegPow2) {
12155     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12156     if (Created)
12157       Created->push_back(Op.getNode());
12158   }
12159
12160   return Op;
12161 }
12162
12163 //===----------------------------------------------------------------------===//
12164 // Inline Assembly Support
12165 //===----------------------------------------------------------------------===//
12166
12167 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12168                                                       KnownBits &Known,
12169                                                       const APInt &DemandedElts,
12170                                                       const SelectionDAG &DAG,
12171                                                       unsigned Depth) const {
12172   Known.resetAll();
12173   switch (Op.getOpcode()) {
12174   default: break;
12175   case PPCISD::LBRX: {
12176     // lhbrx is known to have the top bits cleared out.
12177     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12178       Known.Zero = 0xFFFF0000;
12179     break;
12180   }
12181   case ISD::INTRINSIC_WO_CHAIN: {
12182     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12183     default: break;
12184     case Intrinsic::ppc_altivec_vcmpbfp_p:
12185     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12186     case Intrinsic::ppc_altivec_vcmpequb_p:
12187     case Intrinsic::ppc_altivec_vcmpequh_p:
12188     case Intrinsic::ppc_altivec_vcmpequw_p:
12189     case Intrinsic::ppc_altivec_vcmpequd_p:
12190     case Intrinsic::ppc_altivec_vcmpgefp_p:
12191     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12192     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12193     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12194     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12195     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12196     case Intrinsic::ppc_altivec_vcmpgtub_p:
12197     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12198     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12199     case Intrinsic::ppc_altivec_vcmpgtud_p:
12200       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
12201       break;
12202     }
12203   }
12204   }
12205 }
12206
12207 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12208   switch (Subtarget.getDarwinDirective()) {
12209   default: break;
12210   case PPC::DIR_970:
12211   case PPC::DIR_PWR4:
12212   case PPC::DIR_PWR5:
12213   case PPC::DIR_PWR5X:
12214   case PPC::DIR_PWR6:
12215   case PPC::DIR_PWR6X:
12216   case PPC::DIR_PWR7:
12217   case PPC::DIR_PWR8:
12218   case PPC::DIR_PWR9: {
12219     if (!ML)
12220       break;
12221
12222     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12223
12224     // For small loops (between 5 and 8 instructions), align to a 32-byte
12225     // boundary so that the entire loop fits in one instruction-cache line.
12226     uint64_t LoopSize = 0;
12227     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12228       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12229         LoopSize += TII->getInstSizeInBytes(*J);
12230         if (LoopSize > 32)
12231           break;
12232       }
12233
12234     if (LoopSize > 16 && LoopSize <= 32)
12235       return 5;
12236
12237     break;
12238   }
12239   }
12240
12241   return TargetLowering::getPrefLoopAlignment(ML);
12242 }
12243
12244 /// getConstraintType - Given a constraint, return the type of
12245 /// constraint it is for this target.
12246 PPCTargetLowering::ConstraintType
12247 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12248   if (Constraint.size() == 1) {
12249     switch (Constraint[0]) {
12250     default: break;
12251     case 'b':
12252     case 'r':
12253     case 'f':
12254     case 'd':
12255     case 'v':
12256     case 'y':
12257       return C_RegisterClass;
12258     case 'Z':
12259       // FIXME: While Z does indicate a memory constraint, it specifically
12260       // indicates an r+r address (used in conjunction with the 'y' modifier
12261       // in the replacement string). Currently, we're forcing the base
12262       // register to be r0 in the asm printer (which is interpreted as zero)
12263       // and forming the complete address in the second register. This is
12264       // suboptimal.
12265       return C_Memory;
12266     }
12267   } else if (Constraint == "wc") { // individual CR bits.
12268     return C_RegisterClass;
12269   } else if (Constraint == "wa" || Constraint == "wd" ||
12270              Constraint == "wf" || Constraint == "ws") {
12271     return C_RegisterClass; // VSX registers.
12272   }
12273   return TargetLowering::getConstraintType(Constraint);
12274 }
12275
12276 /// Examine constraint type and operand type and determine a weight value.
12277 /// This object must already have been set up with the operand type
12278 /// and the current alternative constraint selected.
12279 TargetLowering::ConstraintWeight
12280 PPCTargetLowering::getSingleConstraintMatchWeight(
12281     AsmOperandInfo &info, const char *constraint) const {
12282   ConstraintWeight weight = CW_Invalid;
12283   Value *CallOperandVal = info.CallOperandVal;
12284     // If we don't have a value, we can't do a match,
12285     // but allow it at the lowest weight.
12286   if (!CallOperandVal)
12287     return CW_Default;
12288   Type *type = CallOperandVal->getType();
12289
12290   // Look at the constraint type.
12291   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12292     return CW_Register; // an individual CR bit.
12293   else if ((StringRef(constraint) == "wa" ||
12294             StringRef(constraint) == "wd" ||
12295             StringRef(constraint) == "wf") &&
12296            type->isVectorTy())
12297     return CW_Register;
12298   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12299     return CW_Register;
12300
12301   switch (*constraint) {
12302   default:
12303     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12304     break;
12305   case 'b':
12306     if (type->isIntegerTy())
12307       weight = CW_Register;
12308     break;
12309   case 'f':
12310     if (type->isFloatTy())
12311       weight = CW_Register;
12312     break;
12313   case 'd':
12314     if (type->isDoubleTy())
12315       weight = CW_Register;
12316     break;
12317   case 'v':
12318     if (type->isVectorTy())
12319       weight = CW_Register;
12320     break;
12321   case 'y':
12322     weight = CW_Register;
12323     break;
12324   case 'Z':
12325     weight = CW_Memory;
12326     break;
12327   }
12328   return weight;
12329 }
12330
12331 std::pair<unsigned, const TargetRegisterClass *>
12332 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12333                                                 StringRef Constraint,
12334                                                 MVT VT) const {
12335   if (Constraint.size() == 1) {
12336     // GCC RS6000 Constraint Letters
12337     switch (Constraint[0]) {
12338     case 'b':   // R1-R31
12339       if (VT == MVT::i64 && Subtarget.isPPC64())
12340         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12341       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12342     case 'r':   // R0-R31
12343       if (VT == MVT::i64 && Subtarget.isPPC64())
12344         return std::make_pair(0U, &PPC::G8RCRegClass);
12345       return std::make_pair(0U, &PPC::GPRCRegClass);
12346     // 'd' and 'f' constraints are both defined to be "the floating point
12347     // registers", where one is for 32-bit and the other for 64-bit. We don't
12348     // really care overly much here so just give them all the same reg classes.
12349     case 'd':
12350     case 'f':
12351       if (VT == MVT::f32 || VT == MVT::i32)
12352         return std::make_pair(0U, &PPC::F4RCRegClass);
12353       if (VT == MVT::f64 || VT == MVT::i64)
12354         return std::make_pair(0U, &PPC::F8RCRegClass);
12355       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12356         return std::make_pair(0U, &PPC::QFRCRegClass);
12357       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12358         return std::make_pair(0U, &PPC::QSRCRegClass);
12359       break;
12360     case 'v':
12361       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12362         return std::make_pair(0U, &PPC::QFRCRegClass);
12363       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12364         return std::make_pair(0U, &PPC::QSRCRegClass);
12365       if (Subtarget.hasAltivec())
12366         return std::make_pair(0U, &PPC::VRRCRegClass);
12367     case 'y':   // crrc
12368       return std::make_pair(0U, &PPC::CRRCRegClass);
12369     }
12370   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12371     // An individual CR bit.
12372     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12373   } else if ((Constraint == "wa" || Constraint == "wd" ||
12374              Constraint == "wf") && Subtarget.hasVSX()) {
12375     return std::make_pair(0U, &PPC::VSRCRegClass);
12376   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12377     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12378       return std::make_pair(0U, &PPC::VSSRCRegClass);
12379     else
12380       return std::make_pair(0U, &PPC::VSFRCRegClass);
12381   }
12382
12383   std::pair<unsigned, const TargetRegisterClass *> R =
12384       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12385
12386   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12387   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12388   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12389   // register.
12390   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12391   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12392   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12393       PPC::GPRCRegClass.contains(R.first))
12394     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12395                             PPC::sub_32, &PPC::G8RCRegClass),
12396                           &PPC::G8RCRegClass);
12397
12398   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12399   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12400     R.first = PPC::CR0;
12401     R.second = &PPC::CRRCRegClass;
12402   }
12403
12404   return R;
12405 }
12406
12407 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12408 /// vector.  If it is invalid, don't add anything to Ops.
12409 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12410                                                      std::string &Constraint,
12411                                                      std::vector<SDValue>&Ops,
12412                                                      SelectionDAG &DAG) const {
12413   SDValue Result;
12414
12415   // Only support length 1 constraints.
12416   if (Constraint.length() > 1) return;
12417
12418   char Letter = Constraint[0];
12419   switch (Letter) {
12420   default: break;
12421   case 'I':
12422   case 'J':
12423   case 'K':
12424   case 'L':
12425   case 'M':
12426   case 'N':
12427   case 'O':
12428   case 'P': {
12429     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12430     if (!CST) return; // Must be an immediate to match.
12431     SDLoc dl(Op);
12432     int64_t Value = CST->getSExtValue();
12433     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12434                          // numbers are printed as such.
12435     switch (Letter) {
12436     default: llvm_unreachable("Unknown constraint letter!");
12437     case 'I':  // "I" is a signed 16-bit constant.
12438       if (isInt<16>(Value))
12439         Result = DAG.getTargetConstant(Value, dl, TCVT);
12440       break;
12441     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12442       if (isShiftedUInt<16, 16>(Value))
12443         Result = DAG.getTargetConstant(Value, dl, TCVT);
12444       break;
12445     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12446       if (isShiftedInt<16, 16>(Value))
12447         Result = DAG.getTargetConstant(Value, dl, TCVT);
12448       break;
12449     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12450       if (isUInt<16>(Value))
12451         Result = DAG.getTargetConstant(Value, dl, TCVT);
12452       break;
12453     case 'M':  // "M" is a constant that is greater than 31.
12454       if (Value > 31)
12455         Result = DAG.getTargetConstant(Value, dl, TCVT);
12456       break;
12457     case 'N':  // "N" is a positive constant that is an exact power of two.
12458       if (Value > 0 && isPowerOf2_64(Value))
12459         Result = DAG.getTargetConstant(Value, dl, TCVT);
12460       break;
12461     case 'O':  // "O" is the constant zero.
12462       if (Value == 0)
12463         Result = DAG.getTargetConstant(Value, dl, TCVT);
12464       break;
12465     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12466       if (isInt<16>(-Value))
12467         Result = DAG.getTargetConstant(Value, dl, TCVT);
12468       break;
12469     }
12470     break;
12471   }
12472   }
12473
12474   if (Result.getNode()) {
12475     Ops.push_back(Result);
12476     return;
12477   }
12478
12479   // Handle standard constraint letters.
12480   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12481 }
12482
12483 // isLegalAddressingMode - Return true if the addressing mode represented
12484 // by AM is legal for this target, for a load/store of the specified type.
12485 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12486                                               const AddrMode &AM, Type *Ty,
12487                                               unsigned AS) const {
12488   // PPC does not allow r+i addressing modes for vectors!
12489   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12490     return false;
12491
12492   // PPC allows a sign-extended 16-bit immediate field.
12493   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12494     return false;
12495
12496   // No global is ever allowed as a base.
12497   if (AM.BaseGV)
12498     return false;
12499
12500   // PPC only support r+r,
12501   switch (AM.Scale) {
12502   case 0:  // "r+i" or just "i", depending on HasBaseReg.
12503     break;
12504   case 1:
12505     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
12506       return false;
12507     // Otherwise we have r+r or r+i.
12508     break;
12509   case 2:
12510     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
12511       return false;
12512     // Allow 2*r as r+r.
12513     break;
12514   default:
12515     // No other scales are supported.
12516     return false;
12517   }
12518
12519   return true;
12520 }
12521
12522 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12523                                            SelectionDAG &DAG) const {
12524   MachineFunction &MF = DAG.getMachineFunction();
12525   MachineFrameInfo &MFI = MF.getFrameInfo();
12526   MFI.setReturnAddressIsTaken(true);
12527
12528   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12529     return SDValue();
12530
12531   SDLoc dl(Op);
12532   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12533
12534   // Make sure the function does not optimize away the store of the RA to
12535   // the stack.
12536   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12537   FuncInfo->setLRStoreRequired();
12538   bool isPPC64 = Subtarget.isPPC64();
12539   auto PtrVT = getPointerTy(MF.getDataLayout());
12540
12541   if (Depth > 0) {
12542     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12543     SDValue Offset =
12544         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12545                         isPPC64 ? MVT::i64 : MVT::i32);
12546     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12547                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12548                        MachinePointerInfo());
12549   }
12550
12551   // Just load the return address off the stack.
12552   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12553   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12554                      MachinePointerInfo());
12555 }
12556
12557 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12558                                           SelectionDAG &DAG) const {
12559   SDLoc dl(Op);
12560   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12561
12562   MachineFunction &MF = DAG.getMachineFunction();
12563   MachineFrameInfo &MFI = MF.getFrameInfo();
12564   MFI.setFrameAddressIsTaken(true);
12565
12566   EVT PtrVT = getPointerTy(MF.getDataLayout());
12567   bool isPPC64 = PtrVT == MVT::i64;
12568
12569   // Naked functions never have a frame pointer, and so we use r1. For all
12570   // other functions, this decision must be delayed until during PEI.
12571   unsigned FrameReg;
12572   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12573     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12574   else
12575     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12576
12577   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12578                                          PtrVT);
12579   while (Depth--)
12580     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12581                             FrameAddr, MachinePointerInfo());
12582   return FrameAddr;
12583 }
12584
12585 // FIXME? Maybe this could be a TableGen attribute on some registers and
12586 // this table could be generated automatically from RegInfo.
12587 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12588                                               SelectionDAG &DAG) const {
12589   bool isPPC64 = Subtarget.isPPC64();
12590   bool isDarwinABI = Subtarget.isDarwinABI();
12591
12592   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12593       (!isPPC64 && VT != MVT::i32))
12594     report_fatal_error("Invalid register global variable type");
12595
12596   bool is64Bit = isPPC64 && VT == MVT::i64;
12597   unsigned Reg = StringSwitch<unsigned>(RegName)
12598                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12599                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12600                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12601                                   (is64Bit ? PPC::X13 : PPC::R13))
12602                    .Default(0);
12603
12604   if (Reg)
12605     return Reg;
12606   report_fatal_error("Invalid register name global variable");
12607 }
12608
12609 bool
12610 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12611   // The PowerPC target isn't yet aware of offsets.
12612   return false;
12613 }
12614
12615 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12616                                            const CallInst &I,
12617                                            unsigned Intrinsic) const {
12618   switch (Intrinsic) {
12619   case Intrinsic::ppc_qpx_qvlfd:
12620   case Intrinsic::ppc_qpx_qvlfs:
12621   case Intrinsic::ppc_qpx_qvlfcd:
12622   case Intrinsic::ppc_qpx_qvlfcs:
12623   case Intrinsic::ppc_qpx_qvlfiwa:
12624   case Intrinsic::ppc_qpx_qvlfiwz:
12625   case Intrinsic::ppc_altivec_lvx:
12626   case Intrinsic::ppc_altivec_lvxl:
12627   case Intrinsic::ppc_altivec_lvebx:
12628   case Intrinsic::ppc_altivec_lvehx:
12629   case Intrinsic::ppc_altivec_lvewx:
12630   case Intrinsic::ppc_vsx_lxvd2x:
12631   case Intrinsic::ppc_vsx_lxvw4x: {
12632     EVT VT;
12633     switch (Intrinsic) {
12634     case Intrinsic::ppc_altivec_lvebx:
12635       VT = MVT::i8;
12636       break;
12637     case Intrinsic::ppc_altivec_lvehx:
12638       VT = MVT::i16;
12639       break;
12640     case Intrinsic::ppc_altivec_lvewx:
12641       VT = MVT::i32;
12642       break;
12643     case Intrinsic::ppc_vsx_lxvd2x:
12644       VT = MVT::v2f64;
12645       break;
12646     case Intrinsic::ppc_qpx_qvlfd:
12647       VT = MVT::v4f64;
12648       break;
12649     case Intrinsic::ppc_qpx_qvlfs:
12650       VT = MVT::v4f32;
12651       break;
12652     case Intrinsic::ppc_qpx_qvlfcd:
12653       VT = MVT::v2f64;
12654       break;
12655     case Intrinsic::ppc_qpx_qvlfcs:
12656       VT = MVT::v2f32;
12657       break;
12658     default:
12659       VT = MVT::v4i32;
12660       break;
12661     }
12662
12663     Info.opc = ISD::INTRINSIC_W_CHAIN;
12664     Info.memVT = VT;
12665     Info.ptrVal = I.getArgOperand(0);
12666     Info.offset = -VT.getStoreSize()+1;
12667     Info.size = 2*VT.getStoreSize()-1;
12668     Info.align = 1;
12669     Info.vol = false;
12670     Info.readMem = true;
12671     Info.writeMem = false;
12672     return true;
12673   }
12674   case Intrinsic::ppc_qpx_qvlfda:
12675   case Intrinsic::ppc_qpx_qvlfsa:
12676   case Intrinsic::ppc_qpx_qvlfcda:
12677   case Intrinsic::ppc_qpx_qvlfcsa:
12678   case Intrinsic::ppc_qpx_qvlfiwaa:
12679   case Intrinsic::ppc_qpx_qvlfiwza: {
12680     EVT VT;
12681     switch (Intrinsic) {
12682     case Intrinsic::ppc_qpx_qvlfda:
12683       VT = MVT::v4f64;
12684       break;
12685     case Intrinsic::ppc_qpx_qvlfsa:
12686       VT = MVT::v4f32;
12687       break;
12688     case Intrinsic::ppc_qpx_qvlfcda:
12689       VT = MVT::v2f64;
12690       break;
12691     case Intrinsic::ppc_qpx_qvlfcsa:
12692       VT = MVT::v2f32;
12693       break;
12694     default:
12695       VT = MVT::v4i32;
12696       break;
12697     }
12698
12699     Info.opc = ISD::INTRINSIC_W_CHAIN;
12700     Info.memVT = VT;
12701     Info.ptrVal = I.getArgOperand(0);
12702     Info.offset = 0;
12703     Info.size = VT.getStoreSize();
12704     Info.align = 1;
12705     Info.vol = false;
12706     Info.readMem = true;
12707     Info.writeMem = false;
12708     return true;
12709   }
12710   case Intrinsic::ppc_qpx_qvstfd:
12711   case Intrinsic::ppc_qpx_qvstfs:
12712   case Intrinsic::ppc_qpx_qvstfcd:
12713   case Intrinsic::ppc_qpx_qvstfcs:
12714   case Intrinsic::ppc_qpx_qvstfiw:
12715   case Intrinsic::ppc_altivec_stvx:
12716   case Intrinsic::ppc_altivec_stvxl:
12717   case Intrinsic::ppc_altivec_stvebx:
12718   case Intrinsic::ppc_altivec_stvehx:
12719   case Intrinsic::ppc_altivec_stvewx:
12720   case Intrinsic::ppc_vsx_stxvd2x:
12721   case Intrinsic::ppc_vsx_stxvw4x: {
12722     EVT VT;
12723     switch (Intrinsic) {
12724     case Intrinsic::ppc_altivec_stvebx:
12725       VT = MVT::i8;
12726       break;
12727     case Intrinsic::ppc_altivec_stvehx:
12728       VT = MVT::i16;
12729       break;
12730     case Intrinsic::ppc_altivec_stvewx:
12731       VT = MVT::i32;
12732       break;
12733     case Intrinsic::ppc_vsx_stxvd2x:
12734       VT = MVT::v2f64;
12735       break;
12736     case Intrinsic::ppc_qpx_qvstfd:
12737       VT = MVT::v4f64;
12738       break;
12739     case Intrinsic::ppc_qpx_qvstfs:
12740       VT = MVT::v4f32;
12741       break;
12742     case Intrinsic::ppc_qpx_qvstfcd:
12743       VT = MVT::v2f64;
12744       break;
12745     case Intrinsic::ppc_qpx_qvstfcs:
12746       VT = MVT::v2f32;
12747       break;
12748     default:
12749       VT = MVT::v4i32;
12750       break;
12751     }
12752
12753     Info.opc = ISD::INTRINSIC_VOID;
12754     Info.memVT = VT;
12755     Info.ptrVal = I.getArgOperand(1);
12756     Info.offset = -VT.getStoreSize()+1;
12757     Info.size = 2*VT.getStoreSize()-1;
12758     Info.align = 1;
12759     Info.vol = false;
12760     Info.readMem = false;
12761     Info.writeMem = true;
12762     return true;
12763   }
12764   case Intrinsic::ppc_qpx_qvstfda:
12765   case Intrinsic::ppc_qpx_qvstfsa:
12766   case Intrinsic::ppc_qpx_qvstfcda:
12767   case Intrinsic::ppc_qpx_qvstfcsa:
12768   case Intrinsic::ppc_qpx_qvstfiwa: {
12769     EVT VT;
12770     switch (Intrinsic) {
12771     case Intrinsic::ppc_qpx_qvstfda:
12772       VT = MVT::v4f64;
12773       break;
12774     case Intrinsic::ppc_qpx_qvstfsa:
12775       VT = MVT::v4f32;
12776       break;
12777     case Intrinsic::ppc_qpx_qvstfcda:
12778       VT = MVT::v2f64;
12779       break;
12780     case Intrinsic::ppc_qpx_qvstfcsa:
12781       VT = MVT::v2f32;
12782       break;
12783     default:
12784       VT = MVT::v4i32;
12785       break;
12786     }
12787
12788     Info.opc = ISD::INTRINSIC_VOID;
12789     Info.memVT = VT;
12790     Info.ptrVal = I.getArgOperand(1);
12791     Info.offset = 0;
12792     Info.size = VT.getStoreSize();
12793     Info.align = 1;
12794     Info.vol = false;
12795     Info.readMem = false;
12796     Info.writeMem = true;
12797     return true;
12798   }
12799   default:
12800     break;
12801   }
12802
12803   return false;
12804 }
12805
12806 /// getOptimalMemOpType - Returns the target specific optimal type for load
12807 /// and store operations as a result of memset, memcpy, and memmove
12808 /// lowering. If DstAlign is zero that means it's safe to destination
12809 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12810 /// means there isn't a need to check it against alignment requirement,
12811 /// probably because the source does not need to be loaded. If 'IsMemset' is
12812 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12813 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12814 /// source is constant so it does not need to be loaded.
12815 /// It returns EVT::Other if the type should be determined using generic
12816 /// target-independent logic.
12817 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12818                                            unsigned DstAlign, unsigned SrcAlign,
12819                                            bool IsMemset, bool ZeroMemset,
12820                                            bool MemcpyStrSrc,
12821                                            MachineFunction &MF) const {
12822   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12823     const Function *F = MF.getFunction();
12824     // When expanding a memset, require at least two QPX instructions to cover
12825     // the cost of loading the value to be stored from the constant pool.
12826     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12827        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12828         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12829       return MVT::v4f64;
12830     }
12831
12832     // We should use Altivec/VSX loads and stores when available. For unaligned
12833     // addresses, unaligned VSX loads are only fast starting with the P8.
12834     if (Subtarget.hasAltivec() && Size >= 16 &&
12835         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12836          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12837       return MVT::v4i32;
12838   }
12839
12840   if (Subtarget.isPPC64()) {
12841     return MVT::i64;
12842   }
12843
12844   return MVT::i32;
12845 }
12846
12847 /// \brief Returns true if it is beneficial to convert a load of a constant
12848 /// to just the constant itself.
12849 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12850                                                           Type *Ty) const {
12851   assert(Ty->isIntegerTy());
12852
12853   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12854   return !(BitSize == 0 || BitSize > 64);
12855 }
12856
12857 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12858   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12859     return false;
12860   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12861   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12862   return NumBits1 == 64 && NumBits2 == 32;
12863 }
12864
12865 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12866   if (!VT1.isInteger() || !VT2.isInteger())
12867     return false;
12868   unsigned NumBits1 = VT1.getSizeInBits();
12869   unsigned NumBits2 = VT2.getSizeInBits();
12870   return NumBits1 == 64 && NumBits2 == 32;
12871 }
12872
12873 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12874   // Generally speaking, zexts are not free, but they are free when they can be
12875   // folded with other operations.
12876   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12877     EVT MemVT = LD->getMemoryVT();
12878     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12879          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12880         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12881          LD->getExtensionType() == ISD::ZEXTLOAD))
12882       return true;
12883   }
12884
12885   // FIXME: Add other cases...
12886   //  - 32-bit shifts with a zext to i64
12887   //  - zext after ctlz, bswap, etc.
12888   //  - zext after and by a constant mask
12889
12890   return TargetLowering::isZExtFree(Val, VT2);
12891 }
12892
12893 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12894   assert(VT.isFloatingPoint());
12895   return true;
12896 }
12897
12898 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12899   return isInt<16>(Imm) || isUInt<16>(Imm);
12900 }
12901
12902 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12903   return isInt<16>(Imm) || isUInt<16>(Imm);
12904 }
12905
12906 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12907                                                        unsigned,
12908                                                        unsigned,
12909                                                        bool *Fast) const {
12910   if (DisablePPCUnaligned)
12911     return false;
12912
12913   // PowerPC supports unaligned memory access for simple non-vector types.
12914   // Although accessing unaligned addresses is not as efficient as accessing
12915   // aligned addresses, it is generally more efficient than manual expansion,
12916   // and generally only traps for software emulation when crossing page
12917   // boundaries.
12918
12919   if (!VT.isSimple())
12920     return false;
12921
12922   if (VT.getSimpleVT().isVector()) {
12923     if (Subtarget.hasVSX()) {
12924       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12925           VT != MVT::v4f32 && VT != MVT::v4i32)
12926         return false;
12927     } else {
12928       return false;
12929     }
12930   }
12931
12932   if (VT == MVT::ppcf128)
12933     return false;
12934
12935   if (Fast)
12936     *Fast = true;
12937
12938   return true;
12939 }
12940
12941 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12942   VT = VT.getScalarType();
12943
12944   if (!VT.isSimple())
12945     return false;
12946
12947   switch (VT.getSimpleVT().SimpleTy) {
12948   case MVT::f32:
12949   case MVT::f64:
12950     return true;
12951   default:
12952     break;
12953   }
12954
12955   return false;
12956 }
12957
12958 const MCPhysReg *
12959 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12960   // LR is a callee-save register, but we must treat it as clobbered by any call
12961   // site. Hence we include LR in the scratch registers, which are in turn added
12962   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12963   // to CTR, which is used by any indirect call.
12964   static const MCPhysReg ScratchRegs[] = {
12965     PPC::X12, PPC::LR8, PPC::CTR8, 0
12966   };
12967
12968   return ScratchRegs;
12969 }
12970
12971 unsigned PPCTargetLowering::getExceptionPointerRegister(
12972     const Constant *PersonalityFn) const {
12973   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12974 }
12975
12976 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12977     const Constant *PersonalityFn) const {
12978   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12979 }
12980
12981 bool
12982 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12983                      EVT VT , unsigned DefinedValues) const {
12984   if (VT == MVT::v2i64)
12985     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12986
12987   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12988     return true;
12989
12990   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12991 }
12992
12993 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12994   if (DisableILPPref || Subtarget.enableMachineScheduler())
12995     return TargetLowering::getSchedulingPreference(N);
12996
12997   return Sched::ILP;
12998 }
12999
13000 // Create a fast isel object.
13001 FastISel *
13002 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
13003                                   const TargetLibraryInfo *LibInfo) const {
13004   return PPC::createFastISel(FuncInfo, LibInfo);
13005 }
13006
13007 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13008   if (Subtarget.isDarwinABI()) return;
13009   if (!Subtarget.isPPC64()) return;
13010
13011   // Update IsSplitCSR in PPCFunctionInfo
13012   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
13013   PFI->setIsSplitCSR(true);
13014 }
13015
13016 void PPCTargetLowering::insertCopiesSplitCSR(
13017   MachineBasicBlock *Entry,
13018   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13019   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
13020   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13021   if (!IStart)
13022     return;
13023
13024   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
13025   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13026   MachineBasicBlock::iterator MBBI = Entry->begin();
13027   for (const MCPhysReg *I = IStart; *I; ++I) {
13028     const TargetRegisterClass *RC = nullptr;
13029     if (PPC::G8RCRegClass.contains(*I))
13030       RC = &PPC::G8RCRegClass;
13031     else if (PPC::F8RCRegClass.contains(*I))
13032       RC = &PPC::F8RCRegClass;
13033     else if (PPC::CRRCRegClass.contains(*I))
13034       RC = &PPC::CRRCRegClass;
13035     else if (PPC::VRRCRegClass.contains(*I))
13036       RC = &PPC::VRRCRegClass;
13037     else
13038       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
13039
13040     unsigned NewVR = MRI->createVirtualRegister(RC);
13041     // Create copy from CSR to a virtual register.
13042     // FIXME: this currently does not emit CFI pseudo-instructions, it works
13043     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
13044     // nounwind. If we want to generalize this later, we may need to emit
13045     // CFI pseudo-instructions.
13046     assert(Entry->getParent()->getFunction()->hasFnAttribute(
13047              Attribute::NoUnwind) &&
13048            "Function should be nounwind in insertCopiesSplitCSR!");
13049     Entry->addLiveIn(*I);
13050     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
13051       .addReg(*I);
13052
13053     // Insert the copy-back instructions right before the terminator
13054     for (auto *Exit : Exits)
13055       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
13056               TII->get(TargetOpcode::COPY), *I)
13057         .addReg(NewVR);
13058   }
13059 }
13060
13061 // Override to enable LOAD_STACK_GUARD lowering on Linux.
13062 bool PPCTargetLowering::useLoadStackGuardNode() const {
13063   if (!Subtarget.isTargetLinux())
13064     return TargetLowering::useLoadStackGuardNode();
13065   return true;
13066 }
13067
13068 // Override to disable global variable loading on Linux.
13069 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
13070   if (!Subtarget.isTargetLinux())
13071     return TargetLowering::insertSSPDeclarations(M);
13072 }
13073
13074 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13075   if (!VT.isSimple() || !Subtarget.hasVSX())
13076     return false;
13077
13078   switch(VT.getSimpleVT().SimpleTy) {
13079   default:
13080     // For FP types that are currently not supported by PPC backend, return
13081     // false. Examples: f16, f80.
13082     return false;
13083   case MVT::f32:
13084   case MVT::f64:
13085   case MVT::ppcf128:
13086     return Imm.isPosZero();
13087   }
13088 }
13089
13090 // For vector shift operation op, fold
13091 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13092 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13093                                   SelectionDAG &DAG) {
13094   SDValue N0 = N->getOperand(0);
13095   SDValue N1 = N->getOperand(1);
13096   EVT VT = N0.getValueType();
13097   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13098   unsigned Opcode = N->getOpcode();
13099   unsigned TargetOpcode;
13100
13101   switch (Opcode) {
13102   default:
13103     llvm_unreachable("Unexpected shift operation");
13104   case ISD::SHL:
13105     TargetOpcode = PPCISD::SHL;
13106     break;
13107   case ISD::SRL:
13108     TargetOpcode = PPCISD::SRL;
13109     break;
13110   case ISD::SRA:
13111     TargetOpcode = PPCISD::SRA;
13112     break;
13113   }
13114
13115   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13116       N1->getOpcode() == ISD::AND)
13117     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13118       if (Mask->getZExtValue() == OpSizeInBits - 1)
13119         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13120
13121   return SDValue();
13122 }
13123
13124 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13125   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13126     return Value;
13127
13128   return SDValue();
13129 }
13130
13131 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13132   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13133     return Value;
13134
13135   return SDValue();
13136 }
13137
13138 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13139   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13140     return Value;
13141
13142   return SDValue();
13143 }