]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/PowerPC/PPCISelLowering.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r303571, 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::FPOWI, VT, Expand);
543       setOperationAction(ISD::FFLOOR, VT, Expand);
544       setOperationAction(ISD::FCEIL,  VT, Expand);
545       setOperationAction(ISD::FTRUNC, VT, Expand);
546       setOperationAction(ISD::FRINT,  VT, Expand);
547       setOperationAction(ISD::FNEARBYINT, VT, Expand);
548       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
549       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
550       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
551       setOperationAction(ISD::MULHU, VT, Expand);
552       setOperationAction(ISD::MULHS, VT, Expand);
553       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
554       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
555       setOperationAction(ISD::UDIVREM, VT, Expand);
556       setOperationAction(ISD::SDIVREM, VT, Expand);
557       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
558       setOperationAction(ISD::FPOW, VT, Expand);
559       setOperationAction(ISD::BSWAP, VT, Expand);
560       setOperationAction(ISD::VSELECT, VT, Expand);
561       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
562       setOperationAction(ISD::ROTL, VT, Expand);
563       setOperationAction(ISD::ROTR, VT, Expand);
564
565       for (MVT InnerVT : MVT::vector_valuetypes()) {
566         setTruncStoreAction(VT, InnerVT, Expand);
567         setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
568         setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
569         setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
570       }
571     }
572
573     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
574     // with merges, splats, etc.
575     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
576
577     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
578     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
579     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
580     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
581     setOperationAction(ISD::SELECT, MVT::v4i32,
582                        Subtarget.useCRBits() ? Legal : Expand);
583     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
584     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
585     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
586     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
587     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
588     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
589     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
590     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
591     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
592
593     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
594     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
595     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
596     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
597
598     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
599     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
600
601     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
602       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
603       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
604     }
605
606     if (Subtarget.hasP8Altivec())
607       setOperationAction(ISD::MUL, MVT::v4i32, Legal);
608     else
609       setOperationAction(ISD::MUL, MVT::v4i32, Custom);
610
611     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
612     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
613
614     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
615     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
616
617     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
618     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
619     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
620     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
621
622     // Altivec does not contain unordered floating-point compare instructions
623     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
624     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
625     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
626     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
627
628     if (Subtarget.hasVSX()) {
629       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
630       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
631       if (Subtarget.hasP8Vector()) {
632         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
633         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
634       }
635       if (Subtarget.hasDirectMove() && isPPC64) {
636         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Legal);
637         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Legal);
638         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Legal);
639         setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Legal);
640         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Legal);
641         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Legal);
642         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
643         setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
644       }
645       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
646
647       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
648       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
649       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
650       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
651       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
652
653       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
654
655       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
656       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
657
658       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
659       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
660
661       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
662       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
663       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
664       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
665       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
666
667       // Share the Altivec comparison restrictions.
668       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
669       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
670       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
671       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
672
673       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
674       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
675
676       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
677
678       if (Subtarget.hasP8Vector())
679         addRegisterClass(MVT::f32, &PPC::VSSRCRegClass);
680
681       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
682
683       addRegisterClass(MVT::v4i32, &PPC::VSRCRegClass);
684       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
685       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
686
687       if (Subtarget.hasP8Altivec()) {
688         setOperationAction(ISD::SHL, MVT::v2i64, Legal);
689         setOperationAction(ISD::SRA, MVT::v2i64, Legal);
690         setOperationAction(ISD::SRL, MVT::v2i64, Legal);
691
692         // 128 bit shifts can be accomplished via 3 instructions for SHL and
693         // SRL, but not for SRA because of the instructions available:
694         // VS{RL} and VS{RL}O. However due to direct move costs, it's not worth
695         // doing
696         setOperationAction(ISD::SHL, MVT::v1i128, Expand);
697         setOperationAction(ISD::SRL, MVT::v1i128, Expand);
698         setOperationAction(ISD::SRA, MVT::v1i128, Expand);
699
700         setOperationAction(ISD::SETCC, MVT::v2i64, Legal);
701       }
702       else {
703         setOperationAction(ISD::SHL, MVT::v2i64, Expand);
704         setOperationAction(ISD::SRA, MVT::v2i64, Expand);
705         setOperationAction(ISD::SRL, MVT::v2i64, Expand);
706
707         setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
708
709         // VSX v2i64 only supports non-arithmetic operations.
710         setOperationAction(ISD::ADD, MVT::v2i64, Expand);
711         setOperationAction(ISD::SUB, MVT::v2i64, Expand);
712       }
713
714       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
715       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
716       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
717       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
718
719       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
720
721       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
722       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
723       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
724       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
725
726       // Vector operation legalization checks the result type of
727       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
728       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
729       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
730       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
731       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
732
733       setOperationAction(ISD::FNEG, MVT::v4f32, Legal);
734       setOperationAction(ISD::FNEG, MVT::v2f64, Legal);
735       setOperationAction(ISD::FABS, MVT::v4f32, Legal);
736       setOperationAction(ISD::FABS, MVT::v2f64, Legal);
737
738       if (Subtarget.hasDirectMove())
739         setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
740       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
741
742       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
743     }
744
745     if (Subtarget.hasP8Altivec()) {
746       addRegisterClass(MVT::v2i64, &PPC::VRRCRegClass);
747       addRegisterClass(MVT::v1i128, &PPC::VRRCRegClass);
748     }
749
750     if (Subtarget.hasP9Vector()) {
751       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
752       setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
753
754       // 128 bit shifts can be accomplished via 3 instructions for SHL and
755       // SRL, but not for SRA because of the instructions available:
756       // VS{RL} and VS{RL}O.
757       setOperationAction(ISD::SHL, MVT::v1i128, Legal);
758       setOperationAction(ISD::SRL, MVT::v1i128, Legal);
759       setOperationAction(ISD::SRA, MVT::v1i128, Expand);
760     }
761   }
762
763   if (Subtarget.hasQPX()) {
764     setOperationAction(ISD::FADD, MVT::v4f64, Legal);
765     setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
766     setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
767     setOperationAction(ISD::FREM, MVT::v4f64, Expand);
768
769     setOperationAction(ISD::FCOPYSIGN, MVT::v4f64, Legal);
770     setOperationAction(ISD::FGETSIGN, MVT::v4f64, Expand);
771
772     setOperationAction(ISD::LOAD  , MVT::v4f64, Custom);
773     setOperationAction(ISD::STORE , MVT::v4f64, Custom);
774
775     setTruncStoreAction(MVT::v4f64, MVT::v4f32, Custom);
776     setLoadExtAction(ISD::EXTLOAD, MVT::v4f64, MVT::v4f32, Custom);
777
778     if (!Subtarget.useCRBits())
779       setOperationAction(ISD::SELECT, MVT::v4f64, Expand);
780     setOperationAction(ISD::VSELECT, MVT::v4f64, Legal);
781
782     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f64, Legal);
783     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f64, Expand);
784     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f64, Expand);
785     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f64, Expand);
786     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f64, Custom);
787     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f64, Legal);
788     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
789
790     setOperationAction(ISD::FP_TO_SINT , MVT::v4f64, Legal);
791     setOperationAction(ISD::FP_TO_UINT , MVT::v4f64, Expand);
792
793     setOperationAction(ISD::FP_ROUND , MVT::v4f32, Legal);
794     setOperationAction(ISD::FP_ROUND_INREG , MVT::v4f32, Expand);
795     setOperationAction(ISD::FP_EXTEND, MVT::v4f64, Legal);
796
797     setOperationAction(ISD::FNEG , MVT::v4f64, Legal);
798     setOperationAction(ISD::FABS , MVT::v4f64, Legal);
799     setOperationAction(ISD::FSIN , MVT::v4f64, Expand);
800     setOperationAction(ISD::FCOS , MVT::v4f64, Expand);
801     setOperationAction(ISD::FPOWI , MVT::v4f64, Expand);
802     setOperationAction(ISD::FPOW , MVT::v4f64, Expand);
803     setOperationAction(ISD::FLOG , MVT::v4f64, Expand);
804     setOperationAction(ISD::FLOG2 , MVT::v4f64, Expand);
805     setOperationAction(ISD::FLOG10 , MVT::v4f64, Expand);
806     setOperationAction(ISD::FEXP , MVT::v4f64, Expand);
807     setOperationAction(ISD::FEXP2 , MVT::v4f64, Expand);
808
809     setOperationAction(ISD::FMINNUM, MVT::v4f64, Legal);
810     setOperationAction(ISD::FMAXNUM, MVT::v4f64, Legal);
811
812     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f64, Legal);
813     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f64, Legal);
814
815     addRegisterClass(MVT::v4f64, &PPC::QFRCRegClass);
816
817     setOperationAction(ISD::FADD, MVT::v4f32, Legal);
818     setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
819     setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
820     setOperationAction(ISD::FREM, MVT::v4f32, Expand);
821
822     setOperationAction(ISD::FCOPYSIGN, MVT::v4f32, Legal);
823     setOperationAction(ISD::FGETSIGN, MVT::v4f32, Expand);
824
825     setOperationAction(ISD::LOAD  , MVT::v4f32, Custom);
826     setOperationAction(ISD::STORE , MVT::v4f32, Custom);
827
828     if (!Subtarget.useCRBits())
829       setOperationAction(ISD::SELECT, MVT::v4f32, Expand);
830     setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
831
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4f32, Legal);
833     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4f32, Expand);
834     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4f32, Expand);
835     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4f32, Expand);
836     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4f32, Custom);
837     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Legal);
838     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
839
840     setOperationAction(ISD::FP_TO_SINT , MVT::v4f32, Legal);
841     setOperationAction(ISD::FP_TO_UINT , MVT::v4f32, Expand);
842
843     setOperationAction(ISD::FNEG , MVT::v4f32, Legal);
844     setOperationAction(ISD::FABS , MVT::v4f32, Legal);
845     setOperationAction(ISD::FSIN , MVT::v4f32, Expand);
846     setOperationAction(ISD::FCOS , MVT::v4f32, Expand);
847     setOperationAction(ISD::FPOWI , MVT::v4f32, Expand);
848     setOperationAction(ISD::FPOW , MVT::v4f32, Expand);
849     setOperationAction(ISD::FLOG , MVT::v4f32, Expand);
850     setOperationAction(ISD::FLOG2 , MVT::v4f32, Expand);
851     setOperationAction(ISD::FLOG10 , MVT::v4f32, Expand);
852     setOperationAction(ISD::FEXP , MVT::v4f32, Expand);
853     setOperationAction(ISD::FEXP2 , MVT::v4f32, Expand);
854
855     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
856     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
857
858     setIndexedLoadAction(ISD::PRE_INC, MVT::v4f32, Legal);
859     setIndexedStoreAction(ISD::PRE_INC, MVT::v4f32, Legal);
860
861     addRegisterClass(MVT::v4f32, &PPC::QSRCRegClass);
862
863     setOperationAction(ISD::AND , MVT::v4i1, Legal);
864     setOperationAction(ISD::OR , MVT::v4i1, Legal);
865     setOperationAction(ISD::XOR , MVT::v4i1, Legal);
866
867     if (!Subtarget.useCRBits())
868       setOperationAction(ISD::SELECT, MVT::v4i1, Expand);
869     setOperationAction(ISD::VSELECT, MVT::v4i1, Legal);
870
871     setOperationAction(ISD::LOAD  , MVT::v4i1, Custom);
872     setOperationAction(ISD::STORE , MVT::v4i1, Custom);
873
874     setOperationAction(ISD::EXTRACT_VECTOR_ELT , MVT::v4i1, Custom);
875     setOperationAction(ISD::INSERT_VECTOR_ELT , MVT::v4i1, Expand);
876     setOperationAction(ISD::CONCAT_VECTORS , MVT::v4i1, Expand);
877     setOperationAction(ISD::EXTRACT_SUBVECTOR , MVT::v4i1, Expand);
878     setOperationAction(ISD::VECTOR_SHUFFLE , MVT::v4i1, Custom);
879     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i1, Expand);
880     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i1, Custom);
881
882     setOperationAction(ISD::SINT_TO_FP, MVT::v4i1, Custom);
883     setOperationAction(ISD::UINT_TO_FP, MVT::v4i1, Custom);
884
885     addRegisterClass(MVT::v4i1, &PPC::QBRCRegClass);
886
887     setOperationAction(ISD::FFLOOR, MVT::v4f64, Legal);
888     setOperationAction(ISD::FCEIL,  MVT::v4f64, Legal);
889     setOperationAction(ISD::FTRUNC, MVT::v4f64, Legal);
890     setOperationAction(ISD::FROUND, MVT::v4f64, Legal);
891
892     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
893     setOperationAction(ISD::FCEIL,  MVT::v4f32, Legal);
894     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
895     setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
896
897     setOperationAction(ISD::FNEARBYINT, MVT::v4f64, Expand);
898     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
899
900     // These need to set FE_INEXACT, and so cannot be vectorized here.
901     setOperationAction(ISD::FRINT, MVT::v4f64, Expand);
902     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
903
904     if (TM.Options.UnsafeFPMath) {
905       setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
906       setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
907
908       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
909       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
910     } else {
911       setOperationAction(ISD::FDIV, MVT::v4f64, Expand);
912       setOperationAction(ISD::FSQRT, MVT::v4f64, Expand);
913
914       setOperationAction(ISD::FDIV, MVT::v4f32, Expand);
915       setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
916     }
917   }
918
919   if (Subtarget.has64BitSupport())
920     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
921
922   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
923
924   if (!isPPC64) {
925     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
926     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
927   }
928
929   setBooleanContents(ZeroOrOneBooleanContent);
930
931   if (Subtarget.hasAltivec()) {
932     // Altivec instructions set fields to all zeros or all ones.
933     setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
934   }
935
936   if (!isPPC64) {
937     // These libcalls are not available in 32-bit.
938     setLibcallName(RTLIB::SHL_I128, nullptr);
939     setLibcallName(RTLIB::SRL_I128, nullptr);
940     setLibcallName(RTLIB::SRA_I128, nullptr);
941   }
942
943   setStackPointerRegisterToSaveRestore(isPPC64 ? PPC::X1 : PPC::R1);
944
945   // We have target-specific dag combine patterns for the following nodes:
946   setTargetDAGCombine(ISD::SHL);
947   setTargetDAGCombine(ISD::SRA);
948   setTargetDAGCombine(ISD::SRL);
949   setTargetDAGCombine(ISD::SINT_TO_FP);
950   setTargetDAGCombine(ISD::BUILD_VECTOR);
951   if (Subtarget.hasFPCVT())
952     setTargetDAGCombine(ISD::UINT_TO_FP);
953   setTargetDAGCombine(ISD::LOAD);
954   setTargetDAGCombine(ISD::STORE);
955   setTargetDAGCombine(ISD::BR_CC);
956   if (Subtarget.useCRBits())
957     setTargetDAGCombine(ISD::BRCOND);
958   setTargetDAGCombine(ISD::BSWAP);
959   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
960   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
961   setTargetDAGCombine(ISD::INTRINSIC_VOID);
962
963   setTargetDAGCombine(ISD::SIGN_EXTEND);
964   setTargetDAGCombine(ISD::ZERO_EXTEND);
965   setTargetDAGCombine(ISD::ANY_EXTEND);
966
967   if (Subtarget.useCRBits()) {
968     setTargetDAGCombine(ISD::TRUNCATE);
969     setTargetDAGCombine(ISD::SETCC);
970     setTargetDAGCombine(ISD::SELECT_CC);
971   }
972
973   // Use reciprocal estimates.
974   if (TM.Options.UnsafeFPMath) {
975     setTargetDAGCombine(ISD::FDIV);
976     setTargetDAGCombine(ISD::FSQRT);
977   }
978
979   // Darwin long double math library functions have $LDBL128 appended.
980   if (Subtarget.isDarwin()) {
981     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
982     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
983     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
984     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
985     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
986     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
987     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
988     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
989     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
990     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
991   }
992
993   // With 32 condition bits, we don't need to sink (and duplicate) compares
994   // aggressively in CodeGenPrep.
995   if (Subtarget.useCRBits()) {
996     setHasMultipleConditionRegisters();
997     setJumpIsExpensive();
998   }
999
1000   setMinFunctionAlignment(2);
1001   if (Subtarget.isDarwin())
1002     setPrefFunctionAlignment(4);
1003
1004   switch (Subtarget.getDarwinDirective()) {
1005   default: break;
1006   case PPC::DIR_970:
1007   case PPC::DIR_A2:
1008   case PPC::DIR_E500mc:
1009   case PPC::DIR_E5500:
1010   case PPC::DIR_PWR4:
1011   case PPC::DIR_PWR5:
1012   case PPC::DIR_PWR5X:
1013   case PPC::DIR_PWR6:
1014   case PPC::DIR_PWR6X:
1015   case PPC::DIR_PWR7:
1016   case PPC::DIR_PWR8:
1017   case PPC::DIR_PWR9:
1018     setPrefFunctionAlignment(4);
1019     setPrefLoopAlignment(4);
1020     break;
1021   }
1022
1023   if (Subtarget.enableMachineScheduler())
1024     setSchedulingPreference(Sched::Source);
1025   else
1026     setSchedulingPreference(Sched::Hybrid);
1027
1028   computeRegisterProperties(STI.getRegisterInfo());
1029
1030   // The Freescale cores do better with aggressive inlining of memcpy and
1031   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
1032   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
1033       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
1034     MaxStoresPerMemset = 32;
1035     MaxStoresPerMemsetOptSize = 16;
1036     MaxStoresPerMemcpy = 32;
1037     MaxStoresPerMemcpyOptSize = 8;
1038     MaxStoresPerMemmove = 32;
1039     MaxStoresPerMemmoveOptSize = 8;
1040   } else if (Subtarget.getDarwinDirective() == PPC::DIR_A2) {
1041     // The A2 also benefits from (very) aggressive inlining of memcpy and
1042     // friends. The overhead of a the function call, even when warm, can be
1043     // over one hundred cycles.
1044     MaxStoresPerMemset = 128;
1045     MaxStoresPerMemcpy = 128;
1046     MaxStoresPerMemmove = 128;
1047   }
1048 }
1049
1050 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1051 /// the desired ByVal argument alignment.
1052 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
1053                              unsigned MaxMaxAlign) {
1054   if (MaxAlign == MaxMaxAlign)
1055     return;
1056   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1057     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
1058       MaxAlign = 32;
1059     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
1060       MaxAlign = 16;
1061   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1062     unsigned EltAlign = 0;
1063     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
1064     if (EltAlign > MaxAlign)
1065       MaxAlign = EltAlign;
1066   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1067     for (auto *EltTy : STy->elements()) {
1068       unsigned EltAlign = 0;
1069       getMaxByValAlign(EltTy, EltAlign, MaxMaxAlign);
1070       if (EltAlign > MaxAlign)
1071         MaxAlign = EltAlign;
1072       if (MaxAlign == MaxMaxAlign)
1073         break;
1074     }
1075   }
1076 }
1077
1078 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1079 /// function arguments in the caller parameter area.
1080 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty,
1081                                                   const DataLayout &DL) const {
1082   // Darwin passes everything on 4 byte boundary.
1083   if (Subtarget.isDarwin())
1084     return 4;
1085
1086   // 16byte and wider vectors are passed on 16byte boundary.
1087   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
1088   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
1089   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
1090     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
1091   return Align;
1092 }
1093
1094 bool PPCTargetLowering::useSoftFloat() const {
1095   return Subtarget.useSoftFloat();
1096 }
1097
1098 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
1099   switch ((PPCISD::NodeType)Opcode) {
1100   case PPCISD::FIRST_NUMBER:    break;
1101   case PPCISD::FSEL:            return "PPCISD::FSEL";
1102   case PPCISD::FCFID:           return "PPCISD::FCFID";
1103   case PPCISD::FCFIDU:          return "PPCISD::FCFIDU";
1104   case PPCISD::FCFIDS:          return "PPCISD::FCFIDS";
1105   case PPCISD::FCFIDUS:         return "PPCISD::FCFIDUS";
1106   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
1107   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
1108   case PPCISD::FCTIDUZ:         return "PPCISD::FCTIDUZ";
1109   case PPCISD::FCTIWUZ:         return "PPCISD::FCTIWUZ";
1110   case PPCISD::FRE:             return "PPCISD::FRE";
1111   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
1112   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
1113   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
1114   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
1115   case PPCISD::VPERM:           return "PPCISD::VPERM";
1116   case PPCISD::XXSPLT:          return "PPCISD::XXSPLT";
1117   case PPCISD::XXINSERT:        return "PPCISD::XXINSERT";
1118   case PPCISD::VECSHL:          return "PPCISD::VECSHL";
1119   case PPCISD::CMPB:            return "PPCISD::CMPB";
1120   case PPCISD::Hi:              return "PPCISD::Hi";
1121   case PPCISD::Lo:              return "PPCISD::Lo";
1122   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
1123   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
1124   case PPCISD::DYNAREAOFFSET:   return "PPCISD::DYNAREAOFFSET";
1125   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
1126   case PPCISD::SRL:             return "PPCISD::SRL";
1127   case PPCISD::SRA:             return "PPCISD::SRA";
1128   case PPCISD::SHL:             return "PPCISD::SHL";
1129   case PPCISD::SRA_ADDZE:       return "PPCISD::SRA_ADDZE";
1130   case PPCISD::CALL:            return "PPCISD::CALL";
1131   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
1132   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
1133   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
1134   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
1135   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
1136   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
1137   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
1138   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
1139   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
1140   case PPCISD::MFVSR:           return "PPCISD::MFVSR";
1141   case PPCISD::MTVSRA:          return "PPCISD::MTVSRA";
1142   case PPCISD::MTVSRZ:          return "PPCISD::MTVSRZ";
1143   case PPCISD::SINT_VEC_TO_FP:  return "PPCISD::SINT_VEC_TO_FP";
1144   case PPCISD::UINT_VEC_TO_FP:  return "PPCISD::UINT_VEC_TO_FP";
1145   case PPCISD::ANDIo_1_EQ_BIT:  return "PPCISD::ANDIo_1_EQ_BIT";
1146   case PPCISD::ANDIo_1_GT_BIT:  return "PPCISD::ANDIo_1_GT_BIT";
1147   case PPCISD::VCMP:            return "PPCISD::VCMP";
1148   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
1149   case PPCISD::LBRX:            return "PPCISD::LBRX";
1150   case PPCISD::STBRX:           return "PPCISD::STBRX";
1151   case PPCISD::LFIWAX:          return "PPCISD::LFIWAX";
1152   case PPCISD::LFIWZX:          return "PPCISD::LFIWZX";
1153   case PPCISD::LXSIZX:          return "PPCISD::LXSIZX";
1154   case PPCISD::STXSIX:          return "PPCISD::STXSIX";
1155   case PPCISD::VEXTS:           return "PPCISD::VEXTS";
1156   case PPCISD::LXVD2X:          return "PPCISD::LXVD2X";
1157   case PPCISD::STXVD2X:         return "PPCISD::STXVD2X";
1158   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
1159   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
1160   case PPCISD::BDZ:             return "PPCISD::BDZ";
1161   case PPCISD::MFFS:            return "PPCISD::MFFS";
1162   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
1163   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
1164   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
1165   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
1166   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
1167   case PPCISD::PPC32_PICGOT:    return "PPCISD::PPC32_PICGOT";
1168   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
1169   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
1170   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
1171   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
1172   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
1173   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
1174   case PPCISD::ADDI_TLSGD_L_ADDR: return "PPCISD::ADDI_TLSGD_L_ADDR";
1175   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
1176   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
1177   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
1178   case PPCISD::ADDI_TLSLD_L_ADDR: return "PPCISD::ADDI_TLSLD_L_ADDR";
1179   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
1180   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
1181   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
1182   case PPCISD::SC:              return "PPCISD::SC";
1183   case PPCISD::CLRBHRB:         return "PPCISD::CLRBHRB";
1184   case PPCISD::MFBHRBE:         return "PPCISD::MFBHRBE";
1185   case PPCISD::RFEBB:           return "PPCISD::RFEBB";
1186   case PPCISD::XXSWAPD:         return "PPCISD::XXSWAPD";
1187   case PPCISD::SWAP_NO_CHAIN:   return "PPCISD::SWAP_NO_CHAIN";
1188   case PPCISD::QVFPERM:         return "PPCISD::QVFPERM";
1189   case PPCISD::QVGPCI:          return "PPCISD::QVGPCI";
1190   case PPCISD::QVALIGNI:        return "PPCISD::QVALIGNI";
1191   case PPCISD::QVESPLATI:       return "PPCISD::QVESPLATI";
1192   case PPCISD::QBFLT:           return "PPCISD::QBFLT";
1193   case PPCISD::QVLFSb:          return "PPCISD::QVLFSb";
1194   }
1195   return nullptr;
1196 }
1197
1198 EVT PPCTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &C,
1199                                           EVT VT) const {
1200   if (!VT.isVector())
1201     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
1202
1203   if (Subtarget.hasQPX())
1204     return EVT::getVectorVT(C, MVT::i1, VT.getVectorNumElements());
1205
1206   return VT.changeVectorElementTypeToInteger();
1207 }
1208
1209 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
1210   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
1211   return true;
1212 }
1213
1214 //===----------------------------------------------------------------------===//
1215 // Node matching predicates, for use by the tblgen matching code.
1216 //===----------------------------------------------------------------------===//
1217
1218 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
1219 static bool isFloatingPointZero(SDValue Op) {
1220   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
1221     return CFP->getValueAPF().isZero();
1222   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
1223     // Maybe this has already been legalized into the constant pool?
1224     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
1225       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
1226         return CFP->getValueAPF().isZero();
1227   }
1228   return false;
1229 }
1230
1231 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
1232 /// true if Op is undef or if it matches the specified value.
1233 static bool isConstantOrUndef(int Op, int Val) {
1234   return Op < 0 || Op == Val;
1235 }
1236
1237 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
1238 /// VPKUHUM instruction.
1239 /// The ShuffleKind distinguishes between big-endian operations with
1240 /// two different inputs (0), either-endian operations with two identical
1241 /// inputs (1), and little-endian operations with two different inputs (2).
1242 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1243 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1244                                SelectionDAG &DAG) {
1245   bool IsLE = DAG.getDataLayout().isLittleEndian();
1246   if (ShuffleKind == 0) {
1247     if (IsLE)
1248       return false;
1249     for (unsigned i = 0; i != 16; ++i)
1250       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
1251         return false;
1252   } else if (ShuffleKind == 2) {
1253     if (!IsLE)
1254       return false;
1255     for (unsigned i = 0; i != 16; ++i)
1256       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
1257         return false;
1258   } else if (ShuffleKind == 1) {
1259     unsigned j = IsLE ? 0 : 1;
1260     for (unsigned i = 0; i != 8; ++i)
1261       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
1262           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
1263         return false;
1264   }
1265   return true;
1266 }
1267
1268 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
1269 /// VPKUWUM instruction.
1270 /// The ShuffleKind distinguishes between big-endian operations with
1271 /// two different inputs (0), either-endian operations with two identical
1272 /// inputs (1), and little-endian operations with two different inputs (2).
1273 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1274 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1275                                SelectionDAG &DAG) {
1276   bool IsLE = DAG.getDataLayout().isLittleEndian();
1277   if (ShuffleKind == 0) {
1278     if (IsLE)
1279       return false;
1280     for (unsigned i = 0; i != 16; i += 2)
1281       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
1282           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
1283         return false;
1284   } else if (ShuffleKind == 2) {
1285     if (!IsLE)
1286       return false;
1287     for (unsigned i = 0; i != 16; i += 2)
1288       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1289           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
1290         return false;
1291   } else if (ShuffleKind == 1) {
1292     unsigned j = IsLE ? 0 : 2;
1293     for (unsigned i = 0; i != 8; i += 2)
1294       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1295           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1296           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1297           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
1298         return false;
1299   }
1300   return true;
1301 }
1302
1303 /// isVPKUDUMShuffleMask - Return true if this is the shuffle mask for a
1304 /// VPKUDUM instruction, AND the VPKUDUM instruction exists for the
1305 /// current subtarget.
1306 ///
1307 /// The ShuffleKind distinguishes between big-endian operations with
1308 /// two different inputs (0), either-endian operations with two identical
1309 /// inputs (1), and little-endian operations with two different inputs (2).
1310 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
1311 bool PPC::isVPKUDUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
1312                                SelectionDAG &DAG) {
1313   const PPCSubtarget& Subtarget =
1314     static_cast<const PPCSubtarget&>(DAG.getSubtarget());
1315   if (!Subtarget.hasP8Vector())
1316     return false;
1317
1318   bool IsLE = DAG.getDataLayout().isLittleEndian();
1319   if (ShuffleKind == 0) {
1320     if (IsLE)
1321       return false;
1322     for (unsigned i = 0; i != 16; i += 4)
1323       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+4) ||
1324           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+5) ||
1325           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+6) ||
1326           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+7))
1327         return false;
1328   } else if (ShuffleKind == 2) {
1329     if (!IsLE)
1330       return false;
1331     for (unsigned i = 0; i != 16; i += 4)
1332       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
1333           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1) ||
1334           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+2) ||
1335           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+3))
1336         return false;
1337   } else if (ShuffleKind == 1) {
1338     unsigned j = IsLE ? 0 : 4;
1339     for (unsigned i = 0; i != 8; i += 4)
1340       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
1341           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
1342           !isConstantOrUndef(N->getMaskElt(i+2),  i*2+j+2) ||
1343           !isConstantOrUndef(N->getMaskElt(i+3),  i*2+j+3) ||
1344           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
1345           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1) ||
1346           !isConstantOrUndef(N->getMaskElt(i+10), i*2+j+2) ||
1347           !isConstantOrUndef(N->getMaskElt(i+11), i*2+j+3))
1348         return false;
1349   }
1350   return true;
1351 }
1352
1353 /// isVMerge - Common function, used to match vmrg* shuffles.
1354 ///
1355 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
1356                      unsigned LHSStart, unsigned RHSStart) {
1357   if (N->getValueType(0) != MVT::v16i8)
1358     return false;
1359   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
1360          "Unsupported merge size!");
1361
1362   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
1363     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
1364       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
1365                              LHSStart+j+i*UnitSize) ||
1366           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
1367                              RHSStart+j+i*UnitSize))
1368         return false;
1369     }
1370   return true;
1371 }
1372
1373 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
1374 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
1375 /// The ShuffleKind distinguishes between big-endian merges with two
1376 /// different inputs (0), either-endian merges with two identical inputs (1),
1377 /// and little-endian merges with two different inputs (2).  For the latter,
1378 /// the input operands are swapped (see PPCInstrAltivec.td).
1379 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1380                              unsigned ShuffleKind, SelectionDAG &DAG) {
1381   if (DAG.getDataLayout().isLittleEndian()) {
1382     if (ShuffleKind == 1) // unary
1383       return isVMerge(N, UnitSize, 0, 0);
1384     else if (ShuffleKind == 2) // swapped
1385       return isVMerge(N, UnitSize, 0, 16);
1386     else
1387       return false;
1388   } else {
1389     if (ShuffleKind == 1) // unary
1390       return isVMerge(N, UnitSize, 8, 8);
1391     else if (ShuffleKind == 0) // normal
1392       return isVMerge(N, UnitSize, 8, 24);
1393     else
1394       return false;
1395   }
1396 }
1397
1398 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
1399 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
1400 /// The ShuffleKind distinguishes between big-endian merges with two
1401 /// different inputs (0), either-endian merges with two identical inputs (1),
1402 /// and little-endian merges with two different inputs (2).  For the latter,
1403 /// the input operands are swapped (see PPCInstrAltivec.td).
1404 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
1405                              unsigned ShuffleKind, SelectionDAG &DAG) {
1406   if (DAG.getDataLayout().isLittleEndian()) {
1407     if (ShuffleKind == 1) // unary
1408       return isVMerge(N, UnitSize, 8, 8);
1409     else if (ShuffleKind == 2) // swapped
1410       return isVMerge(N, UnitSize, 8, 24);
1411     else
1412       return false;
1413   } else {
1414     if (ShuffleKind == 1) // unary
1415       return isVMerge(N, UnitSize, 0, 0);
1416     else if (ShuffleKind == 0) // normal
1417       return isVMerge(N, UnitSize, 0, 16);
1418     else
1419       return false;
1420   }
1421 }
1422
1423 /**
1424  * \brief Common function used to match vmrgew and vmrgow shuffles
1425  *
1426  * The indexOffset determines whether to look for even or odd words in
1427  * the shuffle mask. This is based on the of the endianness of the target
1428  * machine.
1429  *   - Little Endian:
1430  *     - Use offset of 0 to check for odd elements
1431  *     - Use offset of 4 to check for even elements
1432  *   - Big Endian:
1433  *     - Use offset of 0 to check for even elements
1434  *     - Use offset of 4 to check for odd elements
1435  * A detailed description of the vector element ordering for little endian and
1436  * big endian can be found at
1437  * http://www.ibm.com/developerworks/library/l-ibm-xl-c-cpp-compiler/index.html
1438  * Targeting your applications - what little endian and big endian IBM XL C/C++
1439  * compiler differences mean to you
1440  *
1441  * The mask to the shuffle vector instruction specifies the indices of the
1442  * elements from the two input vectors to place in the result. The elements are
1443  * numbered in array-access order, starting with the first vector. These vectors
1444  * are always of type v16i8, thus each vector will contain 16 elements of size
1445  * 8. More info on the shuffle vector can be found in the
1446  * http://llvm.org/docs/LangRef.html#shufflevector-instruction
1447  * Language Reference.
1448  *
1449  * The RHSStartValue indicates whether the same input vectors are used (unary)
1450  * or two different input vectors are used, based on the following:
1451  *   - If the instruction uses the same vector for both inputs, the range of the
1452  *     indices will be 0 to 15. In this case, the RHSStart value passed should
1453  *     be 0.
1454  *   - If the instruction has two different vectors then the range of the
1455  *     indices will be 0 to 31. In this case, the RHSStart value passed should
1456  *     be 16 (indices 0-15 specify elements in the first vector while indices 16
1457  *     to 31 specify elements in the second vector).
1458  *
1459  * \param[in] N The shuffle vector SD Node to analyze
1460  * \param[in] IndexOffset Specifies whether to look for even or odd elements
1461  * \param[in] RHSStartValue Specifies the starting index for the righthand input
1462  * vector to the shuffle_vector instruction
1463  * \return true iff this shuffle vector represents an even or odd word merge
1464  */
1465 static bool isVMerge(ShuffleVectorSDNode *N, unsigned IndexOffset,
1466                      unsigned RHSStartValue) {
1467   if (N->getValueType(0) != MVT::v16i8)
1468     return false;
1469
1470   for (unsigned i = 0; i < 2; ++i)
1471     for (unsigned j = 0; j < 4; ++j)
1472       if (!isConstantOrUndef(N->getMaskElt(i*4+j),
1473                              i*RHSStartValue+j+IndexOffset) ||
1474           !isConstantOrUndef(N->getMaskElt(i*4+j+8),
1475                              i*RHSStartValue+j+IndexOffset+8))
1476         return false;
1477   return true;
1478 }
1479
1480 /**
1481  * \brief Determine if the specified shuffle mask is suitable for the vmrgew or
1482  * vmrgow instructions.
1483  *
1484  * \param[in] N The shuffle vector SD Node to analyze
1485  * \param[in] CheckEven Check for an even merge (true) or an odd merge (false)
1486  * \param[in] ShuffleKind Identify the type of merge:
1487  *   - 0 = big-endian merge with two different inputs;
1488  *   - 1 = either-endian merge with two identical inputs;
1489  *   - 2 = little-endian merge with two different inputs (inputs are swapped for
1490  *     little-endian merges).
1491  * \param[in] DAG The current SelectionDAG
1492  * \return true iff this shuffle mask
1493  */
1494 bool PPC::isVMRGEOShuffleMask(ShuffleVectorSDNode *N, bool CheckEven,
1495                               unsigned ShuffleKind, SelectionDAG &DAG) {
1496   if (DAG.getDataLayout().isLittleEndian()) {
1497     unsigned indexOffset = CheckEven ? 4 : 0;
1498     if (ShuffleKind == 1) // Unary
1499       return isVMerge(N, indexOffset, 0);
1500     else if (ShuffleKind == 2) // swapped
1501       return isVMerge(N, indexOffset, 16);
1502     else
1503       return false;
1504   }
1505   else {
1506     unsigned indexOffset = CheckEven ? 0 : 4;
1507     if (ShuffleKind == 1) // Unary
1508       return isVMerge(N, indexOffset, 0);
1509     else if (ShuffleKind == 0) // Normal
1510       return isVMerge(N, indexOffset, 16);
1511     else
1512       return false;
1513   }
1514   return false;
1515 }
1516
1517 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1518 /// amount, otherwise return -1.
1519 /// The ShuffleKind distinguishes between big-endian operations with two
1520 /// different inputs (0), either-endian operations with two identical inputs
1521 /// (1), and little-endian operations with two different inputs (2).  For the
1522 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1523 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1524                              SelectionDAG &DAG) {
1525   if (N->getValueType(0) != MVT::v16i8)
1526     return -1;
1527
1528   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1529
1530   // Find the first non-undef value in the shuffle mask.
1531   unsigned i;
1532   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1533     /*search*/;
1534
1535   if (i == 16) return -1;  // all undef.
1536
1537   // Otherwise, check to see if the rest of the elements are consecutively
1538   // numbered from this value.
1539   unsigned ShiftAmt = SVOp->getMaskElt(i);
1540   if (ShiftAmt < i) return -1;
1541
1542   ShiftAmt -= i;
1543   bool isLE = DAG.getDataLayout().isLittleEndian();
1544
1545   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1546     // Check the rest of the elements to see if they are consecutive.
1547     for (++i; i != 16; ++i)
1548       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1549         return -1;
1550   } else if (ShuffleKind == 1) {
1551     // Check the rest of the elements to see if they are consecutive.
1552     for (++i; i != 16; ++i)
1553       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1554         return -1;
1555   } else
1556     return -1;
1557
1558   if (isLE)
1559     ShiftAmt = 16 - ShiftAmt;
1560
1561   return ShiftAmt;
1562 }
1563
1564 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1565 /// specifies a splat of a single element that is suitable for input to
1566 /// VSPLTB/VSPLTH/VSPLTW.
1567 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1568   assert(N->getValueType(0) == MVT::v16i8 &&
1569          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1570
1571   // The consecutive indices need to specify an element, not part of two
1572   // different elements.  So abandon ship early if this isn't the case.
1573   if (N->getMaskElt(0) % EltSize != 0)
1574     return false;
1575
1576   // This is a splat operation if each element of the permute is the same, and
1577   // if the value doesn't reference the second vector.
1578   unsigned ElementBase = N->getMaskElt(0);
1579
1580   // FIXME: Handle UNDEF elements too!
1581   if (ElementBase >= 16)
1582     return false;
1583
1584   // Check that the indices are consecutive, in the case of a multi-byte element
1585   // splatted with a v16i8 mask.
1586   for (unsigned i = 1; i != EltSize; ++i)
1587     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1588       return false;
1589
1590   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1591     if (N->getMaskElt(i) < 0) continue;
1592     for (unsigned j = 0; j != EltSize; ++j)
1593       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1594         return false;
1595   }
1596   return true;
1597 }
1598
1599 bool PPC::isXXINSERTWMask(ShuffleVectorSDNode *N, unsigned &ShiftElts,
1600                           unsigned &InsertAtByte, bool &Swap, bool IsLE) {
1601   // Check that the mask is shuffling words
1602   for (unsigned i = 0; i < 4; ++i) {
1603     unsigned B0 = N->getMaskElt(i*4);
1604     unsigned B1 = N->getMaskElt(i*4+1);
1605     unsigned B2 = N->getMaskElt(i*4+2);
1606     unsigned B3 = N->getMaskElt(i*4+3);
1607     if (B0 % 4)
1608       return false;
1609     if (B1 != B0+1 || B2 != B1+1 || B3 != B2+1)
1610       return false;
1611   }
1612
1613   // Now we look at mask elements 0,4,8,12
1614   unsigned M0 = N->getMaskElt(0) / 4;
1615   unsigned M1 = N->getMaskElt(4) / 4;
1616   unsigned M2 = N->getMaskElt(8) / 4;
1617   unsigned M3 = N->getMaskElt(12) / 4;
1618   unsigned LittleEndianShifts[] = { 2, 1, 0, 3 };
1619   unsigned BigEndianShifts[] = { 3, 0, 1, 2 };
1620
1621   // Below, let H and L be arbitrary elements of the shuffle mask
1622   // where H is in the range [4,7] and L is in the range [0,3].
1623   // H, 1, 2, 3 or L, 5, 6, 7
1624   if ((M0 > 3 && M1 == 1 && M2 == 2 && M3 == 3) ||
1625       (M0 < 4 && M1 == 5 && M2 == 6 && M3 == 7)) {
1626     ShiftElts = IsLE ? LittleEndianShifts[M0 & 0x3] : BigEndianShifts[M0 & 0x3];
1627     InsertAtByte = IsLE ? 12 : 0;
1628     Swap = M0 < 4;
1629     return true;
1630   }
1631   // 0, H, 2, 3 or 4, L, 6, 7
1632   if ((M1 > 3 && M0 == 0 && M2 == 2 && M3 == 3) ||
1633       (M1 < 4 && M0 == 4 && M2 == 6 && M3 == 7)) {
1634     ShiftElts = IsLE ? LittleEndianShifts[M1 & 0x3] : BigEndianShifts[M1 & 0x3];
1635     InsertAtByte = IsLE ? 8 : 4;
1636     Swap = M1 < 4;
1637     return true;
1638   }
1639   // 0, 1, H, 3 or 4, 5, L, 7
1640   if ((M2 > 3 && M0 == 0 && M1 == 1 && M3 == 3) ||
1641       (M2 < 4 && M0 == 4 && M1 == 5 && M3 == 7)) {
1642     ShiftElts = IsLE ? LittleEndianShifts[M2 & 0x3] : BigEndianShifts[M2 & 0x3];
1643     InsertAtByte = IsLE ? 4 : 8;
1644     Swap = M2 < 4;
1645     return true;
1646   }
1647   // 0, 1, 2, H or 4, 5, 6, L
1648   if ((M3 > 3 && M0 == 0 && M1 == 1 && M2 == 2) ||
1649       (M3 < 4 && M0 == 4 && M1 == 5 && M2 == 6)) {
1650     ShiftElts = IsLE ? LittleEndianShifts[M3 & 0x3] : BigEndianShifts[M3 & 0x3];
1651     InsertAtByte = IsLE ? 0 : 12;
1652     Swap = M3 < 4;
1653     return true;
1654   }
1655
1656   // If both vector operands for the shuffle are the same vector, the mask will
1657   // contain only elements from the first one and the second one will be undef.
1658   if (N->getOperand(1).isUndef()) {
1659     ShiftElts = 0;
1660     Swap = true;
1661     unsigned XXINSERTWSrcElem = IsLE ? 2 : 1;
1662     if (M0 == XXINSERTWSrcElem && M1 == 1 && M2 == 2 && M3 == 3) {
1663       InsertAtByte = IsLE ? 12 : 0;
1664       return true;
1665     }
1666     if (M0 == 0 && M1 == XXINSERTWSrcElem && M2 == 2 && M3 == 3) {
1667       InsertAtByte = IsLE ? 8 : 4;
1668       return true;
1669     }
1670     if (M0 == 0 && M1 == 1 && M2 == XXINSERTWSrcElem && M3 == 3) {
1671       InsertAtByte = IsLE ? 4 : 8;
1672       return true;
1673     }
1674     if (M0 == 0 && M1 == 1 && M2 == 2 && M3 == XXINSERTWSrcElem) {
1675       InsertAtByte = IsLE ? 0 : 12;
1676       return true;
1677     }
1678   }
1679
1680   return false;
1681 }
1682
1683 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1684 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1685 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1686                                 SelectionDAG &DAG) {
1687   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1688   assert(isSplatShuffleMask(SVOp, EltSize));
1689   if (DAG.getDataLayout().isLittleEndian())
1690     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1691   else
1692     return SVOp->getMaskElt(0) / EltSize;
1693 }
1694
1695 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1696 /// by using a vspltis[bhw] instruction of the specified element size, return
1697 /// the constant being splatted.  The ByteSize field indicates the number of
1698 /// bytes of each element [124] -> [bhw].
1699 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1700   SDValue OpVal(nullptr, 0);
1701
1702   // If ByteSize of the splat is bigger than the element size of the
1703   // build_vector, then we have a case where we are checking for a splat where
1704   // multiple elements of the buildvector are folded together into a single
1705   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1706   unsigned EltSize = 16/N->getNumOperands();
1707   if (EltSize < ByteSize) {
1708     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1709     SDValue UniquedVals[4];
1710     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1711
1712     // See if all of the elements in the buildvector agree across.
1713     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1714       if (N->getOperand(i).isUndef()) continue;
1715       // If the element isn't a constant, bail fully out.
1716       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1717
1718       if (!UniquedVals[i&(Multiple-1)].getNode())
1719         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1720       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1721         return SDValue();  // no match.
1722     }
1723
1724     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1725     // either constant or undef values that are identical for each chunk.  See
1726     // if these chunks can form into a larger vspltis*.
1727
1728     // Check to see if all of the leading entries are either 0 or -1.  If
1729     // neither, then this won't fit into the immediate field.
1730     bool LeadingZero = true;
1731     bool LeadingOnes = true;
1732     for (unsigned i = 0; i != Multiple-1; ++i) {
1733       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1734
1735       LeadingZero &= isNullConstant(UniquedVals[i]);
1736       LeadingOnes &= isAllOnesConstant(UniquedVals[i]);
1737     }
1738     // Finally, check the least significant entry.
1739     if (LeadingZero) {
1740       if (!UniquedVals[Multiple-1].getNode())
1741         return DAG.getTargetConstant(0, SDLoc(N), MVT::i32);  // 0,0,0,undef
1742       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1743       if (Val < 16)                                   // 0,0,0,4 -> vspltisw(4)
1744         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1745     }
1746     if (LeadingOnes) {
1747       if (!UniquedVals[Multiple-1].getNode())
1748         return DAG.getTargetConstant(~0U, SDLoc(N), MVT::i32); // -1,-1,-1,undef
1749       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1750       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1751         return DAG.getTargetConstant(Val, SDLoc(N), MVT::i32);
1752     }
1753
1754     return SDValue();
1755   }
1756
1757   // Check to see if this buildvec has a single non-undef value in its elements.
1758   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1759     if (N->getOperand(i).isUndef()) continue;
1760     if (!OpVal.getNode())
1761       OpVal = N->getOperand(i);
1762     else if (OpVal != N->getOperand(i))
1763       return SDValue();
1764   }
1765
1766   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1767
1768   unsigned ValSizeInBytes = EltSize;
1769   uint64_t Value = 0;
1770   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1771     Value = CN->getZExtValue();
1772   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1773     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1774     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1775   }
1776
1777   // If the splat value is larger than the element value, then we can never do
1778   // this splat.  The only case that we could fit the replicated bits into our
1779   // immediate field for would be zero, and we prefer to use vxor for it.
1780   if (ValSizeInBytes < ByteSize) return SDValue();
1781
1782   // If the element value is larger than the splat value, check if it consists
1783   // of a repeated bit pattern of size ByteSize.
1784   if (!APInt(ValSizeInBytes * 8, Value).isSplat(ByteSize * 8))
1785     return SDValue();
1786
1787   // Properly sign extend the value.
1788   int MaskVal = SignExtend32(Value, ByteSize * 8);
1789
1790   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1791   if (MaskVal == 0) return SDValue();
1792
1793   // Finally, if this value fits in a 5 bit sext field, return it
1794   if (SignExtend32<5>(MaskVal) == MaskVal)
1795     return DAG.getTargetConstant(MaskVal, SDLoc(N), MVT::i32);
1796   return SDValue();
1797 }
1798
1799 /// isQVALIGNIShuffleMask - If this is a qvaligni shuffle mask, return the shift
1800 /// amount, otherwise return -1.
1801 int PPC::isQVALIGNIShuffleMask(SDNode *N) {
1802   EVT VT = N->getValueType(0);
1803   if (VT != MVT::v4f64 && VT != MVT::v4f32 && VT != MVT::v4i1)
1804     return -1;
1805
1806   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1807
1808   // Find the first non-undef value in the shuffle mask.
1809   unsigned i;
1810   for (i = 0; i != 4 && SVOp->getMaskElt(i) < 0; ++i)
1811     /*search*/;
1812
1813   if (i == 4) return -1;  // all undef.
1814
1815   // Otherwise, check to see if the rest of the elements are consecutively
1816   // numbered from this value.
1817   unsigned ShiftAmt = SVOp->getMaskElt(i);
1818   if (ShiftAmt < i) return -1;
1819   ShiftAmt -= i;
1820
1821   // Check the rest of the elements to see if they are consecutive.
1822   for (++i; i != 4; ++i)
1823     if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1824       return -1;
1825
1826   return ShiftAmt;
1827 }
1828
1829 //===----------------------------------------------------------------------===//
1830 //  Addressing Mode Selection
1831 //===----------------------------------------------------------------------===//
1832
1833 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1834 /// or 64-bit immediate, and if the value can be accurately represented as a
1835 /// sign extension from a 16-bit value.  If so, this returns true and the
1836 /// immediate.
1837 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1838   if (!isa<ConstantSDNode>(N))
1839     return false;
1840
1841   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1842   if (N->getValueType(0) == MVT::i32)
1843     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1844   else
1845     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1846 }
1847 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1848   return isIntS16Immediate(Op.getNode(), Imm);
1849 }
1850
1851 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1852 /// can be represented as an indexed [r+r] operation.  Returns false if it
1853 /// can be more efficiently represented with [r+imm].
1854 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1855                                             SDValue &Index,
1856                                             SelectionDAG &DAG) const {
1857   short imm = 0;
1858   if (N.getOpcode() == ISD::ADD) {
1859     if (isIntS16Immediate(N.getOperand(1), imm))
1860       return false;    // r+i
1861     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1862       return false;    // r+i
1863
1864     Base = N.getOperand(0);
1865     Index = N.getOperand(1);
1866     return true;
1867   } else if (N.getOpcode() == ISD::OR) {
1868     if (isIntS16Immediate(N.getOperand(1), imm))
1869       return false;    // r+i can fold it if we can.
1870
1871     // If this is an or of disjoint bitfields, we can codegen this as an add
1872     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1873     // disjoint.
1874     KnownBits LHSKnown, RHSKnown;
1875     DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1876
1877     if (LHSKnown.Zero.getBoolValue()) {
1878       DAG.computeKnownBits(N.getOperand(1), RHSKnown);
1879       // If all of the bits are known zero on the LHS or RHS, the add won't
1880       // carry.
1881       if (~(LHSKnown.Zero | RHSKnown.Zero) == 0) {
1882         Base = N.getOperand(0);
1883         Index = N.getOperand(1);
1884         return true;
1885       }
1886     }
1887   }
1888
1889   return false;
1890 }
1891
1892 // If we happen to be doing an i64 load or store into a stack slot that has
1893 // less than a 4-byte alignment, then the frame-index elimination may need to
1894 // use an indexed load or store instruction (because the offset may not be a
1895 // multiple of 4). The extra register needed to hold the offset comes from the
1896 // register scavenger, and it is possible that the scavenger will need to use
1897 // an emergency spill slot. As a result, we need to make sure that a spill slot
1898 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1899 // stack slot.
1900 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1901   // FIXME: This does not handle the LWA case.
1902   if (VT != MVT::i64)
1903     return;
1904
1905   // NOTE: We'll exclude negative FIs here, which come from argument
1906   // lowering, because there are no known test cases triggering this problem
1907   // using packed structures (or similar). We can remove this exclusion if
1908   // we find such a test case. The reason why this is so test-case driven is
1909   // because this entire 'fixup' is only to prevent crashes (from the
1910   // register scavenger) on not-really-valid inputs. For example, if we have:
1911   //   %a = alloca i1
1912   //   %b = bitcast i1* %a to i64*
1913   //   store i64* a, i64 b
1914   // then the store should really be marked as 'align 1', but is not. If it
1915   // were marked as 'align 1' then the indexed form would have been
1916   // instruction-selected initially, and the problem this 'fixup' is preventing
1917   // won't happen regardless.
1918   if (FrameIdx < 0)
1919     return;
1920
1921   MachineFunction &MF = DAG.getMachineFunction();
1922   MachineFrameInfo &MFI = MF.getFrameInfo();
1923
1924   unsigned Align = MFI.getObjectAlignment(FrameIdx);
1925   if (Align >= 4)
1926     return;
1927
1928   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1929   FuncInfo->setHasNonRISpills();
1930 }
1931
1932 /// Returns true if the address N can be represented by a base register plus
1933 /// a signed 16-bit displacement [r+imm], and if it is not better
1934 /// represented as reg+reg.  If Aligned is true, only accept displacements
1935 /// suitable for STD and friends, i.e. multiples of 4.
1936 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1937                                             SDValue &Base,
1938                                             SelectionDAG &DAG,
1939                                             bool Aligned) const {
1940   // FIXME dl should come from parent load or store, not from address
1941   SDLoc dl(N);
1942   // If this can be more profitably realized as r+r, fail.
1943   if (SelectAddressRegReg(N, Disp, Base, DAG))
1944     return false;
1945
1946   if (N.getOpcode() == ISD::ADD) {
1947     short imm = 0;
1948     if (isIntS16Immediate(N.getOperand(1), imm) &&
1949         (!Aligned || (imm & 3) == 0)) {
1950       Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1951       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1952         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1953         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1954       } else {
1955         Base = N.getOperand(0);
1956       }
1957       return true; // [r+i]
1958     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1959       // Match LOAD (ADD (X, Lo(G))).
1960       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1961              && "Cannot handle constant offsets yet!");
1962       Disp = N.getOperand(1).getOperand(0);  // The global address.
1963       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1964              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1965              Disp.getOpcode() == ISD::TargetConstantPool ||
1966              Disp.getOpcode() == ISD::TargetJumpTable);
1967       Base = N.getOperand(0);
1968       return true;  // [&g+r]
1969     }
1970   } else if (N.getOpcode() == ISD::OR) {
1971     short imm = 0;
1972     if (isIntS16Immediate(N.getOperand(1), imm) &&
1973         (!Aligned || (imm & 3) == 0)) {
1974       // If this is an or of disjoint bitfields, we can codegen this as an add
1975       // (for better address arithmetic) if the LHS and RHS of the OR are
1976       // provably disjoint.
1977       KnownBits LHSKnown;
1978       DAG.computeKnownBits(N.getOperand(0), LHSKnown);
1979
1980       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1981         // If all of the bits are known zero on the LHS or RHS, the add won't
1982         // carry.
1983         if (FrameIndexSDNode *FI =
1984               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1985           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1986           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1987         } else {
1988           Base = N.getOperand(0);
1989         }
1990         Disp = DAG.getTargetConstant(imm, dl, N.getValueType());
1991         return true;
1992       }
1993     }
1994   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1995     // Loading from a constant address.
1996
1997     // If this address fits entirely in a 16-bit sext immediate field, codegen
1998     // this as "d, 0"
1999     short Imm;
2000     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
2001       Disp = DAG.getTargetConstant(Imm, dl, CN->getValueType(0));
2002       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2003                              CN->getValueType(0));
2004       return true;
2005     }
2006
2007     // Handle 32-bit sext immediates with LIS + addr mode.
2008     if ((CN->getValueType(0) == MVT::i32 ||
2009          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
2010         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
2011       int Addr = (int)CN->getZExtValue();
2012
2013       // Otherwise, break this down into an LIS + disp.
2014       Disp = DAG.getTargetConstant((short)Addr, dl, MVT::i32);
2015
2016       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, dl,
2017                                    MVT::i32);
2018       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
2019       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
2020       return true;
2021     }
2022   }
2023
2024   Disp = DAG.getTargetConstant(0, dl, getPointerTy(DAG.getDataLayout()));
2025   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
2026     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
2027     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
2028   } else
2029     Base = N;
2030   return true;      // [r+0]
2031 }
2032
2033 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
2034 /// represented as an indexed [r+r] operation.
2035 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
2036                                                 SDValue &Index,
2037                                                 SelectionDAG &DAG) const {
2038   // Check to see if we can easily represent this as an [r+r] address.  This
2039   // will fail if it thinks that the address is more profitably represented as
2040   // reg+imm, e.g. where imm = 0.
2041   if (SelectAddressRegReg(N, Base, Index, DAG))
2042     return true;
2043
2044   // If the operand is an addition, always emit this as [r+r], since this is
2045   // better (for code size, and execution, as the memop does the add for free)
2046   // than emitting an explicit add.
2047   if (N.getOpcode() == ISD::ADD) {
2048     Base = N.getOperand(0);
2049     Index = N.getOperand(1);
2050     return true;
2051   }
2052
2053   // Otherwise, do it the hard way, using R0 as the base register.
2054   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
2055                          N.getValueType());
2056   Index = N;
2057   return true;
2058 }
2059
2060 /// getPreIndexedAddressParts - returns true by value, base pointer and
2061 /// offset pointer and addressing mode by reference if the node's address
2062 /// can be legally represented as pre-indexed load / store address.
2063 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
2064                                                   SDValue &Offset,
2065                                                   ISD::MemIndexedMode &AM,
2066                                                   SelectionDAG &DAG) const {
2067   if (DisablePPCPreinc) return false;
2068
2069   bool isLoad = true;
2070   SDValue Ptr;
2071   EVT VT;
2072   unsigned Alignment;
2073   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2074     Ptr = LD->getBasePtr();
2075     VT = LD->getMemoryVT();
2076     Alignment = LD->getAlignment();
2077   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
2078     Ptr = ST->getBasePtr();
2079     VT  = ST->getMemoryVT();
2080     Alignment = ST->getAlignment();
2081     isLoad = false;
2082   } else
2083     return false;
2084
2085   // PowerPC doesn't have preinc load/store instructions for vectors (except
2086   // for QPX, which does have preinc r+r forms).
2087   if (VT.isVector()) {
2088     if (!Subtarget.hasQPX() || (VT != MVT::v4f64 && VT != MVT::v4f32)) {
2089       return false;
2090     } else if (SelectAddressRegRegOnly(Ptr, Offset, Base, DAG)) {
2091       AM = ISD::PRE_INC;
2092       return true;
2093     }
2094   }
2095
2096   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
2097     // Common code will reject creating a pre-inc form if the base pointer
2098     // is a frame index, or if N is a store and the base pointer is either
2099     // the same as or a predecessor of the value being stored.  Check for
2100     // those situations here, and try with swapped Base/Offset instead.
2101     bool Swap = false;
2102
2103     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
2104       Swap = true;
2105     else if (!isLoad) {
2106       SDValue Val = cast<StoreSDNode>(N)->getValue();
2107       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
2108         Swap = true;
2109     }
2110
2111     if (Swap)
2112       std::swap(Base, Offset);
2113
2114     AM = ISD::PRE_INC;
2115     return true;
2116   }
2117
2118   // LDU/STU can only handle immediates that are a multiple of 4.
2119   if (VT != MVT::i64) {
2120     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
2121       return false;
2122   } else {
2123     // LDU/STU need an address with at least 4-byte alignment.
2124     if (Alignment < 4)
2125       return false;
2126
2127     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
2128       return false;
2129   }
2130
2131   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
2132     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
2133     // sext i32 to i64 when addr mode is r+i.
2134     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
2135         LD->getExtensionType() == ISD::SEXTLOAD &&
2136         isa<ConstantSDNode>(Offset))
2137       return false;
2138   }
2139
2140   AM = ISD::PRE_INC;
2141   return true;
2142 }
2143
2144 //===----------------------------------------------------------------------===//
2145 //  LowerOperation implementation
2146 //===----------------------------------------------------------------------===//
2147
2148 /// Return true if we should reference labels using a PICBase, set the HiOpFlags
2149 /// and LoOpFlags to the target MO flags.
2150 static void getLabelAccessInfo(bool IsPIC, const PPCSubtarget &Subtarget,
2151                                unsigned &HiOpFlags, unsigned &LoOpFlags,
2152                                const GlobalValue *GV = nullptr) {
2153   HiOpFlags = PPCII::MO_HA;
2154   LoOpFlags = PPCII::MO_LO;
2155
2156   // Don't use the pic base if not in PIC relocation model.
2157   if (IsPIC) {
2158     HiOpFlags |= PPCII::MO_PIC_FLAG;
2159     LoOpFlags |= PPCII::MO_PIC_FLAG;
2160   }
2161
2162   // If this is a reference to a global value that requires a non-lazy-ptr, make
2163   // sure that instruction lowering adds it.
2164   if (GV && Subtarget.hasLazyResolverStub(GV)) {
2165     HiOpFlags |= PPCII::MO_NLP_FLAG;
2166     LoOpFlags |= PPCII::MO_NLP_FLAG;
2167
2168     if (GV->hasHiddenVisibility()) {
2169       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2170       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
2171     }
2172   }
2173 }
2174
2175 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
2176                              SelectionDAG &DAG) {
2177   SDLoc DL(HiPart);
2178   EVT PtrVT = HiPart.getValueType();
2179   SDValue Zero = DAG.getConstant(0, DL, PtrVT);
2180
2181   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
2182   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
2183
2184   // With PIC, the first instruction is actually "GR+hi(&G)".
2185   if (isPIC)
2186     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
2187                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
2188
2189   // Generate non-pic code that has direct accesses to the constant pool.
2190   // The address of the global is just (hi(&g)+lo(&g)).
2191   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2192 }
2193
2194 static void setUsesTOCBasePtr(MachineFunction &MF) {
2195   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2196   FuncInfo->setUsesTOCBasePtr();
2197 }
2198
2199 static void setUsesTOCBasePtr(SelectionDAG &DAG) {
2200   setUsesTOCBasePtr(DAG.getMachineFunction());
2201 }
2202
2203 static SDValue getTOCEntry(SelectionDAG &DAG, const SDLoc &dl, bool Is64Bit,
2204                            SDValue GA) {
2205   EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
2206   SDValue Reg = Is64Bit ? DAG.getRegister(PPC::X2, VT) :
2207                 DAG.getNode(PPCISD::GlobalBaseReg, dl, VT);
2208
2209   SDValue Ops[] = { GA, Reg };
2210   return DAG.getMemIntrinsicNode(
2211       PPCISD::TOC_ENTRY, dl, DAG.getVTList(VT, MVT::Other), Ops, VT,
2212       MachinePointerInfo::getGOT(DAG.getMachineFunction()), 0, false, true,
2213       false, 0);
2214 }
2215
2216 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
2217                                              SelectionDAG &DAG) const {
2218   EVT PtrVT = Op.getValueType();
2219   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2220   const Constant *C = CP->getConstVal();
2221
2222   // 64-bit SVR4 ABI code is always position-independent.
2223   // The actual address of the GlobalValue is stored in the TOC.
2224   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2225     setUsesTOCBasePtr(DAG);
2226     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
2227     return getTOCEntry(DAG, SDLoc(CP), true, GA);
2228   }
2229
2230   unsigned MOHiFlag, MOLoFlag;
2231   bool IsPIC = isPositionIndependent();
2232   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2233
2234   if (IsPIC && Subtarget.isSVR4ABI()) {
2235     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
2236                                            PPCII::MO_PIC_FLAG);
2237     return getTOCEntry(DAG, SDLoc(CP), false, GA);
2238   }
2239
2240   SDValue CPIHi =
2241     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
2242   SDValue CPILo =
2243     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
2244   return LowerLabelRef(CPIHi, CPILo, IsPIC, DAG);
2245 }
2246
2247 // For 64-bit PowerPC, prefer the more compact relative encodings.
2248 // This trades 32 bits per jump table entry for one or two instructions
2249 // on the jump site.
2250 unsigned PPCTargetLowering::getJumpTableEncoding() const {
2251   if (isJumpTableRelative())
2252     return MachineJumpTableInfo::EK_LabelDifference32;
2253
2254   return TargetLowering::getJumpTableEncoding();
2255 }
2256
2257 bool PPCTargetLowering::isJumpTableRelative() const {
2258   if (Subtarget.isPPC64())
2259     return true;
2260   return TargetLowering::isJumpTableRelative();
2261 }
2262
2263 SDValue PPCTargetLowering::getPICJumpTableRelocBase(SDValue Table,
2264                                                     SelectionDAG &DAG) const {
2265   if (!Subtarget.isPPC64())
2266     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2267
2268   switch (getTargetMachine().getCodeModel()) {
2269   case CodeModel::Default:
2270   case CodeModel::Small:
2271   case CodeModel::Medium:
2272     return TargetLowering::getPICJumpTableRelocBase(Table, DAG);
2273   default:
2274     return DAG.getNode(PPCISD::GlobalBaseReg, SDLoc(),
2275                        getPointerTy(DAG.getDataLayout()));
2276   }
2277 }
2278
2279 const MCExpr *
2280 PPCTargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
2281                                                 unsigned JTI,
2282                                                 MCContext &Ctx) const {
2283   if (!Subtarget.isPPC64())
2284     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2285
2286   switch (getTargetMachine().getCodeModel()) {
2287   case CodeModel::Default:
2288   case CodeModel::Small:
2289   case CodeModel::Medium:
2290     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
2291   default:
2292     return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
2293   }
2294 }
2295
2296 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
2297   EVT PtrVT = Op.getValueType();
2298   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
2299
2300   // 64-bit SVR4 ABI code is always position-independent.
2301   // The actual address of the GlobalValue is stored in the TOC.
2302   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2303     setUsesTOCBasePtr(DAG);
2304     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
2305     return getTOCEntry(DAG, SDLoc(JT), true, GA);
2306   }
2307
2308   unsigned MOHiFlag, MOLoFlag;
2309   bool IsPIC = isPositionIndependent();
2310   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2311
2312   if (IsPIC && Subtarget.isSVR4ABI()) {
2313     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
2314                                         PPCII::MO_PIC_FLAG);
2315     return getTOCEntry(DAG, SDLoc(GA), false, GA);
2316   }
2317
2318   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
2319   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
2320   return LowerLabelRef(JTIHi, JTILo, IsPIC, DAG);
2321 }
2322
2323 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
2324                                              SelectionDAG &DAG) const {
2325   EVT PtrVT = Op.getValueType();
2326   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
2327   const BlockAddress *BA = BASDN->getBlockAddress();
2328
2329   // 64-bit SVR4 ABI code is always position-independent.
2330   // The actual BlockAddress is stored in the TOC.
2331   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2332     setUsesTOCBasePtr(DAG);
2333     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
2334     return getTOCEntry(DAG, SDLoc(BASDN), true, GA);
2335   }
2336
2337   unsigned MOHiFlag, MOLoFlag;
2338   bool IsPIC = isPositionIndependent();
2339   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag);
2340   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
2341   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
2342   return LowerLabelRef(TgtBAHi, TgtBALo, IsPIC, DAG);
2343 }
2344
2345 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
2346                                               SelectionDAG &DAG) const {
2347   // FIXME: TLS addresses currently use medium model code sequences,
2348   // which is the most useful form.  Eventually support for small and
2349   // large models could be added if users need it, at the cost of
2350   // additional complexity.
2351   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2352   if (DAG.getTarget().Options.EmulatedTLS)
2353     return LowerToTLSEmulatedModel(GA, DAG);
2354
2355   SDLoc dl(GA);
2356   const GlobalValue *GV = GA->getGlobal();
2357   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2358   bool is64bit = Subtarget.isPPC64();
2359   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
2360   PICLevel::Level picLevel = M->getPICLevel();
2361
2362   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
2363
2364   if (Model == TLSModel::LocalExec) {
2365     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2366                                                PPCII::MO_TPREL_HA);
2367     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2368                                                PPCII::MO_TPREL_LO);
2369     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
2370                                      is64bit ? MVT::i64 : MVT::i32);
2371     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
2372     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
2373   }
2374
2375   if (Model == TLSModel::InitialExec) {
2376     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2377     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2378                                                 PPCII::MO_TLS);
2379     SDValue GOTPtr;
2380     if (is64bit) {
2381       setUsesTOCBasePtr(DAG);
2382       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2383       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
2384                            PtrVT, GOTReg, TGA);
2385     } else
2386       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
2387     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
2388                                    PtrVT, TGA, GOTPtr);
2389     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
2390   }
2391
2392   if (Model == TLSModel::GeneralDynamic) {
2393     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2394     SDValue GOTPtr;
2395     if (is64bit) {
2396       setUsesTOCBasePtr(DAG);
2397       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2398       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
2399                                    GOTReg, TGA);
2400     } else {
2401       if (picLevel == PICLevel::SmallPIC)
2402         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2403       else
2404         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2405     }
2406     return DAG.getNode(PPCISD::ADDI_TLSGD_L_ADDR, dl, PtrVT,
2407                        GOTPtr, TGA, TGA);
2408   }
2409
2410   if (Model == TLSModel::LocalDynamic) {
2411     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
2412     SDValue GOTPtr;
2413     if (is64bit) {
2414       setUsesTOCBasePtr(DAG);
2415       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
2416       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
2417                            GOTReg, TGA);
2418     } else {
2419       if (picLevel == PICLevel::SmallPIC)
2420         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
2421       else
2422         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
2423     }
2424     SDValue TLSAddr = DAG.getNode(PPCISD::ADDI_TLSLD_L_ADDR, dl,
2425                                   PtrVT, GOTPtr, TGA, TGA);
2426     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl,
2427                                       PtrVT, TLSAddr, TGA);
2428     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
2429   }
2430
2431   llvm_unreachable("Unknown TLS model!");
2432 }
2433
2434 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
2435                                               SelectionDAG &DAG) const {
2436   EVT PtrVT = Op.getValueType();
2437   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
2438   SDLoc DL(GSDN);
2439   const GlobalValue *GV = GSDN->getGlobal();
2440
2441   // 64-bit SVR4 ABI code is always position-independent.
2442   // The actual address of the GlobalValue is stored in the TOC.
2443   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
2444     setUsesTOCBasePtr(DAG);
2445     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
2446     return getTOCEntry(DAG, DL, true, GA);
2447   }
2448
2449   unsigned MOHiFlag, MOLoFlag;
2450   bool IsPIC = isPositionIndependent();
2451   getLabelAccessInfo(IsPIC, Subtarget, MOHiFlag, MOLoFlag, GV);
2452
2453   if (IsPIC && Subtarget.isSVR4ABI()) {
2454     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
2455                                             GSDN->getOffset(),
2456                                             PPCII::MO_PIC_FLAG);
2457     return getTOCEntry(DAG, DL, false, GA);
2458   }
2459
2460   SDValue GAHi =
2461     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
2462   SDValue GALo =
2463     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
2464
2465   SDValue Ptr = LowerLabelRef(GAHi, GALo, IsPIC, DAG);
2466
2467   // If the global reference is actually to a non-lazy-pointer, we have to do an
2468   // extra load to get the address of the global.
2469   if (MOHiFlag & PPCII::MO_NLP_FLAG)
2470     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
2471   return Ptr;
2472 }
2473
2474 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2475   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2476   SDLoc dl(Op);
2477
2478   if (Op.getValueType() == MVT::v2i64) {
2479     // When the operands themselves are v2i64 values, we need to do something
2480     // special because VSX has no underlying comparison operations for these.
2481     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
2482       // Equality can be handled by casting to the legal type for Altivec
2483       // comparisons, everything else needs to be expanded.
2484       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2485         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
2486                  DAG.getSetCC(dl, MVT::v4i32,
2487                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
2488                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
2489                    CC));
2490       }
2491
2492       return SDValue();
2493     }
2494
2495     // We handle most of these in the usual way.
2496     return Op;
2497   }
2498
2499   // If we're comparing for equality to zero, expose the fact that this is
2500   // implemented as a ctlz/srl pair on ppc, so that the dag combiner can
2501   // fold the new nodes.
2502   if (SDValue V = lowerCmpEqZeroToCtlzSrl(Op, DAG))
2503     return V;
2504
2505   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2506     // Leave comparisons against 0 and -1 alone for now, since they're usually
2507     // optimized.  FIXME: revisit this when we can custom lower all setcc
2508     // optimizations.
2509     if (C->isAllOnesValue() || C->isNullValue())
2510       return SDValue();
2511   }
2512
2513   // If we have an integer seteq/setne, turn it into a compare against zero
2514   // by xor'ing the rhs with the lhs, which is faster than setting a
2515   // condition register, reading it back out, and masking the correct bit.  The
2516   // normal approach here uses sub to do this instead of xor.  Using xor exposes
2517   // the result to other bit-twiddling opportunities.
2518   EVT LHSVT = Op.getOperand(0).getValueType();
2519   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
2520     EVT VT = Op.getValueType();
2521     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
2522                                 Op.getOperand(1));
2523     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, dl, LHSVT), CC);
2524   }
2525   return SDValue();
2526 }
2527
2528 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2529   SDNode *Node = Op.getNode();
2530   EVT VT = Node->getValueType(0);
2531   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2532   SDValue InChain = Node->getOperand(0);
2533   SDValue VAListPtr = Node->getOperand(1);
2534   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2535   SDLoc dl(Node);
2536
2537   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
2538
2539   // gpr_index
2540   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2541                                     VAListPtr, MachinePointerInfo(SV), MVT::i8);
2542   InChain = GprIndex.getValue(1);
2543
2544   if (VT == MVT::i64) {
2545     // Check if GprIndex is even
2546     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
2547                                  DAG.getConstant(1, dl, MVT::i32));
2548     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
2549                                 DAG.getConstant(0, dl, MVT::i32), ISD::SETNE);
2550     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
2551                                           DAG.getConstant(1, dl, MVT::i32));
2552     // Align GprIndex to be even if it isn't
2553     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
2554                            GprIndex);
2555   }
2556
2557   // fpr index is 1 byte after gpr
2558   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2559                                DAG.getConstant(1, dl, MVT::i32));
2560
2561   // fpr
2562   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
2563                                     FprPtr, MachinePointerInfo(SV), MVT::i8);
2564   InChain = FprIndex.getValue(1);
2565
2566   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2567                                        DAG.getConstant(8, dl, MVT::i32));
2568
2569   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
2570                                         DAG.getConstant(4, dl, MVT::i32));
2571
2572   // areas
2573   SDValue OverflowArea =
2574       DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr, MachinePointerInfo());
2575   InChain = OverflowArea.getValue(1);
2576
2577   SDValue RegSaveArea =
2578       DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr, MachinePointerInfo());
2579   InChain = RegSaveArea.getValue(1);
2580
2581   // select overflow_area if index > 8
2582   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
2583                             DAG.getConstant(8, dl, MVT::i32), ISD::SETLT);
2584
2585   // adjustment constant gpr_index * 4/8
2586   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
2587                                     VT.isInteger() ? GprIndex : FprIndex,
2588                                     DAG.getConstant(VT.isInteger() ? 4 : 8, dl,
2589                                                     MVT::i32));
2590
2591   // OurReg = RegSaveArea + RegConstant
2592   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
2593                                RegConstant);
2594
2595   // Floating types are 32 bytes into RegSaveArea
2596   if (VT.isFloatingPoint())
2597     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
2598                          DAG.getConstant(32, dl, MVT::i32));
2599
2600   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
2601   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
2602                                    VT.isInteger() ? GprIndex : FprIndex,
2603                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1, dl,
2604                                                    MVT::i32));
2605
2606   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
2607                               VT.isInteger() ? VAListPtr : FprPtr,
2608                               MachinePointerInfo(SV), MVT::i8);
2609
2610   // determine if we should load from reg_save_area or overflow_area
2611   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
2612
2613   // increase overflow_area by 4/8 if gpr/fpr > 8
2614   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
2615                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
2616                                           dl, MVT::i32));
2617
2618   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
2619                              OverflowAreaPlusN);
2620
2621   InChain = DAG.getTruncStore(InChain, dl, OverflowArea, OverflowAreaPtr,
2622                               MachinePointerInfo(), MVT::i32);
2623
2624   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo());
2625 }
2626
2627 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
2628   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2629
2630   // We have to copy the entire va_list struct:
2631   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2632   return DAG.getMemcpy(Op.getOperand(0), Op,
2633                        Op.getOperand(1), Op.getOperand(2),
2634                        DAG.getConstant(12, SDLoc(Op), MVT::i32), 8, false, true,
2635                        false, MachinePointerInfo(), MachinePointerInfo());
2636 }
2637
2638 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2639                                                   SelectionDAG &DAG) const {
2640   return Op.getOperand(0);
2641 }
2642
2643 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2644                                                 SelectionDAG &DAG) const {
2645   SDValue Chain = Op.getOperand(0);
2646   SDValue Trmp = Op.getOperand(1); // trampoline
2647   SDValue FPtr = Op.getOperand(2); // nested function
2648   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2649   SDLoc dl(Op);
2650
2651   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2652   bool isPPC64 = (PtrVT == MVT::i64);
2653   Type *IntPtrTy = DAG.getDataLayout().getIntPtrType(*DAG.getContext());
2654
2655   TargetLowering::ArgListTy Args;
2656   TargetLowering::ArgListEntry Entry;
2657
2658   Entry.Ty = IntPtrTy;
2659   Entry.Node = Trmp; Args.push_back(Entry);
2660
2661   // TrampSize == (isPPC64 ? 48 : 40);
2662   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40, dl,
2663                                isPPC64 ? MVT::i64 : MVT::i32);
2664   Args.push_back(Entry);
2665
2666   Entry.Node = FPtr; Args.push_back(Entry);
2667   Entry.Node = Nest; Args.push_back(Entry);
2668
2669   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2670   TargetLowering::CallLoweringInfo CLI(DAG);
2671   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2672       CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2673       DAG.getExternalSymbol("__trampoline_setup", PtrVT), std::move(Args));
2674
2675   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2676   return CallResult.second;
2677 }
2678
2679 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2680   MachineFunction &MF = DAG.getMachineFunction();
2681   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2682   EVT PtrVT = getPointerTy(MF.getDataLayout());
2683
2684   SDLoc dl(Op);
2685
2686   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2687     // vastart just stores the address of the VarArgsFrameIndex slot into the
2688     // memory location argument.
2689     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2690     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2691     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2692                         MachinePointerInfo(SV));
2693   }
2694
2695   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2696   // We suppose the given va_list is already allocated.
2697   //
2698   // typedef struct {
2699   //  char gpr;     /* index into the array of 8 GPRs
2700   //                 * stored in the register save area
2701   //                 * gpr=0 corresponds to r3,
2702   //                 * gpr=1 to r4, etc.
2703   //                 */
2704   //  char fpr;     /* index into the array of 8 FPRs
2705   //                 * stored in the register save area
2706   //                 * fpr=0 corresponds to f1,
2707   //                 * fpr=1 to f2, etc.
2708   //                 */
2709   //  char *overflow_arg_area;
2710   //                /* location on stack that holds
2711   //                 * the next overflow argument
2712   //                 */
2713   //  char *reg_save_area;
2714   //               /* where r3:r10 and f1:f8 (if saved)
2715   //                * are stored
2716   //                */
2717   // } va_list[1];
2718
2719   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), dl, MVT::i32);
2720   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), dl, MVT::i32);
2721   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2722                                             PtrVT);
2723   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2724                                  PtrVT);
2725
2726   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2727   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, dl, PtrVT);
2728
2729   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2730   SDValue ConstStackOffset = DAG.getConstant(StackOffset, dl, PtrVT);
2731
2732   uint64_t FPROffset = 1;
2733   SDValue ConstFPROffset = DAG.getConstant(FPROffset, dl, PtrVT);
2734
2735   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2736
2737   // Store first byte : number of int regs
2738   SDValue firstStore =
2739       DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR, Op.getOperand(1),
2740                         MachinePointerInfo(SV), MVT::i8);
2741   uint64_t nextOffset = FPROffset;
2742   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2743                                   ConstFPROffset);
2744
2745   // Store second byte : number of float regs
2746   SDValue secondStore =
2747       DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2748                         MachinePointerInfo(SV, nextOffset), MVT::i8);
2749   nextOffset += StackOffset;
2750   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2751
2752   // Store second word : arguments given on stack
2753   SDValue thirdStore = DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2754                                     MachinePointerInfo(SV, nextOffset));
2755   nextOffset += FrameOffset;
2756   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2757
2758   // Store third word : arguments given in registers
2759   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2760                       MachinePointerInfo(SV, nextOffset));
2761 }
2762
2763 #include "PPCGenCallingConv.inc"
2764
2765 // Function whose sole purpose is to kill compiler warnings
2766 // stemming from unused functions included from PPCGenCallingConv.inc.
2767 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2768   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2769 }
2770
2771 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2772                                       CCValAssign::LocInfo &LocInfo,
2773                                       ISD::ArgFlagsTy &ArgFlags,
2774                                       CCState &State) {
2775   return true;
2776 }
2777
2778 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2779                                              MVT &LocVT,
2780                                              CCValAssign::LocInfo &LocInfo,
2781                                              ISD::ArgFlagsTy &ArgFlags,
2782                                              CCState &State) {
2783   static const MCPhysReg ArgRegs[] = {
2784     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2785     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2786   };
2787   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2788
2789   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2790
2791   // Skip one register if the first unallocated register has an even register
2792   // number and there are still argument registers available which have not been
2793   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2794   // need to skip a register if RegNum is odd.
2795   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2796     State.AllocateReg(ArgRegs[RegNum]);
2797   }
2798
2799   // Always return false here, as this function only makes sure that the first
2800   // unallocated register has an odd register number and does not actually
2801   // allocate a register for the current argument.
2802   return false;
2803 }
2804
2805 bool
2806 llvm::CC_PPC32_SVR4_Custom_SkipLastArgRegsPPCF128(unsigned &ValNo, MVT &ValVT,
2807                                                   MVT &LocVT,
2808                                                   CCValAssign::LocInfo &LocInfo,
2809                                                   ISD::ArgFlagsTy &ArgFlags,
2810                                                   CCState &State) {
2811   static const MCPhysReg ArgRegs[] = {
2812     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2813     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2814   };
2815   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2816
2817   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2818   int RegsLeft = NumArgRegs - RegNum;
2819
2820   // Skip if there is not enough registers left for long double type (4 gpr regs
2821   // in soft float mode) and put long double argument on the stack.
2822   if (RegNum != NumArgRegs && RegsLeft < 4) {
2823     for (int i = 0; i < RegsLeft; i++) {
2824       State.AllocateReg(ArgRegs[RegNum + i]);
2825     }
2826   }
2827
2828   return false;
2829 }
2830
2831 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2832                                                MVT &LocVT,
2833                                                CCValAssign::LocInfo &LocInfo,
2834                                                ISD::ArgFlagsTy &ArgFlags,
2835                                                CCState &State) {
2836   static const MCPhysReg ArgRegs[] = {
2837     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2838     PPC::F8
2839   };
2840
2841   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2842
2843   unsigned RegNum = State.getFirstUnallocated(ArgRegs);
2844
2845   // If there is only one Floating-point register left we need to put both f64
2846   // values of a split ppc_fp128 value on the stack.
2847   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2848     State.AllocateReg(ArgRegs[RegNum]);
2849   }
2850
2851   // Always return false here, as this function only makes sure that the two f64
2852   // values a ppc_fp128 value is split into are both passed in registers or both
2853   // passed on the stack and does not actually allocate a register for the
2854   // current argument.
2855   return false;
2856 }
2857
2858 /// FPR - The set of FP registers that should be allocated for arguments,
2859 /// on Darwin.
2860 static const MCPhysReg FPR[] = {PPC::F1,  PPC::F2,  PPC::F3, PPC::F4, PPC::F5,
2861                                 PPC::F6,  PPC::F7,  PPC::F8, PPC::F9, PPC::F10,
2862                                 PPC::F11, PPC::F12, PPC::F13};
2863
2864 /// QFPR - The set of QPX registers that should be allocated for arguments.
2865 static const MCPhysReg QFPR[] = {
2866     PPC::QF1, PPC::QF2, PPC::QF3,  PPC::QF4,  PPC::QF5,  PPC::QF6, PPC::QF7,
2867     PPC::QF8, PPC::QF9, PPC::QF10, PPC::QF11, PPC::QF12, PPC::QF13};
2868
2869 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2870 /// the stack.
2871 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2872                                        unsigned PtrByteSize) {
2873   unsigned ArgSize = ArgVT.getStoreSize();
2874   if (Flags.isByVal())
2875     ArgSize = Flags.getByValSize();
2876
2877   // Round up to multiples of the pointer size, except for array members,
2878   // which are always packed.
2879   if (!Flags.isInConsecutiveRegs())
2880     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2881
2882   return ArgSize;
2883 }
2884
2885 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2886 /// on the stack.
2887 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2888                                             ISD::ArgFlagsTy Flags,
2889                                             unsigned PtrByteSize) {
2890   unsigned Align = PtrByteSize;
2891
2892   // Altivec parameters are padded to a 16 byte boundary.
2893   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2894       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2895       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2896       ArgVT == MVT::v1i128)
2897     Align = 16;
2898   // QPX vector types stored in double-precision are padded to a 32 byte
2899   // boundary.
2900   else if (ArgVT == MVT::v4f64 || ArgVT == MVT::v4i1)
2901     Align = 32;
2902
2903   // ByVal parameters are aligned as requested.
2904   if (Flags.isByVal()) {
2905     unsigned BVAlign = Flags.getByValAlign();
2906     if (BVAlign > PtrByteSize) {
2907       if (BVAlign % PtrByteSize != 0)
2908           llvm_unreachable(
2909             "ByVal alignment is not a multiple of the pointer size");
2910
2911       Align = BVAlign;
2912     }
2913   }
2914
2915   // Array members are always packed to their original alignment.
2916   if (Flags.isInConsecutiveRegs()) {
2917     // If the array member was split into multiple registers, the first
2918     // needs to be aligned to the size of the full type.  (Except for
2919     // ppcf128, which is only aligned as its f64 components.)
2920     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2921       Align = OrigVT.getStoreSize();
2922     else
2923       Align = ArgVT.getStoreSize();
2924   }
2925
2926   return Align;
2927 }
2928
2929 /// CalculateStackSlotUsed - Return whether this argument will use its
2930 /// stack slot (instead of being passed in registers).  ArgOffset,
2931 /// AvailableFPRs, and AvailableVRs must hold the current argument
2932 /// position, and will be updated to account for this argument.
2933 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2934                                    ISD::ArgFlagsTy Flags,
2935                                    unsigned PtrByteSize,
2936                                    unsigned LinkageSize,
2937                                    unsigned ParamAreaSize,
2938                                    unsigned &ArgOffset,
2939                                    unsigned &AvailableFPRs,
2940                                    unsigned &AvailableVRs, bool HasQPX) {
2941   bool UseMemory = false;
2942
2943   // Respect alignment of argument on the stack.
2944   unsigned Align =
2945     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2946   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2947   // If there's no space left in the argument save area, we must
2948   // use memory (this check also catches zero-sized arguments).
2949   if (ArgOffset >= LinkageSize + ParamAreaSize)
2950     UseMemory = true;
2951
2952   // Allocate argument on the stack.
2953   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2954   if (Flags.isInConsecutiveRegsLast())
2955     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2956   // If we overran the argument save area, we must use memory
2957   // (this check catches arguments passed partially in memory)
2958   if (ArgOffset > LinkageSize + ParamAreaSize)
2959     UseMemory = true;
2960
2961   // However, if the argument is actually passed in an FPR or a VR,
2962   // we don't use memory after all.
2963   if (!Flags.isByVal()) {
2964     if (ArgVT == MVT::f32 || ArgVT == MVT::f64 ||
2965         // QPX registers overlap with the scalar FP registers.
2966         (HasQPX && (ArgVT == MVT::v4f32 ||
2967                     ArgVT == MVT::v4f64 ||
2968                     ArgVT == MVT::v4i1)))
2969       if (AvailableFPRs > 0) {
2970         --AvailableFPRs;
2971         return false;
2972       }
2973     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2974         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2975         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64 ||
2976         ArgVT == MVT::v1i128)
2977       if (AvailableVRs > 0) {
2978         --AvailableVRs;
2979         return false;
2980       }
2981   }
2982
2983   return UseMemory;
2984 }
2985
2986 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2987 /// ensure minimum alignment required for target.
2988 static unsigned EnsureStackAlignment(const PPCFrameLowering *Lowering,
2989                                      unsigned NumBytes) {
2990   unsigned TargetAlign = Lowering->getStackAlignment();
2991   unsigned AlignMask = TargetAlign - 1;
2992   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2993   return NumBytes;
2994 }
2995
2996 SDValue PPCTargetLowering::LowerFormalArguments(
2997     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2998     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
2999     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3000   if (Subtarget.isSVR4ABI()) {
3001     if (Subtarget.isPPC64())
3002       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
3003                                          dl, DAG, InVals);
3004     else
3005       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
3006                                          dl, DAG, InVals);
3007   } else {
3008     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
3009                                        dl, DAG, InVals);
3010   }
3011 }
3012
3013 SDValue PPCTargetLowering::LowerFormalArguments_32SVR4(
3014     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3015     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3016     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3017
3018   // 32-bit SVR4 ABI Stack Frame Layout:
3019   //              +-----------------------------------+
3020   //        +-->  |            Back chain             |
3021   //        |     +-----------------------------------+
3022   //        |     | Floating-point register save area |
3023   //        |     +-----------------------------------+
3024   //        |     |    General register save area     |
3025   //        |     +-----------------------------------+
3026   //        |     |          CR save word             |
3027   //        |     +-----------------------------------+
3028   //        |     |         VRSAVE save word          |
3029   //        |     +-----------------------------------+
3030   //        |     |         Alignment padding         |
3031   //        |     +-----------------------------------+
3032   //        |     |     Vector register save area     |
3033   //        |     +-----------------------------------+
3034   //        |     |       Local variable space        |
3035   //        |     +-----------------------------------+
3036   //        |     |        Parameter list area        |
3037   //        |     +-----------------------------------+
3038   //        |     |           LR save word            |
3039   //        |     +-----------------------------------+
3040   // SP-->  +---  |            Back chain             |
3041   //              +-----------------------------------+
3042   //
3043   // Specifications:
3044   //   System V Application Binary Interface PowerPC Processor Supplement
3045   //   AltiVec Technology Programming Interface Manual
3046
3047   MachineFunction &MF = DAG.getMachineFunction();
3048   MachineFrameInfo &MFI = MF.getFrameInfo();
3049   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3050
3051   EVT PtrVT = getPointerTy(MF.getDataLayout());
3052   // Potential tail calls could cause overwriting of argument stack slots.
3053   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3054                        (CallConv == CallingConv::Fast));
3055   unsigned PtrByteSize = 4;
3056
3057   // Assign locations to all of the incoming arguments.
3058   SmallVector<CCValAssign, 16> ArgLocs;
3059   PPCCCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3060                  *DAG.getContext());
3061
3062   // Reserve space for the linkage area on the stack.
3063   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3064   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
3065   if (useSoftFloat())
3066     CCInfo.PreAnalyzeFormalArguments(Ins);
3067
3068   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
3069   CCInfo.clearWasPPCF128();
3070
3071   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3072     CCValAssign &VA = ArgLocs[i];
3073
3074     // Arguments stored in registers.
3075     if (VA.isRegLoc()) {
3076       const TargetRegisterClass *RC;
3077       EVT ValVT = VA.getValVT();
3078
3079       switch (ValVT.getSimpleVT().SimpleTy) {
3080         default:
3081           llvm_unreachable("ValVT not supported by formal arguments Lowering");
3082         case MVT::i1:
3083         case MVT::i32:
3084           RC = &PPC::GPRCRegClass;
3085           break;
3086         case MVT::f32:
3087           if (Subtarget.hasP8Vector())
3088             RC = &PPC::VSSRCRegClass;
3089           else
3090             RC = &PPC::F4RCRegClass;
3091           break;
3092         case MVT::f64:
3093           if (Subtarget.hasVSX())
3094             RC = &PPC::VSFRCRegClass;
3095           else
3096             RC = &PPC::F8RCRegClass;
3097           break;
3098         case MVT::v16i8:
3099         case MVT::v8i16:
3100         case MVT::v4i32:
3101           RC = &PPC::VRRCRegClass;
3102           break;
3103         case MVT::v4f32:
3104           RC = Subtarget.hasQPX() ? &PPC::QSRCRegClass : &PPC::VRRCRegClass;
3105           break;
3106         case MVT::v2f64:
3107         case MVT::v2i64:
3108           RC = &PPC::VRRCRegClass;
3109           break;
3110         case MVT::v4f64:
3111           RC = &PPC::QFRCRegClass;
3112           break;
3113         case MVT::v4i1:
3114           RC = &PPC::QBRCRegClass;
3115           break;
3116       }
3117
3118       // Transform the arguments stored in physical registers into virtual ones.
3119       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3120       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3121                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
3122
3123       if (ValVT == MVT::i1)
3124         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
3125
3126       InVals.push_back(ArgValue);
3127     } else {
3128       // Argument stored in memory.
3129       assert(VA.isMemLoc());
3130
3131       unsigned ArgSize = VA.getLocVT().getStoreSize();
3132       int FI = MFI.CreateFixedObject(ArgSize, VA.getLocMemOffset(),
3133                                      isImmutable);
3134
3135       // Create load nodes to retrieve arguments from the stack.
3136       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3137       InVals.push_back(
3138           DAG.getLoad(VA.getValVT(), dl, Chain, FIN, MachinePointerInfo()));
3139     }
3140   }
3141
3142   // Assign locations to all of the incoming aggregate by value arguments.
3143   // Aggregates passed by value are stored in the local variable space of the
3144   // caller's stack frame, right above the parameter list area.
3145   SmallVector<CCValAssign, 16> ByValArgLocs;
3146   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3147                       ByValArgLocs, *DAG.getContext());
3148
3149   // Reserve stack space for the allocations in CCInfo.
3150   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3151
3152   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
3153
3154   // Area that is at least reserved in the caller of this function.
3155   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
3156   MinReservedArea = std::max(MinReservedArea, LinkageSize);
3157
3158   // Set the size that is at least reserved in caller of this function.  Tail
3159   // call optimized function's reserved stack space needs to be aligned so that
3160   // taking the difference between two stack areas will result in an aligned
3161   // stack.
3162   MinReservedArea =
3163       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3164   FuncInfo->setMinReservedArea(MinReservedArea);
3165
3166   SmallVector<SDValue, 8> MemOps;
3167
3168   // If the function takes variable number of arguments, make a frame index for
3169   // the start of the first vararg value... for expansion of llvm.va_start.
3170   if (isVarArg) {
3171     static const MCPhysReg GPArgRegs[] = {
3172       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3173       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3174     };
3175     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
3176
3177     static const MCPhysReg FPArgRegs[] = {
3178       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
3179       PPC::F8
3180     };
3181     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
3182
3183     if (useSoftFloat())
3184        NumFPArgRegs = 0;
3185
3186     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs));
3187     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs));
3188
3189     // Make room for NumGPArgRegs and NumFPArgRegs.
3190     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
3191                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
3192
3193     FuncInfo->setVarArgsStackOffset(
3194       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3195                             CCInfo.getNextStackOffset(), true));
3196
3197     FuncInfo->setVarArgsFrameIndex(MFI.CreateStackObject(Depth, 8, false));
3198     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3199
3200     // The fixed integer arguments of a variadic function are stored to the
3201     // VarArgsFrameIndex on the stack so that they may be loaded by
3202     // dereferencing the result of va_next.
3203     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
3204       // Get an existing live-in vreg, or add a new one.
3205       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
3206       if (!VReg)
3207         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
3208
3209       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3210       SDValue Store =
3211           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3212       MemOps.push_back(Store);
3213       // Increment the address by four for the next argument to store
3214       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
3215       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3216     }
3217
3218     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
3219     // is set.
3220     // The double arguments are stored to the VarArgsFrameIndex
3221     // on the stack.
3222     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
3223       // Get an existing live-in vreg, or add a new one.
3224       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
3225       if (!VReg)
3226         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
3227
3228       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
3229       SDValue Store =
3230           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3231       MemOps.push_back(Store);
3232       // Increment the address by eight for the next argument to store
3233       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8, dl,
3234                                          PtrVT);
3235       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3236     }
3237   }
3238
3239   if (!MemOps.empty())
3240     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3241
3242   return Chain;
3243 }
3244
3245 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3246 // value to MVT::i64 and then truncate to the correct register size.
3247 SDValue PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags,
3248                                              EVT ObjectVT, SelectionDAG &DAG,
3249                                              SDValue ArgVal,
3250                                              const SDLoc &dl) const {
3251   if (Flags.isSExt())
3252     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
3253                          DAG.getValueType(ObjectVT));
3254   else if (Flags.isZExt())
3255     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
3256                          DAG.getValueType(ObjectVT));
3257
3258   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
3259 }
3260
3261 SDValue PPCTargetLowering::LowerFormalArguments_64SVR4(
3262     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3263     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3264     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3265   // TODO: add description of PPC stack frame format, or at least some docs.
3266   //
3267   bool isELFv2ABI = Subtarget.isELFv2ABI();
3268   bool isLittleEndian = Subtarget.isLittleEndian();
3269   MachineFunction &MF = DAG.getMachineFunction();
3270   MachineFrameInfo &MFI = MF.getFrameInfo();
3271   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3272
3273   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
3274          "fastcc not supported on varargs functions");
3275
3276   EVT PtrVT = getPointerTy(MF.getDataLayout());
3277   // Potential tail calls could cause overwriting of argument stack slots.
3278   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3279                        (CallConv == CallingConv::Fast));
3280   unsigned PtrByteSize = 8;
3281   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3282
3283   static const MCPhysReg GPR[] = {
3284     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3285     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3286   };
3287   static const MCPhysReg VR[] = {
3288     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3289     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3290   };
3291
3292   const unsigned Num_GPR_Regs = array_lengthof(GPR);
3293   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3294   const unsigned Num_VR_Regs  = array_lengthof(VR);
3295   const unsigned Num_QFPR_Regs = Num_FPR_Regs;
3296
3297   // Do a first pass over the arguments to determine whether the ABI
3298   // guarantees that our caller has allocated the parameter save area
3299   // on its stack frame.  In the ELFv1 ABI, this is always the case;
3300   // in the ELFv2 ABI, it is true if this is a vararg function or if
3301   // any parameter is located in a stack slot.
3302
3303   bool HasParameterArea = !isELFv2ABI || isVarArg;
3304   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
3305   unsigned NumBytes = LinkageSize;
3306   unsigned AvailableFPRs = Num_FPR_Regs;
3307   unsigned AvailableVRs = Num_VR_Regs;
3308   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3309     if (Ins[i].Flags.isNest())
3310       continue;
3311
3312     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
3313                                PtrByteSize, LinkageSize, ParamAreaSize,
3314                                NumBytes, AvailableFPRs, AvailableVRs,
3315                                Subtarget.hasQPX()))
3316       HasParameterArea = true;
3317   }
3318
3319   // Add DAG nodes to load the arguments or copy them out of registers.  On
3320   // entry to a function on PPC, the arguments start after the linkage area,
3321   // although the first ones are often in registers.
3322
3323   unsigned ArgOffset = LinkageSize;
3324   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3325   unsigned &QFPR_idx = FPR_idx;
3326   SmallVector<SDValue, 8> MemOps;
3327   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3328   unsigned CurArgIdx = 0;
3329   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3330     SDValue ArgVal;
3331     bool needsLoad = false;
3332     EVT ObjectVT = Ins[ArgNo].VT;
3333     EVT OrigVT = Ins[ArgNo].ArgVT;
3334     unsigned ObjSize = ObjectVT.getStoreSize();
3335     unsigned ArgSize = ObjSize;
3336     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3337     if (Ins[ArgNo].isOrigArg()) {
3338       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3339       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3340     }
3341     // We re-align the argument offset for each argument, except when using the
3342     // fast calling convention, when we need to make sure we do that only when
3343     // we'll actually use a stack slot.
3344     unsigned CurArgOffset, Align;
3345     auto ComputeArgOffset = [&]() {
3346       /* Respect alignment of argument on the stack.  */
3347       Align = CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
3348       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
3349       CurArgOffset = ArgOffset;
3350     };
3351
3352     if (CallConv != CallingConv::Fast) {
3353       ComputeArgOffset();
3354
3355       /* Compute GPR index associated with argument offset.  */
3356       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3357       GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
3358     }
3359
3360     // FIXME the codegen can be much improved in some cases.
3361     // We do not have to keep everything in memory.
3362     if (Flags.isByVal()) {
3363       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3364
3365       if (CallConv == CallingConv::Fast)
3366         ComputeArgOffset();
3367
3368       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3369       ObjSize = Flags.getByValSize();
3370       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3371       // Empty aggregate parameters do not take up registers.  Examples:
3372       //   struct { } a;
3373       //   union  { } b;
3374       //   int c[0];
3375       // etc.  However, we have to provide a place-holder in InVals, so
3376       // pretend we have an 8-byte item at the current address for that
3377       // purpose.
3378       if (!ObjSize) {
3379         int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3380         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3381         InVals.push_back(FIN);
3382         continue;
3383       }
3384
3385       // Create a stack object covering all stack doublewords occupied
3386       // by the argument.  If the argument is (fully or partially) on
3387       // the stack, or if the argument is fully in registers but the
3388       // caller has allocated the parameter save anyway, we can refer
3389       // directly to the caller's stack frame.  Otherwise, create a
3390       // local copy in our own frame.
3391       int FI;
3392       if (HasParameterArea ||
3393           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
3394         FI = MFI.CreateFixedObject(ArgSize, ArgOffset, false, true);
3395       else
3396         FI = MFI.CreateStackObject(ArgSize, Align, false);
3397       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3398
3399       // Handle aggregates smaller than 8 bytes.
3400       if (ObjSize < PtrByteSize) {
3401         // The value of the object is its address, which differs from the
3402         // address of the enclosing doubleword on big-endian systems.
3403         SDValue Arg = FIN;
3404         if (!isLittleEndian) {
3405           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, dl, PtrVT);
3406           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
3407         }
3408         InVals.push_back(Arg);
3409
3410         if (GPR_idx != Num_GPR_Regs) {
3411           unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3412           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3413           SDValue Store;
3414
3415           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
3416             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
3417                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
3418             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
3419                                       MachinePointerInfo(&*FuncArg), ObjType);
3420           } else {
3421             // For sizes that don't fit a truncating store (3, 5, 6, 7),
3422             // store the whole register as-is to the parameter save area
3423             // slot.
3424             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3425                                  MachinePointerInfo(&*FuncArg));
3426           }
3427
3428           MemOps.push_back(Store);
3429         }
3430         // Whether we copied from a register or not, advance the offset
3431         // into the parameter save area by a full doubleword.
3432         ArgOffset += PtrByteSize;
3433         continue;
3434       }
3435
3436       // The value of the object is its address, which is the address of
3437       // its first stack doubleword.
3438       InVals.push_back(FIN);
3439
3440       // Store whatever pieces of the object are in registers to memory.
3441       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3442         if (GPR_idx == Num_GPR_Regs)
3443           break;
3444
3445         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3446         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3447         SDValue Addr = FIN;
3448         if (j) {
3449           SDValue Off = DAG.getConstant(j, dl, PtrVT);
3450           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
3451         }
3452         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
3453                                      MachinePointerInfo(&*FuncArg, j));
3454         MemOps.push_back(Store);
3455         ++GPR_idx;
3456       }
3457       ArgOffset += ArgSize;
3458       continue;
3459     }
3460
3461     switch (ObjectVT.getSimpleVT().SimpleTy) {
3462     default: llvm_unreachable("Unhandled argument type!");
3463     case MVT::i1:
3464     case MVT::i32:
3465     case MVT::i64:
3466       if (Flags.isNest()) {
3467         // The 'nest' parameter, if any, is passed in R11.
3468         unsigned VReg = MF.addLiveIn(PPC::X11, &PPC::G8RCRegClass);
3469         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3470
3471         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3472           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3473
3474         break;
3475       }
3476
3477       // These can be scalar arguments or elements of an integer array type
3478       // passed directly.  Clang may use those instead of "byval" aggregate
3479       // types to avoid forcing arguments to memory unnecessarily.
3480       if (GPR_idx != Num_GPR_Regs) {
3481         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3482         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3483
3484         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3485           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3486           // value to MVT::i64 and then truncate to the correct register size.
3487           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3488       } else {
3489         if (CallConv == CallingConv::Fast)
3490           ComputeArgOffset();
3491
3492         needsLoad = true;
3493         ArgSize = PtrByteSize;
3494       }
3495       if (CallConv != CallingConv::Fast || needsLoad)
3496         ArgOffset += 8;
3497       break;
3498
3499     case MVT::f32:
3500     case MVT::f64:
3501       // These can be scalar arguments or elements of a float array type
3502       // passed directly.  The latter are used to implement ELFv2 homogenous
3503       // float aggregates.
3504       if (FPR_idx != Num_FPR_Regs) {
3505         unsigned VReg;
3506
3507         if (ObjectVT == MVT::f32)
3508           VReg = MF.addLiveIn(FPR[FPR_idx],
3509                               Subtarget.hasP8Vector()
3510                                   ? &PPC::VSSRCRegClass
3511                                   : &PPC::F4RCRegClass);
3512         else
3513           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX()
3514                                                 ? &PPC::VSFRCRegClass
3515                                                 : &PPC::F8RCRegClass);
3516
3517         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3518         ++FPR_idx;
3519       } else if (GPR_idx != Num_GPR_Regs && CallConv != CallingConv::Fast) {
3520         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
3521         // once we support fp <-> gpr moves.
3522
3523         // This can only ever happen in the presence of f32 array types,
3524         // since otherwise we never run out of FPRs before running out
3525         // of GPRs.
3526         unsigned VReg = MF.addLiveIn(GPR[GPR_idx++], &PPC::G8RCRegClass);
3527         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3528
3529         if (ObjectVT == MVT::f32) {
3530           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
3531             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
3532                                  DAG.getConstant(32, dl, MVT::i32));
3533           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
3534         }
3535
3536         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
3537       } else {
3538         if (CallConv == CallingConv::Fast)
3539           ComputeArgOffset();
3540
3541         needsLoad = true;
3542       }
3543
3544       // When passing an array of floats, the array occupies consecutive
3545       // space in the argument area; only round up to the next doubleword
3546       // at the end of the array.  Otherwise, each float takes 8 bytes.
3547       if (CallConv != CallingConv::Fast || needsLoad) {
3548         ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
3549         ArgOffset += ArgSize;
3550         if (Flags.isInConsecutiveRegsLast())
3551           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3552       }
3553       break;
3554     case MVT::v4f32:
3555     case MVT::v4i32:
3556     case MVT::v8i16:
3557     case MVT::v16i8:
3558     case MVT::v2f64:
3559     case MVT::v2i64:
3560     case MVT::v1i128:
3561       if (!Subtarget.hasQPX()) {
3562       // These can be scalar arguments or elements of a vector array type
3563       // passed directly.  The latter are used to implement ELFv2 homogenous
3564       // vector aggregates.
3565       if (VR_idx != Num_VR_Regs) {
3566         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3567         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3568         ++VR_idx;
3569       } else {
3570         if (CallConv == CallingConv::Fast)
3571           ComputeArgOffset();
3572
3573         needsLoad = true;
3574       }
3575       if (CallConv != CallingConv::Fast || needsLoad)
3576         ArgOffset += 16;
3577       break;
3578       } // not QPX
3579
3580       assert(ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 &&
3581              "Invalid QPX parameter type");
3582       /* fall through */
3583
3584     case MVT::v4f64:
3585     case MVT::v4i1:
3586       // QPX vectors are treated like their scalar floating-point subregisters
3587       // (except that they're larger).
3588       unsigned Sz = ObjectVT.getSimpleVT().SimpleTy == MVT::v4f32 ? 16 : 32;
3589       if (QFPR_idx != Num_QFPR_Regs) {
3590         const TargetRegisterClass *RC;
3591         switch (ObjectVT.getSimpleVT().SimpleTy) {
3592         case MVT::v4f64: RC = &PPC::QFRCRegClass; break;
3593         case MVT::v4f32: RC = &PPC::QSRCRegClass; break;
3594         default:         RC = &PPC::QBRCRegClass; break;
3595         }
3596
3597         unsigned VReg = MF.addLiveIn(QFPR[QFPR_idx], RC);
3598         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3599         ++QFPR_idx;
3600       } else {
3601         if (CallConv == CallingConv::Fast)
3602           ComputeArgOffset();
3603         needsLoad = true;
3604       }
3605       if (CallConv != CallingConv::Fast || needsLoad)
3606         ArgOffset += Sz;
3607       break;
3608     }
3609
3610     // We need to load the argument to a virtual register if we determined
3611     // above that we ran out of physical registers of the appropriate type.
3612     if (needsLoad) {
3613       if (ObjSize < ArgSize && !isLittleEndian)
3614         CurArgOffset += ArgSize - ObjSize;
3615       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
3616       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3617       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3618     }
3619
3620     InVals.push_back(ArgVal);
3621   }
3622
3623   // Area that is at least reserved in the caller of this function.
3624   unsigned MinReservedArea;
3625   if (HasParameterArea)
3626     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
3627   else
3628     MinReservedArea = LinkageSize;
3629
3630   // Set the size that is at least reserved in caller of this function.  Tail
3631   // call optimized functions' reserved stack space needs to be aligned so that
3632   // taking the difference between two stack areas will result in an aligned
3633   // stack.
3634   MinReservedArea =
3635       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3636   FuncInfo->setMinReservedArea(MinReservedArea);
3637
3638   // If the function takes variable number of arguments, make a frame index for
3639   // the start of the first vararg value... for expansion of llvm.va_start.
3640   if (isVarArg) {
3641     int Depth = ArgOffset;
3642
3643     FuncInfo->setVarArgsFrameIndex(
3644       MFI.CreateFixedObject(PtrByteSize, Depth, true));
3645     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3646
3647     // If this function is vararg, store any remaining integer argument regs
3648     // to their spots on the stack so that they may be loaded by dereferencing
3649     // the result of va_next.
3650     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
3651          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
3652       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3653       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3654       SDValue Store =
3655           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
3656       MemOps.push_back(Store);
3657       // Increment the address by four for the next argument to store
3658       SDValue PtrOff = DAG.getConstant(PtrByteSize, dl, PtrVT);
3659       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3660     }
3661   }
3662
3663   if (!MemOps.empty())
3664     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3665
3666   return Chain;
3667 }
3668
3669 SDValue PPCTargetLowering::LowerFormalArguments_Darwin(
3670     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3671     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3672     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3673   // TODO: add description of PPC stack frame format, or at least some docs.
3674   //
3675   MachineFunction &MF = DAG.getMachineFunction();
3676   MachineFrameInfo &MFI = MF.getFrameInfo();
3677   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
3678
3679   EVT PtrVT = getPointerTy(MF.getDataLayout());
3680   bool isPPC64 = PtrVT == MVT::i64;
3681   // Potential tail calls could cause overwriting of argument stack slots.
3682   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
3683                        (CallConv == CallingConv::Fast));
3684   unsigned PtrByteSize = isPPC64 ? 8 : 4;
3685   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
3686   unsigned ArgOffset = LinkageSize;
3687   // Area that is at least reserved in caller of this function.
3688   unsigned MinReservedArea = ArgOffset;
3689
3690   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
3691     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3692     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3693   };
3694   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
3695     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3696     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3697   };
3698   static const MCPhysReg VR[] = {
3699     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3700     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3701   };
3702
3703   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
3704   const unsigned Num_FPR_Regs = useSoftFloat() ? 0 : 13;
3705   const unsigned Num_VR_Regs  = array_lengthof( VR);
3706
3707   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3708
3709   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3710
3711   // In 32-bit non-varargs functions, the stack space for vectors is after the
3712   // stack space for non-vectors.  We do not use this space unless we have
3713   // too many vectors to fit in registers, something that only occurs in
3714   // constructed examples:), but we have to walk the arglist to figure
3715   // that out...for the pathological case, compute VecArgOffset as the
3716   // start of the vector parameter area.  Computing VecArgOffset is the
3717   // entire point of the following loop.
3718   unsigned VecArgOffset = ArgOffset;
3719   if (!isVarArg && !isPPC64) {
3720     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3721          ++ArgNo) {
3722       EVT ObjectVT = Ins[ArgNo].VT;
3723       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3724
3725       if (Flags.isByVal()) {
3726         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3727         unsigned ObjSize = Flags.getByValSize();
3728         unsigned ArgSize =
3729                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3730         VecArgOffset += ArgSize;
3731         continue;
3732       }
3733
3734       switch(ObjectVT.getSimpleVT().SimpleTy) {
3735       default: llvm_unreachable("Unhandled argument type!");
3736       case MVT::i1:
3737       case MVT::i32:
3738       case MVT::f32:
3739         VecArgOffset += 4;
3740         break;
3741       case MVT::i64:  // PPC64
3742       case MVT::f64:
3743         // FIXME: We are guaranteed to be !isPPC64 at this point.
3744         // Does MVT::i64 apply?
3745         VecArgOffset += 8;
3746         break;
3747       case MVT::v4f32:
3748       case MVT::v4i32:
3749       case MVT::v8i16:
3750       case MVT::v16i8:
3751         // Nothing to do, we're only looking at Nonvector args here.
3752         break;
3753       }
3754     }
3755   }
3756   // We've found where the vector parameter area in memory is.  Skip the
3757   // first 12 parameters; these don't use that memory.
3758   VecArgOffset = ((VecArgOffset+15)/16)*16;
3759   VecArgOffset += 12*16;
3760
3761   // Add DAG nodes to load the arguments or copy them out of registers.  On
3762   // entry to a function on PPC, the arguments start after the linkage area,
3763   // although the first ones are often in registers.
3764
3765   SmallVector<SDValue, 8> MemOps;
3766   unsigned nAltivecParamsAtEnd = 0;
3767   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3768   unsigned CurArgIdx = 0;
3769   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3770     SDValue ArgVal;
3771     bool needsLoad = false;
3772     EVT ObjectVT = Ins[ArgNo].VT;
3773     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3774     unsigned ArgSize = ObjSize;
3775     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3776     if (Ins[ArgNo].isOrigArg()) {
3777       std::advance(FuncArg, Ins[ArgNo].getOrigArgIndex() - CurArgIdx);
3778       CurArgIdx = Ins[ArgNo].getOrigArgIndex();
3779     }
3780     unsigned CurArgOffset = ArgOffset;
3781
3782     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3783     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3784         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3785       if (isVarArg || isPPC64) {
3786         MinReservedArea = ((MinReservedArea+15)/16)*16;
3787         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3788                                                   Flags,
3789                                                   PtrByteSize);
3790       } else  nAltivecParamsAtEnd++;
3791     } else
3792       // Calculate min reserved area.
3793       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3794                                                 Flags,
3795                                                 PtrByteSize);
3796
3797     // FIXME the codegen can be much improved in some cases.
3798     // We do not have to keep everything in memory.
3799     if (Flags.isByVal()) {
3800       assert(Ins[ArgNo].isOrigArg() && "Byval arguments cannot be implicit");
3801
3802       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3803       ObjSize = Flags.getByValSize();
3804       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3805       // Objects of size 1 and 2 are right justified, everything else is
3806       // left justified.  This means the memory address is adjusted forwards.
3807       if (ObjSize==1 || ObjSize==2) {
3808         CurArgOffset = CurArgOffset + (4 - ObjSize);
3809       }
3810       // The value of the object is its address.
3811       int FI = MFI.CreateFixedObject(ObjSize, CurArgOffset, false, true);
3812       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3813       InVals.push_back(FIN);
3814       if (ObjSize==1 || ObjSize==2) {
3815         if (GPR_idx != Num_GPR_Regs) {
3816           unsigned VReg;
3817           if (isPPC64)
3818             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3819           else
3820             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3821           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3822           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3823           SDValue Store =
3824               DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3825                                 MachinePointerInfo(&*FuncArg), ObjType);
3826           MemOps.push_back(Store);
3827           ++GPR_idx;
3828         }
3829
3830         ArgOffset += PtrByteSize;
3831
3832         continue;
3833       }
3834       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3835         // Store whatever pieces of the object are in registers
3836         // to memory.  ArgOffset will be the address of the beginning
3837         // of the object.
3838         if (GPR_idx != Num_GPR_Regs) {
3839           unsigned VReg;
3840           if (isPPC64)
3841             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3842           else
3843             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3844           int FI = MFI.CreateFixedObject(PtrByteSize, ArgOffset, true);
3845           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3846           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3847           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3848                                        MachinePointerInfo(&*FuncArg, j));
3849           MemOps.push_back(Store);
3850           ++GPR_idx;
3851           ArgOffset += PtrByteSize;
3852         } else {
3853           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3854           break;
3855         }
3856       }
3857       continue;
3858     }
3859
3860     switch (ObjectVT.getSimpleVT().SimpleTy) {
3861     default: llvm_unreachable("Unhandled argument type!");
3862     case MVT::i1:
3863     case MVT::i32:
3864       if (!isPPC64) {
3865         if (GPR_idx != Num_GPR_Regs) {
3866           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3867           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3868
3869           if (ObjectVT == MVT::i1)
3870             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3871
3872           ++GPR_idx;
3873         } else {
3874           needsLoad = true;
3875           ArgSize = PtrByteSize;
3876         }
3877         // All int arguments reserve stack space in the Darwin ABI.
3878         ArgOffset += PtrByteSize;
3879         break;
3880       }
3881       LLVM_FALLTHROUGH;
3882     case MVT::i64:  // PPC64
3883       if (GPR_idx != Num_GPR_Regs) {
3884         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3885         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3886
3887         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3888           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3889           // value to MVT::i64 and then truncate to the correct register size.
3890           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3891
3892         ++GPR_idx;
3893       } else {
3894         needsLoad = true;
3895         ArgSize = PtrByteSize;
3896       }
3897       // All int arguments reserve stack space in the Darwin ABI.
3898       ArgOffset += 8;
3899       break;
3900
3901     case MVT::f32:
3902     case MVT::f64:
3903       // Every 4 bytes of argument space consumes one of the GPRs available for
3904       // argument passing.
3905       if (GPR_idx != Num_GPR_Regs) {
3906         ++GPR_idx;
3907         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3908           ++GPR_idx;
3909       }
3910       if (FPR_idx != Num_FPR_Regs) {
3911         unsigned VReg;
3912
3913         if (ObjectVT == MVT::f32)
3914           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3915         else
3916           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3917
3918         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3919         ++FPR_idx;
3920       } else {
3921         needsLoad = true;
3922       }
3923
3924       // All FP arguments reserve stack space in the Darwin ABI.
3925       ArgOffset += isPPC64 ? 8 : ObjSize;
3926       break;
3927     case MVT::v4f32:
3928     case MVT::v4i32:
3929     case MVT::v8i16:
3930     case MVT::v16i8:
3931       // Note that vector arguments in registers don't reserve stack space,
3932       // except in varargs functions.
3933       if (VR_idx != Num_VR_Regs) {
3934         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3935         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3936         if (isVarArg) {
3937           while ((ArgOffset % 16) != 0) {
3938             ArgOffset += PtrByteSize;
3939             if (GPR_idx != Num_GPR_Regs)
3940               GPR_idx++;
3941           }
3942           ArgOffset += 16;
3943           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3944         }
3945         ++VR_idx;
3946       } else {
3947         if (!isVarArg && !isPPC64) {
3948           // Vectors go after all the nonvectors.
3949           CurArgOffset = VecArgOffset;
3950           VecArgOffset += 16;
3951         } else {
3952           // Vectors are aligned.
3953           ArgOffset = ((ArgOffset+15)/16)*16;
3954           CurArgOffset = ArgOffset;
3955           ArgOffset += 16;
3956         }
3957         needsLoad = true;
3958       }
3959       break;
3960     }
3961
3962     // We need to load the argument to a virtual register if we determined above
3963     // that we ran out of physical registers of the appropriate type.
3964     if (needsLoad) {
3965       int FI = MFI.CreateFixedObject(ObjSize,
3966                                      CurArgOffset + (ArgSize - ObjSize),
3967                                      isImmutable);
3968       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3969       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo());
3970     }
3971
3972     InVals.push_back(ArgVal);
3973   }
3974
3975   // Allow for Altivec parameters at the end, if needed.
3976   if (nAltivecParamsAtEnd) {
3977     MinReservedArea = ((MinReservedArea+15)/16)*16;
3978     MinReservedArea += 16*nAltivecParamsAtEnd;
3979   }
3980
3981   // Area that is at least reserved in the caller of this function.
3982   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3983
3984   // Set the size that is at least reserved in caller of this function.  Tail
3985   // call optimized functions' reserved stack space needs to be aligned so that
3986   // taking the difference between two stack areas will result in an aligned
3987   // stack.
3988   MinReservedArea =
3989       EnsureStackAlignment(Subtarget.getFrameLowering(), MinReservedArea);
3990   FuncInfo->setMinReservedArea(MinReservedArea);
3991
3992   // If the function takes variable number of arguments, make a frame index for
3993   // the start of the first vararg value... for expansion of llvm.va_start.
3994   if (isVarArg) {
3995     int Depth = ArgOffset;
3996
3997     FuncInfo->setVarArgsFrameIndex(
3998       MFI.CreateFixedObject(PtrVT.getSizeInBits()/8,
3999                             Depth, true));
4000     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
4001
4002     // If this function is vararg, store any remaining integer argument regs
4003     // to their spots on the stack so that they may be loaded by dereferencing
4004     // the result of va_next.
4005     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
4006       unsigned VReg;
4007
4008       if (isPPC64)
4009         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
4010       else
4011         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
4012
4013       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
4014       SDValue Store =
4015           DAG.getStore(Val.getValue(1), dl, Val, FIN, MachinePointerInfo());
4016       MemOps.push_back(Store);
4017       // Increment the address by four for the next argument to store
4018       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, dl, PtrVT);
4019       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
4020     }
4021   }
4022
4023   if (!MemOps.empty())
4024     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
4025
4026   return Chain;
4027 }
4028
4029 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
4030 /// adjusted to accommodate the arguments for the tailcall.
4031 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
4032                                    unsigned ParamSize) {
4033
4034   if (!isTailCall) return 0;
4035
4036   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
4037   unsigned CallerMinReservedArea = FI->getMinReservedArea();
4038   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
4039   // Remember only if the new adjustement is bigger.
4040   if (SPDiff < FI->getTailCallSPDelta())
4041     FI->setTailCallSPDelta(SPDiff);
4042
4043   return SPDiff;
4044 }
4045
4046 static bool isFunctionGlobalAddress(SDValue Callee);
4047
4048 static bool
4049 resideInSameSection(const Function *Caller, SDValue Callee,
4050                     const TargetMachine &TM) {
4051   // If !G, Callee can be an external symbol.
4052   GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
4053   if (!G)
4054     return false;
4055
4056   const GlobalValue *GV = G->getGlobal();
4057   if (!GV->isStrongDefinitionForLinker())
4058     return false;
4059
4060   // Any explicitly-specified sections and section prefixes must also match.
4061   // Also, if we're using -ffunction-sections, then each function is always in
4062   // a different section (the same is true for COMDAT functions).
4063   if (TM.getFunctionSections() || GV->hasComdat() || Caller->hasComdat() ||
4064       GV->getSection() != Caller->getSection())
4065     return false;
4066   if (const auto *F = dyn_cast<Function>(GV)) {
4067     if (F->getSectionPrefix() != Caller->getSectionPrefix())
4068       return false;
4069   }
4070
4071   // If the callee might be interposed, then we can't assume the ultimate call
4072   // target will be in the same section. Even in cases where we can assume that
4073   // interposition won't happen, in any case where the linker might insert a
4074   // stub to allow for interposition, we must generate code as though
4075   // interposition might occur. To understand why this matters, consider a
4076   // situation where: a -> b -> c where the arrows indicate calls. b and c are
4077   // in the same section, but a is in a different module (i.e. has a different
4078   // TOC base pointer). If the linker allows for interposition between b and c,
4079   // then it will generate a stub for the call edge between b and c which will
4080   // save the TOC pointer into the designated stack slot allocated by b. If we
4081   // return true here, and therefore allow a tail call between b and c, that
4082   // stack slot won't exist and the b -> c stub will end up saving b'c TOC base
4083   // pointer into the stack slot allocated by a (where the a -> b stub saved
4084   // a's TOC base pointer). If we're not considering a tail call, but rather,
4085   // whether a nop is needed after the call instruction in b, because the linker
4086   // will insert a stub, it might complain about a missing nop if we omit it
4087   // (although many don't complain in this case).
4088   if (!TM.shouldAssumeDSOLocal(*Caller->getParent(), GV))
4089     return false;
4090
4091   return true;
4092 }
4093
4094 static bool
4095 needStackSlotPassParameters(const PPCSubtarget &Subtarget,
4096                             const SmallVectorImpl<ISD::OutputArg> &Outs) {
4097   assert(Subtarget.isSVR4ABI() && Subtarget.isPPC64());
4098
4099   const unsigned PtrByteSize = 8;
4100   const unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
4101
4102   static const MCPhysReg GPR[] = {
4103     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4104     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4105   };
4106   static const MCPhysReg VR[] = {
4107     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4108     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4109   };
4110
4111   const unsigned NumGPRs = array_lengthof(GPR);
4112   const unsigned NumFPRs = 13;
4113   const unsigned NumVRs = array_lengthof(VR);
4114   const unsigned ParamAreaSize = NumGPRs * PtrByteSize;
4115
4116   unsigned NumBytes = LinkageSize;
4117   unsigned AvailableFPRs = NumFPRs;
4118   unsigned AvailableVRs = NumVRs;
4119
4120   for (const ISD::OutputArg& Param : Outs) {
4121     if (Param.Flags.isNest()) continue;
4122
4123     if (CalculateStackSlotUsed(Param.VT, Param.ArgVT, Param.Flags,
4124                                PtrByteSize, LinkageSize, ParamAreaSize,
4125                                NumBytes, AvailableFPRs, AvailableVRs,
4126                                Subtarget.hasQPX()))
4127       return true;
4128   }
4129   return false;
4130 }
4131
4132 static bool
4133 hasSameArgumentList(const Function *CallerFn, ImmutableCallSite *CS) {
4134   if (CS->arg_size() != CallerFn->arg_size())
4135     return false;
4136
4137   ImmutableCallSite::arg_iterator CalleeArgIter = CS->arg_begin();
4138   ImmutableCallSite::arg_iterator CalleeArgEnd = CS->arg_end();
4139   Function::const_arg_iterator CallerArgIter = CallerFn->arg_begin();
4140
4141   for (; CalleeArgIter != CalleeArgEnd; ++CalleeArgIter, ++CallerArgIter) {
4142     const Value* CalleeArg = *CalleeArgIter;
4143     const Value* CallerArg = &(*CallerArgIter);
4144     if (CalleeArg == CallerArg)
4145       continue;
4146
4147     // e.g. @caller([4 x i64] %a, [4 x i64] %b) {
4148     //        tail call @callee([4 x i64] undef, [4 x i64] %b)
4149     //      }
4150     // 1st argument of callee is undef and has the same type as caller.
4151     if (CalleeArg->getType() == CallerArg->getType() &&
4152         isa<UndefValue>(CalleeArg))
4153       continue;
4154
4155     return false;
4156   }
4157
4158   return true;
4159 }
4160
4161 bool
4162 PPCTargetLowering::IsEligibleForTailCallOptimization_64SVR4(
4163                                     SDValue Callee,
4164                                     CallingConv::ID CalleeCC,
4165                                     ImmutableCallSite *CS,
4166                                     bool isVarArg,
4167                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4168                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4169                                     SelectionDAG& DAG) const {
4170   bool TailCallOpt = getTargetMachine().Options.GuaranteedTailCallOpt;
4171
4172   if (DisableSCO && !TailCallOpt) return false;
4173
4174   // Variadic argument functions are not supported.
4175   if (isVarArg) return false;
4176
4177   MachineFunction &MF = DAG.getMachineFunction();
4178   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4179
4180   // Tail or Sibling call optimization (TCO/SCO) needs callee and caller has
4181   // the same calling convention
4182   if (CallerCC != CalleeCC) return false;
4183
4184   // SCO support C calling convention
4185   if (CalleeCC != CallingConv::Fast && CalleeCC != CallingConv::C)
4186     return false;
4187
4188   // Caller contains any byval parameter is not supported.
4189   if (any_of(Ins, [](const ISD::InputArg &IA) { return IA.Flags.isByVal(); }))
4190     return false;
4191
4192   // Callee contains any byval parameter is not supported, too.
4193   // Note: This is a quick work around, because in some cases, e.g.
4194   // caller's stack size > callee's stack size, we are still able to apply
4195   // sibling call optimization. See: https://reviews.llvm.org/D23441#513574
4196   if (any_of(Outs, [](const ISD::OutputArg& OA) { return OA.Flags.isByVal(); }))
4197     return false;
4198
4199   // No TCO/SCO on indirect call because Caller have to restore its TOC
4200   if (!isFunctionGlobalAddress(Callee) &&
4201       !isa<ExternalSymbolSDNode>(Callee))
4202     return false;
4203
4204   // Check if Callee resides in the same section, because for now, PPC64 SVR4
4205   // ABI (ELFv1/ELFv2) doesn't allow tail calls to a symbol resides in another
4206   // section.
4207   // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=973977
4208   if (!resideInSameSection(MF.getFunction(), Callee, getTargetMachine()))
4209     return false;
4210
4211   // TCO allows altering callee ABI, so we don't have to check further.
4212   if (CalleeCC == CallingConv::Fast && TailCallOpt)
4213     return true;
4214
4215   if (DisableSCO) return false;
4216
4217   // If callee use the same argument list that caller is using, then we can
4218   // apply SCO on this case. If it is not, then we need to check if callee needs
4219   // stack for passing arguments.
4220   if (!hasSameArgumentList(MF.getFunction(), CS) &&
4221       needStackSlotPassParameters(Subtarget, Outs)) {
4222     return false;
4223   }
4224
4225   return true;
4226 }
4227
4228 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
4229 /// for tail call optimization. Targets which want to do tail call
4230 /// optimization should implement this function.
4231 bool
4232 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
4233                                                      CallingConv::ID CalleeCC,
4234                                                      bool isVarArg,
4235                                       const SmallVectorImpl<ISD::InputArg> &Ins,
4236                                                      SelectionDAG& DAG) const {
4237   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4238     return false;
4239
4240   // Variable argument functions are not supported.
4241   if (isVarArg)
4242     return false;
4243
4244   MachineFunction &MF = DAG.getMachineFunction();
4245   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
4246   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
4247     // Functions containing by val parameters are not supported.
4248     for (unsigned i = 0; i != Ins.size(); i++) {
4249        ISD::ArgFlagsTy Flags = Ins[i].Flags;
4250        if (Flags.isByVal()) return false;
4251     }
4252
4253     // Non-PIC/GOT tail calls are supported.
4254     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
4255       return true;
4256
4257     // At the moment we can only do local tail calls (in same module, hidden
4258     // or protected) if we are generating PIC.
4259     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
4260       return G->getGlobal()->hasHiddenVisibility()
4261           || G->getGlobal()->hasProtectedVisibility();
4262   }
4263
4264   return false;
4265 }
4266
4267 /// isCallCompatibleAddress - Return the immediate to use if the specified
4268 /// 32-bit value is representable in the immediate field of a BxA instruction.
4269 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
4270   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4271   if (!C) return nullptr;
4272
4273   int Addr = C->getZExtValue();
4274   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
4275       SignExtend32<26>(Addr) != Addr)
4276     return nullptr;  // Top 6 bits have to be sext of immediate.
4277
4278   return DAG
4279       .getConstant(
4280           (int)C->getZExtValue() >> 2, SDLoc(Op),
4281           DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()))
4282       .getNode();
4283 }
4284
4285 namespace {
4286
4287 struct TailCallArgumentInfo {
4288   SDValue Arg;
4289   SDValue FrameIdxOp;
4290   int FrameIdx = 0;
4291
4292   TailCallArgumentInfo() = default;
4293 };
4294
4295 } // end anonymous namespace
4296
4297 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
4298 static void StoreTailCallArgumentsToStackSlot(
4299     SelectionDAG &DAG, SDValue Chain,
4300     const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
4301     SmallVectorImpl<SDValue> &MemOpChains, const SDLoc &dl) {
4302   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
4303     SDValue Arg = TailCallArgs[i].Arg;
4304     SDValue FIN = TailCallArgs[i].FrameIdxOp;
4305     int FI = TailCallArgs[i].FrameIdx;
4306     // Store relative to framepointer.
4307     MemOpChains.push_back(DAG.getStore(
4308         Chain, dl, Arg, FIN,
4309         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI)));
4310   }
4311 }
4312
4313 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
4314 /// the appropriate stack slot for the tail call optimized function call.
4315 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG, SDValue Chain,
4316                                              SDValue OldRetAddr, SDValue OldFP,
4317                                              int SPDiff, const SDLoc &dl) {
4318   if (SPDiff) {
4319     // Calculate the new stack slot for the return address.
4320     MachineFunction &MF = DAG.getMachineFunction();
4321     const PPCSubtarget &Subtarget = MF.getSubtarget<PPCSubtarget>();
4322     const PPCFrameLowering *FL = Subtarget.getFrameLowering();
4323     bool isPPC64 = Subtarget.isPPC64();
4324     int SlotSize = isPPC64 ? 8 : 4;
4325     int NewRetAddrLoc = SPDiff + FL->getReturnSaveOffset();
4326     int NewRetAddr = MF.getFrameInfo().CreateFixedObject(SlotSize,
4327                                                          NewRetAddrLoc, true);
4328     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4329     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
4330     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
4331                          MachinePointerInfo::getFixedStack(MF, NewRetAddr));
4332
4333     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
4334     // slot as the FP is never overwritten.
4335     if (Subtarget.isDarwinABI()) {
4336       int NewFPLoc = SPDiff + FL->getFramePointerSaveOffset();
4337       int NewFPIdx = MF.getFrameInfo().CreateFixedObject(SlotSize, NewFPLoc,
4338                                                          true);
4339       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
4340       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
4341                            MachinePointerInfo::getFixedStack(
4342                                DAG.getMachineFunction(), NewFPIdx));
4343     }
4344   }
4345   return Chain;
4346 }
4347
4348 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
4349 /// the position of the argument.
4350 static void
4351 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
4352                          SDValue Arg, int SPDiff, unsigned ArgOffset,
4353                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
4354   int Offset = ArgOffset + SPDiff;
4355   uint32_t OpSize = (Arg.getValueSizeInBits() + 7) / 8;
4356   int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
4357   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
4358   SDValue FIN = DAG.getFrameIndex(FI, VT);
4359   TailCallArgumentInfo Info;
4360   Info.Arg = Arg;
4361   Info.FrameIdxOp = FIN;
4362   Info.FrameIdx = FI;
4363   TailCallArguments.push_back(Info);
4364 }
4365
4366 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
4367 /// stack slot. Returns the chain as result and the loaded frame pointers in
4368 /// LROpOut/FPOpout. Used when tail calling.
4369 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(
4370     SelectionDAG &DAG, int SPDiff, SDValue Chain, SDValue &LROpOut,
4371     SDValue &FPOpOut, const SDLoc &dl) const {
4372   if (SPDiff) {
4373     // Load the LR and FP stack slot for later adjusting.
4374     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
4375     LROpOut = getReturnAddrFrameIndex(DAG);
4376     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo());
4377     Chain = SDValue(LROpOut.getNode(), 1);
4378
4379     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
4380     // slot as the FP is never overwritten.
4381     if (Subtarget.isDarwinABI()) {
4382       FPOpOut = getFramePointerFrameIndex(DAG);
4383       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo());
4384       Chain = SDValue(FPOpOut.getNode(), 1);
4385     }
4386   }
4387   return Chain;
4388 }
4389
4390 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
4391 /// by "Src" to address "Dst" of size "Size".  Alignment information is
4392 /// specified by the specific parameter attribute. The copy will be passed as
4393 /// a byval function parameter.
4394 /// Sometimes what we are copying is the end of a larger object, the part that
4395 /// does not fit in registers.
4396 static SDValue CreateCopyOfByValArgument(SDValue Src, SDValue Dst,
4397                                          SDValue Chain, ISD::ArgFlagsTy Flags,
4398                                          SelectionDAG &DAG, const SDLoc &dl) {
4399   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
4400   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
4401                        false, false, false, MachinePointerInfo(),
4402                        MachinePointerInfo());
4403 }
4404
4405 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
4406 /// tail calls.
4407 static void LowerMemOpCallTo(
4408     SelectionDAG &DAG, MachineFunction &MF, SDValue Chain, SDValue Arg,
4409     SDValue PtrOff, int SPDiff, unsigned ArgOffset, bool isPPC64,
4410     bool isTailCall, bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
4411     SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments, const SDLoc &dl) {
4412   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4413   if (!isTailCall) {
4414     if (isVector) {
4415       SDValue StackPtr;
4416       if (isPPC64)
4417         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4418       else
4419         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4420       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4421                            DAG.getConstant(ArgOffset, dl, PtrVT));
4422     }
4423     MemOpChains.push_back(
4424         DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
4425     // Calculate and remember argument location.
4426   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
4427                                   TailCallArguments);
4428 }
4429
4430 static void
4431 PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
4432                 const SDLoc &dl, int SPDiff, unsigned NumBytes, SDValue LROp,
4433                 SDValue FPOp,
4434                 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
4435   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
4436   // might overwrite each other in case of tail call optimization.
4437   SmallVector<SDValue, 8> MemOpChains2;
4438   // Do not flag preceding copytoreg stuff together with the following stuff.
4439   InFlag = SDValue();
4440   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
4441                                     MemOpChains2, dl);
4442   if (!MemOpChains2.empty())
4443     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
4444
4445   // Store the return address to the appropriate stack slot.
4446   Chain = EmitTailCallStoreFPAndRetAddr(DAG, Chain, LROp, FPOp, SPDiff, dl);
4447
4448   // Emit callseq_end just before tailcall node.
4449   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4450                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
4451   InFlag = Chain.getValue(1);
4452 }
4453
4454 // Is this global address that of a function that can be called by name? (as
4455 // opposed to something that must hold a descriptor for an indirect call).
4456 static bool isFunctionGlobalAddress(SDValue Callee) {
4457   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
4458     if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
4459         Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
4460       return false;
4461
4462     return G->getGlobal()->getValueType()->isFunctionTy();
4463   }
4464
4465   return false;
4466 }
4467
4468 static unsigned
4469 PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag, SDValue &Chain,
4470             SDValue CallSeqStart, const SDLoc &dl, int SPDiff, bool isTailCall,
4471             bool isPatchPoint, bool hasNest,
4472             SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
4473             SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
4474             ImmutableCallSite *CS, const PPCSubtarget &Subtarget) {
4475   bool isPPC64 = Subtarget.isPPC64();
4476   bool isSVR4ABI = Subtarget.isSVR4ABI();
4477   bool isELFv2ABI = Subtarget.isELFv2ABI();
4478
4479   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
4480   NodeTys.push_back(MVT::Other);   // Returns a chain
4481   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
4482
4483   unsigned CallOpc = PPCISD::CALL;
4484
4485   bool needIndirectCall = true;
4486   if (!isSVR4ABI || !isPPC64)
4487     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
4488       // If this is an absolute destination address, use the munged value.
4489       Callee = SDValue(Dest, 0);
4490       needIndirectCall = false;
4491     }
4492
4493   // PC-relative references to external symbols should go through $stub, unless
4494   // we're building with the leopard linker or later, which automatically
4495   // synthesizes these stubs.
4496   const TargetMachine &TM = DAG.getTarget();
4497   const Module *Mod = DAG.getMachineFunction().getFunction()->getParent();
4498   const GlobalValue *GV = nullptr;
4499   if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee))
4500     GV = G->getGlobal();
4501   bool Local = TM.shouldAssumeDSOLocal(*Mod, GV);
4502   bool UsePlt = !Local && Subtarget.isTargetELF() && !isPPC64;
4503
4504   if (isFunctionGlobalAddress(Callee)) {
4505     GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
4506     // A call to a TLS address is actually an indirect call to a
4507     // thread-specific pointer.
4508     unsigned OpFlags = 0;
4509     if (UsePlt)
4510       OpFlags = PPCII::MO_PLT;
4511
4512     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
4513     // every direct call is) turn it into a TargetGlobalAddress /
4514     // TargetExternalSymbol node so that legalize doesn't hack it.
4515     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
4516                                         Callee.getValueType(), 0, OpFlags);
4517     needIndirectCall = false;
4518   }
4519
4520   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
4521     unsigned char OpFlags = 0;
4522
4523     if (UsePlt)
4524       OpFlags = PPCII::MO_PLT;
4525
4526     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
4527                                          OpFlags);
4528     needIndirectCall = false;
4529   }
4530
4531   if (isPatchPoint) {
4532     // We'll form an invalid direct call when lowering a patchpoint; the full
4533     // sequence for an indirect call is complicated, and many of the
4534     // instructions introduced might have side effects (and, thus, can't be
4535     // removed later). The call itself will be removed as soon as the
4536     // argument/return lowering is complete, so the fact that it has the wrong
4537     // kind of operands should not really matter.
4538     needIndirectCall = false;
4539   }
4540
4541   if (needIndirectCall) {
4542     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
4543     // to do the call, we can't use PPCISD::CALL.
4544     SDValue MTCTROps[] = {Chain, Callee, InFlag};
4545
4546     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
4547       // Function pointers in the 64-bit SVR4 ABI do not point to the function
4548       // entry point, but to the function descriptor (the function entry point
4549       // address is part of the function descriptor though).
4550       // The function descriptor is a three doubleword structure with the
4551       // following fields: function entry point, TOC base address and
4552       // environment pointer.
4553       // Thus for a call through a function pointer, the following actions need
4554       // to be performed:
4555       //   1. Save the TOC of the caller in the TOC save area of its stack
4556       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
4557       //   2. Load the address of the function entry point from the function
4558       //      descriptor.
4559       //   3. Load the TOC of the callee from the function descriptor into r2.
4560       //   4. Load the environment pointer from the function descriptor into
4561       //      r11.
4562       //   5. Branch to the function entry point address.
4563       //   6. On return of the callee, the TOC of the caller needs to be
4564       //      restored (this is done in FinishCall()).
4565       //
4566       // The loads are scheduled at the beginning of the call sequence, and the
4567       // register copies are flagged together to ensure that no other
4568       // operations can be scheduled in between. E.g. without flagging the
4569       // copies together, a TOC access in the caller could be scheduled between
4570       // the assignment of the callee TOC and the branch to the callee, which
4571       // results in the TOC access going through the TOC of the callee instead
4572       // of going through the TOC of the caller, which leads to incorrect code.
4573
4574       // Load the address of the function entry point from the function
4575       // descriptor.
4576       SDValue LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-1);
4577       if (LDChain.getValueType() == MVT::Glue)
4578         LDChain = CallSeqStart.getValue(CallSeqStart->getNumValues()-2);
4579
4580       auto MMOFlags = Subtarget.hasInvariantFunctionDescriptors()
4581                           ? (MachineMemOperand::MODereferenceable |
4582                              MachineMemOperand::MOInvariant)
4583                           : MachineMemOperand::MONone;
4584
4585       MachinePointerInfo MPI(CS ? CS->getCalledValue() : nullptr);
4586       SDValue LoadFuncPtr = DAG.getLoad(MVT::i64, dl, LDChain, Callee, MPI,
4587                                         /* Alignment = */ 8, MMOFlags);
4588
4589       // Load environment pointer into r11.
4590       SDValue PtrOff = DAG.getIntPtrConstant(16, dl);
4591       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
4592       SDValue LoadEnvPtr =
4593           DAG.getLoad(MVT::i64, dl, LDChain, AddPtr, MPI.getWithOffset(16),
4594                       /* Alignment = */ 8, MMOFlags);
4595
4596       SDValue TOCOff = DAG.getIntPtrConstant(8, dl);
4597       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
4598       SDValue TOCPtr =
4599           DAG.getLoad(MVT::i64, dl, LDChain, AddTOC, MPI.getWithOffset(8),
4600                       /* Alignment = */ 8, MMOFlags);
4601
4602       setUsesTOCBasePtr(DAG);
4603       SDValue TOCVal = DAG.getCopyToReg(Chain, dl, PPC::X2, TOCPtr,
4604                                         InFlag);
4605       Chain = TOCVal.getValue(0);
4606       InFlag = TOCVal.getValue(1);
4607
4608       // If the function call has an explicit 'nest' parameter, it takes the
4609       // place of the environment pointer.
4610       if (!hasNest) {
4611         SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
4612                                           InFlag);
4613
4614         Chain = EnvVal.getValue(0);
4615         InFlag = EnvVal.getValue(1);
4616       }
4617
4618       MTCTROps[0] = Chain;
4619       MTCTROps[1] = LoadFuncPtr;
4620       MTCTROps[2] = InFlag;
4621     }
4622
4623     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
4624                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
4625     InFlag = Chain.getValue(1);
4626
4627     NodeTys.clear();
4628     NodeTys.push_back(MVT::Other);
4629     NodeTys.push_back(MVT::Glue);
4630     Ops.push_back(Chain);
4631     CallOpc = PPCISD::BCTRL;
4632     Callee.setNode(nullptr);
4633     // Add use of X11 (holding environment pointer)
4634     if (isSVR4ABI && isPPC64 && !isELFv2ABI && !hasNest)
4635       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
4636     // Add CTR register as callee so a bctr can be emitted later.
4637     if (isTailCall)
4638       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
4639   }
4640
4641   // If this is a direct call, pass the chain and the callee.
4642   if (Callee.getNode()) {
4643     Ops.push_back(Chain);
4644     Ops.push_back(Callee);
4645   }
4646   // If this is a tail call add stack pointer delta.
4647   if (isTailCall)
4648     Ops.push_back(DAG.getConstant(SPDiff, dl, MVT::i32));
4649
4650   // Add argument registers to the end of the list so that they are known live
4651   // into the call.
4652   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
4653     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
4654                                   RegsToPass[i].second.getValueType()));
4655
4656   // All calls, in both the ELF V1 and V2 ABIs, need the TOC register live
4657   // into the call.
4658   if (isSVR4ABI && isPPC64 && !isPatchPoint) {
4659     setUsesTOCBasePtr(DAG);
4660     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
4661   }
4662
4663   return CallOpc;
4664 }
4665
4666 SDValue PPCTargetLowering::LowerCallResult(
4667     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
4668     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4669     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
4670   SmallVector<CCValAssign, 16> RVLocs;
4671   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
4672                     *DAG.getContext());
4673   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
4674
4675   // Copy all of the result registers out of their specified physreg.
4676   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
4677     CCValAssign &VA = RVLocs[i];
4678     assert(VA.isRegLoc() && "Can only return in registers!");
4679
4680     SDValue Val = DAG.getCopyFromReg(Chain, dl,
4681                                      VA.getLocReg(), VA.getLocVT(), InFlag);
4682     Chain = Val.getValue(1);
4683     InFlag = Val.getValue(2);
4684
4685     switch (VA.getLocInfo()) {
4686     default: llvm_unreachable("Unknown loc info!");
4687     case CCValAssign::Full: break;
4688     case CCValAssign::AExt:
4689       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4690       break;
4691     case CCValAssign::ZExt:
4692       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
4693                         DAG.getValueType(VA.getValVT()));
4694       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4695       break;
4696     case CCValAssign::SExt:
4697       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
4698                         DAG.getValueType(VA.getValVT()));
4699       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
4700       break;
4701     }
4702
4703     InVals.push_back(Val);
4704   }
4705
4706   return Chain;
4707 }
4708
4709 SDValue PPCTargetLowering::FinishCall(
4710     CallingConv::ID CallConv, const SDLoc &dl, bool isTailCall, bool isVarArg,
4711     bool isPatchPoint, bool hasNest, SelectionDAG &DAG,
4712     SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass, SDValue InFlag,
4713     SDValue Chain, SDValue CallSeqStart, SDValue &Callee, int SPDiff,
4714     unsigned NumBytes, const SmallVectorImpl<ISD::InputArg> &Ins,
4715     SmallVectorImpl<SDValue> &InVals, ImmutableCallSite *CS) const {
4716   std::vector<EVT> NodeTys;
4717   SmallVector<SDValue, 8> Ops;
4718   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, CallSeqStart, dl,
4719                                  SPDiff, isTailCall, isPatchPoint, hasNest,
4720                                  RegsToPass, Ops, NodeTys, CS, Subtarget);
4721
4722   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
4723   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
4724     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
4725
4726   // When performing tail call optimization the callee pops its arguments off
4727   // the stack. Account for this here so these bytes can be pushed back on in
4728   // PPCFrameLowering::eliminateCallFramePseudoInstr.
4729   int BytesCalleePops =
4730     (CallConv == CallingConv::Fast &&
4731      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
4732
4733   // Add a register mask operand representing the call-preserved registers.
4734   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
4735   const uint32_t *Mask =
4736       TRI->getCallPreservedMask(DAG.getMachineFunction(), CallConv);
4737   assert(Mask && "Missing call preserved mask for calling convention");
4738   Ops.push_back(DAG.getRegisterMask(Mask));
4739
4740   if (InFlag.getNode())
4741     Ops.push_back(InFlag);
4742
4743   // Emit tail call.
4744   if (isTailCall) {
4745     assert(((Callee.getOpcode() == ISD::Register &&
4746              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
4747             Callee.getOpcode() == ISD::TargetExternalSymbol ||
4748             Callee.getOpcode() == ISD::TargetGlobalAddress ||
4749             isa<ConstantSDNode>(Callee)) &&
4750     "Expecting an global address, external symbol, absolute value or register");
4751
4752     DAG.getMachineFunction().getFrameInfo().setHasTailCall();
4753     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
4754   }
4755
4756   // Add a NOP immediately after the branch instruction when using the 64-bit
4757   // SVR4 ABI. At link time, if caller and callee are in a different module and
4758   // thus have a different TOC, the call will be replaced with a call to a stub
4759   // function which saves the current TOC, loads the TOC of the callee and
4760   // branches to the callee. The NOP will be replaced with a load instruction
4761   // which restores the TOC of the caller from the TOC save slot of the current
4762   // stack frame. If caller and callee belong to the same module (and have the
4763   // same TOC), the NOP will remain unchanged.
4764
4765   MachineFunction &MF = DAG.getMachineFunction();
4766   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64() &&
4767       !isPatchPoint) {
4768     if (CallOpc == PPCISD::BCTRL) {
4769       // This is a call through a function pointer.
4770       // Restore the caller TOC from the save area into R2.
4771       // See PrepareCall() for more information about calls through function
4772       // pointers in the 64-bit SVR4 ABI.
4773       // We are using a target-specific load with r2 hard coded, because the
4774       // result of a target-independent load would never go directly into r2,
4775       // since r2 is a reserved register (which prevents the register allocator
4776       // from allocating it), resulting in an additional register being
4777       // allocated and an unnecessary move instruction being generated.
4778       CallOpc = PPCISD::BCTRL_LOAD_TOC;
4779
4780       EVT PtrVT = getPointerTy(DAG.getDataLayout());
4781       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
4782       unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
4783       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
4784       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
4785
4786       // The address needs to go after the chain input but before the flag (or
4787       // any other variadic arguments).
4788       Ops.insert(std::next(Ops.begin()), AddTOC);
4789     } else if (CallOpc == PPCISD::CALL &&
4790       !resideInSameSection(MF.getFunction(), Callee, DAG.getTarget())) {
4791       // Otherwise insert NOP for non-local calls.
4792       CallOpc = PPCISD::CALL_NOP;
4793     }
4794   }
4795
4796   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
4797   InFlag = Chain.getValue(1);
4798
4799   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
4800                              DAG.getIntPtrConstant(BytesCalleePops, dl, true),
4801                              InFlag, dl);
4802   if (!Ins.empty())
4803     InFlag = Chain.getValue(1);
4804
4805   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
4806                          Ins, dl, DAG, InVals);
4807 }
4808
4809 SDValue
4810 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
4811                              SmallVectorImpl<SDValue> &InVals) const {
4812   SelectionDAG &DAG                     = CLI.DAG;
4813   SDLoc &dl                             = CLI.DL;
4814   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
4815   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
4816   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
4817   SDValue Chain                         = CLI.Chain;
4818   SDValue Callee                        = CLI.Callee;
4819   bool &isTailCall                      = CLI.IsTailCall;
4820   CallingConv::ID CallConv              = CLI.CallConv;
4821   bool isVarArg                         = CLI.IsVarArg;
4822   bool isPatchPoint                     = CLI.IsPatchPoint;
4823   ImmutableCallSite *CS                 = CLI.CS;
4824
4825   if (isTailCall) {
4826     if (Subtarget.useLongCalls() && !(CS && CS->isMustTailCall()))
4827       isTailCall = false;
4828     else if (Subtarget.isSVR4ABI() && Subtarget.isPPC64())
4829       isTailCall =
4830         IsEligibleForTailCallOptimization_64SVR4(Callee, CallConv, CS,
4831                                                  isVarArg, Outs, Ins, DAG);
4832     else
4833       isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
4834                                                      Ins, DAG);
4835     if (isTailCall) {
4836       ++NumTailCalls;
4837       if (!getTargetMachine().Options.GuaranteedTailCallOpt)
4838         ++NumSiblingCalls;
4839
4840       assert(isa<GlobalAddressSDNode>(Callee) &&
4841              "Callee should be an llvm::Function object.");
4842       DEBUG(
4843         const GlobalValue *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
4844         const unsigned Width = 80 - strlen("TCO caller: ")
4845                                   - strlen(", callee linkage: 0, 0");
4846         dbgs() << "TCO caller: "
4847                << left_justify(DAG.getMachineFunction().getName(), Width)
4848                << ", callee linkage: "
4849                << GV->getVisibility() << ", " << GV->getLinkage() << "\n"
4850       );
4851     }
4852   }
4853
4854   if (!isTailCall && CS && CS->isMustTailCall())
4855     report_fatal_error("failed to perform tail call elimination on a call "
4856                        "site marked musttail");
4857
4858   // When long calls (i.e. indirect calls) are always used, calls are always
4859   // made via function pointer. If we have a function name, first translate it
4860   // into a pointer.
4861   if (Subtarget.useLongCalls() && isa<GlobalAddressSDNode>(Callee) &&
4862       !isTailCall)
4863     Callee = LowerGlobalAddress(Callee, DAG);
4864
4865   if (Subtarget.isSVR4ABI()) {
4866     if (Subtarget.isPPC64())
4867       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
4868                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4869                               dl, DAG, InVals, CS);
4870     else
4871       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
4872                               isTailCall, isPatchPoint, Outs, OutVals, Ins,
4873                               dl, DAG, InVals, CS);
4874   }
4875
4876   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
4877                           isTailCall, isPatchPoint, Outs, OutVals, Ins,
4878                           dl, DAG, InVals, CS);
4879 }
4880
4881 SDValue PPCTargetLowering::LowerCall_32SVR4(
4882     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
4883     bool isTailCall, bool isPatchPoint,
4884     const SmallVectorImpl<ISD::OutputArg> &Outs,
4885     const SmallVectorImpl<SDValue> &OutVals,
4886     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
4887     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
4888     ImmutableCallSite *CS) const {
4889   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4890   // of the 32-bit SVR4 ABI stack frame layout.
4891
4892   assert((CallConv == CallingConv::C ||
4893           CallConv == CallingConv::Fast) && "Unknown calling convention!");
4894
4895   unsigned PtrByteSize = 4;
4896
4897   MachineFunction &MF = DAG.getMachineFunction();
4898
4899   // Mark this function as potentially containing a function that contains a
4900   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4901   // and restoring the callers stack pointer in this functions epilog. This is
4902   // done because by tail calling the called function might overwrite the value
4903   // in this function's (MF) stack pointer stack slot 0(SP).
4904   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4905       CallConv == CallingConv::Fast)
4906     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4907
4908   // Count how many bytes are to be pushed on the stack, including the linkage
4909   // area, parameter list area and the part of the local variable space which
4910   // contains copies of aggregates which are passed by value.
4911
4912   // Assign locations to all of the outgoing arguments.
4913   SmallVector<CCValAssign, 16> ArgLocs;
4914   PPCCCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
4915
4916   // Reserve space for the linkage area on the stack.
4917   CCInfo.AllocateStack(Subtarget.getFrameLowering()->getLinkageSize(),
4918                        PtrByteSize);
4919   if (useSoftFloat())
4920     CCInfo.PreAnalyzeCallOperands(Outs);
4921
4922   if (isVarArg) {
4923     // Handle fixed and variable vector arguments differently.
4924     // Fixed vector arguments go into registers as long as registers are
4925     // available. Variable vector arguments always go into memory.
4926     unsigned NumArgs = Outs.size();
4927
4928     for (unsigned i = 0; i != NumArgs; ++i) {
4929       MVT ArgVT = Outs[i].VT;
4930       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4931       bool Result;
4932
4933       if (Outs[i].IsFixed) {
4934         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4935                                CCInfo);
4936       } else {
4937         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4938                                       ArgFlags, CCInfo);
4939       }
4940
4941       if (Result) {
4942 #ifndef NDEBUG
4943         errs() << "Call operand #" << i << " has unhandled type "
4944              << EVT(ArgVT).getEVTString() << "\n";
4945 #endif
4946         llvm_unreachable(nullptr);
4947       }
4948     }
4949   } else {
4950     // All arguments are treated the same.
4951     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4952   }
4953   CCInfo.clearWasPPCF128();
4954
4955   // Assign locations to all of the outgoing aggregate by value arguments.
4956   SmallVector<CCValAssign, 16> ByValArgLocs;
4957   CCState CCByValInfo(CallConv, isVarArg, MF, ByValArgLocs, *DAG.getContext());
4958
4959   // Reserve stack space for the allocations in CCInfo.
4960   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4961
4962   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4963
4964   // Size of the linkage area, parameter list area and the part of the local
4965   // space variable where copies of aggregates which are passed by value are
4966   // stored.
4967   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4968
4969   // Calculate by how many bytes the stack has to be adjusted in case of tail
4970   // call optimization.
4971   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4972
4973   // Adjust the stack pointer for the new arguments...
4974   // These operations are automatically eliminated by the prolog/epilog pass
4975   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
4976   SDValue CallSeqStart = Chain;
4977
4978   // Load the return address and frame pointer so it can be moved somewhere else
4979   // later.
4980   SDValue LROp, FPOp;
4981   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
4982
4983   // Set up a copy of the stack pointer for use loading and storing any
4984   // arguments that may not fit in the registers available for argument
4985   // passing.
4986   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4987
4988   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4989   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4990   SmallVector<SDValue, 8> MemOpChains;
4991
4992   bool seenFloatArg = false;
4993   // Walk the register/memloc assignments, inserting copies/loads.
4994   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4995        i != e;
4996        ++i) {
4997     CCValAssign &VA = ArgLocs[i];
4998     SDValue Arg = OutVals[i];
4999     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5000
5001     if (Flags.isByVal()) {
5002       // Argument is an aggregate which is passed by value, thus we need to
5003       // create a copy of it in the local variable space of the current stack
5004       // frame (which is the stack frame of the caller) and pass the address of
5005       // this copy to the callee.
5006       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
5007       CCValAssign &ByValVA = ByValArgLocs[j++];
5008       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
5009
5010       // Memory reserved in the local variable space of the callers stack frame.
5011       unsigned LocMemOffset = ByValVA.getLocMemOffset();
5012
5013       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5014       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5015                            StackPtr, PtrOff);
5016
5017       // Create a copy of the argument in the local area of the current
5018       // stack frame.
5019       SDValue MemcpyCall =
5020         CreateCopyOfByValArgument(Arg, PtrOff,
5021                                   CallSeqStart.getNode()->getOperand(0),
5022                                   Flags, DAG, dl);
5023
5024       // This must go outside the CALLSEQ_START..END.
5025       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, NumBytes, 0,
5026                                                      SDLoc(MemcpyCall));
5027       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5028                              NewCallSeqStart.getNode());
5029       Chain = CallSeqStart = NewCallSeqStart;
5030
5031       // Pass the address of the aggregate copy on the stack either in a
5032       // physical register or in the parameter list area of the current stack
5033       // frame to the callee.
5034       Arg = PtrOff;
5035     }
5036
5037     if (VA.isRegLoc()) {
5038       if (Arg.getValueType() == MVT::i1)
5039         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
5040
5041       seenFloatArg |= VA.getLocVT().isFloatingPoint();
5042       // Put argument in a physical register.
5043       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
5044     } else {
5045       // Put argument in the parameter list area of the current stack frame.
5046       assert(VA.isMemLoc());
5047       unsigned LocMemOffset = VA.getLocMemOffset();
5048
5049       if (!isTailCall) {
5050         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
5051         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(MF.getDataLayout()),
5052                              StackPtr, PtrOff);
5053
5054         MemOpChains.push_back(
5055             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo()));
5056       } else {
5057         // Calculate and remember argument location.
5058         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
5059                                  TailCallArguments);
5060       }
5061     }
5062   }
5063
5064   if (!MemOpChains.empty())
5065     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5066
5067   // Build a sequence of copy-to-reg nodes chained together with token chain
5068   // and flag operands which copy the outgoing args into the appropriate regs.
5069   SDValue InFlag;
5070   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5071     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5072                              RegsToPass[i].second, InFlag);
5073     InFlag = Chain.getValue(1);
5074   }
5075
5076   // Set CR bit 6 to true if this is a vararg call with floating args passed in
5077   // registers.
5078   if (isVarArg) {
5079     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
5080     SDValue Ops[] = { Chain, InFlag };
5081
5082     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
5083                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
5084
5085     InFlag = Chain.getValue(1);
5086   }
5087
5088   if (isTailCall)
5089     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5090                     TailCallArguments);
5091
5092   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
5093                     /* unused except on PPC64 ELFv1 */ false, DAG,
5094                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
5095                     NumBytes, Ins, InVals, CS);
5096 }
5097
5098 // Copy an argument into memory, being careful to do this outside the
5099 // call sequence for the call to which the argument belongs.
5100 SDValue PPCTargetLowering::createMemcpyOutsideCallSeq(
5101     SDValue Arg, SDValue PtrOff, SDValue CallSeqStart, ISD::ArgFlagsTy Flags,
5102     SelectionDAG &DAG, const SDLoc &dl) const {
5103   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
5104                         CallSeqStart.getNode()->getOperand(0),
5105                         Flags, DAG, dl);
5106   // The MEMCPY must go outside the CALLSEQ_START..END.
5107   int64_t FrameSize = CallSeqStart.getConstantOperandVal(1);
5108   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall, FrameSize, 0,
5109                                                  SDLoc(MemcpyCall));
5110   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
5111                          NewCallSeqStart.getNode());
5112   return NewCallSeqStart;
5113 }
5114
5115 SDValue PPCTargetLowering::LowerCall_64SVR4(
5116     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5117     bool isTailCall, bool isPatchPoint,
5118     const SmallVectorImpl<ISD::OutputArg> &Outs,
5119     const SmallVectorImpl<SDValue> &OutVals,
5120     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5121     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5122     ImmutableCallSite *CS) const {
5123   bool isELFv2ABI = Subtarget.isELFv2ABI();
5124   bool isLittleEndian = Subtarget.isLittleEndian();
5125   unsigned NumOps = Outs.size();
5126   bool hasNest = false;
5127   bool IsSibCall = false;
5128
5129   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5130   unsigned PtrByteSize = 8;
5131
5132   MachineFunction &MF = DAG.getMachineFunction();
5133
5134   if (isTailCall && !getTargetMachine().Options.GuaranteedTailCallOpt)
5135     IsSibCall = true;
5136
5137   // Mark this function as potentially containing a function that contains a
5138   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5139   // and restoring the callers stack pointer in this functions epilog. This is
5140   // done because by tail calling the called function might overwrite the value
5141   // in this function's (MF) stack pointer stack slot 0(SP).
5142   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5143       CallConv == CallingConv::Fast)
5144     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5145
5146   assert(!(CallConv == CallingConv::Fast && isVarArg) &&
5147          "fastcc not supported on varargs functions");
5148
5149   // Count how many bytes are to be pushed on the stack, including the linkage
5150   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
5151   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
5152   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
5153   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5154   unsigned NumBytes = LinkageSize;
5155   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5156   unsigned &QFPR_idx = FPR_idx;
5157
5158   static const MCPhysReg GPR[] = {
5159     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5160     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5161   };
5162   static const MCPhysReg VR[] = {
5163     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5164     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5165   };
5166
5167   const unsigned NumGPRs = array_lengthof(GPR);
5168   const unsigned NumFPRs = useSoftFloat() ? 0 : 13;
5169   const unsigned NumVRs  = array_lengthof(VR);
5170   const unsigned NumQFPRs = NumFPRs;
5171
5172   // On ELFv2, we can avoid allocating the parameter area if all the arguments
5173   // can be passed to the callee in registers.
5174   // For the fast calling convention, there is another check below.
5175   // Note: We should keep consistent with LowerFormalArguments_64SVR4()
5176   bool HasParameterArea = !isELFv2ABI || isVarArg || CallConv == CallingConv::Fast;
5177   if (!HasParameterArea) {
5178     unsigned ParamAreaSize = NumGPRs * PtrByteSize;
5179     unsigned AvailableFPRs = NumFPRs;
5180     unsigned AvailableVRs = NumVRs;
5181     unsigned NumBytesTmp = NumBytes;
5182     for (unsigned i = 0; i != NumOps; ++i) {
5183       if (Outs[i].Flags.isNest()) continue;
5184       if (CalculateStackSlotUsed(Outs[i].VT, Outs[i].ArgVT, Outs[i].Flags,
5185                                 PtrByteSize, LinkageSize, ParamAreaSize,
5186                                 NumBytesTmp, AvailableFPRs, AvailableVRs,
5187                                 Subtarget.hasQPX()))
5188         HasParameterArea = true;
5189     }
5190   }
5191
5192   // When using the fast calling convention, we don't provide backing for
5193   // arguments that will be in registers.
5194   unsigned NumGPRsUsed = 0, NumFPRsUsed = 0, NumVRsUsed = 0;
5195
5196   // Add up all the space actually used.
5197   for (unsigned i = 0; i != NumOps; ++i) {
5198     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5199     EVT ArgVT = Outs[i].VT;
5200     EVT OrigVT = Outs[i].ArgVT;
5201
5202     if (Flags.isNest())
5203       continue;
5204
5205     if (CallConv == CallingConv::Fast) {
5206       if (Flags.isByVal())
5207         NumGPRsUsed += (Flags.getByValSize()+7)/8;
5208       else
5209         switch (ArgVT.getSimpleVT().SimpleTy) {
5210         default: llvm_unreachable("Unexpected ValueType for argument!");
5211         case MVT::i1:
5212         case MVT::i32:
5213         case MVT::i64:
5214           if (++NumGPRsUsed <= NumGPRs)
5215             continue;
5216           break;
5217         case MVT::v4i32:
5218         case MVT::v8i16:
5219         case MVT::v16i8:
5220         case MVT::v2f64:
5221         case MVT::v2i64:
5222         case MVT::v1i128:
5223           if (++NumVRsUsed <= NumVRs)
5224             continue;
5225           break;
5226         case MVT::v4f32:
5227           // When using QPX, this is handled like a FP register, otherwise, it
5228           // is an Altivec register.
5229           if (Subtarget.hasQPX()) {
5230             if (++NumFPRsUsed <= NumFPRs)
5231               continue;
5232           } else {
5233             if (++NumVRsUsed <= NumVRs)
5234               continue;
5235           }
5236           break;
5237         case MVT::f32:
5238         case MVT::f64:
5239         case MVT::v4f64: // QPX
5240         case MVT::v4i1:  // QPX
5241           if (++NumFPRsUsed <= NumFPRs)
5242             continue;
5243           break;
5244         }
5245     }
5246
5247     /* Respect alignment of argument on the stack.  */
5248     unsigned Align =
5249       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5250     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
5251
5252     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5253     if (Flags.isInConsecutiveRegsLast())
5254       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5255   }
5256
5257   unsigned NumBytesActuallyUsed = NumBytes;
5258
5259   // In the old ELFv1 ABI,
5260   // the prolog code of the callee may store up to 8 GPR argument registers to
5261   // the stack, allowing va_start to index over them in memory if its varargs.
5262   // Because we cannot tell if this is needed on the caller side, we have to
5263   // conservatively assume that it is needed.  As such, make sure we have at
5264   // least enough stack space for the caller to store the 8 GPRs.
5265   // In the ELFv2 ABI, we allocate the parameter area iff a callee
5266   // really requires memory operands, e.g. a vararg function.
5267   if (HasParameterArea)
5268     NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5269   else
5270     NumBytes = LinkageSize;
5271
5272   // Tail call needs the stack to be aligned.
5273   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5274       CallConv == CallingConv::Fast)
5275     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5276
5277   int SPDiff = 0;
5278
5279   // Calculate by how many bytes the stack has to be adjusted in case of tail
5280   // call optimization.
5281   if (!IsSibCall)
5282     SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5283
5284   // To protect arguments on the stack from being clobbered in a tail call,
5285   // force all the loads to happen before doing any other lowering.
5286   if (isTailCall)
5287     Chain = DAG.getStackArgumentTokenFactor(Chain);
5288
5289   // Adjust the stack pointer for the new arguments...
5290   // These operations are automatically eliminated by the prolog/epilog pass
5291   if (!IsSibCall)
5292     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5293   SDValue CallSeqStart = Chain;
5294
5295   // Load the return address and frame pointer so it can be move somewhere else
5296   // later.
5297   SDValue LROp, FPOp;
5298   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5299
5300   // Set up a copy of the stack pointer for use loading and storing any
5301   // arguments that may not fit in the registers available for argument
5302   // passing.
5303   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5304
5305   // Figure out which arguments are going to go in registers, and which in
5306   // memory.  Also, if this is a vararg function, floating point operations
5307   // must be stored to our stack, and loaded into integer regs as well, if
5308   // any integer regs are available for argument passing.
5309   unsigned ArgOffset = LinkageSize;
5310
5311   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5312   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5313
5314   SmallVector<SDValue, 8> MemOpChains;
5315   for (unsigned i = 0; i != NumOps; ++i) {
5316     SDValue Arg = OutVals[i];
5317     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5318     EVT ArgVT = Outs[i].VT;
5319     EVT OrigVT = Outs[i].ArgVT;
5320
5321     // PtrOff will be used to store the current argument to the stack if a
5322     // register cannot be found for it.
5323     SDValue PtrOff;
5324
5325     // We re-align the argument offset for each argument, except when using the
5326     // fast calling convention, when we need to make sure we do that only when
5327     // we'll actually use a stack slot.
5328     auto ComputePtrOff = [&]() {
5329       /* Respect alignment of argument on the stack.  */
5330       unsigned Align =
5331         CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
5332       ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
5333
5334       PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5335
5336       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5337     };
5338
5339     if (CallConv != CallingConv::Fast) {
5340       ComputePtrOff();
5341
5342       /* Compute GPR index associated with argument offset.  */
5343       GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
5344       GPR_idx = std::min(GPR_idx, NumGPRs);
5345     }
5346
5347     // Promote integers to 64-bit values.
5348     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
5349       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5350       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5351       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5352     }
5353
5354     // FIXME memcpy is used way more than necessary.  Correctness first.
5355     // Note: "by value" is code for passing a structure by value, not
5356     // basic types.
5357     if (Flags.isByVal()) {
5358       // Note: Size includes alignment padding, so
5359       //   struct x { short a; char b; }
5360       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
5361       // These are the proper values we need for right-justifying the
5362       // aggregate in a parameter register.
5363       unsigned Size = Flags.getByValSize();
5364
5365       // An empty aggregate parameter takes up no storage and no
5366       // registers.
5367       if (Size == 0)
5368         continue;
5369
5370       if (CallConv == CallingConv::Fast)
5371         ComputePtrOff();
5372
5373       // All aggregates smaller than 8 bytes must be passed right-justified.
5374       if (Size==1 || Size==2 || Size==4) {
5375         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
5376         if (GPR_idx != NumGPRs) {
5377           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5378                                         MachinePointerInfo(), VT);
5379           MemOpChains.push_back(Load.getValue(1));
5380           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5381
5382           ArgOffset += PtrByteSize;
5383           continue;
5384         }
5385       }
5386
5387       if (GPR_idx == NumGPRs && Size < 8) {
5388         SDValue AddPtr = PtrOff;
5389         if (!isLittleEndian) {
5390           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5391                                           PtrOff.getValueType());
5392           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5393         }
5394         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5395                                                           CallSeqStart,
5396                                                           Flags, DAG, dl);
5397         ArgOffset += PtrByteSize;
5398         continue;
5399       }
5400       // Copy entire object into memory.  There are cases where gcc-generated
5401       // code assumes it is there, even if it could be put entirely into
5402       // registers.  (This is not what the doc says.)
5403
5404       // FIXME: The above statement is likely due to a misunderstanding of the
5405       // documents.  All arguments must be copied into the parameter area BY
5406       // THE CALLEE in the event that the callee takes the address of any
5407       // formal argument.  That has not yet been implemented.  However, it is
5408       // reasonable to use the stack area as a staging area for the register
5409       // load.
5410
5411       // Skip this for small aggregates, as we will use the same slot for a
5412       // right-justified copy, below.
5413       if (Size >= 8)
5414         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5415                                                           CallSeqStart,
5416                                                           Flags, DAG, dl);
5417
5418       // When a register is available, pass a small aggregate right-justified.
5419       if (Size < 8 && GPR_idx != NumGPRs) {
5420         // The easiest way to get this right-justified in a register
5421         // is to copy the structure into the rightmost portion of a
5422         // local variable slot, then load the whole slot into the
5423         // register.
5424         // FIXME: The memcpy seems to produce pretty awful code for
5425         // small aggregates, particularly for packed ones.
5426         // FIXME: It would be preferable to use the slot in the
5427         // parameter save area instead of a new local variable.
5428         SDValue AddPtr = PtrOff;
5429         if (!isLittleEndian) {
5430           SDValue Const = DAG.getConstant(8 - Size, dl, PtrOff.getValueType());
5431           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5432         }
5433         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5434                                                           CallSeqStart,
5435                                                           Flags, DAG, dl);
5436
5437         // Load the slot into the register.
5438         SDValue Load =
5439             DAG.getLoad(PtrVT, dl, Chain, PtrOff, MachinePointerInfo());
5440         MemOpChains.push_back(Load.getValue(1));
5441         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5442
5443         // Done with this argument.
5444         ArgOffset += PtrByteSize;
5445         continue;
5446       }
5447
5448       // For aggregates larger than PtrByteSize, copy the pieces of the
5449       // object that fit into registers from the parameter save area.
5450       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5451         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5452         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5453         if (GPR_idx != NumGPRs) {
5454           SDValue Load =
5455               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5456           MemOpChains.push_back(Load.getValue(1));
5457           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5458           ArgOffset += PtrByteSize;
5459         } else {
5460           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5461           break;
5462         }
5463       }
5464       continue;
5465     }
5466
5467     switch (Arg.getSimpleValueType().SimpleTy) {
5468     default: llvm_unreachable("Unexpected ValueType for argument!");
5469     case MVT::i1:
5470     case MVT::i32:
5471     case MVT::i64:
5472       if (Flags.isNest()) {
5473         // The 'nest' parameter, if any, is passed in R11.
5474         RegsToPass.push_back(std::make_pair(PPC::X11, Arg));
5475         hasNest = true;
5476         break;
5477       }
5478
5479       // These can be scalar arguments or elements of an integer array type
5480       // passed directly.  Clang may use those instead of "byval" aggregate
5481       // types to avoid forcing arguments to memory unnecessarily.
5482       if (GPR_idx != NumGPRs) {
5483         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5484       } else {
5485         if (CallConv == CallingConv::Fast)
5486           ComputePtrOff();
5487
5488         assert(HasParameterArea &&
5489                "Parameter area must exist to pass an argument in memory.");
5490         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5491                          true, isTailCall, false, MemOpChains,
5492                          TailCallArguments, dl);
5493         if (CallConv == CallingConv::Fast)
5494           ArgOffset += PtrByteSize;
5495       }
5496       if (CallConv != CallingConv::Fast)
5497         ArgOffset += PtrByteSize;
5498       break;
5499     case MVT::f32:
5500     case MVT::f64: {
5501       // These can be scalar arguments or elements of a float array type
5502       // passed directly.  The latter are used to implement ELFv2 homogenous
5503       // float aggregates.
5504
5505       // Named arguments go into FPRs first, and once they overflow, the
5506       // remaining arguments go into GPRs and then the parameter save area.
5507       // Unnamed arguments for vararg functions always go to GPRs and
5508       // then the parameter save area.  For now, put all arguments to vararg
5509       // routines always in both locations (FPR *and* GPR or stack slot).
5510       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
5511       bool NeededLoad = false;
5512
5513       // First load the argument into the next available FPR.
5514       if (FPR_idx != NumFPRs)
5515         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5516
5517       // Next, load the argument into GPR or stack slot if needed.
5518       if (!NeedGPROrStack)
5519         ;
5520       else if (GPR_idx != NumGPRs && CallConv != CallingConv::Fast) {
5521         // FIXME: We may want to re-enable this for CallingConv::Fast on the P8
5522         // once we support fp <-> gpr moves.
5523
5524         // In the non-vararg case, this can only ever happen in the
5525         // presence of f32 array types, since otherwise we never run
5526         // out of FPRs before running out of GPRs.
5527         SDValue ArgVal;
5528
5529         // Double values are always passed in a single GPR.
5530         if (Arg.getValueType() != MVT::f32) {
5531           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
5532
5533         // Non-array float values are extended and passed in a GPR.
5534         } else if (!Flags.isInConsecutiveRegs()) {
5535           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5536           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5537
5538         // If we have an array of floats, we collect every odd element
5539         // together with its predecessor into one GPR.
5540         } else if (ArgOffset % PtrByteSize != 0) {
5541           SDValue Lo, Hi;
5542           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
5543           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5544           if (!isLittleEndian)
5545             std::swap(Lo, Hi);
5546           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5547
5548         // The final element, if even, goes into the first half of a GPR.
5549         } else if (Flags.isInConsecutiveRegsLast()) {
5550           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
5551           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
5552           if (!isLittleEndian)
5553             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
5554                                  DAG.getConstant(32, dl, MVT::i32));
5555
5556         // Non-final even elements are skipped; they will be handled
5557         // together the with subsequent argument on the next go-around.
5558         } else
5559           ArgVal = SDValue();
5560
5561         if (ArgVal.getNode())
5562           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], ArgVal));
5563       } else {
5564         if (CallConv == CallingConv::Fast)
5565           ComputePtrOff();
5566
5567         // Single-precision floating-point values are mapped to the
5568         // second (rightmost) word of the stack doubleword.
5569         if (Arg.getValueType() == MVT::f32 &&
5570             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
5571           SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
5572           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
5573         }
5574
5575         assert(HasParameterArea &&
5576                "Parameter area must exist to pass an argument in memory.");
5577         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5578                          true, isTailCall, false, MemOpChains,
5579                          TailCallArguments, dl);
5580
5581         NeededLoad = true;
5582       }
5583       // When passing an array of floats, the array occupies consecutive
5584       // space in the argument area; only round up to the next doubleword
5585       // at the end of the array.  Otherwise, each float takes 8 bytes.
5586       if (CallConv != CallingConv::Fast || NeededLoad) {
5587         ArgOffset += (Arg.getValueType() == MVT::f32 &&
5588                       Flags.isInConsecutiveRegs()) ? 4 : 8;
5589         if (Flags.isInConsecutiveRegsLast())
5590           ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
5591       }
5592       break;
5593     }
5594     case MVT::v4f32:
5595     case MVT::v4i32:
5596     case MVT::v8i16:
5597     case MVT::v16i8:
5598     case MVT::v2f64:
5599     case MVT::v2i64:
5600     case MVT::v1i128:
5601       if (!Subtarget.hasQPX()) {
5602       // These can be scalar arguments or elements of a vector array type
5603       // passed directly.  The latter are used to implement ELFv2 homogenous
5604       // vector aggregates.
5605
5606       // For a varargs call, named arguments go into VRs or on the stack as
5607       // usual; unnamed arguments always go to the stack or the corresponding
5608       // GPRs when within range.  For now, we always put the value in both
5609       // locations (or even all three).
5610       if (isVarArg) {
5611         assert(HasParameterArea &&
5612                "Parameter area must exist if we have a varargs call.");
5613         // We could elide this store in the case where the object fits
5614         // entirely in R registers.  Maybe later.
5615         SDValue Store =
5616             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5617         MemOpChains.push_back(Store);
5618         if (VR_idx != NumVRs) {
5619           SDValue Load =
5620               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
5621           MemOpChains.push_back(Load.getValue(1));
5622           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5623         }
5624         ArgOffset += 16;
5625         for (unsigned i=0; i<16; i+=PtrByteSize) {
5626           if (GPR_idx == NumGPRs)
5627             break;
5628           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5629                                    DAG.getConstant(i, dl, PtrVT));
5630           SDValue Load =
5631               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5632           MemOpChains.push_back(Load.getValue(1));
5633           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5634         }
5635         break;
5636       }
5637
5638       // Non-varargs Altivec params go into VRs or on the stack.
5639       if (VR_idx != NumVRs) {
5640         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5641       } else {
5642         if (CallConv == CallingConv::Fast)
5643           ComputePtrOff();
5644
5645         assert(HasParameterArea &&
5646                "Parameter area must exist to pass an argument in memory.");
5647         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5648                          true, isTailCall, true, MemOpChains,
5649                          TailCallArguments, dl);
5650         if (CallConv == CallingConv::Fast)
5651           ArgOffset += 16;
5652       }
5653
5654       if (CallConv != CallingConv::Fast)
5655         ArgOffset += 16;
5656       break;
5657       } // not QPX
5658
5659       assert(Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32 &&
5660              "Invalid QPX parameter type");
5661
5662       /* fall through */
5663     case MVT::v4f64:
5664     case MVT::v4i1: {
5665       bool IsF32 = Arg.getValueType().getSimpleVT().SimpleTy == MVT::v4f32;
5666       if (isVarArg) {
5667         assert(HasParameterArea &&
5668                "Parameter area must exist if we have a varargs call.");
5669         // We could elide this store in the case where the object fits
5670         // entirely in R registers.  Maybe later.
5671         SDValue Store =
5672             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5673         MemOpChains.push_back(Store);
5674         if (QFPR_idx != NumQFPRs) {
5675           SDValue Load = DAG.getLoad(IsF32 ? MVT::v4f32 : MVT::v4f64, dl, Store,
5676                                      PtrOff, MachinePointerInfo());
5677           MemOpChains.push_back(Load.getValue(1));
5678           RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Load));
5679         }
5680         ArgOffset += (IsF32 ? 16 : 32);
5681         for (unsigned i = 0; i < (IsF32 ? 16U : 32U); i += PtrByteSize) {
5682           if (GPR_idx == NumGPRs)
5683             break;
5684           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5685                                    DAG.getConstant(i, dl, PtrVT));
5686           SDValue Load =
5687               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
5688           MemOpChains.push_back(Load.getValue(1));
5689           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5690         }
5691         break;
5692       }
5693
5694       // Non-varargs QPX params go into registers or on the stack.
5695       if (QFPR_idx != NumQFPRs) {
5696         RegsToPass.push_back(std::make_pair(QFPR[QFPR_idx++], Arg));
5697       } else {
5698         if (CallConv == CallingConv::Fast)
5699           ComputePtrOff();
5700
5701         assert(HasParameterArea &&
5702                "Parameter area must exist to pass an argument in memory.");
5703         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5704                          true, isTailCall, true, MemOpChains,
5705                          TailCallArguments, dl);
5706         if (CallConv == CallingConv::Fast)
5707           ArgOffset += (IsF32 ? 16 : 32);
5708       }
5709
5710       if (CallConv != CallingConv::Fast)
5711         ArgOffset += (IsF32 ? 16 : 32);
5712       break;
5713       }
5714     }
5715   }
5716
5717   assert((!HasParameterArea || NumBytesActuallyUsed == ArgOffset) &&
5718          "mismatch in size of parameter area");
5719   (void)NumBytesActuallyUsed;
5720
5721   if (!MemOpChains.empty())
5722     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5723
5724   // Check if this is an indirect call (MTCTR/BCTRL).
5725   // See PrepareCall() for more information about calls through function
5726   // pointers in the 64-bit SVR4 ABI.
5727   if (!isTailCall && !isPatchPoint &&
5728       !isFunctionGlobalAddress(Callee) &&
5729       !isa<ExternalSymbolSDNode>(Callee)) {
5730     // Load r2 into a virtual register and store it to the TOC save area.
5731     setUsesTOCBasePtr(DAG);
5732     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
5733     // TOC save area offset.
5734     unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset();
5735     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset, dl);
5736     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5737     Chain = DAG.getStore(
5738         Val.getValue(1), dl, Val, AddPtr,
5739         MachinePointerInfo::getStack(DAG.getMachineFunction(), TOCSaveOffset));
5740     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
5741     // This does not mean the MTCTR instruction must use R12; it's easier
5742     // to model this as an extra parameter, so do that.
5743     if (isELFv2ABI && !isPatchPoint)
5744       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
5745   }
5746
5747   // Build a sequence of copy-to-reg nodes chained together with token chain
5748   // and flag operands which copy the outgoing args into the appropriate regs.
5749   SDValue InFlag;
5750   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5751     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5752                              RegsToPass[i].second, InFlag);
5753     InFlag = Chain.getValue(1);
5754   }
5755
5756   if (isTailCall && !IsSibCall)
5757     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
5758                     TailCallArguments);
5759
5760   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint, hasNest,
5761                     DAG, RegsToPass, InFlag, Chain, CallSeqStart, Callee,
5762                     SPDiff, NumBytes, Ins, InVals, CS);
5763 }
5764
5765 SDValue PPCTargetLowering::LowerCall_Darwin(
5766     SDValue Chain, SDValue Callee, CallingConv::ID CallConv, bool isVarArg,
5767     bool isTailCall, bool isPatchPoint,
5768     const SmallVectorImpl<ISD::OutputArg> &Outs,
5769     const SmallVectorImpl<SDValue> &OutVals,
5770     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
5771     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
5772     ImmutableCallSite *CS) const {
5773   unsigned NumOps = Outs.size();
5774
5775   EVT PtrVT = getPointerTy(DAG.getDataLayout());
5776   bool isPPC64 = PtrVT == MVT::i64;
5777   unsigned PtrByteSize = isPPC64 ? 8 : 4;
5778
5779   MachineFunction &MF = DAG.getMachineFunction();
5780
5781   // Mark this function as potentially containing a function that contains a
5782   // tail call. As a consequence the frame pointer will be used for dynamicalloc
5783   // and restoring the callers stack pointer in this functions epilog. This is
5784   // done because by tail calling the called function might overwrite the value
5785   // in this function's (MF) stack pointer stack slot 0(SP).
5786   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5787       CallConv == CallingConv::Fast)
5788     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
5789
5790   // Count how many bytes are to be pushed on the stack, including the linkage
5791   // area, and parameter passing area.  We start with 24/48 bytes, which is
5792   // prereserved space for [SP][CR][LR][3 x unused].
5793   unsigned LinkageSize = Subtarget.getFrameLowering()->getLinkageSize();
5794   unsigned NumBytes = LinkageSize;
5795
5796   // Add up all the space actually used.
5797   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
5798   // they all go in registers, but we must reserve stack space for them for
5799   // possible use by the caller.  In varargs or 64-bit calls, parameters are
5800   // assigned stack space in order, with padding so Altivec parameters are
5801   // 16-byte aligned.
5802   unsigned nAltivecParamsAtEnd = 0;
5803   for (unsigned i = 0; i != NumOps; ++i) {
5804     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5805     EVT ArgVT = Outs[i].VT;
5806     // Varargs Altivec parameters are padded to a 16 byte boundary.
5807     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
5808         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
5809         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
5810       if (!isVarArg && !isPPC64) {
5811         // Non-varargs Altivec parameters go after all the non-Altivec
5812         // parameters; handle those later so we know how much padding we need.
5813         nAltivecParamsAtEnd++;
5814         continue;
5815       }
5816       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
5817       NumBytes = ((NumBytes+15)/16)*16;
5818     }
5819     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
5820   }
5821
5822   // Allow for Altivec parameters at the end, if needed.
5823   if (nAltivecParamsAtEnd) {
5824     NumBytes = ((NumBytes+15)/16)*16;
5825     NumBytes += 16*nAltivecParamsAtEnd;
5826   }
5827
5828   // The prolog code of the callee may store up to 8 GPR argument registers to
5829   // the stack, allowing va_start to index over them in memory if its varargs.
5830   // Because we cannot tell if this is needed on the caller side, we have to
5831   // conservatively assume that it is needed.  As such, make sure we have at
5832   // least enough stack space for the caller to store the 8 GPRs.
5833   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
5834
5835   // Tail call needs the stack to be aligned.
5836   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
5837       CallConv == CallingConv::Fast)
5838     NumBytes = EnsureStackAlignment(Subtarget.getFrameLowering(), NumBytes);
5839
5840   // Calculate by how many bytes the stack has to be adjusted in case of tail
5841   // call optimization.
5842   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
5843
5844   // To protect arguments on the stack from being clobbered in a tail call,
5845   // force all the loads to happen before doing any other lowering.
5846   if (isTailCall)
5847     Chain = DAG.getStackArgumentTokenFactor(Chain);
5848
5849   // Adjust the stack pointer for the new arguments...
5850   // These operations are automatically eliminated by the prolog/epilog pass
5851   Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
5852   SDValue CallSeqStart = Chain;
5853
5854   // Load the return address and frame pointer so it can be move somewhere else
5855   // later.
5856   SDValue LROp, FPOp;
5857   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, dl);
5858
5859   // Set up a copy of the stack pointer for use loading and storing any
5860   // arguments that may not fit in the registers available for argument
5861   // passing.
5862   SDValue StackPtr;
5863   if (isPPC64)
5864     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
5865   else
5866     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
5867
5868   // Figure out which arguments are going to go in registers, and which in
5869   // memory.  Also, if this is a vararg function, floating point operations
5870   // must be stored to our stack, and loaded into integer regs as well, if
5871   // any integer regs are available for argument passing.
5872   unsigned ArgOffset = LinkageSize;
5873   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
5874
5875   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
5876     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
5877     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
5878   };
5879   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
5880     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
5881     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
5882   };
5883   static const MCPhysReg VR[] = {
5884     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
5885     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
5886   };
5887   const unsigned NumGPRs = array_lengthof(GPR_32);
5888   const unsigned NumFPRs = 13;
5889   const unsigned NumVRs  = array_lengthof(VR);
5890
5891   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
5892
5893   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
5894   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
5895
5896   SmallVector<SDValue, 8> MemOpChains;
5897   for (unsigned i = 0; i != NumOps; ++i) {
5898     SDValue Arg = OutVals[i];
5899     ISD::ArgFlagsTy Flags = Outs[i].Flags;
5900
5901     // PtrOff will be used to store the current argument to the stack if a
5902     // register cannot be found for it.
5903     SDValue PtrOff;
5904
5905     PtrOff = DAG.getConstant(ArgOffset, dl, StackPtr.getValueType());
5906
5907     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
5908
5909     // On PPC64, promote integers to 64-bit values.
5910     if (isPPC64 && Arg.getValueType() == MVT::i32) {
5911       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
5912       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
5913       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
5914     }
5915
5916     // FIXME memcpy is used way more than necessary.  Correctness first.
5917     // Note: "by value" is code for passing a structure by value, not
5918     // basic types.
5919     if (Flags.isByVal()) {
5920       unsigned Size = Flags.getByValSize();
5921       // Very small objects are passed right-justified.  Everything else is
5922       // passed left-justified.
5923       if (Size==1 || Size==2) {
5924         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
5925         if (GPR_idx != NumGPRs) {
5926           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
5927                                         MachinePointerInfo(), VT);
5928           MemOpChains.push_back(Load.getValue(1));
5929           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5930
5931           ArgOffset += PtrByteSize;
5932         } else {
5933           SDValue Const = DAG.getConstant(PtrByteSize - Size, dl,
5934                                           PtrOff.getValueType());
5935           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
5936           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
5937                                                             CallSeqStart,
5938                                                             Flags, DAG, dl);
5939           ArgOffset += PtrByteSize;
5940         }
5941         continue;
5942       }
5943       // Copy entire object into memory.  There are cases where gcc-generated
5944       // code assumes it is there, even if it could be put entirely into
5945       // registers.  (This is not what the doc says.)
5946       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
5947                                                         CallSeqStart,
5948                                                         Flags, DAG, dl);
5949
5950       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
5951       // copy the pieces of the object that fit into registers from the
5952       // parameter save area.
5953       for (unsigned j=0; j<Size; j+=PtrByteSize) {
5954         SDValue Const = DAG.getConstant(j, dl, PtrOff.getValueType());
5955         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
5956         if (GPR_idx != NumGPRs) {
5957           SDValue Load =
5958               DAG.getLoad(PtrVT, dl, Chain, AddArg, MachinePointerInfo());
5959           MemOpChains.push_back(Load.getValue(1));
5960           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5961           ArgOffset += PtrByteSize;
5962         } else {
5963           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
5964           break;
5965         }
5966       }
5967       continue;
5968     }
5969
5970     switch (Arg.getSimpleValueType().SimpleTy) {
5971     default: llvm_unreachable("Unexpected ValueType for argument!");
5972     case MVT::i1:
5973     case MVT::i32:
5974     case MVT::i64:
5975       if (GPR_idx != NumGPRs) {
5976         if (Arg.getValueType() == MVT::i1)
5977           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
5978
5979         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
5980       } else {
5981         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5982                          isPPC64, isTailCall, false, MemOpChains,
5983                          TailCallArguments, dl);
5984       }
5985       ArgOffset += PtrByteSize;
5986       break;
5987     case MVT::f32:
5988     case MVT::f64:
5989       if (FPR_idx != NumFPRs) {
5990         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
5991
5992         if (isVarArg) {
5993           SDValue Store =
5994               DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
5995           MemOpChains.push_back(Store);
5996
5997           // Float varargs are always shadowed in available integer registers
5998           if (GPR_idx != NumGPRs) {
5999             SDValue Load =
6000                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6001             MemOpChains.push_back(Load.getValue(1));
6002             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6003           }
6004           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
6005             SDValue ConstFour = DAG.getConstant(4, dl, PtrOff.getValueType());
6006             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
6007             SDValue Load =
6008                 DAG.getLoad(PtrVT, dl, Store, PtrOff, MachinePointerInfo());
6009             MemOpChains.push_back(Load.getValue(1));
6010             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6011           }
6012         } else {
6013           // If we have any FPRs remaining, we may also have GPRs remaining.
6014           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
6015           // GPRs.
6016           if (GPR_idx != NumGPRs)
6017             ++GPR_idx;
6018           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
6019               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
6020             ++GPR_idx;
6021         }
6022       } else
6023         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6024                          isPPC64, isTailCall, false, MemOpChains,
6025                          TailCallArguments, dl);
6026       if (isPPC64)
6027         ArgOffset += 8;
6028       else
6029         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
6030       break;
6031     case MVT::v4f32:
6032     case MVT::v4i32:
6033     case MVT::v8i16:
6034     case MVT::v16i8:
6035       if (isVarArg) {
6036         // These go aligned on the stack, or in the corresponding R registers
6037         // when within range.  The Darwin PPC ABI doc claims they also go in
6038         // V registers; in fact gcc does this only for arguments that are
6039         // prototyped, not for those that match the ...  We do it for all
6040         // arguments, seems to work.
6041         while (ArgOffset % 16 !=0) {
6042           ArgOffset += PtrByteSize;
6043           if (GPR_idx != NumGPRs)
6044             GPR_idx++;
6045         }
6046         // We could elide this store in the case where the object fits
6047         // entirely in R registers.  Maybe later.
6048         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
6049                              DAG.getConstant(ArgOffset, dl, PtrVT));
6050         SDValue Store =
6051             DAG.getStore(Chain, dl, Arg, PtrOff, MachinePointerInfo());
6052         MemOpChains.push_back(Store);
6053         if (VR_idx != NumVRs) {
6054           SDValue Load =
6055               DAG.getLoad(MVT::v4f32, dl, Store, PtrOff, MachinePointerInfo());
6056           MemOpChains.push_back(Load.getValue(1));
6057           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
6058         }
6059         ArgOffset += 16;
6060         for (unsigned i=0; i<16; i+=PtrByteSize) {
6061           if (GPR_idx == NumGPRs)
6062             break;
6063           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
6064                                    DAG.getConstant(i, dl, PtrVT));
6065           SDValue Load =
6066               DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo());
6067           MemOpChains.push_back(Load.getValue(1));
6068           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
6069         }
6070         break;
6071       }
6072
6073       // Non-varargs Altivec params generally go in registers, but have
6074       // stack space allocated at the end.
6075       if (VR_idx != NumVRs) {
6076         // Doesn't have GPR space allocated.
6077         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
6078       } else if (nAltivecParamsAtEnd==0) {
6079         // We are emitting Altivec params in order.
6080         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6081                          isPPC64, isTailCall, true, MemOpChains,
6082                          TailCallArguments, dl);
6083         ArgOffset += 16;
6084       }
6085       break;
6086     }
6087   }
6088   // If all Altivec parameters fit in registers, as they usually do,
6089   // they get stack space following the non-Altivec parameters.  We
6090   // don't track this here because nobody below needs it.
6091   // If there are more Altivec parameters than fit in registers emit
6092   // the stores here.
6093   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
6094     unsigned j = 0;
6095     // Offset is aligned; skip 1st 12 params which go in V registers.
6096     ArgOffset = ((ArgOffset+15)/16)*16;
6097     ArgOffset += 12*16;
6098     for (unsigned i = 0; i != NumOps; ++i) {
6099       SDValue Arg = OutVals[i];
6100       EVT ArgType = Outs[i].VT;
6101       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
6102           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
6103         if (++j > NumVRs) {
6104           SDValue PtrOff;
6105           // We are emitting Altivec params in order.
6106           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
6107                            isPPC64, isTailCall, true, MemOpChains,
6108                            TailCallArguments, dl);
6109           ArgOffset += 16;
6110         }
6111       }
6112     }
6113   }
6114
6115   if (!MemOpChains.empty())
6116     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
6117
6118   // On Darwin, R12 must contain the address of an indirect callee.  This does
6119   // not mean the MTCTR instruction must use R12; it's easier to model this as
6120   // an extra parameter, so do that.
6121   if (!isTailCall &&
6122       !isFunctionGlobalAddress(Callee) &&
6123       !isa<ExternalSymbolSDNode>(Callee) &&
6124       !isBLACompatibleAddress(Callee, DAG))
6125     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
6126                                                    PPC::R12), Callee));
6127
6128   // Build a sequence of copy-to-reg nodes chained together with token chain
6129   // and flag operands which copy the outgoing args into the appropriate regs.
6130   SDValue InFlag;
6131   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
6132     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
6133                              RegsToPass[i].second, InFlag);
6134     InFlag = Chain.getValue(1);
6135   }
6136
6137   if (isTailCall)
6138     PrepareTailCall(DAG, InFlag, Chain, dl, SPDiff, NumBytes, LROp, FPOp,
6139                     TailCallArguments);
6140
6141   return FinishCall(CallConv, dl, isTailCall, isVarArg, isPatchPoint,
6142                     /* unused except on PPC64 ELFv1 */ false, DAG,
6143                     RegsToPass, InFlag, Chain, CallSeqStart, Callee, SPDiff,
6144                     NumBytes, Ins, InVals, CS);
6145 }
6146
6147 bool
6148 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
6149                                   MachineFunction &MF, bool isVarArg,
6150                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
6151                                   LLVMContext &Context) const {
6152   SmallVector<CCValAssign, 16> RVLocs;
6153   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
6154   return CCInfo.CheckReturn(Outs, RetCC_PPC);
6155 }
6156
6157 SDValue
6158 PPCTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
6159                                bool isVarArg,
6160                                const SmallVectorImpl<ISD::OutputArg> &Outs,
6161                                const SmallVectorImpl<SDValue> &OutVals,
6162                                const SDLoc &dl, SelectionDAG &DAG) const {
6163   SmallVector<CCValAssign, 16> RVLocs;
6164   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
6165                  *DAG.getContext());
6166   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
6167
6168   SDValue Flag;
6169   SmallVector<SDValue, 4> RetOps(1, Chain);
6170
6171   // Copy the result values into the output registers.
6172   for (unsigned i = 0; i != RVLocs.size(); ++i) {
6173     CCValAssign &VA = RVLocs[i];
6174     assert(VA.isRegLoc() && "Can only return in registers!");
6175
6176     SDValue Arg = OutVals[i];
6177
6178     switch (VA.getLocInfo()) {
6179     default: llvm_unreachable("Unknown loc info!");
6180     case CCValAssign::Full: break;
6181     case CCValAssign::AExt:
6182       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
6183       break;
6184     case CCValAssign::ZExt:
6185       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
6186       break;
6187     case CCValAssign::SExt:
6188       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
6189       break;
6190     }
6191
6192     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
6193     Flag = Chain.getValue(1);
6194     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
6195   }
6196
6197   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
6198   const MCPhysReg *I =
6199     TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
6200   if (I) {
6201     for (; *I; ++I) {
6202
6203       if (PPC::G8RCRegClass.contains(*I))
6204         RetOps.push_back(DAG.getRegister(*I, MVT::i64));
6205       else if (PPC::F8RCRegClass.contains(*I))
6206         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
6207       else if (PPC::CRRCRegClass.contains(*I))
6208         RetOps.push_back(DAG.getRegister(*I, MVT::i1));
6209       else if (PPC::VRRCRegClass.contains(*I))
6210         RetOps.push_back(DAG.getRegister(*I, MVT::Other));
6211       else
6212         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
6213     }
6214   }
6215
6216   RetOps[0] = Chain;  // Update chain.
6217
6218   // Add the flag if we have it.
6219   if (Flag.getNode())
6220     RetOps.push_back(Flag);
6221
6222   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
6223 }
6224
6225 SDValue
6226 PPCTargetLowering::LowerGET_DYNAMIC_AREA_OFFSET(SDValue Op,
6227                                                 SelectionDAG &DAG) const {
6228   SDLoc dl(Op);
6229
6230   // Get the corect type for integers.
6231   EVT IntVT = Op.getValueType();
6232
6233   // Get the inputs.
6234   SDValue Chain = Op.getOperand(0);
6235   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6236   // Build a DYNAREAOFFSET node.
6237   SDValue Ops[2] = {Chain, FPSIdx};
6238   SDVTList VTs = DAG.getVTList(IntVT);
6239   return DAG.getNode(PPCISD::DYNAREAOFFSET, dl, VTs, Ops);
6240 }
6241
6242 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op,
6243                                              SelectionDAG &DAG) const {
6244   // When we pop the dynamic allocation we need to restore the SP link.
6245   SDLoc dl(Op);
6246
6247   // Get the corect type for pointers.
6248   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6249
6250   // Construct the stack pointer operand.
6251   bool isPPC64 = Subtarget.isPPC64();
6252   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
6253   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
6254
6255   // Get the operands for the STACKRESTORE.
6256   SDValue Chain = Op.getOperand(0);
6257   SDValue SaveSP = Op.getOperand(1);
6258
6259   // Load the old link SP.
6260   SDValue LoadLinkSP =
6261       DAG.getLoad(PtrVT, dl, Chain, StackPtr, MachinePointerInfo());
6262
6263   // Restore the stack pointer.
6264   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
6265
6266   // Store the old link SP.
6267   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo());
6268 }
6269
6270 SDValue PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG &DAG) const {
6271   MachineFunction &MF = DAG.getMachineFunction();
6272   bool isPPC64 = Subtarget.isPPC64();
6273   EVT PtrVT = getPointerTy(MF.getDataLayout());
6274
6275   // Get current frame pointer save index.  The users of this index will be
6276   // primarily DYNALLOC instructions.
6277   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6278   int RASI = FI->getReturnAddrSaveIndex();
6279
6280   // If the frame pointer save index hasn't been defined yet.
6281   if (!RASI) {
6282     // Find out what the fix offset of the frame pointer save area.
6283     int LROffset = Subtarget.getFrameLowering()->getReturnSaveOffset();
6284     // Allocate the frame index for frame pointer save area.
6285     RASI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
6286     // Save the result.
6287     FI->setReturnAddrSaveIndex(RASI);
6288   }
6289   return DAG.getFrameIndex(RASI, PtrVT);
6290 }
6291
6292 SDValue
6293 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
6294   MachineFunction &MF = DAG.getMachineFunction();
6295   bool isPPC64 = Subtarget.isPPC64();
6296   EVT PtrVT = getPointerTy(MF.getDataLayout());
6297
6298   // Get current frame pointer save index.  The users of this index will be
6299   // primarily DYNALLOC instructions.
6300   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
6301   int FPSI = FI->getFramePointerSaveIndex();
6302
6303   // If the frame pointer save index hasn't been defined yet.
6304   if (!FPSI) {
6305     // Find out what the fix offset of the frame pointer save area.
6306     int FPOffset = Subtarget.getFrameLowering()->getFramePointerSaveOffset();
6307     // Allocate the frame index for frame pointer save area.
6308     FPSI = MF.getFrameInfo().CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
6309     // Save the result.
6310     FI->setFramePointerSaveIndex(FPSI);
6311   }
6312   return DAG.getFrameIndex(FPSI, PtrVT);
6313 }
6314
6315 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6316                                                    SelectionDAG &DAG) const {
6317   // Get the inputs.
6318   SDValue Chain = Op.getOperand(0);
6319   SDValue Size  = Op.getOperand(1);
6320   SDLoc dl(Op);
6321
6322   // Get the corect type for pointers.
6323   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6324   // Negate the size.
6325   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
6326                                 DAG.getConstant(0, dl, PtrVT), Size);
6327   // Construct a node for the frame pointer save index.
6328   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
6329   // Build a DYNALLOC node.
6330   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
6331   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
6332   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
6333 }
6334
6335 SDValue PPCTargetLowering::LowerEH_DWARF_CFA(SDValue Op,
6336                                                      SelectionDAG &DAG) const {
6337   MachineFunction &MF = DAG.getMachineFunction();
6338
6339   bool isPPC64 = Subtarget.isPPC64();
6340   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6341
6342   int FI = MF.getFrameInfo().CreateFixedObject(isPPC64 ? 8 : 4, 0, false);
6343   return DAG.getFrameIndex(FI, PtrVT);
6344 }
6345
6346 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
6347                                                SelectionDAG &DAG) const {
6348   SDLoc DL(Op);
6349   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
6350                      DAG.getVTList(MVT::i32, MVT::Other),
6351                      Op.getOperand(0), Op.getOperand(1));
6352 }
6353
6354 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
6355                                                 SelectionDAG &DAG) const {
6356   SDLoc DL(Op);
6357   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
6358                      Op.getOperand(0), Op.getOperand(1));
6359 }
6360
6361 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6362   if (Op.getValueType().isVector())
6363     return LowerVectorLoad(Op, DAG);
6364
6365   assert(Op.getValueType() == MVT::i1 &&
6366          "Custom lowering only for i1 loads");
6367
6368   // First, load 8 bits into 32 bits, then truncate to 1 bit.
6369
6370   SDLoc dl(Op);
6371   LoadSDNode *LD = cast<LoadSDNode>(Op);
6372
6373   SDValue Chain = LD->getChain();
6374   SDValue BasePtr = LD->getBasePtr();
6375   MachineMemOperand *MMO = LD->getMemOperand();
6376
6377   SDValue NewLD =
6378       DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(DAG.getDataLayout()), Chain,
6379                      BasePtr, MVT::i8, MMO);
6380   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
6381
6382   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
6383   return DAG.getMergeValues(Ops, dl);
6384 }
6385
6386 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
6387   if (Op.getOperand(1).getValueType().isVector())
6388     return LowerVectorStore(Op, DAG);
6389
6390   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
6391          "Custom lowering only for i1 stores");
6392
6393   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
6394
6395   SDLoc dl(Op);
6396   StoreSDNode *ST = cast<StoreSDNode>(Op);
6397
6398   SDValue Chain = ST->getChain();
6399   SDValue BasePtr = ST->getBasePtr();
6400   SDValue Value = ST->getValue();
6401   MachineMemOperand *MMO = ST->getMemOperand();
6402
6403   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(DAG.getDataLayout()),
6404                       Value);
6405   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
6406 }
6407
6408 // FIXME: Remove this once the ANDI glue bug is fixed:
6409 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
6410   assert(Op.getValueType() == MVT::i1 &&
6411          "Custom lowering only for i1 results");
6412
6413   SDLoc DL(Op);
6414   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
6415                      Op.getOperand(0));
6416 }
6417
6418 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
6419 /// possible.
6420 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
6421   // Not FP? Not a fsel.
6422   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
6423       !Op.getOperand(2).getValueType().isFloatingPoint())
6424     return Op;
6425
6426   // We might be able to do better than this under some circumstances, but in
6427   // general, fsel-based lowering of select is a finite-math-only optimization.
6428   // For more information, see section F.3 of the 2.06 ISA specification.
6429   if (!DAG.getTarget().Options.NoInfsFPMath ||
6430       !DAG.getTarget().Options.NoNaNsFPMath)
6431     return Op;
6432   // TODO: Propagate flags from the select rather than global settings.
6433   SDNodeFlags Flags;
6434   Flags.setNoInfs(true);
6435   Flags.setNoNaNs(true);
6436
6437   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
6438
6439   EVT ResVT = Op.getValueType();
6440   EVT CmpVT = Op.getOperand(0).getValueType();
6441   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6442   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
6443   SDLoc dl(Op);
6444
6445   // If the RHS of the comparison is a 0.0, we don't need to do the
6446   // subtraction at all.
6447   SDValue Sel1;
6448   if (isFloatingPointZero(RHS))
6449     switch (CC) {
6450     default: break;       // SETUO etc aren't handled by fsel.
6451     case ISD::SETNE:
6452       std::swap(TV, FV);
6453     case ISD::SETEQ:
6454       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6455         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6456       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6457       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6458         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6459       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6460                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
6461     case ISD::SETULT:
6462     case ISD::SETLT:
6463       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6464     case ISD::SETOGE:
6465     case ISD::SETGE:
6466       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6467         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6468       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
6469     case ISD::SETUGT:
6470     case ISD::SETGT:
6471       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
6472     case ISD::SETOLE:
6473     case ISD::SETLE:
6474       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
6475         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
6476       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6477                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
6478     }
6479
6480   SDValue Cmp;
6481   switch (CC) {
6482   default: break;       // SETUO etc aren't handled by fsel.
6483   case ISD::SETNE:
6484     std::swap(TV, FV);
6485   case ISD::SETEQ:
6486     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6487     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6488       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6489     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6490     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
6491       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
6492     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
6493                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
6494   case ISD::SETULT:
6495   case ISD::SETLT:
6496     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6497     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6498       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6499     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6500   case ISD::SETOGE:
6501   case ISD::SETGE:
6502     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS, Flags);
6503     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6504       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6505     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6506   case ISD::SETUGT:
6507   case ISD::SETGT:
6508     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6509     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6510       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6511     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
6512   case ISD::SETOLE:
6513   case ISD::SETLE:
6514     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS, Flags);
6515     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
6516       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
6517     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
6518   }
6519   return Op;
6520 }
6521
6522 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
6523                                                SelectionDAG &DAG,
6524                                                const SDLoc &dl) const {
6525   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6526   SDValue Src = Op.getOperand(0);
6527   if (Src.getValueType() == MVT::f32)
6528     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6529
6530   SDValue Tmp;
6531   switch (Op.getSimpleValueType().SimpleTy) {
6532   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6533   case MVT::i32:
6534     Tmp = DAG.getNode(
6535         Op.getOpcode() == ISD::FP_TO_SINT
6536             ? PPCISD::FCTIWZ
6537             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6538         dl, MVT::f64, Src);
6539     break;
6540   case MVT::i64:
6541     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6542            "i64 FP_TO_UINT is supported only with FPCVT");
6543     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6544                                                         PPCISD::FCTIDUZ,
6545                       dl, MVT::f64, Src);
6546     break;
6547   }
6548
6549   // Convert the FP value to an int value through memory.
6550   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
6551     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
6552   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
6553   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
6554   MachinePointerInfo MPI =
6555       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
6556
6557   // Emit a store to the stack slot.
6558   SDValue Chain;
6559   if (i32Stack) {
6560     MachineFunction &MF = DAG.getMachineFunction();
6561     MachineMemOperand *MMO =
6562       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
6563     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
6564     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6565               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
6566   } else
6567     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr, MPI);
6568
6569   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
6570   // add in a bias on big endian.
6571   if (Op.getValueType() == MVT::i32 && !i32Stack) {
6572     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
6573                         DAG.getConstant(4, dl, FIPtr.getValueType()));
6574     MPI = MPI.getWithOffset(Subtarget.isLittleEndian() ? 0 : 4);
6575   }
6576
6577   RLI.Chain = Chain;
6578   RLI.Ptr = FIPtr;
6579   RLI.MPI = MPI;
6580 }
6581
6582 /// \brief Custom lowers floating point to integer conversions to use
6583 /// the direct move instructions available in ISA 2.07 to avoid the
6584 /// need for load/store combinations.
6585 SDValue PPCTargetLowering::LowerFP_TO_INTDirectMove(SDValue Op,
6586                                                     SelectionDAG &DAG,
6587                                                     const SDLoc &dl) const {
6588   assert(Op.getOperand(0).getValueType().isFloatingPoint());
6589   SDValue Src = Op.getOperand(0);
6590
6591   if (Src.getValueType() == MVT::f32)
6592     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
6593
6594   SDValue Tmp;
6595   switch (Op.getSimpleValueType().SimpleTy) {
6596   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
6597   case MVT::i32:
6598     Tmp = DAG.getNode(
6599         Op.getOpcode() == ISD::FP_TO_SINT
6600             ? PPCISD::FCTIWZ
6601             : (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ : PPCISD::FCTIDZ),
6602         dl, MVT::f64, Src);
6603     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i32, Tmp);
6604     break;
6605   case MVT::i64:
6606     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
6607            "i64 FP_TO_UINT is supported only with FPCVT");
6608     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
6609                                                         PPCISD::FCTIDUZ,
6610                       dl, MVT::f64, Src);
6611     Tmp = DAG.getNode(PPCISD::MFVSR, dl, MVT::i64, Tmp);
6612     break;
6613   }
6614   return Tmp;
6615 }
6616
6617 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
6618                                           const SDLoc &dl) const {
6619   if (Subtarget.hasDirectMove() && Subtarget.isPPC64())
6620     return LowerFP_TO_INTDirectMove(Op, DAG, dl);
6621
6622   ReuseLoadInfo RLI;
6623   LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6624
6625   return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6626                      RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6627 }
6628
6629 // We're trying to insert a regular store, S, and then a load, L. If the
6630 // incoming value, O, is a load, we might just be able to have our load use the
6631 // address used by O. However, we don't know if anything else will store to
6632 // that address before we can load from it. To prevent this situation, we need
6633 // to insert our load, L, into the chain as a peer of O. To do this, we give L
6634 // the same chain operand as O, we create a token factor from the chain results
6635 // of O and L, and we replace all uses of O's chain result with that token
6636 // factor (see spliceIntoChain below for this last part).
6637 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
6638                                             ReuseLoadInfo &RLI,
6639                                             SelectionDAG &DAG,
6640                                             ISD::LoadExtType ET) const {
6641   SDLoc dl(Op);
6642   if (ET == ISD::NON_EXTLOAD &&
6643       (Op.getOpcode() == ISD::FP_TO_UINT ||
6644        Op.getOpcode() == ISD::FP_TO_SINT) &&
6645       isOperationLegalOrCustom(Op.getOpcode(),
6646                                Op.getOperand(0).getValueType())) {
6647
6648     LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
6649     return true;
6650   }
6651
6652   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
6653   if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
6654       LD->isNonTemporal())
6655     return false;
6656   if (LD->getMemoryVT() != MemVT)
6657     return false;
6658
6659   RLI.Ptr = LD->getBasePtr();
6660   if (LD->isIndexed() && !LD->getOffset().isUndef()) {
6661     assert(LD->getAddressingMode() == ISD::PRE_INC &&
6662            "Non-pre-inc AM on PPC?");
6663     RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
6664                           LD->getOffset());
6665   }
6666
6667   RLI.Chain = LD->getChain();
6668   RLI.MPI = LD->getPointerInfo();
6669   RLI.IsDereferenceable = LD->isDereferenceable();
6670   RLI.IsInvariant = LD->isInvariant();
6671   RLI.Alignment = LD->getAlignment();
6672   RLI.AAInfo = LD->getAAInfo();
6673   RLI.Ranges = LD->getRanges();
6674
6675   RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
6676   return true;
6677 }
6678
6679 // Given the head of the old chain, ResChain, insert a token factor containing
6680 // it and NewResChain, and make users of ResChain now be users of that token
6681 // factor.
6682 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
6683                                         SDValue NewResChain,
6684                                         SelectionDAG &DAG) const {
6685   if (!ResChain)
6686     return;
6687
6688   SDLoc dl(NewResChain);
6689
6690   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6691                            NewResChain, DAG.getUNDEF(MVT::Other));
6692   assert(TF.getNode() != NewResChain.getNode() &&
6693          "A new TF really is required here");
6694
6695   DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
6696   DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
6697 }
6698
6699 /// \brief Analyze profitability of direct move
6700 /// prefer float load to int load plus direct move
6701 /// when there is no integer use of int load
6702 bool PPCTargetLowering::directMoveIsProfitable(const SDValue &Op) const {
6703   SDNode *Origin = Op.getOperand(0).getNode();
6704   if (Origin->getOpcode() != ISD::LOAD)
6705     return true;
6706
6707   // If there is no LXSIBZX/LXSIHZX, like Power8,
6708   // prefer direct move if the memory size is 1 or 2 bytes.
6709   MachineMemOperand *MMO = cast<LoadSDNode>(Origin)->getMemOperand();
6710   if (!Subtarget.hasP9Vector() && MMO->getSize() <= 2)
6711     return true;
6712
6713   for (SDNode::use_iterator UI = Origin->use_begin(),
6714                             UE = Origin->use_end();
6715        UI != UE; ++UI) {
6716
6717     // Only look at the users of the loaded value.
6718     if (UI.getUse().get().getResNo() != 0)
6719       continue;
6720
6721     if (UI->getOpcode() != ISD::SINT_TO_FP &&
6722         UI->getOpcode() != ISD::UINT_TO_FP)
6723       return true;
6724   }
6725
6726   return false;
6727 }
6728
6729 /// \brief Custom lowers integer to floating point conversions to use
6730 /// the direct move instructions available in ISA 2.07 to avoid the
6731 /// need for load/store combinations.
6732 SDValue PPCTargetLowering::LowerINT_TO_FPDirectMove(SDValue Op,
6733                                                     SelectionDAG &DAG,
6734                                                     const SDLoc &dl) const {
6735   assert((Op.getValueType() == MVT::f32 ||
6736           Op.getValueType() == MVT::f64) &&
6737          "Invalid floating point type as target of conversion");
6738   assert(Subtarget.hasFPCVT() &&
6739          "Int to FP conversions with direct moves require FPCVT");
6740   SDValue FP;
6741   SDValue Src = Op.getOperand(0);
6742   bool SinglePrec = Op.getValueType() == MVT::f32;
6743   bool WordInt = Src.getSimpleValueType().SimpleTy == MVT::i32;
6744   bool Signed = Op.getOpcode() == ISD::SINT_TO_FP;
6745   unsigned ConvOp = Signed ? (SinglePrec ? PPCISD::FCFIDS : PPCISD::FCFID) :
6746                              (SinglePrec ? PPCISD::FCFIDUS : PPCISD::FCFIDU);
6747
6748   if (WordInt) {
6749     FP = DAG.getNode(Signed ? PPCISD::MTVSRA : PPCISD::MTVSRZ,
6750                      dl, MVT::f64, Src);
6751     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6752   }
6753   else {
6754     FP = DAG.getNode(PPCISD::MTVSRA, dl, MVT::f64, Src);
6755     FP = DAG.getNode(ConvOp, dl, SinglePrec ? MVT::f32 : MVT::f64, FP);
6756   }
6757
6758   return FP;
6759 }
6760
6761 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
6762                                           SelectionDAG &DAG) const {
6763   SDLoc dl(Op);
6764
6765   if (Subtarget.hasQPX() && Op.getOperand(0).getValueType() == MVT::v4i1) {
6766     if (Op.getValueType() != MVT::v4f32 && Op.getValueType() != MVT::v4f64)
6767       return SDValue();
6768
6769     SDValue Value = Op.getOperand(0);
6770     // The values are now known to be -1 (false) or 1 (true). To convert this
6771     // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
6772     // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
6773     Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
6774
6775     SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
6776
6777     Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
6778
6779     if (Op.getValueType() != MVT::v4f64)
6780       Value = DAG.getNode(ISD::FP_ROUND, dl,
6781                           Op.getValueType(), Value,
6782                           DAG.getIntPtrConstant(1, dl));
6783     return Value;
6784   }
6785
6786   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
6787   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
6788     return SDValue();
6789
6790   if (Op.getOperand(0).getValueType() == MVT::i1)
6791     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
6792                        DAG.getConstantFP(1.0, dl, Op.getValueType()),
6793                        DAG.getConstantFP(0.0, dl, Op.getValueType()));
6794
6795   // If we have direct moves, we can do all the conversion, skip the store/load
6796   // however, without FPCVT we can't do most conversions.
6797   if (Subtarget.hasDirectMove() && directMoveIsProfitable(Op) &&
6798       Subtarget.isPPC64() && Subtarget.hasFPCVT())
6799     return LowerINT_TO_FPDirectMove(Op, DAG, dl);
6800
6801   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
6802          "UINT_TO_FP is supported only with FPCVT");
6803
6804   // If we have FCFIDS, then use it when converting to single-precision.
6805   // Otherwise, convert to double-precision and then round.
6806   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6807                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
6808                                                             : PPCISD::FCFIDS)
6809                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
6810                                                             : PPCISD::FCFID);
6811   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
6812                   ? MVT::f32
6813                   : MVT::f64;
6814
6815   if (Op.getOperand(0).getValueType() == MVT::i64) {
6816     SDValue SINT = Op.getOperand(0);
6817     // When converting to single-precision, we actually need to convert
6818     // to double-precision first and then round to single-precision.
6819     // To avoid double-rounding effects during that operation, we have
6820     // to prepare the input operand.  Bits that might be truncated when
6821     // converting to double-precision are replaced by a bit that won't
6822     // be lost at this stage, but is below the single-precision rounding
6823     // position.
6824     //
6825     // However, if -enable-unsafe-fp-math is in effect, accept double
6826     // rounding to avoid the extra overhead.
6827     if (Op.getValueType() == MVT::f32 &&
6828         !Subtarget.hasFPCVT() &&
6829         !DAG.getTarget().Options.UnsafeFPMath) {
6830
6831       // Twiddle input to make sure the low 11 bits are zero.  (If this
6832       // is the case, we are guaranteed the value will fit into the 53 bit
6833       // mantissa of an IEEE double-precision value without rounding.)
6834       // If any of those low 11 bits were not zero originally, make sure
6835       // bit 12 (value 2048) is set instead, so that the final rounding
6836       // to single-precision gets the correct result.
6837       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6838                                   SINT, DAG.getConstant(2047, dl, MVT::i64));
6839       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
6840                           Round, DAG.getConstant(2047, dl, MVT::i64));
6841       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
6842       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
6843                           Round, DAG.getConstant(-2048, dl, MVT::i64));
6844
6845       // However, we cannot use that value unconditionally: if the magnitude
6846       // of the input value is small, the bit-twiddling we did above might
6847       // end up visibly changing the output.  Fortunately, in that case, we
6848       // don't need to twiddle bits since the original input will convert
6849       // exactly to double-precision floating-point already.  Therefore,
6850       // construct a conditional to use the original value if the top 11
6851       // bits are all sign-bit copies, and use the rounded value computed
6852       // above otherwise.
6853       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
6854                                  SINT, DAG.getConstant(53, dl, MVT::i32));
6855       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
6856                          Cond, DAG.getConstant(1, dl, MVT::i64));
6857       Cond = DAG.getSetCC(dl, MVT::i32,
6858                           Cond, DAG.getConstant(1, dl, MVT::i64), ISD::SETUGT);
6859
6860       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
6861     }
6862
6863     ReuseLoadInfo RLI;
6864     SDValue Bits;
6865
6866     MachineFunction &MF = DAG.getMachineFunction();
6867     if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
6868       Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI,
6869                          RLI.Alignment, RLI.MMOFlags(), RLI.AAInfo, RLI.Ranges);
6870       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6871     } else if (Subtarget.hasLFIWAX() &&
6872                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
6873       MachineMemOperand *MMO =
6874         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6875                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6876       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6877       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
6878                                      DAG.getVTList(MVT::f64, MVT::Other),
6879                                      Ops, MVT::i32, MMO);
6880       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6881     } else if (Subtarget.hasFPCVT() &&
6882                canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
6883       MachineMemOperand *MMO =
6884         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6885                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6886       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6887       Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
6888                                      DAG.getVTList(MVT::f64, MVT::Other),
6889                                      Ops, MVT::i32, MMO);
6890       spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
6891     } else if (((Subtarget.hasLFIWAX() &&
6892                  SINT.getOpcode() == ISD::SIGN_EXTEND) ||
6893                 (Subtarget.hasFPCVT() &&
6894                  SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
6895                SINT.getOperand(0).getValueType() == MVT::i32) {
6896       MachineFrameInfo &MFI = MF.getFrameInfo();
6897       EVT PtrVT = getPointerTy(DAG.getDataLayout());
6898
6899       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6900       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6901
6902       SDValue Store =
6903           DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
6904                        MachinePointerInfo::getFixedStack(
6905                            DAG.getMachineFunction(), FrameIdx));
6906
6907       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6908              "Expected an i32 store");
6909
6910       RLI.Ptr = FIdx;
6911       RLI.Chain = Store;
6912       RLI.MPI =
6913           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6914       RLI.Alignment = 4;
6915
6916       MachineMemOperand *MMO =
6917         MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6918                                 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6919       SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6920       Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
6921                                      PPCISD::LFIWZX : PPCISD::LFIWAX,
6922                                      dl, DAG.getVTList(MVT::f64, MVT::Other),
6923                                      Ops, MVT::i32, MMO);
6924     } else
6925       Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
6926
6927     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
6928
6929     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
6930       FP = DAG.getNode(ISD::FP_ROUND, dl,
6931                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
6932     return FP;
6933   }
6934
6935   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
6936          "Unhandled INT_TO_FP type in custom expander!");
6937   // Since we only generate this in 64-bit mode, we can take advantage of
6938   // 64-bit registers.  In particular, sign extend the input value into the
6939   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
6940   // then lfd it and fcfid it.
6941   MachineFunction &MF = DAG.getMachineFunction();
6942   MachineFrameInfo &MFI = MF.getFrameInfo();
6943   EVT PtrVT = getPointerTy(MF.getDataLayout());
6944
6945   SDValue Ld;
6946   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
6947     ReuseLoadInfo RLI;
6948     bool ReusingLoad;
6949     if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
6950                                             DAG))) {
6951       int FrameIdx = MFI.CreateStackObject(4, 4, false);
6952       SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6953
6954       SDValue Store =
6955           DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
6956                        MachinePointerInfo::getFixedStack(
6957                            DAG.getMachineFunction(), FrameIdx));
6958
6959       assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
6960              "Expected an i32 store");
6961
6962       RLI.Ptr = FIdx;
6963       RLI.Chain = Store;
6964       RLI.MPI =
6965           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
6966       RLI.Alignment = 4;
6967     }
6968
6969     MachineMemOperand *MMO =
6970       MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
6971                               RLI.Alignment, RLI.AAInfo, RLI.Ranges);
6972     SDValue Ops[] = { RLI.Chain, RLI.Ptr };
6973     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
6974                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
6975                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
6976                                  Ops, MVT::i32, MMO);
6977     if (ReusingLoad)
6978       spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
6979   } else {
6980     assert(Subtarget.isPPC64() &&
6981            "i32->FP without LFIWAX supported only on PPC64");
6982
6983     int FrameIdx = MFI.CreateStackObject(8, 8, false);
6984     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6985
6986     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
6987                                 Op.getOperand(0));
6988
6989     // STD the extended value into the stack slot.
6990     SDValue Store = DAG.getStore(
6991         DAG.getEntryNode(), dl, Ext64, FIdx,
6992         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6993
6994     // Load the value as a double.
6995     Ld = DAG.getLoad(
6996         MVT::f64, dl, Store, FIdx,
6997         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx));
6998   }
6999
7000   // FCFID it and return it.
7001   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
7002   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
7003     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP,
7004                      DAG.getIntPtrConstant(0, dl));
7005   return FP;
7006 }
7007
7008 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7009                                             SelectionDAG &DAG) const {
7010   SDLoc dl(Op);
7011   /*
7012    The rounding mode is in bits 30:31 of FPSR, and has the following
7013    settings:
7014      00 Round to nearest
7015      01 Round to 0
7016      10 Round to +inf
7017      11 Round to -inf
7018
7019   FLT_ROUNDS, on the other hand, expects the following:
7020     -1 Undefined
7021      0 Round to 0
7022      1 Round to nearest
7023      2 Round to +inf
7024      3 Round to -inf
7025
7026   To perform the conversion, we do:
7027     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
7028   */
7029
7030   MachineFunction &MF = DAG.getMachineFunction();
7031   EVT VT = Op.getValueType();
7032   EVT PtrVT = getPointerTy(MF.getDataLayout());
7033
7034   // Save FP Control Word to register
7035   EVT NodeTys[] = {
7036     MVT::f64,    // return register
7037     MVT::Glue    // unused in this context
7038   };
7039   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
7040
7041   // Save FP register to stack slot
7042   int SSFI = MF.getFrameInfo().CreateStackObject(8, 8, false);
7043   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
7044   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain, StackSlot,
7045                                MachinePointerInfo());
7046
7047   // Load FP Control Word from low 32 bits of stack slot.
7048   SDValue Four = DAG.getConstant(4, dl, PtrVT);
7049   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
7050   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo());
7051
7052   // Transform as necessary
7053   SDValue CWD1 =
7054     DAG.getNode(ISD::AND, dl, MVT::i32,
7055                 CWD, DAG.getConstant(3, dl, MVT::i32));
7056   SDValue CWD2 =
7057     DAG.getNode(ISD::SRL, dl, MVT::i32,
7058                 DAG.getNode(ISD::AND, dl, MVT::i32,
7059                             DAG.getNode(ISD::XOR, dl, MVT::i32,
7060                                         CWD, DAG.getConstant(3, dl, MVT::i32)),
7061                             DAG.getConstant(3, dl, MVT::i32)),
7062                 DAG.getConstant(1, dl, MVT::i32));
7063
7064   SDValue RetVal =
7065     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
7066
7067   return DAG.getNode((VT.getSizeInBits() < 16 ?
7068                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7069 }
7070
7071 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7072   EVT VT = Op.getValueType();
7073   unsigned BitWidth = VT.getSizeInBits();
7074   SDLoc dl(Op);
7075   assert(Op.getNumOperands() == 3 &&
7076          VT == Op.getOperand(1).getValueType() &&
7077          "Unexpected SHL!");
7078
7079   // Expand into a bunch of logical ops.  Note that these ops
7080   // depend on the PPC behavior for oversized shift amounts.
7081   SDValue Lo = Op.getOperand(0);
7082   SDValue Hi = Op.getOperand(1);
7083   SDValue Amt = Op.getOperand(2);
7084   EVT AmtVT = Amt.getValueType();
7085
7086   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7087                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7088   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
7089   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
7090   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
7091   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7092                              DAG.getConstant(-BitWidth, dl, AmtVT));
7093   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
7094   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7095   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
7096   SDValue OutOps[] = { OutLo, OutHi };
7097   return DAG.getMergeValues(OutOps, dl);
7098 }
7099
7100 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
7101   EVT VT = Op.getValueType();
7102   SDLoc dl(Op);
7103   unsigned BitWidth = VT.getSizeInBits();
7104   assert(Op.getNumOperands() == 3 &&
7105          VT == Op.getOperand(1).getValueType() &&
7106          "Unexpected SRL!");
7107
7108   // Expand into a bunch of logical ops.  Note that these ops
7109   // depend on the PPC behavior for oversized shift amounts.
7110   SDValue Lo = Op.getOperand(0);
7111   SDValue Hi = Op.getOperand(1);
7112   SDValue Amt = Op.getOperand(2);
7113   EVT AmtVT = Amt.getValueType();
7114
7115   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7116                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7117   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7118   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7119   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7120   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7121                              DAG.getConstant(-BitWidth, dl, AmtVT));
7122   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
7123   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
7124   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
7125   SDValue OutOps[] = { OutLo, OutHi };
7126   return DAG.getMergeValues(OutOps, dl);
7127 }
7128
7129 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
7130   SDLoc dl(Op);
7131   EVT VT = Op.getValueType();
7132   unsigned BitWidth = VT.getSizeInBits();
7133   assert(Op.getNumOperands() == 3 &&
7134          VT == Op.getOperand(1).getValueType() &&
7135          "Unexpected SRA!");
7136
7137   // Expand into a bunch of logical ops, followed by a select_cc.
7138   SDValue Lo = Op.getOperand(0);
7139   SDValue Hi = Op.getOperand(1);
7140   SDValue Amt = Op.getOperand(2);
7141   EVT AmtVT = Amt.getValueType();
7142
7143   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
7144                              DAG.getConstant(BitWidth, dl, AmtVT), Amt);
7145   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
7146   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
7147   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7148   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
7149                              DAG.getConstant(-BitWidth, dl, AmtVT));
7150   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
7151   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
7152   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, dl, AmtVT),
7153                                   Tmp4, Tmp6, ISD::SETLE);
7154   SDValue OutOps[] = { OutLo, OutHi };
7155   return DAG.getMergeValues(OutOps, dl);
7156 }
7157
7158 //===----------------------------------------------------------------------===//
7159 // Vector related lowering.
7160 //
7161
7162 /// BuildSplatI - Build a canonical splati of Val with an element size of
7163 /// SplatSize.  Cast the result to VT.
7164 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
7165                            SelectionDAG &DAG, const SDLoc &dl) {
7166   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
7167
7168   static const MVT VTys[] = { // canonical VT to use for each size.
7169     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
7170   };
7171
7172   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
7173
7174   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
7175   if (Val == -1)
7176     SplatSize = 1;
7177
7178   EVT CanonicalVT = VTys[SplatSize-1];
7179
7180   // Build a canonical splat for this value.
7181   return DAG.getBitcast(ReqVT, DAG.getConstant(Val, dl, CanonicalVT));
7182 }
7183
7184 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
7185 /// specified intrinsic ID.
7186 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op, SelectionDAG &DAG,
7187                                 const SDLoc &dl, EVT DestVT = MVT::Other) {
7188   if (DestVT == MVT::Other) DestVT = Op.getValueType();
7189   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7190                      DAG.getConstant(IID, dl, MVT::i32), Op);
7191 }
7192
7193 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
7194 /// specified intrinsic ID.
7195 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
7196                                 SelectionDAG &DAG, const SDLoc &dl,
7197                                 EVT DestVT = MVT::Other) {
7198   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
7199   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7200                      DAG.getConstant(IID, dl, MVT::i32), LHS, RHS);
7201 }
7202
7203 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
7204 /// specified intrinsic ID.
7205 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
7206                                 SDValue Op2, SelectionDAG &DAG, const SDLoc &dl,
7207                                 EVT DestVT = MVT::Other) {
7208   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
7209   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
7210                      DAG.getConstant(IID, dl, MVT::i32), Op0, Op1, Op2);
7211 }
7212
7213 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
7214 /// amount.  The result has the specified value type.
7215 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt, EVT VT,
7216                            SelectionDAG &DAG, const SDLoc &dl) {
7217   // Force LHS/RHS to be the right type.
7218   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
7219   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
7220
7221   int Ops[16];
7222   for (unsigned i = 0; i != 16; ++i)
7223     Ops[i] = i + Amt;
7224   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
7225   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7226 }
7227
7228 /// Do we have an efficient pattern in a .td file for this node?
7229 ///
7230 /// \param V - pointer to the BuildVectorSDNode being matched
7231 /// \param HasDirectMove - does this subtarget have VSR <-> GPR direct moves?
7232 ///
7233 /// There are some patterns where it is beneficial to keep a BUILD_VECTOR
7234 /// node as a BUILD_VECTOR node rather than expanding it. The patterns where
7235 /// the opposite is true (expansion is beneficial) are:
7236 /// - The node builds a vector out of integers that are not 32 or 64-bits
7237 /// - The node builds a vector out of constants
7238 /// - The node is a "load-and-splat"
7239 /// In all other cases, we will choose to keep the BUILD_VECTOR.
7240 static bool haveEfficientBuildVectorPattern(BuildVectorSDNode *V,
7241                                             bool HasDirectMove) {
7242   EVT VecVT = V->getValueType(0);
7243   bool RightType = VecVT == MVT::v2f64 || VecVT == MVT::v4f32 ||
7244     (HasDirectMove && (VecVT == MVT::v2i64 || VecVT == MVT::v4i32));
7245   if (!RightType)
7246     return false;
7247
7248   bool IsSplat = true;
7249   bool IsLoad = false;
7250   SDValue Op0 = V->getOperand(0);
7251
7252   // This function is called in a block that confirms the node is not a constant
7253   // splat. So a constant BUILD_VECTOR here means the vector is built out of
7254   // different constants.
7255   if (V->isConstant())
7256     return false;
7257   for (int i = 0, e = V->getNumOperands(); i < e; ++i) {
7258     if (V->getOperand(i).isUndef())
7259       return false;
7260     // We want to expand nodes that represent load-and-splat even if the
7261     // loaded value is a floating point truncation or conversion to int.
7262     if (V->getOperand(i).getOpcode() == ISD::LOAD ||
7263         (V->getOperand(i).getOpcode() == ISD::FP_ROUND &&
7264          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7265         (V->getOperand(i).getOpcode() == ISD::FP_TO_SINT &&
7266          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD) ||
7267         (V->getOperand(i).getOpcode() == ISD::FP_TO_UINT &&
7268          V->getOperand(i).getOperand(0).getOpcode() == ISD::LOAD))
7269       IsLoad = true;
7270     // If the operands are different or the input is not a load and has more
7271     // uses than just this BV node, then it isn't a splat.
7272     if (V->getOperand(i) != Op0 ||
7273         (!IsLoad && !V->isOnlyUserOf(V->getOperand(i).getNode())))
7274       IsSplat = false;
7275   }
7276   return !(IsSplat && IsLoad);
7277 }
7278
7279 // If this is a case we can't handle, return null and let the default
7280 // expansion code take care of it.  If we CAN select this case, and if it
7281 // selects to a single instruction, return Op.  Otherwise, if we can codegen
7282 // this case more efficiently than a constant pool load, lower it to the
7283 // sequence of ops that should be used.
7284 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
7285                                              SelectionDAG &DAG) const {
7286   SDLoc dl(Op);
7287   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7288   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
7289
7290   if (Subtarget.hasQPX() && Op.getValueType() == MVT::v4i1) {
7291     // We first build an i32 vector, load it into a QPX register,
7292     // then convert it to a floating-point vector and compare it
7293     // to a zero vector to get the boolean result.
7294     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7295     int FrameIdx = MFI.CreateStackObject(16, 16, false);
7296     MachinePointerInfo PtrInfo =
7297         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
7298     EVT PtrVT = getPointerTy(DAG.getDataLayout());
7299     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
7300
7301     assert(BVN->getNumOperands() == 4 &&
7302       "BUILD_VECTOR for v4i1 does not have 4 operands");
7303
7304     bool IsConst = true;
7305     for (unsigned i = 0; i < 4; ++i) {
7306       if (BVN->getOperand(i).isUndef()) continue;
7307       if (!isa<ConstantSDNode>(BVN->getOperand(i))) {
7308         IsConst = false;
7309         break;
7310       }
7311     }
7312
7313     if (IsConst) {
7314       Constant *One =
7315         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), 1.0);
7316       Constant *NegOne =
7317         ConstantFP::get(Type::getFloatTy(*DAG.getContext()), -1.0);
7318
7319       Constant *CV[4];
7320       for (unsigned i = 0; i < 4; ++i) {
7321         if (BVN->getOperand(i).isUndef())
7322           CV[i] = UndefValue::get(Type::getFloatTy(*DAG.getContext()));
7323         else if (isNullConstant(BVN->getOperand(i)))
7324           CV[i] = NegOne;
7325         else
7326           CV[i] = One;
7327       }
7328
7329       Constant *CP = ConstantVector::get(CV);
7330       SDValue CPIdx = DAG.getConstantPool(CP, getPointerTy(DAG.getDataLayout()),
7331                                           16 /* alignment */);
7332
7333       SDValue Ops[] = {DAG.getEntryNode(), CPIdx};
7334       SDVTList VTs = DAG.getVTList({MVT::v4i1, /*chain*/ MVT::Other});
7335       return DAG.getMemIntrinsicNode(
7336           PPCISD::QVLFSb, dl, VTs, Ops, MVT::v4f32,
7337           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
7338     }
7339
7340     SmallVector<SDValue, 4> Stores;
7341     for (unsigned i = 0; i < 4; ++i) {
7342       if (BVN->getOperand(i).isUndef()) continue;
7343
7344       unsigned Offset = 4*i;
7345       SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
7346       Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
7347
7348       unsigned StoreSize = BVN->getOperand(i).getValueType().getStoreSize();
7349       if (StoreSize > 4) {
7350         Stores.push_back(
7351             DAG.getTruncStore(DAG.getEntryNode(), dl, BVN->getOperand(i), Idx,
7352                               PtrInfo.getWithOffset(Offset), MVT::i32));
7353       } else {
7354         SDValue StoreValue = BVN->getOperand(i);
7355         if (StoreSize < 4)
7356           StoreValue = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, StoreValue);
7357
7358         Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, StoreValue, Idx,
7359                                       PtrInfo.getWithOffset(Offset)));
7360       }
7361     }
7362
7363     SDValue StoreChain;
7364     if (!Stores.empty())
7365       StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7366     else
7367       StoreChain = DAG.getEntryNode();
7368
7369     // Now load from v4i32 into the QPX register; this will extend it to
7370     // v4i64 but not yet convert it to a floating point. Nevertheless, this
7371     // is typed as v4f64 because the QPX register integer states are not
7372     // explicitly represented.
7373
7374     SDValue Ops[] = {StoreChain,
7375                      DAG.getConstant(Intrinsic::ppc_qpx_qvlfiwz, dl, MVT::i32),
7376                      FIdx};
7377     SDVTList VTs = DAG.getVTList({MVT::v4f64, /*chain*/ MVT::Other});
7378
7379     SDValue LoadedVect = DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN,
7380       dl, VTs, Ops, MVT::v4i32, PtrInfo);
7381     LoadedVect = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
7382       DAG.getConstant(Intrinsic::ppc_qpx_qvfcfidu, dl, MVT::i32),
7383       LoadedVect);
7384
7385     SDValue FPZeros = DAG.getConstantFP(0.0, dl, MVT::v4f64);
7386
7387     return DAG.getSetCC(dl, MVT::v4i1, LoadedVect, FPZeros, ISD::SETEQ);
7388   }
7389
7390   // All other QPX vectors are handled by generic code.
7391   if (Subtarget.hasQPX())
7392     return SDValue();
7393
7394   // Check if this is a splat of a constant value.
7395   APInt APSplatBits, APSplatUndef;
7396   unsigned SplatBitSize;
7397   bool HasAnyUndefs;
7398   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
7399                              HasAnyUndefs, 0, !Subtarget.isLittleEndian()) ||
7400       SplatBitSize > 32) {
7401     // BUILD_VECTOR nodes that are not constant splats of up to 32-bits can be
7402     // lowered to VSX instructions under certain conditions.
7403     // Without VSX, there is no pattern more efficient than expanding the node.
7404     if (Subtarget.hasVSX() &&
7405         haveEfficientBuildVectorPattern(BVN, Subtarget.hasDirectMove()))
7406       return Op;
7407     return SDValue();
7408   }
7409
7410   unsigned SplatBits = APSplatBits.getZExtValue();
7411   unsigned SplatUndef = APSplatUndef.getZExtValue();
7412   unsigned SplatSize = SplatBitSize / 8;
7413
7414   // First, handle single instruction cases.
7415
7416   // All zeros?
7417   if (SplatBits == 0) {
7418     // Canonicalize all zero vectors to be v4i32.
7419     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
7420       SDValue Z = DAG.getConstant(0, dl, MVT::v4i32);
7421       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
7422     }
7423     return Op;
7424   }
7425
7426   // We have XXSPLTIB for constant splats one byte wide
7427   if (Subtarget.hasP9Vector() && SplatSize == 1) {
7428     // This is a splat of 1-byte elements with some elements potentially undef.
7429     // Rather than trying to match undef in the SDAG patterns, ensure that all
7430     // elements are the same constant.
7431     if (HasAnyUndefs || ISD::isBuildVectorAllOnes(BVN)) {
7432       SmallVector<SDValue, 16> Ops(16, DAG.getConstant(SplatBits,
7433                                                        dl, MVT::i32));
7434       SDValue NewBV = DAG.getBuildVector(MVT::v16i8, dl, Ops);
7435       if (Op.getValueType() != MVT::v16i8)
7436         return DAG.getBitcast(Op.getValueType(), NewBV);
7437       return NewBV;
7438     }
7439     return Op;
7440   }
7441
7442   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
7443   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
7444                     (32-SplatBitSize));
7445   if (SextVal >= -16 && SextVal <= 15)
7446     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
7447
7448   // Two instruction sequences.
7449
7450   // If this value is in the range [-32,30] and is even, use:
7451   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
7452   // If this value is in the range [17,31] and is odd, use:
7453   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
7454   // If this value is in the range [-31,-17] and is odd, use:
7455   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
7456   // Note the last two are three-instruction sequences.
7457   if (SextVal >= -32 && SextVal <= 31) {
7458     // To avoid having these optimizations undone by constant folding,
7459     // we convert to a pseudo that will be expanded later into one of
7460     // the above forms.
7461     SDValue Elt = DAG.getConstant(SextVal, dl, MVT::i32);
7462     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
7463               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
7464     SDValue EltSize = DAG.getConstant(SplatSize, dl, MVT::i32);
7465     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
7466     if (VT == Op.getValueType())
7467       return RetVal;
7468     else
7469       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
7470   }
7471
7472   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
7473   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
7474   // for fneg/fabs.
7475   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
7476     // Make -1 and vspltisw -1:
7477     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
7478
7479     // Make the VSLW intrinsic, computing 0x8000_0000.
7480     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
7481                                    OnesV, DAG, dl);
7482
7483     // xor by OnesV to invert it.
7484     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
7485     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7486   }
7487
7488   // Check to see if this is a wide variety of vsplti*, binop self cases.
7489   static const signed char SplatCsts[] = {
7490     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
7491     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
7492   };
7493
7494   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
7495     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
7496     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
7497     int i = SplatCsts[idx];
7498
7499     // Figure out what shift amount will be used by altivec if shifted by i in
7500     // this splat size.
7501     unsigned TypeShiftAmt = i & (SplatBitSize-1);
7502
7503     // vsplti + shl self.
7504     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
7505       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7506       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7507         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
7508         Intrinsic::ppc_altivec_vslw
7509       };
7510       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7511       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7512     }
7513
7514     // vsplti + srl self.
7515     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7516       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7517       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7518         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
7519         Intrinsic::ppc_altivec_vsrw
7520       };
7521       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7522       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7523     }
7524
7525     // vsplti + sra self.
7526     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
7527       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7528       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7529         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
7530         Intrinsic::ppc_altivec_vsraw
7531       };
7532       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7533       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7534     }
7535
7536     // vsplti + rol self.
7537     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
7538                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
7539       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
7540       static const unsigned IIDs[] = { // Intrinsic to use for each size.
7541         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
7542         Intrinsic::ppc_altivec_vrlw
7543       };
7544       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
7545       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
7546     }
7547
7548     // t = vsplti c, result = vsldoi t, t, 1
7549     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
7550       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7551       unsigned Amt = Subtarget.isLittleEndian() ? 15 : 1;
7552       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7553     }
7554     // t = vsplti c, result = vsldoi t, t, 2
7555     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
7556       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7557       unsigned Amt = Subtarget.isLittleEndian() ? 14 : 2;
7558       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7559     }
7560     // t = vsplti c, result = vsldoi t, t, 3
7561     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
7562       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
7563       unsigned Amt = Subtarget.isLittleEndian() ? 13 : 3;
7564       return BuildVSLDOI(T, T, Amt, Op.getValueType(), DAG, dl);
7565     }
7566   }
7567
7568   return SDValue();
7569 }
7570
7571 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
7572 /// the specified operations to build the shuffle.
7573 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
7574                                       SDValue RHS, SelectionDAG &DAG,
7575                                       const SDLoc &dl) {
7576   unsigned OpNum = (PFEntry >> 26) & 0x0F;
7577   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
7578   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
7579
7580   enum {
7581     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
7582     OP_VMRGHW,
7583     OP_VMRGLW,
7584     OP_VSPLTISW0,
7585     OP_VSPLTISW1,
7586     OP_VSPLTISW2,
7587     OP_VSPLTISW3,
7588     OP_VSLDOI4,
7589     OP_VSLDOI8,
7590     OP_VSLDOI12
7591   };
7592
7593   if (OpNum == OP_COPY) {
7594     if (LHSID == (1*9+2)*9+3) return LHS;
7595     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
7596     return RHS;
7597   }
7598
7599   SDValue OpLHS, OpRHS;
7600   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
7601   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
7602
7603   int ShufIdxs[16];
7604   switch (OpNum) {
7605   default: llvm_unreachable("Unknown i32 permute!");
7606   case OP_VMRGHW:
7607     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
7608     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
7609     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
7610     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
7611     break;
7612   case OP_VMRGLW:
7613     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
7614     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
7615     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
7616     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
7617     break;
7618   case OP_VSPLTISW0:
7619     for (unsigned i = 0; i != 16; ++i)
7620       ShufIdxs[i] = (i&3)+0;
7621     break;
7622   case OP_VSPLTISW1:
7623     for (unsigned i = 0; i != 16; ++i)
7624       ShufIdxs[i] = (i&3)+4;
7625     break;
7626   case OP_VSPLTISW2:
7627     for (unsigned i = 0; i != 16; ++i)
7628       ShufIdxs[i] = (i&3)+8;
7629     break;
7630   case OP_VSPLTISW3:
7631     for (unsigned i = 0; i != 16; ++i)
7632       ShufIdxs[i] = (i&3)+12;
7633     break;
7634   case OP_VSLDOI4:
7635     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
7636   case OP_VSLDOI8:
7637     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
7638   case OP_VSLDOI12:
7639     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
7640   }
7641   EVT VT = OpLHS.getValueType();
7642   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
7643   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
7644   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
7645   return DAG.getNode(ISD::BITCAST, dl, VT, T);
7646 }
7647
7648 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
7649 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
7650 /// return the code it can be lowered into.  Worst case, it can always be
7651 /// lowered into a vperm.
7652 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
7653                                                SelectionDAG &DAG) const {
7654   SDLoc dl(Op);
7655   SDValue V1 = Op.getOperand(0);
7656   SDValue V2 = Op.getOperand(1);
7657   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7658   EVT VT = Op.getValueType();
7659   bool isLittleEndian = Subtarget.isLittleEndian();
7660
7661   unsigned ShiftElts, InsertAtByte;
7662   bool Swap;
7663   if (Subtarget.hasP9Vector() &&
7664       PPC::isXXINSERTWMask(SVOp, ShiftElts, InsertAtByte, Swap,
7665                            isLittleEndian)) {
7666     if (Swap)
7667       std::swap(V1, V2);
7668     SDValue Conv1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7669     SDValue Conv2 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V2);
7670     if (ShiftElts) {
7671       SDValue Shl = DAG.getNode(PPCISD::VECSHL, dl, MVT::v4i32, Conv2, Conv2,
7672                                 DAG.getConstant(ShiftElts, dl, MVT::i32));
7673       SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Shl,
7674                                 DAG.getConstant(InsertAtByte, dl, MVT::i32));
7675       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7676     }
7677     SDValue Ins = DAG.getNode(PPCISD::XXINSERT, dl, MVT::v4i32, Conv1, Conv2,
7678                               DAG.getConstant(InsertAtByte, dl, MVT::i32));
7679     return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Ins);
7680   }
7681
7682   if (Subtarget.hasVSX()) {
7683     if (V2.isUndef() && PPC::isSplatShuffleMask(SVOp, 4)) {
7684       int SplatIdx = PPC::getVSPLTImmediate(SVOp, 4, DAG);
7685
7686       // If the source for the shuffle is a scalar_to_vector that came from a
7687       // 32-bit load, it will have used LXVWSX so we don't need to splat again.
7688       if (Subtarget.hasP9Vector() &&
7689           ((isLittleEndian && SplatIdx == 3) ||
7690            (!isLittleEndian && SplatIdx == 0))) {
7691         SDValue Src = V1.getOperand(0);
7692         if (Src.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7693             Src.getOperand(0).getOpcode() == ISD::LOAD &&
7694             Src.getOperand(0).hasOneUse())
7695           return V1;
7696       }
7697       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
7698       SDValue Splat = DAG.getNode(PPCISD::XXSPLT, dl, MVT::v4i32, Conv,
7699                                   DAG.getConstant(SplatIdx, dl, MVT::i32));
7700       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Splat);
7701     }
7702
7703     // Left shifts of 8 bytes are actually swaps. Convert accordingly.
7704     if (V2.isUndef() && PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) == 8) {
7705       SDValue Conv = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7706       SDValue Swap = DAG.getNode(PPCISD::SWAP_NO_CHAIN, dl, MVT::v2f64, Conv);
7707       return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, Swap);
7708     }
7709   }
7710
7711   if (Subtarget.hasQPX()) {
7712     if (VT.getVectorNumElements() != 4)
7713       return SDValue();
7714
7715     if (V2.isUndef()) V2 = V1;
7716
7717     int AlignIdx = PPC::isQVALIGNIShuffleMask(SVOp);
7718     if (AlignIdx != -1) {
7719       return DAG.getNode(PPCISD::QVALIGNI, dl, VT, V1, V2,
7720                          DAG.getConstant(AlignIdx, dl, MVT::i32));
7721     } else if (SVOp->isSplat()) {
7722       int SplatIdx = SVOp->getSplatIndex();
7723       if (SplatIdx >= 4) {
7724         std::swap(V1, V2);
7725         SplatIdx -= 4;
7726       }
7727
7728       return DAG.getNode(PPCISD::QVESPLATI, dl, VT, V1,
7729                          DAG.getConstant(SplatIdx, dl, MVT::i32));
7730     }
7731
7732     // Lower this into a qvgpci/qvfperm pair.
7733
7734     // Compute the qvgpci literal
7735     unsigned idx = 0;
7736     for (unsigned i = 0; i < 4; ++i) {
7737       int m = SVOp->getMaskElt(i);
7738       unsigned mm = m >= 0 ? (unsigned) m : i;
7739       idx |= mm << (3-i)*3;
7740     }
7741
7742     SDValue V3 = DAG.getNode(PPCISD::QVGPCI, dl, MVT::v4f64,
7743                              DAG.getConstant(idx, dl, MVT::i32));
7744     return DAG.getNode(PPCISD::QVFPERM, dl, VT, V1, V2, V3);
7745   }
7746
7747   // Cases that are handled by instructions that take permute immediates
7748   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
7749   // selected by the instruction selector.
7750   if (V2.isUndef()) {
7751     if (PPC::isSplatShuffleMask(SVOp, 1) ||
7752         PPC::isSplatShuffleMask(SVOp, 2) ||
7753         PPC::isSplatShuffleMask(SVOp, 4) ||
7754         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
7755         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
7756         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
7757         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
7758         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
7759         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
7760         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
7761         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
7762         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG) ||
7763         (Subtarget.hasP8Altivec() && (
7764          PPC::isVPKUDUMShuffleMask(SVOp, 1, DAG) ||
7765          PPC::isVMRGEOShuffleMask(SVOp, true, 1, DAG) ||
7766          PPC::isVMRGEOShuffleMask(SVOp, false, 1, DAG)))) {
7767       return Op;
7768     }
7769   }
7770
7771   // Altivec has a variety of "shuffle immediates" that take two vector inputs
7772   // and produce a fixed permutation.  If any of these match, do not lower to
7773   // VPERM.
7774   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
7775   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7776       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7777       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
7778       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7779       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7780       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7781       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
7782       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
7783       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
7784       (Subtarget.hasP8Altivec() && (
7785        PPC::isVPKUDUMShuffleMask(SVOp, ShuffleKind, DAG) ||
7786        PPC::isVMRGEOShuffleMask(SVOp, true, ShuffleKind, DAG) ||
7787        PPC::isVMRGEOShuffleMask(SVOp, false, ShuffleKind, DAG))))
7788     return Op;
7789
7790   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
7791   // perfect shuffle table to emit an optimal matching sequence.
7792   ArrayRef<int> PermMask = SVOp->getMask();
7793
7794   unsigned PFIndexes[4];
7795   bool isFourElementShuffle = true;
7796   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
7797     unsigned EltNo = 8;   // Start out undef.
7798     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
7799       if (PermMask[i*4+j] < 0)
7800         continue;   // Undef, ignore it.
7801
7802       unsigned ByteSource = PermMask[i*4+j];
7803       if ((ByteSource & 3) != j) {
7804         isFourElementShuffle = false;
7805         break;
7806       }
7807
7808       if (EltNo == 8) {
7809         EltNo = ByteSource/4;
7810       } else if (EltNo != ByteSource/4) {
7811         isFourElementShuffle = false;
7812         break;
7813       }
7814     }
7815     PFIndexes[i] = EltNo;
7816   }
7817
7818   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
7819   // perfect shuffle vector to determine if it is cost effective to do this as
7820   // discrete instructions, or whether we should use a vperm.
7821   // For now, we skip this for little endian until such time as we have a
7822   // little-endian perfect shuffle table.
7823   if (isFourElementShuffle && !isLittleEndian) {
7824     // Compute the index in the perfect shuffle table.
7825     unsigned PFTableIndex =
7826       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7827
7828     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7829     unsigned Cost  = (PFEntry >> 30);
7830
7831     // Determining when to avoid vperm is tricky.  Many things affect the cost
7832     // of vperm, particularly how many times the perm mask needs to be computed.
7833     // For example, if the perm mask can be hoisted out of a loop or is already
7834     // used (perhaps because there are multiple permutes with the same shuffle
7835     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
7836     // the loop requires an extra register.
7837     //
7838     // As a compromise, we only emit discrete instructions if the shuffle can be
7839     // generated in 3 or fewer operations.  When we have loop information
7840     // available, if this block is within a loop, we should avoid using vperm
7841     // for 3-operation perms and use a constant pool load instead.
7842     if (Cost < 3)
7843       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7844   }
7845
7846   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
7847   // vector that will get spilled to the constant pool.
7848   if (V2.isUndef()) V2 = V1;
7849
7850   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
7851   // that it is in input element units, not in bytes.  Convert now.
7852
7853   // For little endian, the order of the input vectors is reversed, and
7854   // the permutation mask is complemented with respect to 31.  This is
7855   // necessary to produce proper semantics with the big-endian-biased vperm
7856   // instruction.
7857   EVT EltVT = V1.getValueType().getVectorElementType();
7858   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
7859
7860   SmallVector<SDValue, 16> ResultMask;
7861   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
7862     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
7863
7864     for (unsigned j = 0; j != BytesPerElement; ++j)
7865       if (isLittleEndian)
7866         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement + j),
7867                                              dl, MVT::i32));
7868       else
7869         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement + j, dl,
7870                                              MVT::i32));
7871   }
7872
7873   SDValue VPermMask = DAG.getBuildVector(MVT::v16i8, dl, ResultMask);
7874   if (isLittleEndian)
7875     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7876                        V2, V1, VPermMask);
7877   else
7878     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
7879                        V1, V2, VPermMask);
7880 }
7881
7882 /// getVectorCompareInfo - Given an intrinsic, return false if it is not a
7883 /// vector comparison.  If it is, return true and fill in Opc/isDot with
7884 /// information about the intrinsic.
7885 static bool getVectorCompareInfo(SDValue Intrin, int &CompareOpc,
7886                                  bool &isDot, const PPCSubtarget &Subtarget) {
7887   unsigned IntrinsicID =
7888       cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
7889   CompareOpc = -1;
7890   isDot = false;
7891   switch (IntrinsicID) {
7892   default:
7893     return false;
7894   // Comparison predicates.
7895   case Intrinsic::ppc_altivec_vcmpbfp_p:
7896     CompareOpc = 966;
7897     isDot = true;
7898     break;
7899   case Intrinsic::ppc_altivec_vcmpeqfp_p:
7900     CompareOpc = 198;
7901     isDot = true;
7902     break;
7903   case Intrinsic::ppc_altivec_vcmpequb_p:
7904     CompareOpc = 6;
7905     isDot = true;
7906     break;
7907   case Intrinsic::ppc_altivec_vcmpequh_p:
7908     CompareOpc = 70;
7909     isDot = true;
7910     break;
7911   case Intrinsic::ppc_altivec_vcmpequw_p:
7912     CompareOpc = 134;
7913     isDot = true;
7914     break;
7915   case Intrinsic::ppc_altivec_vcmpequd_p:
7916     if (Subtarget.hasP8Altivec()) {
7917       CompareOpc = 199;
7918       isDot = true;
7919     } else
7920       return false;
7921     break;
7922   case Intrinsic::ppc_altivec_vcmpneb_p:
7923   case Intrinsic::ppc_altivec_vcmpneh_p:
7924   case Intrinsic::ppc_altivec_vcmpnew_p:
7925   case Intrinsic::ppc_altivec_vcmpnezb_p:
7926   case Intrinsic::ppc_altivec_vcmpnezh_p:
7927   case Intrinsic::ppc_altivec_vcmpnezw_p:
7928     if (Subtarget.hasP9Altivec()) {
7929       switch (IntrinsicID) {
7930       default:
7931         llvm_unreachable("Unknown comparison intrinsic.");
7932       case Intrinsic::ppc_altivec_vcmpneb_p:
7933         CompareOpc = 7;
7934         break;
7935       case Intrinsic::ppc_altivec_vcmpneh_p:
7936         CompareOpc = 71;
7937         break;
7938       case Intrinsic::ppc_altivec_vcmpnew_p:
7939         CompareOpc = 135;
7940         break;
7941       case Intrinsic::ppc_altivec_vcmpnezb_p:
7942         CompareOpc = 263;
7943         break;
7944       case Intrinsic::ppc_altivec_vcmpnezh_p:
7945         CompareOpc = 327;
7946         break;
7947       case Intrinsic::ppc_altivec_vcmpnezw_p:
7948         CompareOpc = 391;
7949         break;
7950       }
7951       isDot = true;
7952     } else
7953       return false;
7954     break;
7955   case Intrinsic::ppc_altivec_vcmpgefp_p:
7956     CompareOpc = 454;
7957     isDot = true;
7958     break;
7959   case Intrinsic::ppc_altivec_vcmpgtfp_p:
7960     CompareOpc = 710;
7961     isDot = true;
7962     break;
7963   case Intrinsic::ppc_altivec_vcmpgtsb_p:
7964     CompareOpc = 774;
7965     isDot = true;
7966     break;
7967   case Intrinsic::ppc_altivec_vcmpgtsh_p:
7968     CompareOpc = 838;
7969     isDot = true;
7970     break;
7971   case Intrinsic::ppc_altivec_vcmpgtsw_p:
7972     CompareOpc = 902;
7973     isDot = true;
7974     break;
7975   case Intrinsic::ppc_altivec_vcmpgtsd_p:
7976     if (Subtarget.hasP8Altivec()) {
7977       CompareOpc = 967;
7978       isDot = true;
7979     } else
7980       return false;
7981     break;
7982   case Intrinsic::ppc_altivec_vcmpgtub_p:
7983     CompareOpc = 518;
7984     isDot = true;
7985     break;
7986   case Intrinsic::ppc_altivec_vcmpgtuh_p:
7987     CompareOpc = 582;
7988     isDot = true;
7989     break;
7990   case Intrinsic::ppc_altivec_vcmpgtuw_p:
7991     CompareOpc = 646;
7992     isDot = true;
7993     break;
7994   case Intrinsic::ppc_altivec_vcmpgtud_p:
7995     if (Subtarget.hasP8Altivec()) {
7996       CompareOpc = 711;
7997       isDot = true;
7998     } else
7999       return false;
8000     break;
8001
8002   // VSX predicate comparisons use the same infrastructure
8003   case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8004   case Intrinsic::ppc_vsx_xvcmpgedp_p:
8005   case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8006   case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8007   case Intrinsic::ppc_vsx_xvcmpgesp_p:
8008   case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8009     if (Subtarget.hasVSX()) {
8010       switch (IntrinsicID) {
8011       case Intrinsic::ppc_vsx_xvcmpeqdp_p:
8012         CompareOpc = 99;
8013         break;
8014       case Intrinsic::ppc_vsx_xvcmpgedp_p:
8015         CompareOpc = 115;
8016         break;
8017       case Intrinsic::ppc_vsx_xvcmpgtdp_p:
8018         CompareOpc = 107;
8019         break;
8020       case Intrinsic::ppc_vsx_xvcmpeqsp_p:
8021         CompareOpc = 67;
8022         break;
8023       case Intrinsic::ppc_vsx_xvcmpgesp_p:
8024         CompareOpc = 83;
8025         break;
8026       case Intrinsic::ppc_vsx_xvcmpgtsp_p:
8027         CompareOpc = 75;
8028         break;
8029       }
8030       isDot = true;
8031     } else
8032       return false;
8033     break;
8034
8035   // Normal Comparisons.
8036   case Intrinsic::ppc_altivec_vcmpbfp:
8037     CompareOpc = 966;
8038     break;
8039   case Intrinsic::ppc_altivec_vcmpeqfp:
8040     CompareOpc = 198;
8041     break;
8042   case Intrinsic::ppc_altivec_vcmpequb:
8043     CompareOpc = 6;
8044     break;
8045   case Intrinsic::ppc_altivec_vcmpequh:
8046     CompareOpc = 70;
8047     break;
8048   case Intrinsic::ppc_altivec_vcmpequw:
8049     CompareOpc = 134;
8050     break;
8051   case Intrinsic::ppc_altivec_vcmpequd:
8052     if (Subtarget.hasP8Altivec())
8053       CompareOpc = 199;
8054     else
8055       return false;
8056     break;
8057   case Intrinsic::ppc_altivec_vcmpneb:
8058   case Intrinsic::ppc_altivec_vcmpneh:
8059   case Intrinsic::ppc_altivec_vcmpnew:
8060   case Intrinsic::ppc_altivec_vcmpnezb:
8061   case Intrinsic::ppc_altivec_vcmpnezh:
8062   case Intrinsic::ppc_altivec_vcmpnezw:
8063     if (Subtarget.hasP9Altivec())
8064       switch (IntrinsicID) {
8065       default:
8066         llvm_unreachable("Unknown comparison intrinsic.");
8067       case Intrinsic::ppc_altivec_vcmpneb:
8068         CompareOpc = 7;
8069         break;
8070       case Intrinsic::ppc_altivec_vcmpneh:
8071         CompareOpc = 71;
8072         break;
8073       case Intrinsic::ppc_altivec_vcmpnew:
8074         CompareOpc = 135;
8075         break;
8076       case Intrinsic::ppc_altivec_vcmpnezb:
8077         CompareOpc = 263;
8078         break;
8079       case Intrinsic::ppc_altivec_vcmpnezh:
8080         CompareOpc = 327;
8081         break;
8082       case Intrinsic::ppc_altivec_vcmpnezw:
8083         CompareOpc = 391;
8084         break;
8085       }
8086     else
8087       return false;
8088     break;
8089   case Intrinsic::ppc_altivec_vcmpgefp:
8090     CompareOpc = 454;
8091     break;
8092   case Intrinsic::ppc_altivec_vcmpgtfp:
8093     CompareOpc = 710;
8094     break;
8095   case Intrinsic::ppc_altivec_vcmpgtsb:
8096     CompareOpc = 774;
8097     break;
8098   case Intrinsic::ppc_altivec_vcmpgtsh:
8099     CompareOpc = 838;
8100     break;
8101   case Intrinsic::ppc_altivec_vcmpgtsw:
8102     CompareOpc = 902;
8103     break;
8104   case Intrinsic::ppc_altivec_vcmpgtsd:
8105     if (Subtarget.hasP8Altivec())
8106       CompareOpc = 967;
8107     else
8108       return false;
8109     break;
8110   case Intrinsic::ppc_altivec_vcmpgtub:
8111     CompareOpc = 518;
8112     break;
8113   case Intrinsic::ppc_altivec_vcmpgtuh:
8114     CompareOpc = 582;
8115     break;
8116   case Intrinsic::ppc_altivec_vcmpgtuw:
8117     CompareOpc = 646;
8118     break;
8119   case Intrinsic::ppc_altivec_vcmpgtud:
8120     if (Subtarget.hasP8Altivec())
8121       CompareOpc = 711;
8122     else
8123       return false;
8124     break;
8125   }
8126   return true;
8127 }
8128
8129 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
8130 /// lower, do it, otherwise return null.
8131 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
8132                                                    SelectionDAG &DAG) const {
8133   unsigned IntrinsicID =
8134     cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8135
8136   if (IntrinsicID == Intrinsic::thread_pointer) {
8137     // Reads the thread pointer register, used for __builtin_thread_pointer.
8138     bool is64bit = Subtarget.isPPC64();
8139     return DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
8140                            is64bit ? MVT::i64 : MVT::i32);
8141   }
8142
8143   // If this is a lowered altivec predicate compare, CompareOpc is set to the
8144   // opcode number of the comparison.
8145   SDLoc dl(Op);
8146   int CompareOpc;
8147   bool isDot;
8148   if (!getVectorCompareInfo(Op, CompareOpc, isDot, Subtarget))
8149     return SDValue();    // Don't custom lower most intrinsics.
8150
8151   // If this is a non-dot comparison, make the VCMP node and we are done.
8152   if (!isDot) {
8153     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
8154                               Op.getOperand(1), Op.getOperand(2),
8155                               DAG.getConstant(CompareOpc, dl, MVT::i32));
8156     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
8157   }
8158
8159   // Create the PPCISD altivec 'dot' comparison node.
8160   SDValue Ops[] = {
8161     Op.getOperand(2),  // LHS
8162     Op.getOperand(3),  // RHS
8163     DAG.getConstant(CompareOpc, dl, MVT::i32)
8164   };
8165   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
8166   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8167
8168   // Now that we have the comparison, emit a copy from the CR to a GPR.
8169   // This is flagged to the above dot comparison.
8170   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
8171                                 DAG.getRegister(PPC::CR6, MVT::i32),
8172                                 CompNode.getValue(1));
8173
8174   // Unpack the result based on how the target uses it.
8175   unsigned BitNo;   // Bit # of CR6.
8176   bool InvertBit;   // Invert result?
8177   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
8178   default:  // Can't happen, don't crash on invalid number though.
8179   case 0:   // Return the value of the EQ bit of CR6.
8180     BitNo = 0; InvertBit = false;
8181     break;
8182   case 1:   // Return the inverted value of the EQ bit of CR6.
8183     BitNo = 0; InvertBit = true;
8184     break;
8185   case 2:   // Return the value of the LT bit of CR6.
8186     BitNo = 2; InvertBit = false;
8187     break;
8188   case 3:   // Return the inverted value of the LT bit of CR6.
8189     BitNo = 2; InvertBit = true;
8190     break;
8191   }
8192
8193   // Shift the bit into the low position.
8194   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
8195                       DAG.getConstant(8 - (3 - BitNo), dl, MVT::i32));
8196   // Isolate the bit.
8197   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
8198                       DAG.getConstant(1, dl, MVT::i32));
8199
8200   // If we are supposed to, toggle the bit.
8201   if (InvertBit)
8202     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
8203                         DAG.getConstant(1, dl, MVT::i32));
8204   return Flags;
8205 }
8206
8207 SDValue PPCTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
8208                                                SelectionDAG &DAG) const {
8209   // SelectionDAGBuilder::visitTargetIntrinsic may insert one extra chain to
8210   // the beginning of the argument list.
8211   int ArgStart = isa<ConstantSDNode>(Op.getOperand(0)) ? 0 : 1;
8212   SDLoc DL(Op);
8213   switch (cast<ConstantSDNode>(Op.getOperand(ArgStart))->getZExtValue()) {
8214   case Intrinsic::ppc_cfence: {
8215     assert(Subtarget.isPPC64() && "Only 64-bit is supported for now.");
8216     return SDValue(DAG.getMachineNode(PPC::CFENCE8, DL, MVT::Other,
8217                                       DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64,
8218                                                   Op.getOperand(ArgStart + 1))),
8219                    0);
8220   }
8221   default:
8222     break;
8223   }
8224   return SDValue();
8225 }
8226
8227 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
8228                                                   SelectionDAG &DAG) const {
8229   SDLoc dl(Op);
8230   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
8231   // instructions), but for smaller types, we need to first extend up to v2i32
8232   // before doing going farther.
8233   if (Op.getValueType() == MVT::v2i64) {
8234     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
8235     if (ExtVT != MVT::v2i32) {
8236       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
8237       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
8238                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
8239                                         ExtVT.getVectorElementType(), 4)));
8240       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
8241       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
8242                        DAG.getValueType(MVT::v2i32));
8243     }
8244
8245     return Op;
8246   }
8247
8248   return SDValue();
8249 }
8250
8251 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
8252                                                  SelectionDAG &DAG) const {
8253   SDLoc dl(Op);
8254   // Create a stack slot that is 16-byte aligned.
8255   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8256   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8257   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8258   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8259
8260   // Store the input value into Value#0 of the stack slot.
8261   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
8262                                MachinePointerInfo());
8263   // Load it out.
8264   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo());
8265 }
8266
8267 SDValue PPCTargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
8268                                                   SelectionDAG &DAG) const {
8269   assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT &&
8270          "Should only be called for ISD::INSERT_VECTOR_ELT");
8271   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(2));
8272   // We have legal lowering for constant indices but not for variable ones.
8273   if (C)
8274     return Op;
8275   return SDValue();
8276 }
8277
8278 SDValue PPCTargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8279                                                    SelectionDAG &DAG) const {
8280   SDLoc dl(Op);
8281   SDNode *N = Op.getNode();
8282
8283   assert(N->getOperand(0).getValueType() == MVT::v4i1 &&
8284          "Unknown extract_vector_elt type");
8285
8286   SDValue Value = N->getOperand(0);
8287
8288   // The first part of this is like the store lowering except that we don't
8289   // need to track the chain.
8290
8291   // The values are now known to be -1 (false) or 1 (true). To convert this
8292   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8293   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8294   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8295
8296   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8297   // understand how to form the extending load.
8298   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8299
8300   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8301
8302   // Now convert to an integer and store.
8303   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8304     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8305     Value);
8306
8307   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8308   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8309   MachinePointerInfo PtrInfo =
8310       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8311   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8312   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8313
8314   SDValue StoreChain = DAG.getEntryNode();
8315   SDValue Ops[] = {StoreChain,
8316                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8317                    Value, FIdx};
8318   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8319
8320   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8321     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8322
8323   // Extract the value requested.
8324   unsigned Offset = 4*cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8325   SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8326   Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8327
8328   SDValue IntVal =
8329       DAG.getLoad(MVT::i32, dl, StoreChain, Idx, PtrInfo.getWithOffset(Offset));
8330
8331   if (!Subtarget.useCRBits())
8332     return IntVal;
8333
8334   return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, IntVal);
8335 }
8336
8337 /// Lowering for QPX v4i1 loads
8338 SDValue PPCTargetLowering::LowerVectorLoad(SDValue Op,
8339                                            SelectionDAG &DAG) const {
8340   SDLoc dl(Op);
8341   LoadSDNode *LN = cast<LoadSDNode>(Op.getNode());
8342   SDValue LoadChain = LN->getChain();
8343   SDValue BasePtr = LN->getBasePtr();
8344
8345   if (Op.getValueType() == MVT::v4f64 ||
8346       Op.getValueType() == MVT::v4f32) {
8347     EVT MemVT = LN->getMemoryVT();
8348     unsigned Alignment = LN->getAlignment();
8349
8350     // If this load is properly aligned, then it is legal.
8351     if (Alignment >= MemVT.getStoreSize())
8352       return Op;
8353
8354     EVT ScalarVT = Op.getValueType().getScalarType(),
8355         ScalarMemVT = MemVT.getScalarType();
8356     unsigned Stride = ScalarMemVT.getStoreSize();
8357
8358     SDValue Vals[4], LoadChains[4];
8359     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8360       SDValue Load;
8361       if (ScalarVT != ScalarMemVT)
8362         Load = DAG.getExtLoad(LN->getExtensionType(), dl, ScalarVT, LoadChain,
8363                               BasePtr,
8364                               LN->getPointerInfo().getWithOffset(Idx * Stride),
8365                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8366                               LN->getMemOperand()->getFlags(), LN->getAAInfo());
8367       else
8368         Load = DAG.getLoad(ScalarVT, dl, LoadChain, BasePtr,
8369                            LN->getPointerInfo().getWithOffset(Idx * Stride),
8370                            MinAlign(Alignment, Idx * Stride),
8371                            LN->getMemOperand()->getFlags(), LN->getAAInfo());
8372
8373       if (Idx == 0 && LN->isIndexed()) {
8374         assert(LN->getAddressingMode() == ISD::PRE_INC &&
8375                "Unknown addressing mode on vector load");
8376         Load = DAG.getIndexedLoad(Load, dl, BasePtr, LN->getOffset(),
8377                                   LN->getAddressingMode());
8378       }
8379
8380       Vals[Idx] = Load;
8381       LoadChains[Idx] = Load.getValue(1);
8382
8383       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8384                             DAG.getConstant(Stride, dl,
8385                                             BasePtr.getValueType()));
8386     }
8387
8388     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8389     SDValue Value = DAG.getBuildVector(Op.getValueType(), dl, Vals);
8390
8391     if (LN->isIndexed()) {
8392       SDValue RetOps[] = { Value, Vals[0].getValue(1), TF };
8393       return DAG.getMergeValues(RetOps, dl);
8394     }
8395
8396     SDValue RetOps[] = { Value, TF };
8397     return DAG.getMergeValues(RetOps, dl);
8398   }
8399
8400   assert(Op.getValueType() == MVT::v4i1 && "Unknown load to lower");
8401   assert(LN->isUnindexed() && "Indexed v4i1 loads are not supported");
8402
8403   // To lower v4i1 from a byte array, we load the byte elements of the
8404   // vector and then reuse the BUILD_VECTOR logic.
8405
8406   SDValue VectElmts[4], VectElmtChains[4];
8407   for (unsigned i = 0; i < 4; ++i) {
8408     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8409     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8410
8411     VectElmts[i] = DAG.getExtLoad(
8412         ISD::EXTLOAD, dl, MVT::i32, LoadChain, Idx,
8413         LN->getPointerInfo().getWithOffset(i), MVT::i8,
8414         /* Alignment = */ 1, LN->getMemOperand()->getFlags(), LN->getAAInfo());
8415     VectElmtChains[i] = VectElmts[i].getValue(1);
8416   }
8417
8418   LoadChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, VectElmtChains);
8419   SDValue Value = DAG.getBuildVector(MVT::v4i1, dl, VectElmts);
8420
8421   SDValue RVals[] = { Value, LoadChain };
8422   return DAG.getMergeValues(RVals, dl);
8423 }
8424
8425 /// Lowering for QPX v4i1 stores
8426 SDValue PPCTargetLowering::LowerVectorStore(SDValue Op,
8427                                             SelectionDAG &DAG) const {
8428   SDLoc dl(Op);
8429   StoreSDNode *SN = cast<StoreSDNode>(Op.getNode());
8430   SDValue StoreChain = SN->getChain();
8431   SDValue BasePtr = SN->getBasePtr();
8432   SDValue Value = SN->getValue();
8433
8434   if (Value.getValueType() == MVT::v4f64 ||
8435       Value.getValueType() == MVT::v4f32) {
8436     EVT MemVT = SN->getMemoryVT();
8437     unsigned Alignment = SN->getAlignment();
8438
8439     // If this store is properly aligned, then it is legal.
8440     if (Alignment >= MemVT.getStoreSize())
8441       return Op;
8442
8443     EVT ScalarVT = Value.getValueType().getScalarType(),
8444         ScalarMemVT = MemVT.getScalarType();
8445     unsigned Stride = ScalarMemVT.getStoreSize();
8446
8447     SDValue Stores[4];
8448     for (unsigned Idx = 0; Idx < 4; ++Idx) {
8449       SDValue Ex = DAG.getNode(
8450           ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, Value,
8451           DAG.getConstant(Idx, dl, getVectorIdxTy(DAG.getDataLayout())));
8452       SDValue Store;
8453       if (ScalarVT != ScalarMemVT)
8454         Store =
8455             DAG.getTruncStore(StoreChain, dl, Ex, BasePtr,
8456                               SN->getPointerInfo().getWithOffset(Idx * Stride),
8457                               ScalarMemVT, MinAlign(Alignment, Idx * Stride),
8458                               SN->getMemOperand()->getFlags(), SN->getAAInfo());
8459       else
8460         Store = DAG.getStore(StoreChain, dl, Ex, BasePtr,
8461                              SN->getPointerInfo().getWithOffset(Idx * Stride),
8462                              MinAlign(Alignment, Idx * Stride),
8463                              SN->getMemOperand()->getFlags(), SN->getAAInfo());
8464
8465       if (Idx == 0 && SN->isIndexed()) {
8466         assert(SN->getAddressingMode() == ISD::PRE_INC &&
8467                "Unknown addressing mode on vector store");
8468         Store = DAG.getIndexedStore(Store, dl, BasePtr, SN->getOffset(),
8469                                     SN->getAddressingMode());
8470       }
8471
8472       BasePtr = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
8473                             DAG.getConstant(Stride, dl,
8474                                             BasePtr.getValueType()));
8475       Stores[Idx] = Store;
8476     }
8477
8478     SDValue TF =  DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8479
8480     if (SN->isIndexed()) {
8481       SDValue RetOps[] = { TF, Stores[0].getValue(1) };
8482       return DAG.getMergeValues(RetOps, dl);
8483     }
8484
8485     return TF;
8486   }
8487
8488   assert(SN->isUnindexed() && "Indexed v4i1 stores are not supported");
8489   assert(Value.getValueType() == MVT::v4i1 && "Unknown store to lower");
8490
8491   // The values are now known to be -1 (false) or 1 (true). To convert this
8492   // into 0 (false) and 1 (true), add 1 and then divide by 2 (multiply by 0.5).
8493   // This can be done with an fma and the 0.5 constant: (V+1.0)*0.5 = 0.5*V+0.5
8494   Value = DAG.getNode(PPCISD::QBFLT, dl, MVT::v4f64, Value);
8495
8496   // FIXME: We can make this an f32 vector, but the BUILD_VECTOR code needs to
8497   // understand how to form the extending load.
8498   SDValue FPHalfs = DAG.getConstantFP(0.5, dl, MVT::v4f64);
8499
8500   Value = DAG.getNode(ISD::FMA, dl, MVT::v4f64, Value, FPHalfs, FPHalfs);
8501
8502   // Now convert to an integer and store.
8503   Value = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f64,
8504     DAG.getConstant(Intrinsic::ppc_qpx_qvfctiwu, dl, MVT::i32),
8505     Value);
8506
8507   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8508   int FrameIdx = MFI.CreateStackObject(16, 16, false);
8509   MachinePointerInfo PtrInfo =
8510       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FrameIdx);
8511   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8512   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
8513
8514   SDValue Ops[] = {StoreChain,
8515                    DAG.getConstant(Intrinsic::ppc_qpx_qvstfiw, dl, MVT::i32),
8516                    Value, FIdx};
8517   SDVTList VTs = DAG.getVTList(/*chain*/ MVT::Other);
8518
8519   StoreChain = DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID,
8520     dl, VTs, Ops, MVT::v4i32, PtrInfo);
8521
8522   // Move data into the byte array.
8523   SDValue Loads[4], LoadChains[4];
8524   for (unsigned i = 0; i < 4; ++i) {
8525     unsigned Offset = 4*i;
8526     SDValue Idx = DAG.getConstant(Offset, dl, FIdx.getValueType());
8527     Idx = DAG.getNode(ISD::ADD, dl, FIdx.getValueType(), FIdx, Idx);
8528
8529     Loads[i] = DAG.getLoad(MVT::i32, dl, StoreChain, Idx,
8530                            PtrInfo.getWithOffset(Offset));
8531     LoadChains[i] = Loads[i].getValue(1);
8532   }
8533
8534   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
8535
8536   SDValue Stores[4];
8537   for (unsigned i = 0; i < 4; ++i) {
8538     SDValue Idx = DAG.getConstant(i, dl, BasePtr.getValueType());
8539     Idx = DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr, Idx);
8540
8541     Stores[i] = DAG.getTruncStore(
8542         StoreChain, dl, Loads[i], Idx, SN->getPointerInfo().getWithOffset(i),
8543         MVT::i8, /* Alignment = */ 1, SN->getMemOperand()->getFlags(),
8544         SN->getAAInfo());
8545   }
8546
8547   StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8548
8549   return StoreChain;
8550 }
8551
8552 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
8553   SDLoc dl(Op);
8554   if (Op.getValueType() == MVT::v4i32) {
8555     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8556
8557     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
8558     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
8559
8560     SDValue RHSSwap =   // = vrlw RHS, 16
8561       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
8562
8563     // Shrinkify inputs to v8i16.
8564     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
8565     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
8566     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
8567
8568     // Low parts multiplied together, generating 32-bit results (we ignore the
8569     // top parts).
8570     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
8571                                         LHS, RHS, DAG, dl, MVT::v4i32);
8572
8573     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
8574                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
8575     // Shift the high parts up 16 bits.
8576     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
8577                               Neg16, DAG, dl);
8578     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
8579   } else if (Op.getValueType() == MVT::v8i16) {
8580     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8581
8582     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
8583
8584     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
8585                             LHS, RHS, Zero, DAG, dl);
8586   } else if (Op.getValueType() == MVT::v16i8) {
8587     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
8588     bool isLittleEndian = Subtarget.isLittleEndian();
8589
8590     // Multiply the even 8-bit parts, producing 16-bit sums.
8591     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
8592                                            LHS, RHS, DAG, dl, MVT::v8i16);
8593     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
8594
8595     // Multiply the odd 8-bit parts, producing 16-bit sums.
8596     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
8597                                           LHS, RHS, DAG, dl, MVT::v8i16);
8598     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
8599
8600     // Merge the results together.  Because vmuleub and vmuloub are
8601     // instructions with a big-endian bias, we must reverse the
8602     // element numbering and reverse the meaning of "odd" and "even"
8603     // when generating little endian code.
8604     int Ops[16];
8605     for (unsigned i = 0; i != 8; ++i) {
8606       if (isLittleEndian) {
8607         Ops[i*2  ] = 2*i;
8608         Ops[i*2+1] = 2*i+16;
8609       } else {
8610         Ops[i*2  ] = 2*i+1;
8611         Ops[i*2+1] = 2*i+1+16;
8612       }
8613     }
8614     if (isLittleEndian)
8615       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
8616     else
8617       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
8618   } else {
8619     llvm_unreachable("Unknown mul to lower!");
8620   }
8621 }
8622
8623 /// LowerOperation - Provide custom lowering hooks for some operations.
8624 ///
8625 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8626   switch (Op.getOpcode()) {
8627   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
8628   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
8629   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
8630   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
8631   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
8632   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
8633   case ISD::SETCC:              return LowerSETCC(Op, DAG);
8634   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
8635   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
8636   case ISD::VASTART:
8637     return LowerVASTART(Op, DAG);
8638
8639   case ISD::VAARG:
8640     return LowerVAARG(Op, DAG);
8641
8642   case ISD::VACOPY:
8643     return LowerVACOPY(Op, DAG);
8644
8645   case ISD::STACKRESTORE:
8646     return LowerSTACKRESTORE(Op, DAG);
8647
8648   case ISD::DYNAMIC_STACKALLOC:
8649     return LowerDYNAMIC_STACKALLOC(Op, DAG);
8650
8651   case ISD::GET_DYNAMIC_AREA_OFFSET:
8652     return LowerGET_DYNAMIC_AREA_OFFSET(Op, DAG);
8653
8654   case ISD::EH_DWARF_CFA:
8655     return LowerEH_DWARF_CFA(Op, DAG);
8656
8657   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
8658   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
8659
8660   case ISD::LOAD:               return LowerLOAD(Op, DAG);
8661   case ISD::STORE:              return LowerSTORE(Op, DAG);
8662   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
8663   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
8664   case ISD::FP_TO_UINT:
8665   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
8666                                                       SDLoc(Op));
8667   case ISD::UINT_TO_FP:
8668   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
8669   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
8670
8671   // Lower 64-bit shifts.
8672   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
8673   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
8674   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
8675
8676   // Vector-related lowering.
8677   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
8678   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
8679   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8680   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
8681   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
8682   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8683   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
8684   case ISD::MUL:                return LowerMUL(Op, DAG);
8685
8686   // For counter-based loop handling.
8687   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
8688
8689   // Frame & Return address.
8690   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
8691   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
8692
8693   case ISD::INTRINSIC_VOID:
8694     return LowerINTRINSIC_VOID(Op, DAG);
8695   }
8696 }
8697
8698 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
8699                                            SmallVectorImpl<SDValue>&Results,
8700                                            SelectionDAG &DAG) const {
8701   SDLoc dl(N);
8702   switch (N->getOpcode()) {
8703   default:
8704     llvm_unreachable("Do not know how to custom type legalize this operation!");
8705   case ISD::READCYCLECOUNTER: {
8706     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8707     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
8708
8709     Results.push_back(RTB);
8710     Results.push_back(RTB.getValue(1));
8711     Results.push_back(RTB.getValue(2));
8712     break;
8713   }
8714   case ISD::INTRINSIC_W_CHAIN: {
8715     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
8716         Intrinsic::ppc_is_decremented_ctr_nonzero)
8717       break;
8718
8719     assert(N->getValueType(0) == MVT::i1 &&
8720            "Unexpected result type for CTR decrement intrinsic");
8721     EVT SVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
8722                                  N->getValueType(0));
8723     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
8724     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
8725                                  N->getOperand(1));
8726
8727     Results.push_back(NewInt);
8728     Results.push_back(NewInt.getValue(1));
8729     break;
8730   }
8731   case ISD::VAARG: {
8732     if (!Subtarget.isSVR4ABI() || Subtarget.isPPC64())
8733       return;
8734
8735     EVT VT = N->getValueType(0);
8736
8737     if (VT == MVT::i64) {
8738       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG);
8739
8740       Results.push_back(NewNode);
8741       Results.push_back(NewNode.getValue(1));
8742     }
8743     return;
8744   }
8745   case ISD::FP_ROUND_INREG: {
8746     assert(N->getValueType(0) == MVT::ppcf128);
8747     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
8748     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8749                              MVT::f64, N->getOperand(0),
8750                              DAG.getIntPtrConstant(0, dl));
8751     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
8752                              MVT::f64, N->getOperand(0),
8753                              DAG.getIntPtrConstant(1, dl));
8754
8755     // Add the two halves of the long double in round-to-zero mode.
8756     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
8757
8758     // We know the low half is about to be thrown away, so just use something
8759     // convenient.
8760     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
8761                                 FPreg, FPreg));
8762     return;
8763   }
8764   case ISD::FP_TO_SINT:
8765   case ISD::FP_TO_UINT:
8766     // LowerFP_TO_INT() can only handle f32 and f64.
8767     if (N->getOperand(0).getValueType() == MVT::ppcf128)
8768       return;
8769     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
8770     return;
8771   }
8772 }
8773
8774 //===----------------------------------------------------------------------===//
8775 //  Other Lowering Code
8776 //===----------------------------------------------------------------------===//
8777
8778 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
8779   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8780   Function *Func = Intrinsic::getDeclaration(M, Id);
8781   return Builder.CreateCall(Func, {});
8782 }
8783
8784 // The mappings for emitLeading/TrailingFence is taken from
8785 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
8786 Instruction *PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
8787                                                  Instruction *Inst,
8788                                                  AtomicOrdering Ord) const {
8789   if (Ord == AtomicOrdering::SequentiallyConsistent)
8790     return callIntrinsic(Builder, Intrinsic::ppc_sync);
8791   if (isReleaseOrStronger(Ord))
8792     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8793   return nullptr;
8794 }
8795
8796 Instruction *PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
8797                                                   Instruction *Inst,
8798                                                   AtomicOrdering Ord) const {
8799   if (Inst->hasAtomicLoad() && isAcquireOrStronger(Ord)) {
8800     // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
8801     // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
8802     // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
8803     if (isa<LoadInst>(Inst) && Subtarget.isPPC64())
8804       return Builder.CreateCall(
8805           Intrinsic::getDeclaration(
8806               Builder.GetInsertBlock()->getParent()->getParent(),
8807               Intrinsic::ppc_cfence, {Inst->getType()}),
8808           {Inst});
8809     // FIXME: Can use isync for rmw operation.
8810     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
8811   }
8812   return nullptr;
8813 }
8814
8815 MachineBasicBlock *
8816 PPCTargetLowering::EmitAtomicBinary(MachineInstr &MI, MachineBasicBlock *BB,
8817                                     unsigned AtomicSize,
8818                                     unsigned BinOpcode,
8819                                     unsigned CmpOpcode,
8820                                     unsigned CmpPred) const {
8821   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8822   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8823
8824   auto LoadMnemonic = PPC::LDARX;
8825   auto StoreMnemonic = PPC::STDCX;
8826   switch (AtomicSize) {
8827   default:
8828     llvm_unreachable("Unexpected size of atomic entity");
8829   case 1:
8830     LoadMnemonic = PPC::LBARX;
8831     StoreMnemonic = PPC::STBCX;
8832     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8833     break;
8834   case 2:
8835     LoadMnemonic = PPC::LHARX;
8836     StoreMnemonic = PPC::STHCX;
8837     assert(Subtarget.hasPartwordAtomics() && "Call this only with size >=4");
8838     break;
8839   case 4:
8840     LoadMnemonic = PPC::LWARX;
8841     StoreMnemonic = PPC::STWCX;
8842     break;
8843   case 8:
8844     LoadMnemonic = PPC::LDARX;
8845     StoreMnemonic = PPC::STDCX;
8846     break;
8847   }
8848
8849   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8850   MachineFunction *F = BB->getParent();
8851   MachineFunction::iterator It = ++BB->getIterator();
8852
8853   unsigned dest = MI.getOperand(0).getReg();
8854   unsigned ptrA = MI.getOperand(1).getReg();
8855   unsigned ptrB = MI.getOperand(2).getReg();
8856   unsigned incr = MI.getOperand(3).getReg();
8857   DebugLoc dl = MI.getDebugLoc();
8858
8859   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8860   MachineBasicBlock *loop2MBB =
8861     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8862   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8863   F->insert(It, loopMBB);
8864   if (CmpOpcode)
8865     F->insert(It, loop2MBB);
8866   F->insert(It, exitMBB);
8867   exitMBB->splice(exitMBB->begin(), BB,
8868                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8869   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8870
8871   MachineRegisterInfo &RegInfo = F->getRegInfo();
8872   unsigned TmpReg = (!BinOpcode) ? incr :
8873     RegInfo.createVirtualRegister( AtomicSize == 8 ? &PPC::G8RCRegClass
8874                                            : &PPC::GPRCRegClass);
8875
8876   //  thisMBB:
8877   //   ...
8878   //   fallthrough --> loopMBB
8879   BB->addSuccessor(loopMBB);
8880
8881   //  loopMBB:
8882   //   l[wd]arx dest, ptr
8883   //   add r0, dest, incr
8884   //   st[wd]cx. r0, ptr
8885   //   bne- loopMBB
8886   //   fallthrough --> exitMBB
8887
8888   // For max/min...
8889   //  loopMBB:
8890   //   l[wd]arx dest, ptr
8891   //   cmpl?[wd] incr, dest
8892   //   bgt exitMBB
8893   //  loop2MBB:
8894   //   st[wd]cx. dest, ptr
8895   //   bne- loopMBB
8896   //   fallthrough --> exitMBB
8897
8898   BB = loopMBB;
8899   BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
8900     .addReg(ptrA).addReg(ptrB);
8901   if (BinOpcode)
8902     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
8903   if (CmpOpcode) {
8904     // Signed comparisons of byte or halfword values must be sign-extended.
8905     if (CmpOpcode == PPC::CMPW && AtomicSize < 4) {
8906       unsigned ExtReg =  RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
8907       BuildMI(BB, dl, TII->get(AtomicSize == 1 ? PPC::EXTSB : PPC::EXTSH),
8908               ExtReg).addReg(dest);
8909       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8910         .addReg(incr).addReg(ExtReg);
8911     } else
8912       BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
8913         .addReg(incr).addReg(dest);
8914
8915     BuildMI(BB, dl, TII->get(PPC::BCC))
8916       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
8917     BB->addSuccessor(loop2MBB);
8918     BB->addSuccessor(exitMBB);
8919     BB = loop2MBB;
8920   }
8921   BuildMI(BB, dl, TII->get(StoreMnemonic))
8922     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
8923   BuildMI(BB, dl, TII->get(PPC::BCC))
8924     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
8925   BB->addSuccessor(loopMBB);
8926   BB->addSuccessor(exitMBB);
8927
8928   //  exitMBB:
8929   //   ...
8930   BB = exitMBB;
8931   return BB;
8932 }
8933
8934 MachineBasicBlock *
8935 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr &MI,
8936                                             MachineBasicBlock *BB,
8937                                             bool is8bit, // operation
8938                                             unsigned BinOpcode,
8939                                             unsigned CmpOpcode,
8940                                             unsigned CmpPred) const {
8941   // If we support part-word atomic mnemonics, just use them
8942   if (Subtarget.hasPartwordAtomics())
8943     return EmitAtomicBinary(MI, BB, is8bit ? 1 : 2, BinOpcode,
8944                             CmpOpcode, CmpPred);
8945
8946   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
8947   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
8948   // In 64 bit mode we have to use 64 bits for addresses, even though the
8949   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
8950   // registers without caring whether they're 32 or 64, but here we're
8951   // doing actual arithmetic on the addresses.
8952   bool is64bit = Subtarget.isPPC64();
8953   bool isLittleEndian = Subtarget.isLittleEndian();
8954   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
8955
8956   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8957   MachineFunction *F = BB->getParent();
8958   MachineFunction::iterator It = ++BB->getIterator();
8959
8960   unsigned dest = MI.getOperand(0).getReg();
8961   unsigned ptrA = MI.getOperand(1).getReg();
8962   unsigned ptrB = MI.getOperand(2).getReg();
8963   unsigned incr = MI.getOperand(3).getReg();
8964   DebugLoc dl = MI.getDebugLoc();
8965
8966   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
8967   MachineBasicBlock *loop2MBB =
8968     CmpOpcode ? F->CreateMachineBasicBlock(LLVM_BB) : nullptr;
8969   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
8970   F->insert(It, loopMBB);
8971   if (CmpOpcode)
8972     F->insert(It, loop2MBB);
8973   F->insert(It, exitMBB);
8974   exitMBB->splice(exitMBB->begin(), BB,
8975                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8976   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8977
8978   MachineRegisterInfo &RegInfo = F->getRegInfo();
8979   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
8980                                           : &PPC::GPRCRegClass;
8981   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
8982   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
8983   unsigned ShiftReg =
8984     isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
8985   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
8986   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
8987   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
8988   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
8989   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
8990   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
8991   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
8992   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
8993   unsigned Ptr1Reg;
8994   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
8995
8996   //  thisMBB:
8997   //   ...
8998   //   fallthrough --> loopMBB
8999   BB->addSuccessor(loopMBB);
9000
9001   // The 4-byte load must be aligned, while a char or short may be
9002   // anywhere in the word.  Hence all this nasty bookkeeping code.
9003   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9004   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9005   //   xori shift, shift1, 24 [16]
9006   //   rlwinm ptr, ptr1, 0, 0, 29
9007   //   slw incr2, incr, shift
9008   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9009   //   slw mask, mask2, shift
9010   //  loopMBB:
9011   //   lwarx tmpDest, ptr
9012   //   add tmp, tmpDest, incr2
9013   //   andc tmp2, tmpDest, mask
9014   //   and tmp3, tmp, mask
9015   //   or tmp4, tmp3, tmp2
9016   //   stwcx. tmp4, ptr
9017   //   bne- loopMBB
9018   //   fallthrough --> exitMBB
9019   //   srw dest, tmpDest, shift
9020   if (ptrA != ZeroReg) {
9021     Ptr1Reg = RegInfo.createVirtualRegister(RC);
9022     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9023       .addReg(ptrA).addReg(ptrB);
9024   } else {
9025     Ptr1Reg = ptrB;
9026   }
9027   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9028       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9029   if (!isLittleEndian)
9030     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9031         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9032   if (is64bit)
9033     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9034       .addReg(Ptr1Reg).addImm(0).addImm(61);
9035   else
9036     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9037       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9038   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
9039       .addReg(incr).addReg(ShiftReg);
9040   if (is8bit)
9041     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9042   else {
9043     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9044     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
9045   }
9046   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9047       .addReg(Mask2Reg).addReg(ShiftReg);
9048
9049   BB = loopMBB;
9050   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9051     .addReg(ZeroReg).addReg(PtrReg);
9052   if (BinOpcode)
9053     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
9054       .addReg(Incr2Reg).addReg(TmpDestReg);
9055   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
9056     .addReg(TmpDestReg).addReg(MaskReg);
9057   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
9058     .addReg(TmpReg).addReg(MaskReg);
9059   if (CmpOpcode) {
9060     // For unsigned comparisons, we can directly compare the shifted values.
9061     // For signed comparisons we shift and sign extend.
9062     unsigned SReg = RegInfo.createVirtualRegister(RC);
9063     BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), SReg)
9064       .addReg(TmpDestReg).addReg(MaskReg);
9065     unsigned ValueReg = SReg;
9066     unsigned CmpReg = Incr2Reg;
9067     if (CmpOpcode == PPC::CMPW) {
9068       ValueReg = RegInfo.createVirtualRegister(RC);
9069       BuildMI(BB, dl, TII->get(PPC::SRW), ValueReg)
9070         .addReg(SReg).addReg(ShiftReg);
9071       unsigned ValueSReg = RegInfo.createVirtualRegister(RC);
9072       BuildMI(BB, dl, TII->get(is8bit ? PPC::EXTSB : PPC::EXTSH), ValueSReg)
9073         .addReg(ValueReg);
9074       ValueReg = ValueSReg;
9075       CmpReg = incr;
9076     }
9077     BuildMI(BB, dl, TII->get(CmpOpcode), PPC::CR0)
9078       .addReg(CmpReg).addReg(ValueReg);
9079     BuildMI(BB, dl, TII->get(PPC::BCC))
9080       .addImm(CmpPred).addReg(PPC::CR0).addMBB(exitMBB);
9081     BB->addSuccessor(loop2MBB);
9082     BB->addSuccessor(exitMBB);
9083     BB = loop2MBB;
9084   }
9085   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
9086     .addReg(Tmp3Reg).addReg(Tmp2Reg);
9087   BuildMI(BB, dl, TII->get(PPC::STWCX))
9088     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
9089   BuildMI(BB, dl, TII->get(PPC::BCC))
9090     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
9091   BB->addSuccessor(loopMBB);
9092   BB->addSuccessor(exitMBB);
9093
9094   //  exitMBB:
9095   //   ...
9096   BB = exitMBB;
9097   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
9098     .addReg(ShiftReg);
9099   return BB;
9100 }
9101
9102 llvm::MachineBasicBlock *
9103 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr &MI,
9104                                     MachineBasicBlock *MBB) const {
9105   DebugLoc DL = MI.getDebugLoc();
9106   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9107   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
9108
9109   MachineFunction *MF = MBB->getParent();
9110   MachineRegisterInfo &MRI = MF->getRegInfo();
9111
9112   const BasicBlock *BB = MBB->getBasicBlock();
9113   MachineFunction::iterator I = ++MBB->getIterator();
9114
9115   // Memory Reference
9116   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9117   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9118
9119   unsigned DstReg = MI.getOperand(0).getReg();
9120   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
9121   assert(TRI->isTypeLegalForClass(*RC, MVT::i32) && "Invalid destination!");
9122   unsigned mainDstReg = MRI.createVirtualRegister(RC);
9123   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
9124
9125   MVT PVT = getPointerTy(MF->getDataLayout());
9126   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9127          "Invalid Pointer Size!");
9128   // For v = setjmp(buf), we generate
9129   //
9130   // thisMBB:
9131   //  SjLjSetup mainMBB
9132   //  bl mainMBB
9133   //  v_restore = 1
9134   //  b sinkMBB
9135   //
9136   // mainMBB:
9137   //  buf[LabelOffset] = LR
9138   //  v_main = 0
9139   //
9140   // sinkMBB:
9141   //  v = phi(main, restore)
9142   //
9143
9144   MachineBasicBlock *thisMBB = MBB;
9145   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
9146   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
9147   MF->insert(I, mainMBB);
9148   MF->insert(I, sinkMBB);
9149
9150   MachineInstrBuilder MIB;
9151
9152   // Transfer the remainder of BB and its successor edges to sinkMBB.
9153   sinkMBB->splice(sinkMBB->begin(), MBB,
9154                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9155   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
9156
9157   // Note that the structure of the jmp_buf used here is not compatible
9158   // with that used by libc, and is not designed to be. Specifically, it
9159   // stores only those 'reserved' registers that LLVM does not otherwise
9160   // understand how to spill. Also, by convention, by the time this
9161   // intrinsic is called, Clang has already stored the frame address in the
9162   // first slot of the buffer and stack address in the third. Following the
9163   // X86 target code, we'll store the jump address in the second slot. We also
9164   // need to save the TOC pointer (R2) to handle jumps between shared
9165   // libraries, and that will be stored in the fourth slot. The thread
9166   // identifier (R13) is not affected.
9167
9168   // thisMBB:
9169   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9170   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9171   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9172
9173   // Prepare IP either in reg.
9174   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
9175   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
9176   unsigned BufReg = MI.getOperand(1).getReg();
9177
9178   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
9179     setUsesTOCBasePtr(*MBB->getParent());
9180     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
9181             .addReg(PPC::X2)
9182             .addImm(TOCOffset)
9183             .addReg(BufReg);
9184     MIB.setMemRefs(MMOBegin, MMOEnd);
9185   }
9186
9187   // Naked functions never have a base pointer, and so we use r1. For all
9188   // other functions, this decision must be delayed until during PEI.
9189   unsigned BaseReg;
9190   if (MF->getFunction()->hasFnAttribute(Attribute::Naked))
9191     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
9192   else
9193     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
9194
9195   MIB = BuildMI(*thisMBB, MI, DL,
9196                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
9197             .addReg(BaseReg)
9198             .addImm(BPOffset)
9199             .addReg(BufReg);
9200   MIB.setMemRefs(MMOBegin, MMOEnd);
9201
9202   // Setup
9203   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
9204   MIB.addRegMask(TRI->getNoPreservedMask());
9205
9206   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
9207
9208   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
9209           .addMBB(mainMBB);
9210   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
9211
9212   thisMBB->addSuccessor(mainMBB, BranchProbability::getZero());
9213   thisMBB->addSuccessor(sinkMBB, BranchProbability::getOne());
9214
9215   // mainMBB:
9216   //  mainDstReg = 0
9217   MIB =
9218       BuildMI(mainMBB, DL,
9219               TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
9220
9221   // Store IP
9222   if (Subtarget.isPPC64()) {
9223     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
9224             .addReg(LabelReg)
9225             .addImm(LabelOffset)
9226             .addReg(BufReg);
9227   } else {
9228     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
9229             .addReg(LabelReg)
9230             .addImm(LabelOffset)
9231             .addReg(BufReg);
9232   }
9233
9234   MIB.setMemRefs(MMOBegin, MMOEnd);
9235
9236   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
9237   mainMBB->addSuccessor(sinkMBB);
9238
9239   // sinkMBB:
9240   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9241           TII->get(PPC::PHI), DstReg)
9242     .addReg(mainDstReg).addMBB(mainMBB)
9243     .addReg(restoreDstReg).addMBB(thisMBB);
9244
9245   MI.eraseFromParent();
9246   return sinkMBB;
9247 }
9248
9249 MachineBasicBlock *
9250 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr &MI,
9251                                      MachineBasicBlock *MBB) const {
9252   DebugLoc DL = MI.getDebugLoc();
9253   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9254
9255   MachineFunction *MF = MBB->getParent();
9256   MachineRegisterInfo &MRI = MF->getRegInfo();
9257
9258   // Memory Reference
9259   MachineInstr::mmo_iterator MMOBegin = MI.memoperands_begin();
9260   MachineInstr::mmo_iterator MMOEnd = MI.memoperands_end();
9261
9262   MVT PVT = getPointerTy(MF->getDataLayout());
9263   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
9264          "Invalid Pointer Size!");
9265
9266   const TargetRegisterClass *RC =
9267     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
9268   unsigned Tmp = MRI.createVirtualRegister(RC);
9269   // Since FP is only updated here but NOT referenced, it's treated as GPR.
9270   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
9271   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
9272   unsigned BP =
9273       (PVT == MVT::i64)
9274           ? PPC::X30
9275           : (Subtarget.isSVR4ABI() && isPositionIndependent() ? PPC::R29
9276                                                               : PPC::R30);
9277
9278   MachineInstrBuilder MIB;
9279
9280   const int64_t LabelOffset = 1 * PVT.getStoreSize();
9281   const int64_t SPOffset    = 2 * PVT.getStoreSize();
9282   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
9283   const int64_t BPOffset    = 4 * PVT.getStoreSize();
9284
9285   unsigned BufReg = MI.getOperand(0).getReg();
9286
9287   // Reload FP (the jumped-to function may not have had a
9288   // frame pointer, and if so, then its r31 will be restored
9289   // as necessary).
9290   if (PVT == MVT::i64) {
9291     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
9292             .addImm(0)
9293             .addReg(BufReg);
9294   } else {
9295     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
9296             .addImm(0)
9297             .addReg(BufReg);
9298   }
9299   MIB.setMemRefs(MMOBegin, MMOEnd);
9300
9301   // Reload IP
9302   if (PVT == MVT::i64) {
9303     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
9304             .addImm(LabelOffset)
9305             .addReg(BufReg);
9306   } else {
9307     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
9308             .addImm(LabelOffset)
9309             .addReg(BufReg);
9310   }
9311   MIB.setMemRefs(MMOBegin, MMOEnd);
9312
9313   // Reload SP
9314   if (PVT == MVT::i64) {
9315     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
9316             .addImm(SPOffset)
9317             .addReg(BufReg);
9318   } else {
9319     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
9320             .addImm(SPOffset)
9321             .addReg(BufReg);
9322   }
9323   MIB.setMemRefs(MMOBegin, MMOEnd);
9324
9325   // Reload BP
9326   if (PVT == MVT::i64) {
9327     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
9328             .addImm(BPOffset)
9329             .addReg(BufReg);
9330   } else {
9331     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
9332             .addImm(BPOffset)
9333             .addReg(BufReg);
9334   }
9335   MIB.setMemRefs(MMOBegin, MMOEnd);
9336
9337   // Reload TOC
9338   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
9339     setUsesTOCBasePtr(*MBB->getParent());
9340     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
9341             .addImm(TOCOffset)
9342             .addReg(BufReg);
9343
9344     MIB.setMemRefs(MMOBegin, MMOEnd);
9345   }
9346
9347   // Jump
9348   BuildMI(*MBB, MI, DL,
9349           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
9350   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
9351
9352   MI.eraseFromParent();
9353   return MBB;
9354 }
9355
9356 MachineBasicBlock *
9357 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9358                                                MachineBasicBlock *BB) const {
9359   if (MI.getOpcode() == TargetOpcode::STACKMAP ||
9360       MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9361     if (Subtarget.isPPC64() && Subtarget.isSVR4ABI() &&
9362         MI.getOpcode() == TargetOpcode::PATCHPOINT) {
9363       // Call lowering should have added an r2 operand to indicate a dependence
9364       // on the TOC base pointer value. It can't however, because there is no
9365       // way to mark the dependence as implicit there, and so the stackmap code
9366       // will confuse it with a regular operand. Instead, add the dependence
9367       // here.
9368       setUsesTOCBasePtr(*BB->getParent());
9369       MI.addOperand(MachineOperand::CreateReg(PPC::X2, false, true));
9370     }
9371
9372     return emitPatchPoint(MI, BB);
9373   }
9374
9375   if (MI.getOpcode() == PPC::EH_SjLj_SetJmp32 ||
9376       MI.getOpcode() == PPC::EH_SjLj_SetJmp64) {
9377     return emitEHSjLjSetJmp(MI, BB);
9378   } else if (MI.getOpcode() == PPC::EH_SjLj_LongJmp32 ||
9379              MI.getOpcode() == PPC::EH_SjLj_LongJmp64) {
9380     return emitEHSjLjLongJmp(MI, BB);
9381   }
9382
9383   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
9384
9385   // To "insert" these instructions we actually have to insert their
9386   // control-flow patterns.
9387   const BasicBlock *LLVM_BB = BB->getBasicBlock();
9388   MachineFunction::iterator It = ++BB->getIterator();
9389
9390   MachineFunction *F = BB->getParent();
9391
9392   if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9393        MI.getOpcode() == PPC::SELECT_CC_I8 ||
9394        MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8) {
9395     SmallVector<MachineOperand, 2> Cond;
9396     if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9397         MI.getOpcode() == PPC::SELECT_CC_I8)
9398       Cond.push_back(MI.getOperand(4));
9399     else
9400       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
9401     Cond.push_back(MI.getOperand(1));
9402
9403     DebugLoc dl = MI.getDebugLoc();
9404     TII->insertSelect(*BB, MI, dl, MI.getOperand(0).getReg(), Cond,
9405                       MI.getOperand(2).getReg(), MI.getOperand(3).getReg());
9406   } else if (MI.getOpcode() == PPC::SELECT_CC_I4 ||
9407              MI.getOpcode() == PPC::SELECT_CC_I8 ||
9408              MI.getOpcode() == PPC::SELECT_CC_F4 ||
9409              MI.getOpcode() == PPC::SELECT_CC_F8 ||
9410              MI.getOpcode() == PPC::SELECT_CC_QFRC ||
9411              MI.getOpcode() == PPC::SELECT_CC_QSRC ||
9412              MI.getOpcode() == PPC::SELECT_CC_QBRC ||
9413              MI.getOpcode() == PPC::SELECT_CC_VRRC ||
9414              MI.getOpcode() == PPC::SELECT_CC_VSFRC ||
9415              MI.getOpcode() == PPC::SELECT_CC_VSSRC ||
9416              MI.getOpcode() == PPC::SELECT_CC_VSRC ||
9417              MI.getOpcode() == PPC::SELECT_I4 ||
9418              MI.getOpcode() == PPC::SELECT_I8 ||
9419              MI.getOpcode() == PPC::SELECT_F4 ||
9420              MI.getOpcode() == PPC::SELECT_F8 ||
9421              MI.getOpcode() == PPC::SELECT_QFRC ||
9422              MI.getOpcode() == PPC::SELECT_QSRC ||
9423              MI.getOpcode() == PPC::SELECT_QBRC ||
9424              MI.getOpcode() == PPC::SELECT_VRRC ||
9425              MI.getOpcode() == PPC::SELECT_VSFRC ||
9426              MI.getOpcode() == PPC::SELECT_VSSRC ||
9427              MI.getOpcode() == PPC::SELECT_VSRC) {
9428     // The incoming instruction knows the destination vreg to set, the
9429     // condition code register to branch on, the true/false values to
9430     // select between, and a branch opcode to use.
9431
9432     //  thisMBB:
9433     //  ...
9434     //   TrueVal = ...
9435     //   cmpTY ccX, r1, r2
9436     //   bCC copy1MBB
9437     //   fallthrough --> copy0MBB
9438     MachineBasicBlock *thisMBB = BB;
9439     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9440     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9441     DebugLoc dl = MI.getDebugLoc();
9442     F->insert(It, copy0MBB);
9443     F->insert(It, sinkMBB);
9444
9445     // Transfer the remainder of BB and its successor edges to sinkMBB.
9446     sinkMBB->splice(sinkMBB->begin(), BB,
9447                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9448     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9449
9450     // Next, add the true and fallthrough blocks as its successors.
9451     BB->addSuccessor(copy0MBB);
9452     BB->addSuccessor(sinkMBB);
9453
9454     if (MI.getOpcode() == PPC::SELECT_I4 || MI.getOpcode() == PPC::SELECT_I8 ||
9455         MI.getOpcode() == PPC::SELECT_F4 || MI.getOpcode() == PPC::SELECT_F8 ||
9456         MI.getOpcode() == PPC::SELECT_QFRC ||
9457         MI.getOpcode() == PPC::SELECT_QSRC ||
9458         MI.getOpcode() == PPC::SELECT_QBRC ||
9459         MI.getOpcode() == PPC::SELECT_VRRC ||
9460         MI.getOpcode() == PPC::SELECT_VSFRC ||
9461         MI.getOpcode() == PPC::SELECT_VSSRC ||
9462         MI.getOpcode() == PPC::SELECT_VSRC) {
9463       BuildMI(BB, dl, TII->get(PPC::BC))
9464           .addReg(MI.getOperand(1).getReg())
9465           .addMBB(sinkMBB);
9466     } else {
9467       unsigned SelectPred = MI.getOperand(4).getImm();
9468       BuildMI(BB, dl, TII->get(PPC::BCC))
9469           .addImm(SelectPred)
9470           .addReg(MI.getOperand(1).getReg())
9471           .addMBB(sinkMBB);
9472     }
9473
9474     //  copy0MBB:
9475     //   %FalseValue = ...
9476     //   # fallthrough to sinkMBB
9477     BB = copy0MBB;
9478
9479     // Update machine-CFG edges
9480     BB->addSuccessor(sinkMBB);
9481
9482     //  sinkMBB:
9483     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9484     //  ...
9485     BB = sinkMBB;
9486     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::PHI), MI.getOperand(0).getReg())
9487         .addReg(MI.getOperand(3).getReg())
9488         .addMBB(copy0MBB)
9489         .addReg(MI.getOperand(2).getReg())
9490         .addMBB(thisMBB);
9491   } else if (MI.getOpcode() == PPC::ReadTB) {
9492     // To read the 64-bit time-base register on a 32-bit target, we read the
9493     // two halves. Should the counter have wrapped while it was being read, we
9494     // need to try again.
9495     // ...
9496     // readLoop:
9497     // mfspr Rx,TBU # load from TBU
9498     // mfspr Ry,TB  # load from TB
9499     // mfspr Rz,TBU # load from TBU
9500     // cmpw crX,Rx,Rz # check if 'old'='new'
9501     // bne readLoop   # branch if they're not equal
9502     // ...
9503
9504     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
9505     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9506     DebugLoc dl = MI.getDebugLoc();
9507     F->insert(It, readMBB);
9508     F->insert(It, sinkMBB);
9509
9510     // Transfer the remainder of BB and its successor edges to sinkMBB.
9511     sinkMBB->splice(sinkMBB->begin(), BB,
9512                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9513     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9514
9515     BB->addSuccessor(readMBB);
9516     BB = readMBB;
9517
9518     MachineRegisterInfo &RegInfo = F->getRegInfo();
9519     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
9520     unsigned LoReg = MI.getOperand(0).getReg();
9521     unsigned HiReg = MI.getOperand(1).getReg();
9522
9523     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
9524     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
9525     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
9526
9527     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9528
9529     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
9530       .addReg(HiReg).addReg(ReadAgainReg);
9531     BuildMI(BB, dl, TII->get(PPC::BCC))
9532       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
9533
9534     BB->addSuccessor(readMBB);
9535     BB->addSuccessor(sinkMBB);
9536   } else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
9537     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
9538   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
9539     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
9540   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
9541     BB = EmitAtomicBinary(MI, BB, 4, PPC::ADD4);
9542   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
9543     BB = EmitAtomicBinary(MI, BB, 8, PPC::ADD8);
9544
9545   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
9546     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
9547   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
9548     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
9549   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
9550     BB = EmitAtomicBinary(MI, BB, 4, PPC::AND);
9551   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
9552     BB = EmitAtomicBinary(MI, BB, 8, PPC::AND8);
9553
9554   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
9555     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
9556   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
9557     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
9558   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
9559     BB = EmitAtomicBinary(MI, BB, 4, PPC::OR);
9560   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
9561     BB = EmitAtomicBinary(MI, BB, 8, PPC::OR8);
9562
9563   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
9564     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
9565   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
9566     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
9567   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
9568     BB = EmitAtomicBinary(MI, BB, 4, PPC::XOR);
9569   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
9570     BB = EmitAtomicBinary(MI, BB, 8, PPC::XOR8);
9571
9572   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
9573     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
9574   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
9575     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
9576   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
9577     BB = EmitAtomicBinary(MI, BB, 4, PPC::NAND);
9578   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
9579     BB = EmitAtomicBinary(MI, BB, 8, PPC::NAND8);
9580
9581   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
9582     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
9583   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
9584     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
9585   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
9586     BB = EmitAtomicBinary(MI, BB, 4, PPC::SUBF);
9587   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
9588     BB = EmitAtomicBinary(MI, BB, 8, PPC::SUBF8);
9589
9590   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I8)
9591     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_GE);
9592   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I16)
9593     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_GE);
9594   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I32)
9595     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_GE);
9596   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MIN_I64)
9597     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_GE);
9598
9599   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I8)
9600     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPW, PPC::PRED_LE);
9601   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I16)
9602     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPW, PPC::PRED_LE);
9603   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I32)
9604     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPW, PPC::PRED_LE);
9605   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_MAX_I64)
9606     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPD, PPC::PRED_LE);
9607
9608   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I8)
9609     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_GE);
9610   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I16)
9611     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_GE);
9612   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I32)
9613     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_GE);
9614   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMIN_I64)
9615     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_GE);
9616
9617   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I8)
9618     BB = EmitPartwordAtomicBinary(MI, BB, true, 0, PPC::CMPLW, PPC::PRED_LE);
9619   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I16)
9620     BB = EmitPartwordAtomicBinary(MI, BB, false, 0, PPC::CMPLW, PPC::PRED_LE);
9621   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I32)
9622     BB = EmitAtomicBinary(MI, BB, 4, 0, PPC::CMPLW, PPC::PRED_LE);
9623   else if (MI.getOpcode() == PPC::ATOMIC_LOAD_UMAX_I64)
9624     BB = EmitAtomicBinary(MI, BB, 8, 0, PPC::CMPLD, PPC::PRED_LE);
9625
9626   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I8)
9627     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
9628   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I16)
9629     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
9630   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I32)
9631     BB = EmitAtomicBinary(MI, BB, 4, 0);
9632   else if (MI.getOpcode() == PPC::ATOMIC_SWAP_I64)
9633     BB = EmitAtomicBinary(MI, BB, 8, 0);
9634   else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
9635            MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64 ||
9636            (Subtarget.hasPartwordAtomics() &&
9637             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8) ||
9638            (Subtarget.hasPartwordAtomics() &&
9639             MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16)) {
9640     bool is64bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
9641
9642     auto LoadMnemonic = PPC::LDARX;
9643     auto StoreMnemonic = PPC::STDCX;
9644     switch (MI.getOpcode()) {
9645     default:
9646       llvm_unreachable("Compare and swap of unknown size");
9647     case PPC::ATOMIC_CMP_SWAP_I8:
9648       LoadMnemonic = PPC::LBARX;
9649       StoreMnemonic = PPC::STBCX;
9650       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9651       break;
9652     case PPC::ATOMIC_CMP_SWAP_I16:
9653       LoadMnemonic = PPC::LHARX;
9654       StoreMnemonic = PPC::STHCX;
9655       assert(Subtarget.hasPartwordAtomics() && "No support partword atomics.");
9656       break;
9657     case PPC::ATOMIC_CMP_SWAP_I32:
9658       LoadMnemonic = PPC::LWARX;
9659       StoreMnemonic = PPC::STWCX;
9660       break;
9661     case PPC::ATOMIC_CMP_SWAP_I64:
9662       LoadMnemonic = PPC::LDARX;
9663       StoreMnemonic = PPC::STDCX;
9664       break;
9665     }
9666     unsigned dest = MI.getOperand(0).getReg();
9667     unsigned ptrA = MI.getOperand(1).getReg();
9668     unsigned ptrB = MI.getOperand(2).getReg();
9669     unsigned oldval = MI.getOperand(3).getReg();
9670     unsigned newval = MI.getOperand(4).getReg();
9671     DebugLoc dl = MI.getDebugLoc();
9672
9673     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9674     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9675     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9676     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9677     F->insert(It, loop1MBB);
9678     F->insert(It, loop2MBB);
9679     F->insert(It, midMBB);
9680     F->insert(It, exitMBB);
9681     exitMBB->splice(exitMBB->begin(), BB,
9682                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9683     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9684
9685     //  thisMBB:
9686     //   ...
9687     //   fallthrough --> loopMBB
9688     BB->addSuccessor(loop1MBB);
9689
9690     // loop1MBB:
9691     //   l[bhwd]arx dest, ptr
9692     //   cmp[wd] dest, oldval
9693     //   bne- midMBB
9694     // loop2MBB:
9695     //   st[bhwd]cx. newval, ptr
9696     //   bne- loopMBB
9697     //   b exitBB
9698     // midMBB:
9699     //   st[bhwd]cx. dest, ptr
9700     // exitBB:
9701     BB = loop1MBB;
9702     BuildMI(BB, dl, TII->get(LoadMnemonic), dest)
9703       .addReg(ptrA).addReg(ptrB);
9704     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
9705       .addReg(oldval).addReg(dest);
9706     BuildMI(BB, dl, TII->get(PPC::BCC))
9707       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9708     BB->addSuccessor(loop2MBB);
9709     BB->addSuccessor(midMBB);
9710
9711     BB = loop2MBB;
9712     BuildMI(BB, dl, TII->get(StoreMnemonic))
9713       .addReg(newval).addReg(ptrA).addReg(ptrB);
9714     BuildMI(BB, dl, TII->get(PPC::BCC))
9715       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9716     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9717     BB->addSuccessor(loop1MBB);
9718     BB->addSuccessor(exitMBB);
9719
9720     BB = midMBB;
9721     BuildMI(BB, dl, TII->get(StoreMnemonic))
9722       .addReg(dest).addReg(ptrA).addReg(ptrB);
9723     BB->addSuccessor(exitMBB);
9724
9725     //  exitMBB:
9726     //   ...
9727     BB = exitMBB;
9728   } else if (MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
9729              MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
9730     // We must use 64-bit registers for addresses when targeting 64-bit,
9731     // since we're actually doing arithmetic on them.  Other registers
9732     // can be 32-bit.
9733     bool is64bit = Subtarget.isPPC64();
9734     bool isLittleEndian = Subtarget.isLittleEndian();
9735     bool is8bit = MI.getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
9736
9737     unsigned dest = MI.getOperand(0).getReg();
9738     unsigned ptrA = MI.getOperand(1).getReg();
9739     unsigned ptrB = MI.getOperand(2).getReg();
9740     unsigned oldval = MI.getOperand(3).getReg();
9741     unsigned newval = MI.getOperand(4).getReg();
9742     DebugLoc dl = MI.getDebugLoc();
9743
9744     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
9745     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
9746     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
9747     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
9748     F->insert(It, loop1MBB);
9749     F->insert(It, loop2MBB);
9750     F->insert(It, midMBB);
9751     F->insert(It, exitMBB);
9752     exitMBB->splice(exitMBB->begin(), BB,
9753                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9754     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9755
9756     MachineRegisterInfo &RegInfo = F->getRegInfo();
9757     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
9758                                             : &PPC::GPRCRegClass;
9759     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
9760     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
9761     unsigned ShiftReg =
9762       isLittleEndian ? Shift1Reg : RegInfo.createVirtualRegister(RC);
9763     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
9764     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
9765     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
9766     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
9767     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
9768     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
9769     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
9770     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
9771     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
9772     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
9773     unsigned Ptr1Reg;
9774     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
9775     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
9776     //  thisMBB:
9777     //   ...
9778     //   fallthrough --> loopMBB
9779     BB->addSuccessor(loop1MBB);
9780
9781     // The 4-byte load must be aligned, while a char or short may be
9782     // anywhere in the word.  Hence all this nasty bookkeeping code.
9783     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
9784     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
9785     //   xori shift, shift1, 24 [16]
9786     //   rlwinm ptr, ptr1, 0, 0, 29
9787     //   slw newval2, newval, shift
9788     //   slw oldval2, oldval,shift
9789     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
9790     //   slw mask, mask2, shift
9791     //   and newval3, newval2, mask
9792     //   and oldval3, oldval2, mask
9793     // loop1MBB:
9794     //   lwarx tmpDest, ptr
9795     //   and tmp, tmpDest, mask
9796     //   cmpw tmp, oldval3
9797     //   bne- midMBB
9798     // loop2MBB:
9799     //   andc tmp2, tmpDest, mask
9800     //   or tmp4, tmp2, newval3
9801     //   stwcx. tmp4, ptr
9802     //   bne- loop1MBB
9803     //   b exitBB
9804     // midMBB:
9805     //   stwcx. tmpDest, ptr
9806     // exitBB:
9807     //   srw dest, tmpDest, shift
9808     if (ptrA != ZeroReg) {
9809       Ptr1Reg = RegInfo.createVirtualRegister(RC);
9810       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
9811         .addReg(ptrA).addReg(ptrB);
9812     } else {
9813       Ptr1Reg = ptrB;
9814     }
9815     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
9816         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
9817     if (!isLittleEndian)
9818       BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
9819           .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
9820     if (is64bit)
9821       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
9822         .addReg(Ptr1Reg).addImm(0).addImm(61);
9823     else
9824       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
9825         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
9826     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
9827         .addReg(newval).addReg(ShiftReg);
9828     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
9829         .addReg(oldval).addReg(ShiftReg);
9830     if (is8bit)
9831       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
9832     else {
9833       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
9834       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
9835         .addReg(Mask3Reg).addImm(65535);
9836     }
9837     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
9838         .addReg(Mask2Reg).addReg(ShiftReg);
9839     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
9840         .addReg(NewVal2Reg).addReg(MaskReg);
9841     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
9842         .addReg(OldVal2Reg).addReg(MaskReg);
9843
9844     BB = loop1MBB;
9845     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
9846         .addReg(ZeroReg).addReg(PtrReg);
9847     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
9848         .addReg(TmpDestReg).addReg(MaskReg);
9849     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
9850         .addReg(TmpReg).addReg(OldVal3Reg);
9851     BuildMI(BB, dl, TII->get(PPC::BCC))
9852         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
9853     BB->addSuccessor(loop2MBB);
9854     BB->addSuccessor(midMBB);
9855
9856     BB = loop2MBB;
9857     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
9858         .addReg(TmpDestReg).addReg(MaskReg);
9859     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
9860         .addReg(Tmp2Reg).addReg(NewVal3Reg);
9861     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
9862         .addReg(ZeroReg).addReg(PtrReg);
9863     BuildMI(BB, dl, TII->get(PPC::BCC))
9864       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
9865     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
9866     BB->addSuccessor(loop1MBB);
9867     BB->addSuccessor(exitMBB);
9868
9869     BB = midMBB;
9870     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
9871       .addReg(ZeroReg).addReg(PtrReg);
9872     BB->addSuccessor(exitMBB);
9873
9874     //  exitMBB:
9875     //   ...
9876     BB = exitMBB;
9877     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
9878       .addReg(ShiftReg);
9879   } else if (MI.getOpcode() == PPC::FADDrtz) {
9880     // This pseudo performs an FADD with rounding mode temporarily forced
9881     // to round-to-zero.  We emit this via custom inserter since the FPSCR
9882     // is not modeled at the SelectionDAG level.
9883     unsigned Dest = MI.getOperand(0).getReg();
9884     unsigned Src1 = MI.getOperand(1).getReg();
9885     unsigned Src2 = MI.getOperand(2).getReg();
9886     DebugLoc dl = MI.getDebugLoc();
9887
9888     MachineRegisterInfo &RegInfo = F->getRegInfo();
9889     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
9890
9891     // Save FPSCR value.
9892     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
9893
9894     // Set rounding mode to round-to-zero.
9895     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
9896     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
9897
9898     // Perform addition.
9899     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
9900
9901     // Restore FPSCR value.
9902     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSFb)).addImm(1).addReg(MFFSReg);
9903   } else if (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9904              MI.getOpcode() == PPC::ANDIo_1_GT_BIT ||
9905              MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9906              MI.getOpcode() == PPC::ANDIo_1_GT_BIT8) {
9907     unsigned Opcode = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
9908                        MI.getOpcode() == PPC::ANDIo_1_GT_BIT8)
9909                           ? PPC::ANDIo8
9910                           : PPC::ANDIo;
9911     bool isEQ = (MI.getOpcode() == PPC::ANDIo_1_EQ_BIT ||
9912                  MI.getOpcode() == PPC::ANDIo_1_EQ_BIT8);
9913
9914     MachineRegisterInfo &RegInfo = F->getRegInfo();
9915     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
9916                                                   &PPC::GPRCRegClass :
9917                                                   &PPC::G8RCRegClass);
9918
9919     DebugLoc dl = MI.getDebugLoc();
9920     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
9921         .addReg(MI.getOperand(1).getReg())
9922         .addImm(1);
9923     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
9924             MI.getOperand(0).getReg())
9925         .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
9926   } else if (MI.getOpcode() == PPC::TCHECK_RET) {
9927     DebugLoc Dl = MI.getDebugLoc();
9928     MachineRegisterInfo &RegInfo = F->getRegInfo();
9929     unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
9930     BuildMI(*BB, MI, Dl, TII->get(PPC::TCHECK), CRReg);
9931     return BB;
9932   } else {
9933     llvm_unreachable("Unexpected instr type to insert");
9934   }
9935
9936   MI.eraseFromParent(); // The pseudo instruction is gone now.
9937   return BB;
9938 }
9939
9940 //===----------------------------------------------------------------------===//
9941 // Target Optimization Hooks
9942 //===----------------------------------------------------------------------===//
9943
9944 static int getEstimateRefinementSteps(EVT VT, const PPCSubtarget &Subtarget) {
9945   // For the estimates, convergence is quadratic, so we essentially double the
9946   // number of digits correct after every iteration. For both FRE and FRSQRTE,
9947   // the minimum architected relative accuracy is 2^-5. When hasRecipPrec(),
9948   // this is 2^-14. IEEE float has 23 digits and double has 52 digits.
9949   int RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
9950   if (VT.getScalarType() == MVT::f64)
9951     RefinementSteps++;
9952   return RefinementSteps;
9953 }
9954
9955 SDValue PPCTargetLowering::getSqrtEstimate(SDValue Operand, SelectionDAG &DAG,
9956                                            int Enabled, int &RefinementSteps,
9957                                            bool &UseOneConstNR,
9958                                            bool Reciprocal) const {
9959   EVT VT = Operand.getValueType();
9960   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
9961       (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
9962       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9963       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9964       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9965       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9966     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9967       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9968
9969     UseOneConstNR = true;
9970     return DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
9971   }
9972   return SDValue();
9973 }
9974
9975 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand, SelectionDAG &DAG,
9976                                             int Enabled,
9977                                             int &RefinementSteps) const {
9978   EVT VT = Operand.getValueType();
9979   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
9980       (VT == MVT::f64 && Subtarget.hasFRE()) ||
9981       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
9982       (VT == MVT::v2f64 && Subtarget.hasVSX()) ||
9983       (VT == MVT::v4f32 && Subtarget.hasQPX()) ||
9984       (VT == MVT::v4f64 && Subtarget.hasQPX())) {
9985     if (RefinementSteps == ReciprocalEstimate::Unspecified)
9986       RefinementSteps = getEstimateRefinementSteps(VT, Subtarget);
9987     return DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
9988   }
9989   return SDValue();
9990 }
9991
9992 unsigned PPCTargetLowering::combineRepeatedFPDivisors() const {
9993   // Note: This functionality is used only when unsafe-fp-math is enabled, and
9994   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
9995   // enabled for division), this functionality is redundant with the default
9996   // combiner logic (once the division -> reciprocal/multiply transformation
9997   // has taken place). As a result, this matters more for older cores than for
9998   // newer ones.
9999
10000   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10001   // reciprocal if there are two or more FDIVs (for embedded cores with only
10002   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
10003   switch (Subtarget.getDarwinDirective()) {
10004   default:
10005     return 3;
10006   case PPC::DIR_440:
10007   case PPC::DIR_A2:
10008   case PPC::DIR_E500mc:
10009   case PPC::DIR_E5500:
10010     return 2;
10011   }
10012 }
10013
10014 // isConsecutiveLSLoc needs to work even if all adds have not yet been
10015 // collapsed, and so we need to look through chains of them.
10016 static void getBaseWithConstantOffset(SDValue Loc, SDValue &Base,
10017                                      int64_t& Offset, SelectionDAG &DAG) {
10018   if (DAG.isBaseWithConstantOffset(Loc)) {
10019     Base = Loc.getOperand(0);
10020     Offset += cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue();
10021
10022     // The base might itself be a base plus an offset, and if so, accumulate
10023     // that as well.
10024     getBaseWithConstantOffset(Loc.getOperand(0), Base, Offset, DAG);
10025   }
10026 }
10027
10028 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
10029                             unsigned Bytes, int Dist,
10030                             SelectionDAG &DAG) {
10031   if (VT.getSizeInBits() / 8 != Bytes)
10032     return false;
10033
10034   SDValue BaseLoc = Base->getBasePtr();
10035   if (Loc.getOpcode() == ISD::FrameIndex) {
10036     if (BaseLoc.getOpcode() != ISD::FrameIndex)
10037       return false;
10038     const MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
10039     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
10040     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
10041     int FS  = MFI.getObjectSize(FI);
10042     int BFS = MFI.getObjectSize(BFI);
10043     if (FS != BFS || FS != (int)Bytes) return false;
10044     return MFI.getObjectOffset(FI) == (MFI.getObjectOffset(BFI) + Dist*Bytes);
10045   }
10046
10047   SDValue Base1 = Loc, Base2 = BaseLoc;
10048   int64_t Offset1 = 0, Offset2 = 0;
10049   getBaseWithConstantOffset(Loc, Base1, Offset1, DAG);
10050   getBaseWithConstantOffset(BaseLoc, Base2, Offset2, DAG);
10051   if (Base1 == Base2 && Offset1 == (Offset2 + Dist * Bytes))
10052     return true;
10053
10054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10055   const GlobalValue *GV1 = nullptr;
10056   const GlobalValue *GV2 = nullptr;
10057   Offset1 = 0;
10058   Offset2 = 0;
10059   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
10060   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
10061   if (isGA1 && isGA2 && GV1 == GV2)
10062     return Offset1 == (Offset2 + Dist*Bytes);
10063   return false;
10064 }
10065
10066 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
10067 // not enforce equality of the chain operands.
10068 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
10069                             unsigned Bytes, int Dist,
10070                             SelectionDAG &DAG) {
10071   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
10072     EVT VT = LS->getMemoryVT();
10073     SDValue Loc = LS->getBasePtr();
10074     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
10075   }
10076
10077   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
10078     EVT VT;
10079     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10080     default: return false;
10081     case Intrinsic::ppc_qpx_qvlfd:
10082     case Intrinsic::ppc_qpx_qvlfda:
10083       VT = MVT::v4f64;
10084       break;
10085     case Intrinsic::ppc_qpx_qvlfs:
10086     case Intrinsic::ppc_qpx_qvlfsa:
10087       VT = MVT::v4f32;
10088       break;
10089     case Intrinsic::ppc_qpx_qvlfcd:
10090     case Intrinsic::ppc_qpx_qvlfcda:
10091       VT = MVT::v2f64;
10092       break;
10093     case Intrinsic::ppc_qpx_qvlfcs:
10094     case Intrinsic::ppc_qpx_qvlfcsa:
10095       VT = MVT::v2f32;
10096       break;
10097     case Intrinsic::ppc_qpx_qvlfiwa:
10098     case Intrinsic::ppc_qpx_qvlfiwz:
10099     case Intrinsic::ppc_altivec_lvx:
10100     case Intrinsic::ppc_altivec_lvxl:
10101     case Intrinsic::ppc_vsx_lxvw4x:
10102     case Intrinsic::ppc_vsx_lxvw4x_be:
10103       VT = MVT::v4i32;
10104       break;
10105     case Intrinsic::ppc_vsx_lxvd2x:
10106     case Intrinsic::ppc_vsx_lxvd2x_be:
10107       VT = MVT::v2f64;
10108       break;
10109     case Intrinsic::ppc_altivec_lvebx:
10110       VT = MVT::i8;
10111       break;
10112     case Intrinsic::ppc_altivec_lvehx:
10113       VT = MVT::i16;
10114       break;
10115     case Intrinsic::ppc_altivec_lvewx:
10116       VT = MVT::i32;
10117       break;
10118     }
10119
10120     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
10121   }
10122
10123   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
10124     EVT VT;
10125     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10126     default: return false;
10127     case Intrinsic::ppc_qpx_qvstfd:
10128     case Intrinsic::ppc_qpx_qvstfda:
10129       VT = MVT::v4f64;
10130       break;
10131     case Intrinsic::ppc_qpx_qvstfs:
10132     case Intrinsic::ppc_qpx_qvstfsa:
10133       VT = MVT::v4f32;
10134       break;
10135     case Intrinsic::ppc_qpx_qvstfcd:
10136     case Intrinsic::ppc_qpx_qvstfcda:
10137       VT = MVT::v2f64;
10138       break;
10139     case Intrinsic::ppc_qpx_qvstfcs:
10140     case Intrinsic::ppc_qpx_qvstfcsa:
10141       VT = MVT::v2f32;
10142       break;
10143     case Intrinsic::ppc_qpx_qvstfiw:
10144     case Intrinsic::ppc_qpx_qvstfiwa:
10145     case Intrinsic::ppc_altivec_stvx:
10146     case Intrinsic::ppc_altivec_stvxl:
10147     case Intrinsic::ppc_vsx_stxvw4x:
10148       VT = MVT::v4i32;
10149       break;
10150     case Intrinsic::ppc_vsx_stxvd2x:
10151       VT = MVT::v2f64;
10152       break;
10153     case Intrinsic::ppc_vsx_stxvw4x_be:
10154       VT = MVT::v4i32;
10155       break;
10156     case Intrinsic::ppc_vsx_stxvd2x_be:
10157       VT = MVT::v2f64;
10158       break;
10159     case Intrinsic::ppc_altivec_stvebx:
10160       VT = MVT::i8;
10161       break;
10162     case Intrinsic::ppc_altivec_stvehx:
10163       VT = MVT::i16;
10164       break;
10165     case Intrinsic::ppc_altivec_stvewx:
10166       VT = MVT::i32;
10167       break;
10168     }
10169
10170     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
10171   }
10172
10173   return false;
10174 }
10175
10176 // Return true is there is a nearyby consecutive load to the one provided
10177 // (regardless of alignment). We search up and down the chain, looking though
10178 // token factors and other loads (but nothing else). As a result, a true result
10179 // indicates that it is safe to create a new consecutive load adjacent to the
10180 // load provided.
10181 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
10182   SDValue Chain = LD->getChain();
10183   EVT VT = LD->getMemoryVT();
10184
10185   SmallSet<SDNode *, 16> LoadRoots;
10186   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
10187   SmallSet<SDNode *, 16> Visited;
10188
10189   // First, search up the chain, branching to follow all token-factor operands.
10190   // If we find a consecutive load, then we're done, otherwise, record all
10191   // nodes just above the top-level loads and token factors.
10192   while (!Queue.empty()) {
10193     SDNode *ChainNext = Queue.pop_back_val();
10194     if (!Visited.insert(ChainNext).second)
10195       continue;
10196
10197     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
10198       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10199         return true;
10200
10201       if (!Visited.count(ChainLD->getChain().getNode()))
10202         Queue.push_back(ChainLD->getChain().getNode());
10203     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
10204       for (const SDUse &O : ChainNext->ops())
10205         if (!Visited.count(O.getNode()))
10206           Queue.push_back(O.getNode());
10207     } else
10208       LoadRoots.insert(ChainNext);
10209   }
10210
10211   // Second, search down the chain, starting from the top-level nodes recorded
10212   // in the first phase. These top-level nodes are the nodes just above all
10213   // loads and token factors. Starting with their uses, recursively look though
10214   // all loads (just the chain uses) and token factors to find a consecutive
10215   // load.
10216   Visited.clear();
10217   Queue.clear();
10218
10219   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
10220        IE = LoadRoots.end(); I != IE; ++I) {
10221     Queue.push_back(*I);
10222
10223     while (!Queue.empty()) {
10224       SDNode *LoadRoot = Queue.pop_back_val();
10225       if (!Visited.insert(LoadRoot).second)
10226         continue;
10227
10228       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
10229         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
10230           return true;
10231
10232       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
10233            UE = LoadRoot->use_end(); UI != UE; ++UI)
10234         if (((isa<MemSDNode>(*UI) &&
10235             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
10236             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
10237           Queue.push_back(*UI);
10238     }
10239   }
10240
10241   return false;
10242 }
10243
10244 /// This function is called when we have proved that a SETCC node can be replaced
10245 /// by subtraction (and other supporting instructions) so that the result of
10246 /// comparison is kept in a GPR instead of CR. This function is purely for
10247 /// codegen purposes and has some flags to guide the codegen process.
10248 static SDValue generateEquivalentSub(SDNode *N, int Size, bool Complement,
10249                                      bool Swap, SDLoc &DL, SelectionDAG &DAG) {
10250   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10251
10252   // Zero extend the operands to the largest legal integer. Originally, they
10253   // must be of a strictly smaller size.
10254   auto Op0 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(0),
10255                          DAG.getConstant(Size, DL, MVT::i32));
10256   auto Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1),
10257                          DAG.getConstant(Size, DL, MVT::i32));
10258
10259   // Swap if needed. Depends on the condition code.
10260   if (Swap)
10261     std::swap(Op0, Op1);
10262
10263   // Subtract extended integers.
10264   auto SubNode = DAG.getNode(ISD::SUB, DL, MVT::i64, Op0, Op1);
10265
10266   // Move the sign bit to the least significant position and zero out the rest.
10267   // Now the least significant bit carries the result of original comparison.
10268   auto Shifted = DAG.getNode(ISD::SRL, DL, MVT::i64, SubNode,
10269                              DAG.getConstant(Size - 1, DL, MVT::i32));
10270   auto Final = Shifted;
10271
10272   // Complement the result if needed. Based on the condition code.
10273   if (Complement)
10274     Final = DAG.getNode(ISD::XOR, DL, MVT::i64, Shifted,
10275                         DAG.getConstant(1, DL, MVT::i64));
10276
10277   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Final);
10278 }
10279
10280 SDValue PPCTargetLowering::ConvertSETCCToSubtract(SDNode *N,
10281                                                   DAGCombinerInfo &DCI) const {
10282   assert(N->getOpcode() == ISD::SETCC && "ISD::SETCC Expected.");
10283
10284   SelectionDAG &DAG = DCI.DAG;
10285   SDLoc DL(N);
10286
10287   // Size of integers being compared has a critical role in the following
10288   // analysis, so we prefer to do this when all types are legal.
10289   if (!DCI.isAfterLegalizeVectorOps())
10290     return SDValue();
10291
10292   // If all users of SETCC extend its value to a legal integer type
10293   // then we replace SETCC with a subtraction
10294   for (SDNode::use_iterator UI = N->use_begin(),
10295        UE = N->use_end(); UI != UE; ++UI) {
10296     if (UI->getOpcode() != ISD::ZERO_EXTEND)
10297       return SDValue();
10298   }
10299
10300   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10301   auto OpSize = N->getOperand(0).getValueSizeInBits();
10302
10303   unsigned Size = DAG.getDataLayout().getLargestLegalIntTypeSizeInBits();
10304
10305   if (OpSize < Size) {
10306     switch (CC) {
10307     default: break;
10308     case ISD::SETULT:
10309       return generateEquivalentSub(N, Size, false, false, DL, DAG);
10310     case ISD::SETULE:
10311       return generateEquivalentSub(N, Size, true, true, DL, DAG);
10312     case ISD::SETUGT:
10313       return generateEquivalentSub(N, Size, false, true, DL, DAG);
10314     case ISD::SETUGE:
10315       return generateEquivalentSub(N, Size, true, false, DL, DAG);
10316     }
10317   }
10318
10319   return SDValue();
10320 }
10321
10322 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
10323                                                   DAGCombinerInfo &DCI) const {
10324   SelectionDAG &DAG = DCI.DAG;
10325   SDLoc dl(N);
10326
10327   assert(Subtarget.useCRBits() && "Expecting to be tracking CR bits");
10328   // If we're tracking CR bits, we need to be careful that we don't have:
10329   //   trunc(binary-ops(zext(x), zext(y)))
10330   // or
10331   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
10332   // such that we're unnecessarily moving things into GPRs when it would be
10333   // better to keep them in CR bits.
10334
10335   // Note that trunc here can be an actual i1 trunc, or can be the effective
10336   // truncation that comes from a setcc or select_cc.
10337   if (N->getOpcode() == ISD::TRUNCATE &&
10338       N->getValueType(0) != MVT::i1)
10339     return SDValue();
10340
10341   if (N->getOperand(0).getValueType() != MVT::i32 &&
10342       N->getOperand(0).getValueType() != MVT::i64)
10343     return SDValue();
10344
10345   if (N->getOpcode() == ISD::SETCC ||
10346       N->getOpcode() == ISD::SELECT_CC) {
10347     // If we're looking at a comparison, then we need to make sure that the
10348     // high bits (all except for the first) don't matter the result.
10349     ISD::CondCode CC =
10350       cast<CondCodeSDNode>(N->getOperand(
10351         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
10352     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
10353
10354     if (ISD::isSignedIntSetCC(CC)) {
10355       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
10356           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
10357         return SDValue();
10358     } else if (ISD::isUnsignedIntSetCC(CC)) {
10359       if (!DAG.MaskedValueIsZero(N->getOperand(0),
10360                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
10361           !DAG.MaskedValueIsZero(N->getOperand(1),
10362                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
10363         return (N->getOpcode() == ISD::SETCC ? ConvertSETCCToSubtract(N, DCI)
10364                                              : SDValue());
10365     } else {
10366       // This is neither a signed nor an unsigned comparison, just make sure
10367       // that the high bits are equal.
10368       KnownBits Op1Known, Op2Known;
10369       DAG.computeKnownBits(N->getOperand(0), Op1Known);
10370       DAG.computeKnownBits(N->getOperand(1), Op2Known);
10371
10372       // We don't really care about what is known about the first bit (if
10373       // anything), so clear it in all masks prior to comparing them.
10374       Op1Known.Zero.clearBit(0); Op1Known.One.clearBit(0);
10375       Op2Known.Zero.clearBit(0); Op2Known.One.clearBit(0);
10376
10377       if (Op1Known.Zero != Op2Known.Zero || Op1Known.One != Op2Known.One)
10378         return SDValue();
10379     }
10380   }
10381
10382   // We now know that the higher-order bits are irrelevant, we just need to
10383   // make sure that all of the intermediate operations are bit operations, and
10384   // all inputs are extensions.
10385   if (N->getOperand(0).getOpcode() != ISD::AND &&
10386       N->getOperand(0).getOpcode() != ISD::OR  &&
10387       N->getOperand(0).getOpcode() != ISD::XOR &&
10388       N->getOperand(0).getOpcode() != ISD::SELECT &&
10389       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
10390       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
10391       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
10392       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
10393       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
10394     return SDValue();
10395
10396   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
10397       N->getOperand(1).getOpcode() != ISD::AND &&
10398       N->getOperand(1).getOpcode() != ISD::OR  &&
10399       N->getOperand(1).getOpcode() != ISD::XOR &&
10400       N->getOperand(1).getOpcode() != ISD::SELECT &&
10401       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
10402       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
10403       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
10404       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
10405       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
10406     return SDValue();
10407
10408   SmallVector<SDValue, 4> Inputs;
10409   SmallVector<SDValue, 8> BinOps, PromOps;
10410   SmallPtrSet<SDNode *, 16> Visited;
10411
10412   for (unsigned i = 0; i < 2; ++i) {
10413     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10414           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10415           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10416           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10417         isa<ConstantSDNode>(N->getOperand(i)))
10418       Inputs.push_back(N->getOperand(i));
10419     else
10420       BinOps.push_back(N->getOperand(i));
10421
10422     if (N->getOpcode() == ISD::TRUNCATE)
10423       break;
10424   }
10425
10426   // Visit all inputs, collect all binary operations (and, or, xor and
10427   // select) that are all fed by extensions.
10428   while (!BinOps.empty()) {
10429     SDValue BinOp = BinOps.back();
10430     BinOps.pop_back();
10431
10432     if (!Visited.insert(BinOp.getNode()).second)
10433       continue;
10434
10435     PromOps.push_back(BinOp);
10436
10437     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10438       // The condition of the select is not promoted.
10439       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10440         continue;
10441       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10442         continue;
10443
10444       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10445             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10446             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
10447            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
10448           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10449         Inputs.push_back(BinOp.getOperand(i));
10450       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10451                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10452                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10453                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10454                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
10455                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10456                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
10457                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
10458                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
10459         BinOps.push_back(BinOp.getOperand(i));
10460       } else {
10461         // We have an input that is not an extension or another binary
10462         // operation; we'll abort this transformation.
10463         return SDValue();
10464       }
10465     }
10466   }
10467
10468   // Make sure that this is a self-contained cluster of operations (which
10469   // is not quite the same thing as saying that everything has only one
10470   // use).
10471   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10472     if (isa<ConstantSDNode>(Inputs[i]))
10473       continue;
10474
10475     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10476                               UE = Inputs[i].getNode()->use_end();
10477          UI != UE; ++UI) {
10478       SDNode *User = *UI;
10479       if (User != N && !Visited.count(User))
10480         return SDValue();
10481
10482       // Make sure that we're not going to promote the non-output-value
10483       // operand(s) or SELECT or SELECT_CC.
10484       // FIXME: Although we could sometimes handle this, and it does occur in
10485       // practice that one of the condition inputs to the select is also one of
10486       // the outputs, we currently can't deal with this.
10487       if (User->getOpcode() == ISD::SELECT) {
10488         if (User->getOperand(0) == Inputs[i])
10489           return SDValue();
10490       } else if (User->getOpcode() == ISD::SELECT_CC) {
10491         if (User->getOperand(0) == Inputs[i] ||
10492             User->getOperand(1) == Inputs[i])
10493           return SDValue();
10494       }
10495     }
10496   }
10497
10498   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10499     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10500                               UE = PromOps[i].getNode()->use_end();
10501          UI != UE; ++UI) {
10502       SDNode *User = *UI;
10503       if (User != N && !Visited.count(User))
10504         return SDValue();
10505
10506       // Make sure that we're not going to promote the non-output-value
10507       // operand(s) or SELECT or SELECT_CC.
10508       // FIXME: Although we could sometimes handle this, and it does occur in
10509       // practice that one of the condition inputs to the select is also one of
10510       // the outputs, we currently can't deal with this.
10511       if (User->getOpcode() == ISD::SELECT) {
10512         if (User->getOperand(0) == PromOps[i])
10513           return SDValue();
10514       } else if (User->getOpcode() == ISD::SELECT_CC) {
10515         if (User->getOperand(0) == PromOps[i] ||
10516             User->getOperand(1) == PromOps[i])
10517           return SDValue();
10518       }
10519     }
10520   }
10521
10522   // Replace all inputs with the extension operand.
10523   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10524     // Constants may have users outside the cluster of to-be-promoted nodes,
10525     // and so we need to replace those as we do the promotions.
10526     if (isa<ConstantSDNode>(Inputs[i]))
10527       continue;
10528     else
10529       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
10530   }
10531
10532   std::list<HandleSDNode> PromOpHandles;
10533   for (auto &PromOp : PromOps)
10534     PromOpHandles.emplace_back(PromOp);
10535
10536   // Replace all operations (these are all the same, but have a different
10537   // (i1) return type). DAG.getNode will validate that the types of
10538   // a binary operator match, so go through the list in reverse so that
10539   // we've likely promoted both operands first. Any intermediate truncations or
10540   // extensions disappear.
10541   while (!PromOpHandles.empty()) {
10542     SDValue PromOp = PromOpHandles.back().getValue();
10543     PromOpHandles.pop_back();
10544
10545     if (PromOp.getOpcode() == ISD::TRUNCATE ||
10546         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
10547         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
10548         PromOp.getOpcode() == ISD::ANY_EXTEND) {
10549       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
10550           PromOp.getOperand(0).getValueType() != MVT::i1) {
10551         // The operand is not yet ready (see comment below).
10552         PromOpHandles.emplace_front(PromOp);
10553         continue;
10554       }
10555
10556       SDValue RepValue = PromOp.getOperand(0);
10557       if (isa<ConstantSDNode>(RepValue))
10558         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
10559
10560       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
10561       continue;
10562     }
10563
10564     unsigned C;
10565     switch (PromOp.getOpcode()) {
10566     default:             C = 0; break;
10567     case ISD::SELECT:    C = 1; break;
10568     case ISD::SELECT_CC: C = 2; break;
10569     }
10570
10571     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10572          PromOp.getOperand(C).getValueType() != MVT::i1) ||
10573         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10574          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
10575       // The to-be-promoted operands of this node have not yet been
10576       // promoted (this should be rare because we're going through the
10577       // list backward, but if one of the operands has several users in
10578       // this cluster of to-be-promoted nodes, it is possible).
10579       PromOpHandles.emplace_front(PromOp);
10580       continue;
10581     }
10582
10583     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10584                                 PromOp.getNode()->op_end());
10585
10586     // If there are any constant inputs, make sure they're replaced now.
10587     for (unsigned i = 0; i < 2; ++i)
10588       if (isa<ConstantSDNode>(Ops[C+i]))
10589         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
10590
10591     DAG.ReplaceAllUsesOfValueWith(PromOp,
10592       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
10593   }
10594
10595   // Now we're left with the initial truncation itself.
10596   if (N->getOpcode() == ISD::TRUNCATE)
10597     return N->getOperand(0);
10598
10599   // Otherwise, this is a comparison. The operands to be compared have just
10600   // changed type (to i1), but everything else is the same.
10601   return SDValue(N, 0);
10602 }
10603
10604 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
10605                                                   DAGCombinerInfo &DCI) const {
10606   SelectionDAG &DAG = DCI.DAG;
10607   SDLoc dl(N);
10608
10609   // If we're tracking CR bits, we need to be careful that we don't have:
10610   //   zext(binary-ops(trunc(x), trunc(y)))
10611   // or
10612   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
10613   // such that we're unnecessarily moving things into CR bits that can more
10614   // efficiently stay in GPRs. Note that if we're not certain that the high
10615   // bits are set as required by the final extension, we still may need to do
10616   // some masking to get the proper behavior.
10617
10618   // This same functionality is important on PPC64 when dealing with
10619   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
10620   // the return values of functions. Because it is so similar, it is handled
10621   // here as well.
10622
10623   if (N->getValueType(0) != MVT::i32 &&
10624       N->getValueType(0) != MVT::i64)
10625     return SDValue();
10626
10627   if (!((N->getOperand(0).getValueType() == MVT::i1 && Subtarget.useCRBits()) ||
10628         (N->getOperand(0).getValueType() == MVT::i32 && Subtarget.isPPC64())))
10629     return SDValue();
10630
10631   if (N->getOperand(0).getOpcode() != ISD::AND &&
10632       N->getOperand(0).getOpcode() != ISD::OR  &&
10633       N->getOperand(0).getOpcode() != ISD::XOR &&
10634       N->getOperand(0).getOpcode() != ISD::SELECT &&
10635       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
10636     return SDValue();
10637
10638   SmallVector<SDValue, 4> Inputs;
10639   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
10640   SmallPtrSet<SDNode *, 16> Visited;
10641
10642   // Visit all inputs, collect all binary operations (and, or, xor and
10643   // select) that are all fed by truncations.
10644   while (!BinOps.empty()) {
10645     SDValue BinOp = BinOps.back();
10646     BinOps.pop_back();
10647
10648     if (!Visited.insert(BinOp.getNode()).second)
10649       continue;
10650
10651     PromOps.push_back(BinOp);
10652
10653     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
10654       // The condition of the select is not promoted.
10655       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
10656         continue;
10657       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
10658         continue;
10659
10660       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
10661           isa<ConstantSDNode>(BinOp.getOperand(i))) {
10662         Inputs.push_back(BinOp.getOperand(i));
10663       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
10664                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
10665                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
10666                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
10667                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
10668         BinOps.push_back(BinOp.getOperand(i));
10669       } else {
10670         // We have an input that is not a truncation or another binary
10671         // operation; we'll abort this transformation.
10672         return SDValue();
10673       }
10674     }
10675   }
10676
10677   // The operands of a select that must be truncated when the select is
10678   // promoted because the operand is actually part of the to-be-promoted set.
10679   DenseMap<SDNode *, EVT> SelectTruncOp[2];
10680
10681   // Make sure that this is a self-contained cluster of operations (which
10682   // is not quite the same thing as saying that everything has only one
10683   // use).
10684   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10685     if (isa<ConstantSDNode>(Inputs[i]))
10686       continue;
10687
10688     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
10689                               UE = Inputs[i].getNode()->use_end();
10690          UI != UE; ++UI) {
10691       SDNode *User = *UI;
10692       if (User != N && !Visited.count(User))
10693         return SDValue();
10694
10695       // If we're going to promote the non-output-value operand(s) or SELECT or
10696       // SELECT_CC, record them for truncation.
10697       if (User->getOpcode() == ISD::SELECT) {
10698         if (User->getOperand(0) == Inputs[i])
10699           SelectTruncOp[0].insert(std::make_pair(User,
10700                                     User->getOperand(0).getValueType()));
10701       } else if (User->getOpcode() == ISD::SELECT_CC) {
10702         if (User->getOperand(0) == Inputs[i])
10703           SelectTruncOp[0].insert(std::make_pair(User,
10704                                     User->getOperand(0).getValueType()));
10705         if (User->getOperand(1) == Inputs[i])
10706           SelectTruncOp[1].insert(std::make_pair(User,
10707                                     User->getOperand(1).getValueType()));
10708       }
10709     }
10710   }
10711
10712   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
10713     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
10714                               UE = PromOps[i].getNode()->use_end();
10715          UI != UE; ++UI) {
10716       SDNode *User = *UI;
10717       if (User != N && !Visited.count(User))
10718         return SDValue();
10719
10720       // If we're going to promote the non-output-value operand(s) or SELECT or
10721       // SELECT_CC, record them for truncation.
10722       if (User->getOpcode() == ISD::SELECT) {
10723         if (User->getOperand(0) == PromOps[i])
10724           SelectTruncOp[0].insert(std::make_pair(User,
10725                                     User->getOperand(0).getValueType()));
10726       } else if (User->getOpcode() == ISD::SELECT_CC) {
10727         if (User->getOperand(0) == PromOps[i])
10728           SelectTruncOp[0].insert(std::make_pair(User,
10729                                     User->getOperand(0).getValueType()));
10730         if (User->getOperand(1) == PromOps[i])
10731           SelectTruncOp[1].insert(std::make_pair(User,
10732                                     User->getOperand(1).getValueType()));
10733       }
10734     }
10735   }
10736
10737   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
10738   bool ReallyNeedsExt = false;
10739   if (N->getOpcode() != ISD::ANY_EXTEND) {
10740     // If all of the inputs are not already sign/zero extended, then
10741     // we'll still need to do that at the end.
10742     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10743       if (isa<ConstantSDNode>(Inputs[i]))
10744         continue;
10745
10746       unsigned OpBits =
10747         Inputs[i].getOperand(0).getValueSizeInBits();
10748       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
10749
10750       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
10751            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
10752                                   APInt::getHighBitsSet(OpBits,
10753                                                         OpBits-PromBits))) ||
10754           (N->getOpcode() == ISD::SIGN_EXTEND &&
10755            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
10756              (OpBits-(PromBits-1)))) {
10757         ReallyNeedsExt = true;
10758         break;
10759       }
10760     }
10761   }
10762
10763   // Replace all inputs, either with the truncation operand, or a
10764   // truncation or extension to the final output type.
10765   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
10766     // Constant inputs need to be replaced with the to-be-promoted nodes that
10767     // use them because they might have users outside of the cluster of
10768     // promoted nodes.
10769     if (isa<ConstantSDNode>(Inputs[i]))
10770       continue;
10771
10772     SDValue InSrc = Inputs[i].getOperand(0);
10773     if (Inputs[i].getValueType() == N->getValueType(0))
10774       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
10775     else if (N->getOpcode() == ISD::SIGN_EXTEND)
10776       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10777         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
10778     else if (N->getOpcode() == ISD::ZERO_EXTEND)
10779       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10780         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
10781     else
10782       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
10783         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
10784   }
10785
10786   std::list<HandleSDNode> PromOpHandles;
10787   for (auto &PromOp : PromOps)
10788     PromOpHandles.emplace_back(PromOp);
10789
10790   // Replace all operations (these are all the same, but have a different
10791   // (promoted) return type). DAG.getNode will validate that the types of
10792   // a binary operator match, so go through the list in reverse so that
10793   // we've likely promoted both operands first.
10794   while (!PromOpHandles.empty()) {
10795     SDValue PromOp = PromOpHandles.back().getValue();
10796     PromOpHandles.pop_back();
10797
10798     unsigned C;
10799     switch (PromOp.getOpcode()) {
10800     default:             C = 0; break;
10801     case ISD::SELECT:    C = 1; break;
10802     case ISD::SELECT_CC: C = 2; break;
10803     }
10804
10805     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
10806          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
10807         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
10808          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
10809       // The to-be-promoted operands of this node have not yet been
10810       // promoted (this should be rare because we're going through the
10811       // list backward, but if one of the operands has several users in
10812       // this cluster of to-be-promoted nodes, it is possible).
10813       PromOpHandles.emplace_front(PromOp);
10814       continue;
10815     }
10816
10817     // For SELECT and SELECT_CC nodes, we do a similar check for any
10818     // to-be-promoted comparison inputs.
10819     if (PromOp.getOpcode() == ISD::SELECT ||
10820         PromOp.getOpcode() == ISD::SELECT_CC) {
10821       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
10822            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
10823           (SelectTruncOp[1].count(PromOp.getNode()) &&
10824            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
10825         PromOpHandles.emplace_front(PromOp);
10826         continue;
10827       }
10828     }
10829
10830     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
10831                                 PromOp.getNode()->op_end());
10832
10833     // If this node has constant inputs, then they'll need to be promoted here.
10834     for (unsigned i = 0; i < 2; ++i) {
10835       if (!isa<ConstantSDNode>(Ops[C+i]))
10836         continue;
10837       if (Ops[C+i].getValueType() == N->getValueType(0))
10838         continue;
10839
10840       if (N->getOpcode() == ISD::SIGN_EXTEND)
10841         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10842       else if (N->getOpcode() == ISD::ZERO_EXTEND)
10843         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10844       else
10845         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
10846     }
10847
10848     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
10849     // truncate them again to the original value type.
10850     if (PromOp.getOpcode() == ISD::SELECT ||
10851         PromOp.getOpcode() == ISD::SELECT_CC) {
10852       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
10853       if (SI0 != SelectTruncOp[0].end())
10854         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
10855       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
10856       if (SI1 != SelectTruncOp[1].end())
10857         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
10858     }
10859
10860     DAG.ReplaceAllUsesOfValueWith(PromOp,
10861       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
10862   }
10863
10864   // Now we're left with the initial extension itself.
10865   if (!ReallyNeedsExt)
10866     return N->getOperand(0);
10867
10868   // To zero extend, just mask off everything except for the first bit (in the
10869   // i1 case).
10870   if (N->getOpcode() == ISD::ZERO_EXTEND)
10871     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
10872                        DAG.getConstant(APInt::getLowBitsSet(
10873                                          N->getValueSizeInBits(0), PromBits),
10874                                        dl, N->getValueType(0)));
10875
10876   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
10877          "Invalid extension type");
10878   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0), DAG.getDataLayout());
10879   SDValue ShiftCst =
10880       DAG.getConstant(N->getValueSizeInBits(0) - PromBits, dl, ShiftAmountTy);
10881   return DAG.getNode(
10882       ISD::SRA, dl, N->getValueType(0),
10883       DAG.getNode(ISD::SHL, dl, N->getValueType(0), N->getOperand(0), ShiftCst),
10884       ShiftCst);
10885 }
10886
10887 /// \brief Reduces the number of fp-to-int conversion when building a vector.
10888 ///
10889 /// If this vector is built out of floating to integer conversions,
10890 /// transform it to a vector built out of floating point values followed by a
10891 /// single floating to integer conversion of the vector.
10892 /// Namely  (build_vector (fptosi $A), (fptosi $B), ...)
10893 /// becomes (fptosi (build_vector ($A, $B, ...)))
10894 SDValue PPCTargetLowering::
10895 combineElementTruncationToVectorTruncation(SDNode *N,
10896                                            DAGCombinerInfo &DCI) const {
10897   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10898          "Should be called with a BUILD_VECTOR node");
10899
10900   SelectionDAG &DAG = DCI.DAG;
10901   SDLoc dl(N);
10902
10903   SDValue FirstInput = N->getOperand(0);
10904   assert(FirstInput.getOpcode() == PPCISD::MFVSR &&
10905          "The input operand must be an fp-to-int conversion.");
10906
10907   // This combine happens after legalization so the fp_to_[su]i nodes are
10908   // already converted to PPCSISD nodes.
10909   unsigned FirstConversion = FirstInput.getOperand(0).getOpcode();
10910   if (FirstConversion == PPCISD::FCTIDZ ||
10911       FirstConversion == PPCISD::FCTIDUZ ||
10912       FirstConversion == PPCISD::FCTIWZ ||
10913       FirstConversion == PPCISD::FCTIWUZ) {
10914     bool IsSplat = true;
10915     bool Is32Bit = FirstConversion == PPCISD::FCTIWZ ||
10916       FirstConversion == PPCISD::FCTIWUZ;
10917     EVT SrcVT = FirstInput.getOperand(0).getValueType();
10918     SmallVector<SDValue, 4> Ops;
10919     EVT TargetVT = N->getValueType(0);
10920     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10921       if (N->getOperand(i).getOpcode() != PPCISD::MFVSR)
10922         return SDValue();
10923       unsigned NextConversion = N->getOperand(i).getOperand(0).getOpcode();
10924       if (NextConversion != FirstConversion)
10925         return SDValue();
10926       if (N->getOperand(i) != FirstInput)
10927         IsSplat = false;
10928     }
10929
10930     // If this is a splat, we leave it as-is since there will be only a single
10931     // fp-to-int conversion followed by a splat of the integer. This is better
10932     // for 32-bit and smaller ints and neutral for 64-bit ints.
10933     if (IsSplat)
10934       return SDValue();
10935
10936     // Now that we know we have the right type of node, get its operands
10937     for (int i = 0, e = N->getNumOperands(); i < e; ++i) {
10938       SDValue In = N->getOperand(i).getOperand(0);
10939       // For 32-bit values, we need to add an FP_ROUND node.
10940       if (Is32Bit) {
10941         if (In.isUndef())
10942           Ops.push_back(DAG.getUNDEF(SrcVT));
10943         else {
10944           SDValue Trunc = DAG.getNode(ISD::FP_ROUND, dl,
10945                                       MVT::f32, In.getOperand(0),
10946                                       DAG.getIntPtrConstant(1, dl));
10947           Ops.push_back(Trunc);
10948         }
10949       } else
10950         Ops.push_back(In.isUndef() ? DAG.getUNDEF(SrcVT) : In.getOperand(0));
10951     }
10952
10953     unsigned Opcode;
10954     if (FirstConversion == PPCISD::FCTIDZ ||
10955         FirstConversion == PPCISD::FCTIWZ)
10956       Opcode = ISD::FP_TO_SINT;
10957     else
10958       Opcode = ISD::FP_TO_UINT;
10959
10960     EVT NewVT = TargetVT == MVT::v2i64 ? MVT::v2f64 : MVT::v4f32;
10961     SDValue BV = DAG.getBuildVector(NewVT, dl, Ops);
10962     return DAG.getNode(Opcode, dl, TargetVT, BV);
10963   }
10964   return SDValue();
10965 }
10966
10967 /// \brief Reduce the number of loads when building a vector.
10968 ///
10969 /// Building a vector out of multiple loads can be converted to a load
10970 /// of the vector type if the loads are consecutive. If the loads are
10971 /// consecutive but in descending order, a shuffle is added at the end
10972 /// to reorder the vector.
10973 static SDValue combineBVOfConsecutiveLoads(SDNode *N, SelectionDAG &DAG) {
10974   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
10975          "Should be called with a BUILD_VECTOR node");
10976
10977   SDLoc dl(N);
10978   bool InputsAreConsecutiveLoads = true;
10979   bool InputsAreReverseConsecutive = true;
10980   unsigned ElemSize = N->getValueType(0).getScalarSizeInBits() / 8;
10981   SDValue FirstInput = N->getOperand(0);
10982   bool IsRoundOfExtLoad = false;
10983
10984   if (FirstInput.getOpcode() == ISD::FP_ROUND &&
10985       FirstInput.getOperand(0).getOpcode() == ISD::LOAD) {
10986     LoadSDNode *LD = dyn_cast<LoadSDNode>(FirstInput.getOperand(0));
10987     IsRoundOfExtLoad = LD->getExtensionType() == ISD::EXTLOAD;
10988   }
10989   // Not a build vector of (possibly fp_rounded) loads.
10990   if (!IsRoundOfExtLoad && FirstInput.getOpcode() != ISD::LOAD)
10991     return SDValue();
10992
10993   for (int i = 1, e = N->getNumOperands(); i < e; ++i) {
10994     // If any inputs are fp_round(extload), they all must be.
10995     if (IsRoundOfExtLoad && N->getOperand(i).getOpcode() != ISD::FP_ROUND)
10996       return SDValue();
10997
10998     SDValue NextInput = IsRoundOfExtLoad ? N->getOperand(i).getOperand(0) :
10999       N->getOperand(i);
11000     if (NextInput.getOpcode() != ISD::LOAD)
11001       return SDValue();
11002
11003     SDValue PreviousInput =
11004       IsRoundOfExtLoad ? N->getOperand(i-1).getOperand(0) : N->getOperand(i-1);
11005     LoadSDNode *LD1 = dyn_cast<LoadSDNode>(PreviousInput);
11006     LoadSDNode *LD2 = dyn_cast<LoadSDNode>(NextInput);
11007
11008     // If any inputs are fp_round(extload), they all must be.
11009     if (IsRoundOfExtLoad && LD2->getExtensionType() != ISD::EXTLOAD)
11010       return SDValue();
11011
11012     if (!isConsecutiveLS(LD2, LD1, ElemSize, 1, DAG))
11013       InputsAreConsecutiveLoads = false;
11014     if (!isConsecutiveLS(LD1, LD2, ElemSize, 1, DAG))
11015       InputsAreReverseConsecutive = false;
11016
11017     // Exit early if the loads are neither consecutive nor reverse consecutive.
11018     if (!InputsAreConsecutiveLoads && !InputsAreReverseConsecutive)
11019       return SDValue();
11020   }
11021
11022   assert(!(InputsAreConsecutiveLoads && InputsAreReverseConsecutive) &&
11023          "The loads cannot be both consecutive and reverse consecutive.");
11024
11025   SDValue FirstLoadOp =
11026     IsRoundOfExtLoad ? FirstInput.getOperand(0) : FirstInput;
11027   SDValue LastLoadOp =
11028     IsRoundOfExtLoad ? N->getOperand(N->getNumOperands()-1).getOperand(0) :
11029                        N->getOperand(N->getNumOperands()-1);
11030
11031   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(FirstLoadOp);
11032   LoadSDNode *LDL = dyn_cast<LoadSDNode>(LastLoadOp);
11033   if (InputsAreConsecutiveLoads) {
11034     assert(LD1 && "Input needs to be a LoadSDNode.");
11035     return DAG.getLoad(N->getValueType(0), dl, LD1->getChain(),
11036                        LD1->getBasePtr(), LD1->getPointerInfo(),
11037                        LD1->getAlignment());
11038   }
11039   if (InputsAreReverseConsecutive) {
11040     assert(LDL && "Input needs to be a LoadSDNode.");
11041     SDValue Load = DAG.getLoad(N->getValueType(0), dl, LDL->getChain(),
11042                                LDL->getBasePtr(), LDL->getPointerInfo(),
11043                                LDL->getAlignment());
11044     SmallVector<int, 16> Ops;
11045     for (int i = N->getNumOperands() - 1; i >= 0; i--)
11046       Ops.push_back(i);
11047
11048     return DAG.getVectorShuffle(N->getValueType(0), dl, Load,
11049                                 DAG.getUNDEF(N->getValueType(0)), Ops);
11050   }
11051   return SDValue();
11052 }
11053
11054 SDValue PPCTargetLowering::DAGCombineBuildVector(SDNode *N,
11055                                                  DAGCombinerInfo &DCI) const {
11056   assert(N->getOpcode() == ISD::BUILD_VECTOR &&
11057          "Should be called with a BUILD_VECTOR node");
11058
11059   SelectionDAG &DAG = DCI.DAG;
11060   SDLoc dl(N);
11061
11062   if (!Subtarget.hasVSX())
11063     return SDValue();
11064
11065   // The target independent DAG combiner will leave a build_vector of
11066   // float-to-int conversions intact. We can generate MUCH better code for
11067   // a float-to-int conversion of a vector of floats.
11068   SDValue FirstInput = N->getOperand(0);
11069   if (FirstInput.getOpcode() == PPCISD::MFVSR) {
11070     SDValue Reduced = combineElementTruncationToVectorTruncation(N, DCI);
11071     if (Reduced)
11072       return Reduced;
11073   }
11074
11075   // If we're building a vector out of consecutive loads, just load that
11076   // vector type.
11077   SDValue Reduced = combineBVOfConsecutiveLoads(N, DAG);
11078   if (Reduced)
11079     return Reduced;
11080
11081   if (N->getValueType(0) != MVT::v2f64)
11082     return SDValue();
11083
11084   // Looking for:
11085   // (build_vector ([su]int_to_fp (extractelt 0)), [su]int_to_fp (extractelt 1))
11086   if (FirstInput.getOpcode() != ISD::SINT_TO_FP &&
11087       FirstInput.getOpcode() != ISD::UINT_TO_FP)
11088     return SDValue();
11089   if (N->getOperand(1).getOpcode() != ISD::SINT_TO_FP &&
11090       N->getOperand(1).getOpcode() != ISD::UINT_TO_FP)
11091     return SDValue();
11092   if (FirstInput.getOpcode() != N->getOperand(1).getOpcode())
11093     return SDValue();
11094
11095   SDValue Ext1 = FirstInput.getOperand(0);
11096   SDValue Ext2 = N->getOperand(1).getOperand(0);
11097   if(Ext1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11098      Ext2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11099     return SDValue();
11100
11101   ConstantSDNode *Ext1Op = dyn_cast<ConstantSDNode>(Ext1.getOperand(1));
11102   ConstantSDNode *Ext2Op = dyn_cast<ConstantSDNode>(Ext2.getOperand(1));
11103   if (!Ext1Op || !Ext2Op)
11104     return SDValue();
11105   if (Ext1.getValueType() != MVT::i32 ||
11106       Ext2.getValueType() != MVT::i32)
11107   if (Ext1.getOperand(0) != Ext2.getOperand(0))
11108     return SDValue();
11109
11110   int FirstElem = Ext1Op->getZExtValue();
11111   int SecondElem = Ext2Op->getZExtValue();
11112   int SubvecIdx;
11113   if (FirstElem == 0 && SecondElem == 1)
11114     SubvecIdx = Subtarget.isLittleEndian() ? 1 : 0;
11115   else if (FirstElem == 2 && SecondElem == 3)
11116     SubvecIdx = Subtarget.isLittleEndian() ? 0 : 1;
11117   else
11118     return SDValue();
11119
11120   SDValue SrcVec = Ext1.getOperand(0);
11121   auto NodeType = (N->getOperand(1).getOpcode() == ISD::SINT_TO_FP) ?
11122     PPCISD::SINT_VEC_TO_FP : PPCISD::UINT_VEC_TO_FP;
11123   return DAG.getNode(NodeType, dl, MVT::v2f64,
11124                      SrcVec, DAG.getIntPtrConstant(SubvecIdx, dl));
11125 }
11126
11127 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
11128                                               DAGCombinerInfo &DCI) const {
11129   assert((N->getOpcode() == ISD::SINT_TO_FP ||
11130           N->getOpcode() == ISD::UINT_TO_FP) &&
11131          "Need an int -> FP conversion node here");
11132
11133   if (useSoftFloat() || !Subtarget.has64BitSupport())
11134     return SDValue();
11135
11136   SelectionDAG &DAG = DCI.DAG;
11137   SDLoc dl(N);
11138   SDValue Op(N, 0);
11139
11140   SDValue FirstOperand(Op.getOperand(0));
11141   bool SubWordLoad = FirstOperand.getOpcode() == ISD::LOAD &&
11142     (FirstOperand.getValueType() == MVT::i8 ||
11143      FirstOperand.getValueType() == MVT::i16);
11144   if (Subtarget.hasP9Vector() && Subtarget.hasP9Altivec() && SubWordLoad) {
11145     bool Signed = N->getOpcode() == ISD::SINT_TO_FP;
11146     bool DstDouble = Op.getValueType() == MVT::f64;
11147     unsigned ConvOp = Signed ?
11148       (DstDouble ? PPCISD::FCFID  : PPCISD::FCFIDS) :
11149       (DstDouble ? PPCISD::FCFIDU : PPCISD::FCFIDUS);
11150     SDValue WidthConst =
11151       DAG.getIntPtrConstant(FirstOperand.getValueType() == MVT::i8 ? 1 : 2,
11152                             dl, false);
11153     LoadSDNode *LDN = cast<LoadSDNode>(FirstOperand.getNode());
11154     SDValue Ops[] = { LDN->getChain(), LDN->getBasePtr(), WidthConst };
11155     SDValue Ld = DAG.getMemIntrinsicNode(PPCISD::LXSIZX, dl,
11156                                          DAG.getVTList(MVT::f64, MVT::Other),
11157                                          Ops, MVT::i8, LDN->getMemOperand());
11158
11159     // For signed conversion, we need to sign-extend the value in the VSR
11160     if (Signed) {
11161       SDValue ExtOps[] = { Ld, WidthConst };
11162       SDValue Ext = DAG.getNode(PPCISD::VEXTS, dl, MVT::f64, ExtOps);
11163       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ext);
11164     } else
11165       return DAG.getNode(ConvOp, dl, DstDouble ? MVT::f64 : MVT::f32, Ld);
11166   }
11167
11168   // Don't handle ppc_fp128 here or i1 conversions.
11169   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
11170     return SDValue();
11171   if (Op.getOperand(0).getValueType() == MVT::i1)
11172     return SDValue();
11173
11174   // For i32 intermediate values, unfortunately, the conversion functions
11175   // leave the upper 32 bits of the value are undefined. Within the set of
11176   // scalar instructions, we have no method for zero- or sign-extending the
11177   // value. Thus, we cannot handle i32 intermediate values here.
11178   if (Op.getOperand(0).getValueType() == MVT::i32)
11179     return SDValue();
11180
11181   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
11182          "UINT_TO_FP is supported only with FPCVT");
11183
11184   // If we have FCFIDS, then use it when converting to single-precision.
11185   // Otherwise, convert to double-precision and then round.
11186   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11187                        ? (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDUS
11188                                                             : PPCISD::FCFIDS)
11189                        : (Op.getOpcode() == ISD::UINT_TO_FP ? PPCISD::FCFIDU
11190                                                             : PPCISD::FCFID);
11191   MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32)
11192                   ? MVT::f32
11193                   : MVT::f64;
11194
11195   // If we're converting from a float, to an int, and back to a float again,
11196   // then we don't need the store/load pair at all.
11197   if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
11198        Subtarget.hasFPCVT()) ||
11199       (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
11200     SDValue Src = Op.getOperand(0).getOperand(0);
11201     if (Src.getValueType() == MVT::f32) {
11202       Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
11203       DCI.AddToWorklist(Src.getNode());
11204     } else if (Src.getValueType() != MVT::f64) {
11205       // Make sure that we don't pick up a ppc_fp128 source value.
11206       return SDValue();
11207     }
11208
11209     unsigned FCTOp =
11210       Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
11211                                                         PPCISD::FCTIDUZ;
11212
11213     SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
11214     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
11215
11216     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
11217       FP = DAG.getNode(ISD::FP_ROUND, dl,
11218                        MVT::f32, FP, DAG.getIntPtrConstant(0, dl));
11219       DCI.AddToWorklist(FP.getNode());
11220     }
11221
11222     return FP;
11223   }
11224
11225   return SDValue();
11226 }
11227
11228 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
11229 // builtins) into loads with swaps.
11230 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
11231                                               DAGCombinerInfo &DCI) const {
11232   SelectionDAG &DAG = DCI.DAG;
11233   SDLoc dl(N);
11234   SDValue Chain;
11235   SDValue Base;
11236   MachineMemOperand *MMO;
11237
11238   switch (N->getOpcode()) {
11239   default:
11240     llvm_unreachable("Unexpected opcode for little endian VSX load");
11241   case ISD::LOAD: {
11242     LoadSDNode *LD = cast<LoadSDNode>(N);
11243     Chain = LD->getChain();
11244     Base = LD->getBasePtr();
11245     MMO = LD->getMemOperand();
11246     // If the MMO suggests this isn't a load of a full vector, leave
11247     // things alone.  For a built-in, we have to make the change for
11248     // correctness, so if there is a size problem that will be a bug.
11249     if (MMO->getSize() < 16)
11250       return SDValue();
11251     break;
11252   }
11253   case ISD::INTRINSIC_W_CHAIN: {
11254     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11255     Chain = Intrin->getChain();
11256     // Similarly to the store case below, Intrin->getBasePtr() doesn't get
11257     // us what we want. Get operand 2 instead.
11258     Base = Intrin->getOperand(2);
11259     MMO = Intrin->getMemOperand();
11260     break;
11261   }
11262   }
11263
11264   MVT VecTy = N->getValueType(0).getSimpleVT();
11265
11266   // Do not expand to PPCISD::LXVD2X + PPCISD::XXSWAPD when the load is
11267   // aligned and the type is a vector with elements up to 4 bytes
11268   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11269       && VecTy.getScalarSizeInBits() <= 32 ) {
11270     return SDValue();
11271   }
11272
11273   SDValue LoadOps[] = { Chain, Base };
11274   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
11275                                          DAG.getVTList(MVT::v2f64, MVT::Other),
11276                                          LoadOps, MVT::v2f64, MMO);
11277
11278   DCI.AddToWorklist(Load.getNode());
11279   Chain = Load.getValue(1);
11280   SDValue Swap = DAG.getNode(
11281       PPCISD::XXSWAPD, dl, DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Load);
11282   DCI.AddToWorklist(Swap.getNode());
11283
11284   // Add a bitcast if the resulting load type doesn't match v2f64.
11285   if (VecTy != MVT::v2f64) {
11286     SDValue N = DAG.getNode(ISD::BITCAST, dl, VecTy, Swap);
11287     DCI.AddToWorklist(N.getNode());
11288     // Package {bitcast value, swap's chain} to match Load's shape.
11289     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VecTy, MVT::Other),
11290                        N, Swap.getValue(1));
11291   }
11292
11293   return Swap;
11294 }
11295
11296 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
11297 // builtins) into stores with swaps.
11298 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
11299                                                DAGCombinerInfo &DCI) const {
11300   SelectionDAG &DAG = DCI.DAG;
11301   SDLoc dl(N);
11302   SDValue Chain;
11303   SDValue Base;
11304   unsigned SrcOpnd;
11305   MachineMemOperand *MMO;
11306
11307   switch (N->getOpcode()) {
11308   default:
11309     llvm_unreachable("Unexpected opcode for little endian VSX store");
11310   case ISD::STORE: {
11311     StoreSDNode *ST = cast<StoreSDNode>(N);
11312     Chain = ST->getChain();
11313     Base = ST->getBasePtr();
11314     MMO = ST->getMemOperand();
11315     SrcOpnd = 1;
11316     // If the MMO suggests this isn't a store of a full vector, leave
11317     // things alone.  For a built-in, we have to make the change for
11318     // correctness, so if there is a size problem that will be a bug.
11319     if (MMO->getSize() < 16)
11320       return SDValue();
11321     break;
11322   }
11323   case ISD::INTRINSIC_VOID: {
11324     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
11325     Chain = Intrin->getChain();
11326     // Intrin->getBasePtr() oddly does not get what we want.
11327     Base = Intrin->getOperand(3);
11328     MMO = Intrin->getMemOperand();
11329     SrcOpnd = 2;
11330     break;
11331   }
11332   }
11333
11334   SDValue Src = N->getOperand(SrcOpnd);
11335   MVT VecTy = Src.getValueType().getSimpleVT();
11336
11337   // Do not expand to PPCISD::XXSWAPD and PPCISD::STXVD2X when the load is
11338   // aligned and the type is a vector with elements up to 4 bytes
11339   if (Subtarget.needsSwapsForVSXMemOps() && !(MMO->getAlignment()%16)
11340       && VecTy.getScalarSizeInBits() <= 32 ) {
11341     return SDValue();
11342   }
11343
11344   // All stores are done as v2f64 and possible bit cast.
11345   if (VecTy != MVT::v2f64) {
11346     Src = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Src);
11347     DCI.AddToWorklist(Src.getNode());
11348   }
11349
11350   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
11351                              DAG.getVTList(MVT::v2f64, MVT::Other), Chain, Src);
11352   DCI.AddToWorklist(Swap.getNode());
11353   Chain = Swap.getValue(1);
11354   SDValue StoreOps[] = { Chain, Swap, Base };
11355   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
11356                                           DAG.getVTList(MVT::Other),
11357                                           StoreOps, VecTy, MMO);
11358   DCI.AddToWorklist(Store.getNode());
11359   return Store;
11360 }
11361
11362 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
11363                                              DAGCombinerInfo &DCI) const {
11364   SelectionDAG &DAG = DCI.DAG;
11365   SDLoc dl(N);
11366   switch (N->getOpcode()) {
11367   default: break;
11368   case ISD::SHL:
11369     return combineSHL(N, DCI);
11370   case ISD::SRA:
11371     return combineSRA(N, DCI);
11372   case ISD::SRL:
11373     return combineSRL(N, DCI);
11374   case PPCISD::SHL:
11375     if (isNullConstant(N->getOperand(0))) // 0 << V -> 0.
11376         return N->getOperand(0);
11377     break;
11378   case PPCISD::SRL:
11379     if (isNullConstant(N->getOperand(0))) // 0 >>u V -> 0.
11380         return N->getOperand(0);
11381     break;
11382   case PPCISD::SRA:
11383     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
11384       if (C->isNullValue() ||   //  0 >>s V -> 0.
11385           C->isAllOnesValue())    // -1 >>s V -> -1.
11386         return N->getOperand(0);
11387     }
11388     break;
11389   case ISD::SIGN_EXTEND:
11390   case ISD::ZERO_EXTEND:
11391   case ISD::ANY_EXTEND:
11392     return DAGCombineExtBoolTrunc(N, DCI);
11393   case ISD::TRUNCATE:
11394   case ISD::SETCC:
11395   case ISD::SELECT_CC:
11396     return DAGCombineTruncBoolExt(N, DCI);
11397   case ISD::SINT_TO_FP:
11398   case ISD::UINT_TO_FP:
11399     return combineFPToIntToFP(N, DCI);
11400   case ISD::STORE: {
11401     EVT Op1VT = N->getOperand(1).getValueType();
11402     bool ValidTypeForStoreFltAsInt = (Op1VT == MVT::i32) ||
11403       (Subtarget.hasP9Vector() && (Op1VT == MVT::i8 || Op1VT == MVT::i16));
11404
11405     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
11406     if (Subtarget.hasSTFIWX() && !cast<StoreSDNode>(N)->isTruncatingStore() &&
11407         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
11408         ValidTypeForStoreFltAsInt &&
11409         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
11410       SDValue Val = N->getOperand(1).getOperand(0);
11411       if (Val.getValueType() == MVT::f32) {
11412         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
11413         DCI.AddToWorklist(Val.getNode());
11414       }
11415       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
11416       DCI.AddToWorklist(Val.getNode());
11417
11418       if (Op1VT == MVT::i32) {
11419         SDValue Ops[] = {
11420           N->getOperand(0), Val, N->getOperand(2),
11421           DAG.getValueType(N->getOperand(1).getValueType())
11422         };
11423
11424         Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
11425                 DAG.getVTList(MVT::Other), Ops,
11426                 cast<StoreSDNode>(N)->getMemoryVT(),
11427                 cast<StoreSDNode>(N)->getMemOperand());
11428       } else {
11429         unsigned WidthInBytes =
11430           N->getOperand(1).getValueType() == MVT::i8 ? 1 : 2;
11431         SDValue WidthConst = DAG.getIntPtrConstant(WidthInBytes, dl, false);
11432
11433         SDValue Ops[] = {
11434           N->getOperand(0), Val, N->getOperand(2), WidthConst,
11435           DAG.getValueType(N->getOperand(1).getValueType())
11436         };
11437         Val = DAG.getMemIntrinsicNode(PPCISD::STXSIX, dl,
11438                                       DAG.getVTList(MVT::Other), Ops,
11439                                       cast<StoreSDNode>(N)->getMemoryVT(),
11440                                       cast<StoreSDNode>(N)->getMemOperand());
11441       }
11442
11443       DCI.AddToWorklist(Val.getNode());
11444       return Val;
11445     }
11446
11447     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
11448     if (cast<StoreSDNode>(N)->isUnindexed() &&
11449         N->getOperand(1).getOpcode() == ISD::BSWAP &&
11450         N->getOperand(1).getNode()->hasOneUse() &&
11451         (N->getOperand(1).getValueType() == MVT::i32 ||
11452          N->getOperand(1).getValueType() == MVT::i16 ||
11453          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11454           N->getOperand(1).getValueType() == MVT::i64))) {
11455       SDValue BSwapOp = N->getOperand(1).getOperand(0);
11456       // Do an any-extend to 32-bits if this is a half-word input.
11457       if (BSwapOp.getValueType() == MVT::i16)
11458         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
11459
11460       // If the type of BSWAP operand is wider than stored memory width
11461       // it need to be shifted to the right side before STBRX.
11462       EVT mVT = cast<StoreSDNode>(N)->getMemoryVT();
11463       if (Op1VT.bitsGT(mVT)) {
11464         int Shift = Op1VT.getSizeInBits() - mVT.getSizeInBits();
11465         BSwapOp = DAG.getNode(ISD::SRL, dl, Op1VT, BSwapOp,
11466                               DAG.getConstant(Shift, dl, MVT::i32));
11467         // Need to truncate if this is a bswap of i64 stored as i32/i16.
11468         if (Op1VT == MVT::i64)
11469           BSwapOp = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BSwapOp);
11470       }
11471
11472       SDValue Ops[] = {
11473         N->getOperand(0), BSwapOp, N->getOperand(2), DAG.getValueType(mVT)
11474       };
11475       return
11476         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
11477                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
11478                                 cast<StoreSDNode>(N)->getMemOperand());
11479     }
11480
11481     // For little endian, VSX stores require generating xxswapd/lxvd2x.
11482     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11483     EVT VT = N->getOperand(1).getValueType();
11484     if (VT.isSimple()) {
11485       MVT StoreVT = VT.getSimpleVT();
11486       if (Subtarget.needsSwapsForVSXMemOps() &&
11487           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
11488            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
11489         return expandVSXStoreForLE(N, DCI);
11490     }
11491     break;
11492   }
11493   case ISD::LOAD: {
11494     LoadSDNode *LD = cast<LoadSDNode>(N);
11495     EVT VT = LD->getValueType(0);
11496
11497     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11498     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11499     if (VT.isSimple()) {
11500       MVT LoadVT = VT.getSimpleVT();
11501       if (Subtarget.needsSwapsForVSXMemOps() &&
11502           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
11503            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
11504         return expandVSXLoadForLE(N, DCI);
11505     }
11506
11507     // We sometimes end up with a 64-bit integer load, from which we extract
11508     // two single-precision floating-point numbers. This happens with
11509     // std::complex<float>, and other similar structures, because of the way we
11510     // canonicalize structure copies. However, if we lack direct moves,
11511     // then the final bitcasts from the extracted integer values to the
11512     // floating-point numbers turn into store/load pairs. Even with direct moves,
11513     // just loading the two floating-point numbers is likely better.
11514     auto ReplaceTwoFloatLoad = [&]() {
11515       if (VT != MVT::i64)
11516         return false;
11517
11518       if (LD->getExtensionType() != ISD::NON_EXTLOAD ||
11519           LD->isVolatile())
11520         return false;
11521
11522       //  We're looking for a sequence like this:
11523       //  t13: i64,ch = load<LD8[%ref.tmp]> t0, t6, undef:i64
11524       //      t16: i64 = srl t13, Constant:i32<32>
11525       //    t17: i32 = truncate t16
11526       //  t18: f32 = bitcast t17
11527       //    t19: i32 = truncate t13
11528       //  t20: f32 = bitcast t19
11529
11530       if (!LD->hasNUsesOfValue(2, 0))
11531         return false;
11532
11533       auto UI = LD->use_begin();
11534       while (UI.getUse().getResNo() != 0) ++UI;
11535       SDNode *Trunc = *UI++;
11536       while (UI.getUse().getResNo() != 0) ++UI;
11537       SDNode *RightShift = *UI;
11538       if (Trunc->getOpcode() != ISD::TRUNCATE)
11539         std::swap(Trunc, RightShift);
11540
11541       if (Trunc->getOpcode() != ISD::TRUNCATE ||
11542           Trunc->getValueType(0) != MVT::i32 ||
11543           !Trunc->hasOneUse())
11544         return false;
11545       if (RightShift->getOpcode() != ISD::SRL ||
11546           !isa<ConstantSDNode>(RightShift->getOperand(1)) ||
11547           RightShift->getConstantOperandVal(1) != 32 ||
11548           !RightShift->hasOneUse())
11549         return false;
11550
11551       SDNode *Trunc2 = *RightShift->use_begin();
11552       if (Trunc2->getOpcode() != ISD::TRUNCATE ||
11553           Trunc2->getValueType(0) != MVT::i32 ||
11554           !Trunc2->hasOneUse())
11555         return false;
11556
11557       SDNode *Bitcast = *Trunc->use_begin();
11558       SDNode *Bitcast2 = *Trunc2->use_begin();
11559
11560       if (Bitcast->getOpcode() != ISD::BITCAST ||
11561           Bitcast->getValueType(0) != MVT::f32)
11562         return false;
11563       if (Bitcast2->getOpcode() != ISD::BITCAST ||
11564           Bitcast2->getValueType(0) != MVT::f32)
11565         return false;
11566
11567       if (Subtarget.isLittleEndian())
11568         std::swap(Bitcast, Bitcast2);
11569
11570       // Bitcast has the second float (in memory-layout order) and Bitcast2
11571       // has the first one.
11572
11573       SDValue BasePtr = LD->getBasePtr();
11574       if (LD->isIndexed()) {
11575         assert(LD->getAddressingMode() == ISD::PRE_INC &&
11576                "Non-pre-inc AM on PPC?");
11577         BasePtr =
11578           DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(), BasePtr,
11579                       LD->getOffset());
11580       }
11581
11582       auto MMOFlags =
11583           LD->getMemOperand()->getFlags() & ~MachineMemOperand::MOVolatile;
11584       SDValue FloatLoad = DAG.getLoad(MVT::f32, dl, LD->getChain(), BasePtr,
11585                                       LD->getPointerInfo(), LD->getAlignment(),
11586                                       MMOFlags, LD->getAAInfo());
11587       SDValue AddPtr =
11588         DAG.getNode(ISD::ADD, dl, BasePtr.getValueType(),
11589                     BasePtr, DAG.getIntPtrConstant(4, dl));
11590       SDValue FloatLoad2 = DAG.getLoad(
11591           MVT::f32, dl, SDValue(FloatLoad.getNode(), 1), AddPtr,
11592           LD->getPointerInfo().getWithOffset(4),
11593           MinAlign(LD->getAlignment(), 4), MMOFlags, LD->getAAInfo());
11594
11595       if (LD->isIndexed()) {
11596         // Note that DAGCombine should re-form any pre-increment load(s) from
11597         // what is produced here if that makes sense.
11598         DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), BasePtr);
11599       }
11600
11601       DCI.CombineTo(Bitcast2, FloatLoad);
11602       DCI.CombineTo(Bitcast, FloatLoad2);
11603
11604       DAG.ReplaceAllUsesOfValueWith(SDValue(LD, LD->isIndexed() ? 2 : 1),
11605                                     SDValue(FloatLoad2.getNode(), 1));
11606       return true;
11607     };
11608
11609     if (ReplaceTwoFloatLoad())
11610       return SDValue(N, 0);
11611
11612     EVT MemVT = LD->getMemoryVT();
11613     Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
11614     unsigned ABIAlignment = DAG.getDataLayout().getABITypeAlignment(Ty);
11615     Type *STy = MemVT.getScalarType().getTypeForEVT(*DAG.getContext());
11616     unsigned ScalarABIAlignment = DAG.getDataLayout().getABITypeAlignment(STy);
11617     if (LD->isUnindexed() && VT.isVector() &&
11618         ((Subtarget.hasAltivec() && ISD::isNON_EXTLoad(N) &&
11619           // P8 and later hardware should just use LOAD.
11620           !Subtarget.hasP8Vector() && (VT == MVT::v16i8 || VT == MVT::v8i16 ||
11621                                        VT == MVT::v4i32 || VT == MVT::v4f32)) ||
11622          (Subtarget.hasQPX() && (VT == MVT::v4f64 || VT == MVT::v4f32) &&
11623           LD->getAlignment() >= ScalarABIAlignment)) &&
11624         LD->getAlignment() < ABIAlignment) {
11625       // This is a type-legal unaligned Altivec or QPX load.
11626       SDValue Chain = LD->getChain();
11627       SDValue Ptr = LD->getBasePtr();
11628       bool isLittleEndian = Subtarget.isLittleEndian();
11629
11630       // This implements the loading of unaligned vectors as described in
11631       // the venerable Apple Velocity Engine overview. Specifically:
11632       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
11633       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
11634       //
11635       // The general idea is to expand a sequence of one or more unaligned
11636       // loads into an alignment-based permutation-control instruction (lvsl
11637       // or lvsr), a series of regular vector loads (which always truncate
11638       // their input address to an aligned address), and a series of
11639       // permutations.  The results of these permutations are the requested
11640       // loaded values.  The trick is that the last "extra" load is not taken
11641       // from the address you might suspect (sizeof(vector) bytes after the
11642       // last requested load), but rather sizeof(vector) - 1 bytes after the
11643       // last requested vector. The point of this is to avoid a page fault if
11644       // the base address happened to be aligned. This works because if the
11645       // base address is aligned, then adding less than a full vector length
11646       // will cause the last vector in the sequence to be (re)loaded.
11647       // Otherwise, the next vector will be fetched as you might suspect was
11648       // necessary.
11649
11650       // We might be able to reuse the permutation generation from
11651       // a different base address offset from this one by an aligned amount.
11652       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
11653       // optimization later.
11654       Intrinsic::ID Intr, IntrLD, IntrPerm;
11655       MVT PermCntlTy, PermTy, LDTy;
11656       if (Subtarget.hasAltivec()) {
11657         Intr = isLittleEndian ?  Intrinsic::ppc_altivec_lvsr :
11658                                  Intrinsic::ppc_altivec_lvsl;
11659         IntrLD = Intrinsic::ppc_altivec_lvx;
11660         IntrPerm = Intrinsic::ppc_altivec_vperm;
11661         PermCntlTy = MVT::v16i8;
11662         PermTy = MVT::v4i32;
11663         LDTy = MVT::v4i32;
11664       } else {
11665         Intr =   MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlpcld :
11666                                        Intrinsic::ppc_qpx_qvlpcls;
11667         IntrLD = MemVT == MVT::v4f64 ? Intrinsic::ppc_qpx_qvlfd :
11668                                        Intrinsic::ppc_qpx_qvlfs;
11669         IntrPerm = Intrinsic::ppc_qpx_qvfperm;
11670         PermCntlTy = MVT::v4f64;
11671         PermTy = MVT::v4f64;
11672         LDTy = MemVT.getSimpleVT();
11673       }
11674
11675       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, PermCntlTy);
11676
11677       // Create the new MMO for the new base load. It is like the original MMO,
11678       // but represents an area in memory almost twice the vector size centered
11679       // on the original address. If the address is unaligned, we might start
11680       // reading up to (sizeof(vector)-1) bytes below the address of the
11681       // original unaligned load.
11682       MachineFunction &MF = DAG.getMachineFunction();
11683       MachineMemOperand *BaseMMO =
11684         MF.getMachineMemOperand(LD->getMemOperand(),
11685                                 -(long)MemVT.getStoreSize()+1,
11686                                 2*MemVT.getStoreSize()-1);
11687
11688       // Create the new base load.
11689       SDValue LDXIntID =
11690           DAG.getTargetConstant(IntrLD, dl, getPointerTy(MF.getDataLayout()));
11691       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
11692       SDValue BaseLoad =
11693         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11694                                 DAG.getVTList(PermTy, MVT::Other),
11695                                 BaseLoadOps, LDTy, BaseMMO);
11696
11697       // Note that the value of IncOffset (which is provided to the next
11698       // load's pointer info offset value, and thus used to calculate the
11699       // alignment), and the value of IncValue (which is actually used to
11700       // increment the pointer value) are different! This is because we
11701       // require the next load to appear to be aligned, even though it
11702       // is actually offset from the base pointer by a lesser amount.
11703       int IncOffset = VT.getSizeInBits() / 8;
11704       int IncValue = IncOffset;
11705
11706       // Walk (both up and down) the chain looking for another load at the real
11707       // (aligned) offset (the alignment of the other load does not matter in
11708       // this case). If found, then do not use the offset reduction trick, as
11709       // that will prevent the loads from being later combined (as they would
11710       // otherwise be duplicates).
11711       if (!findConsecutiveLoad(LD, DAG))
11712         --IncValue;
11713
11714       SDValue Increment =
11715           DAG.getConstant(IncValue, dl, getPointerTy(MF.getDataLayout()));
11716       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
11717
11718       MachineMemOperand *ExtraMMO =
11719         MF.getMachineMemOperand(LD->getMemOperand(),
11720                                 1, 2*MemVT.getStoreSize()-1);
11721       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
11722       SDValue ExtraLoad =
11723         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
11724                                 DAG.getVTList(PermTy, MVT::Other),
11725                                 ExtraLoadOps, LDTy, ExtraMMO);
11726
11727       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
11728         BaseLoad.getValue(1), ExtraLoad.getValue(1));
11729
11730       // Because vperm has a big-endian bias, we must reverse the order
11731       // of the input vectors and complement the permute control vector
11732       // when generating little endian code.  We have already handled the
11733       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
11734       // and ExtraLoad here.
11735       SDValue Perm;
11736       if (isLittleEndian)
11737         Perm = BuildIntrinsicOp(IntrPerm,
11738                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
11739       else
11740         Perm = BuildIntrinsicOp(IntrPerm,
11741                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
11742
11743       if (VT != PermTy)
11744         Perm = Subtarget.hasAltivec() ?
11745                  DAG.getNode(ISD::BITCAST, dl, VT, Perm) :
11746                  DAG.getNode(ISD::FP_ROUND, dl, VT, Perm, // QPX
11747                                DAG.getTargetConstant(1, dl, MVT::i64));
11748                                // second argument is 1 because this rounding
11749                                // is always exact.
11750
11751       // The output of the permutation is our loaded result, the TokenFactor is
11752       // our new chain.
11753       DCI.CombineTo(N, Perm, TF);
11754       return SDValue(N, 0);
11755     }
11756     }
11757     break;
11758     case ISD::INTRINSIC_WO_CHAIN: {
11759       bool isLittleEndian = Subtarget.isLittleEndian();
11760       unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11761       Intrinsic::ID Intr = (isLittleEndian ? Intrinsic::ppc_altivec_lvsr
11762                                            : Intrinsic::ppc_altivec_lvsl);
11763       if ((IID == Intr ||
11764            IID == Intrinsic::ppc_qpx_qvlpcld  ||
11765            IID == Intrinsic::ppc_qpx_qvlpcls) &&
11766         N->getOperand(1)->getOpcode() == ISD::ADD) {
11767         SDValue Add = N->getOperand(1);
11768
11769         int Bits = IID == Intrinsic::ppc_qpx_qvlpcld ?
11770                    5 /* 32 byte alignment */ : 4 /* 16 byte alignment */;
11771
11772         if (DAG.MaskedValueIsZero(Add->getOperand(1),
11773                                   APInt::getAllOnesValue(Bits /* alignment */)
11774                                       .zext(Add.getScalarValueSizeInBits()))) {
11775           SDNode *BasePtr = Add->getOperand(0).getNode();
11776           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11777                                     UE = BasePtr->use_end();
11778                UI != UE; ++UI) {
11779             if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11780                 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() == IID) {
11781               // We've found another LVSL/LVSR, and this address is an aligned
11782               // multiple of that one. The results will be the same, so use the
11783               // one we've just found instead.
11784
11785               return SDValue(*UI, 0);
11786             }
11787           }
11788         }
11789
11790         if (isa<ConstantSDNode>(Add->getOperand(1))) {
11791           SDNode *BasePtr = Add->getOperand(0).getNode();
11792           for (SDNode::use_iterator UI = BasePtr->use_begin(),
11793                UE = BasePtr->use_end(); UI != UE; ++UI) {
11794             if (UI->getOpcode() == ISD::ADD &&
11795                 isa<ConstantSDNode>(UI->getOperand(1)) &&
11796                 (cast<ConstantSDNode>(Add->getOperand(1))->getZExtValue() -
11797                  cast<ConstantSDNode>(UI->getOperand(1))->getZExtValue()) %
11798                 (1ULL << Bits) == 0) {
11799               SDNode *OtherAdd = *UI;
11800               for (SDNode::use_iterator VI = OtherAdd->use_begin(),
11801                    VE = OtherAdd->use_end(); VI != VE; ++VI) {
11802                 if (VI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11803                     cast<ConstantSDNode>(VI->getOperand(0))->getZExtValue() == IID) {
11804                   return SDValue(*VI, 0);
11805                 }
11806               }
11807             }
11808           }
11809         }
11810       }
11811     }
11812
11813     break;
11814   case ISD::INTRINSIC_W_CHAIN:
11815     // For little endian, VSX loads require generating lxvd2x/xxswapd.
11816     // Not needed on ISA 3.0 based CPUs since we have a non-permuting load.
11817     if (Subtarget.needsSwapsForVSXMemOps()) {
11818       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11819       default:
11820         break;
11821       case Intrinsic::ppc_vsx_lxvw4x:
11822       case Intrinsic::ppc_vsx_lxvd2x:
11823         return expandVSXLoadForLE(N, DCI);
11824       }
11825     }
11826     break;
11827   case ISD::INTRINSIC_VOID:
11828     // For little endian, VSX stores require generating xxswapd/stxvd2x.
11829     // Not needed on ISA 3.0 based CPUs since we have a non-permuting store.
11830     if (Subtarget.needsSwapsForVSXMemOps()) {
11831       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
11832       default:
11833         break;
11834       case Intrinsic::ppc_vsx_stxvw4x:
11835       case Intrinsic::ppc_vsx_stxvd2x:
11836         return expandVSXStoreForLE(N, DCI);
11837       }
11838     }
11839     break;
11840   case ISD::BSWAP:
11841     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
11842     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
11843         N->getOperand(0).hasOneUse() &&
11844         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
11845          (Subtarget.hasLDBRX() && Subtarget.isPPC64() &&
11846           N->getValueType(0) == MVT::i64))) {
11847       SDValue Load = N->getOperand(0);
11848       LoadSDNode *LD = cast<LoadSDNode>(Load);
11849       // Create the byte-swapping load.
11850       SDValue Ops[] = {
11851         LD->getChain(),    // Chain
11852         LD->getBasePtr(),  // Ptr
11853         DAG.getValueType(N->getValueType(0)) // VT
11854       };
11855       SDValue BSLoad =
11856         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
11857                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
11858                                               MVT::i64 : MVT::i32, MVT::Other),
11859                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
11860
11861       // If this is an i16 load, insert the truncate.
11862       SDValue ResVal = BSLoad;
11863       if (N->getValueType(0) == MVT::i16)
11864         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
11865
11866       // First, combine the bswap away.  This makes the value produced by the
11867       // load dead.
11868       DCI.CombineTo(N, ResVal);
11869
11870       // Next, combine the load away, we give it a bogus result value but a real
11871       // chain result.  The result value is dead because the bswap is dead.
11872       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
11873
11874       // Return N so it doesn't get rechecked!
11875       return SDValue(N, 0);
11876     }
11877     break;
11878   case PPCISD::VCMP:
11879     // If a VCMPo node already exists with exactly the same operands as this
11880     // node, use its result instead of this node (VCMPo computes both a CR6 and
11881     // a normal output).
11882     //
11883     if (!N->getOperand(0).hasOneUse() &&
11884         !N->getOperand(1).hasOneUse() &&
11885         !N->getOperand(2).hasOneUse()) {
11886
11887       // Scan all of the users of the LHS, looking for VCMPo's that match.
11888       SDNode *VCMPoNode = nullptr;
11889
11890       SDNode *LHSN = N->getOperand(0).getNode();
11891       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
11892            UI != E; ++UI)
11893         if (UI->getOpcode() == PPCISD::VCMPo &&
11894             UI->getOperand(1) == N->getOperand(1) &&
11895             UI->getOperand(2) == N->getOperand(2) &&
11896             UI->getOperand(0) == N->getOperand(0)) {
11897           VCMPoNode = *UI;
11898           break;
11899         }
11900
11901       // If there is no VCMPo node, or if the flag value has a single use, don't
11902       // transform this.
11903       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
11904         break;
11905
11906       // Look at the (necessarily single) use of the flag value.  If it has a
11907       // chain, this transformation is more complex.  Note that multiple things
11908       // could use the value result, which we should ignore.
11909       SDNode *FlagUser = nullptr;
11910       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
11911            FlagUser == nullptr; ++UI) {
11912         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
11913         SDNode *User = *UI;
11914         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
11915           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
11916             FlagUser = User;
11917             break;
11918           }
11919         }
11920       }
11921
11922       // If the user is a MFOCRF instruction, we know this is safe.
11923       // Otherwise we give up for right now.
11924       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
11925         return SDValue(VCMPoNode, 0);
11926     }
11927     break;
11928   case ISD::BRCOND: {
11929     SDValue Cond = N->getOperand(1);
11930     SDValue Target = N->getOperand(2);
11931
11932     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11933         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
11934           Intrinsic::ppc_is_decremented_ctr_nonzero) {
11935
11936       // We now need to make the intrinsic dead (it cannot be instruction
11937       // selected).
11938       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
11939       assert(Cond.getNode()->hasOneUse() &&
11940              "Counter decrement has more than one use");
11941
11942       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
11943                          N->getOperand(0), Target);
11944     }
11945   }
11946   break;
11947   case ISD::BR_CC: {
11948     // If this is a branch on an altivec predicate comparison, lower this so
11949     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
11950     // lowering is done pre-legalize, because the legalizer lowers the predicate
11951     // compare down to code that is difficult to reassemble.
11952     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
11953     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
11954
11955     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
11956     // value. If so, pass-through the AND to get to the intrinsic.
11957     if (LHS.getOpcode() == ISD::AND &&
11958         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11959         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
11960           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11961         isa<ConstantSDNode>(LHS.getOperand(1)) &&
11962         !isNullConstant(LHS.getOperand(1)))
11963       LHS = LHS.getOperand(0);
11964
11965     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
11966         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
11967           Intrinsic::ppc_is_decremented_ctr_nonzero &&
11968         isa<ConstantSDNode>(RHS)) {
11969       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
11970              "Counter decrement comparison is not EQ or NE");
11971
11972       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11973       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
11974                     (CC == ISD::SETNE && !Val);
11975
11976       // We now need to make the intrinsic dead (it cannot be instruction
11977       // selected).
11978       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
11979       assert(LHS.getNode()->hasOneUse() &&
11980              "Counter decrement has more than one use");
11981
11982       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
11983                          N->getOperand(0), N->getOperand(4));
11984     }
11985
11986     int CompareOpc;
11987     bool isDot;
11988
11989     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
11990         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
11991         getVectorCompareInfo(LHS, CompareOpc, isDot, Subtarget)) {
11992       assert(isDot && "Can't compare against a vector result!");
11993
11994       // If this is a comparison against something other than 0/1, then we know
11995       // that the condition is never/always true.
11996       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
11997       if (Val != 0 && Val != 1) {
11998         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
11999           return N->getOperand(0);
12000         // Always !=, turn it into an unconditional branch.
12001         return DAG.getNode(ISD::BR, dl, MVT::Other,
12002                            N->getOperand(0), N->getOperand(4));
12003       }
12004
12005       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
12006
12007       // Create the PPCISD altivec 'dot' comparison node.
12008       SDValue Ops[] = {
12009         LHS.getOperand(2),  // LHS of compare
12010         LHS.getOperand(3),  // RHS of compare
12011         DAG.getConstant(CompareOpc, dl, MVT::i32)
12012       };
12013       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
12014       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
12015
12016       // Unpack the result based on how the target uses it.
12017       PPC::Predicate CompOpc;
12018       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
12019       default:  // Can't happen, don't crash on invalid number though.
12020       case 0:   // Branch on the value of the EQ bit of CR6.
12021         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
12022         break;
12023       case 1:   // Branch on the inverted value of the EQ bit of CR6.
12024         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
12025         break;
12026       case 2:   // Branch on the value of the LT bit of CR6.
12027         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
12028         break;
12029       case 3:   // Branch on the inverted value of the LT bit of CR6.
12030         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
12031         break;
12032       }
12033
12034       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
12035                          DAG.getConstant(CompOpc, dl, MVT::i32),
12036                          DAG.getRegister(PPC::CR6, MVT::i32),
12037                          N->getOperand(4), CompNode.getValue(1));
12038     }
12039     break;
12040   }
12041   case ISD::BUILD_VECTOR:
12042     return DAGCombineBuildVector(N, DCI);
12043   }
12044
12045   return SDValue();
12046 }
12047
12048 SDValue
12049 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
12050                                   SelectionDAG &DAG,
12051                                   std::vector<SDNode *> *Created) const {
12052   // fold (sdiv X, pow2)
12053   EVT VT = N->getValueType(0);
12054   if (VT == MVT::i64 && !Subtarget.isPPC64())
12055     return SDValue();
12056   if ((VT != MVT::i32 && VT != MVT::i64) ||
12057       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
12058     return SDValue();
12059
12060   SDLoc DL(N);
12061   SDValue N0 = N->getOperand(0);
12062
12063   bool IsNegPow2 = (-Divisor).isPowerOf2();
12064   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
12065   SDValue ShiftAmt = DAG.getConstant(Lg2, DL, VT);
12066
12067   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
12068   if (Created)
12069     Created->push_back(Op.getNode());
12070
12071   if (IsNegPow2) {
12072     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
12073     if (Created)
12074       Created->push_back(Op.getNode());
12075   }
12076
12077   return Op;
12078 }
12079
12080 //===----------------------------------------------------------------------===//
12081 // Inline Assembly Support
12082 //===----------------------------------------------------------------------===//
12083
12084 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12085                                                       KnownBits &Known,
12086                                                       const APInt &DemandedElts,
12087                                                       const SelectionDAG &DAG,
12088                                                       unsigned Depth) const {
12089   Known.resetAll();
12090   switch (Op.getOpcode()) {
12091   default: break;
12092   case PPCISD::LBRX: {
12093     // lhbrx is known to have the top bits cleared out.
12094     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
12095       Known.Zero = 0xFFFF0000;
12096     break;
12097   }
12098   case ISD::INTRINSIC_WO_CHAIN: {
12099     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
12100     default: break;
12101     case Intrinsic::ppc_altivec_vcmpbfp_p:
12102     case Intrinsic::ppc_altivec_vcmpeqfp_p:
12103     case Intrinsic::ppc_altivec_vcmpequb_p:
12104     case Intrinsic::ppc_altivec_vcmpequh_p:
12105     case Intrinsic::ppc_altivec_vcmpequw_p:
12106     case Intrinsic::ppc_altivec_vcmpequd_p:
12107     case Intrinsic::ppc_altivec_vcmpgefp_p:
12108     case Intrinsic::ppc_altivec_vcmpgtfp_p:
12109     case Intrinsic::ppc_altivec_vcmpgtsb_p:
12110     case Intrinsic::ppc_altivec_vcmpgtsh_p:
12111     case Intrinsic::ppc_altivec_vcmpgtsw_p:
12112     case Intrinsic::ppc_altivec_vcmpgtsd_p:
12113     case Intrinsic::ppc_altivec_vcmpgtub_p:
12114     case Intrinsic::ppc_altivec_vcmpgtuh_p:
12115     case Intrinsic::ppc_altivec_vcmpgtuw_p:
12116     case Intrinsic::ppc_altivec_vcmpgtud_p:
12117       Known.Zero = ~1U;  // All bits but the low one are known to be zero.
12118       break;
12119     }
12120   }
12121   }
12122 }
12123
12124 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
12125   switch (Subtarget.getDarwinDirective()) {
12126   default: break;
12127   case PPC::DIR_970:
12128   case PPC::DIR_PWR4:
12129   case PPC::DIR_PWR5:
12130   case PPC::DIR_PWR5X:
12131   case PPC::DIR_PWR6:
12132   case PPC::DIR_PWR6X:
12133   case PPC::DIR_PWR7:
12134   case PPC::DIR_PWR8:
12135   case PPC::DIR_PWR9: {
12136     if (!ML)
12137       break;
12138
12139     const PPCInstrInfo *TII = Subtarget.getInstrInfo();
12140
12141     // For small loops (between 5 and 8 instructions), align to a 32-byte
12142     // boundary so that the entire loop fits in one instruction-cache line.
12143     uint64_t LoopSize = 0;
12144     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
12145       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J) {
12146         LoopSize += TII->getInstSizeInBytes(*J);
12147         if (LoopSize > 32)
12148           break;
12149       }
12150
12151     if (LoopSize > 16 && LoopSize <= 32)
12152       return 5;
12153
12154     break;
12155   }
12156   }
12157
12158   return TargetLowering::getPrefLoopAlignment(ML);
12159 }
12160
12161 /// getConstraintType - Given a constraint, return the type of
12162 /// constraint it is for this target.
12163 PPCTargetLowering::ConstraintType
12164 PPCTargetLowering::getConstraintType(StringRef Constraint) const {
12165   if (Constraint.size() == 1) {
12166     switch (Constraint[0]) {
12167     default: break;
12168     case 'b':
12169     case 'r':
12170     case 'f':
12171     case 'd':
12172     case 'v':
12173     case 'y':
12174       return C_RegisterClass;
12175     case 'Z':
12176       // FIXME: While Z does indicate a memory constraint, it specifically
12177       // indicates an r+r address (used in conjunction with the 'y' modifier
12178       // in the replacement string). Currently, we're forcing the base
12179       // register to be r0 in the asm printer (which is interpreted as zero)
12180       // and forming the complete address in the second register. This is
12181       // suboptimal.
12182       return C_Memory;
12183     }
12184   } else if (Constraint == "wc") { // individual CR bits.
12185     return C_RegisterClass;
12186   } else if (Constraint == "wa" || Constraint == "wd" ||
12187              Constraint == "wf" || Constraint == "ws") {
12188     return C_RegisterClass; // VSX registers.
12189   }
12190   return TargetLowering::getConstraintType(Constraint);
12191 }
12192
12193 /// Examine constraint type and operand type and determine a weight value.
12194 /// This object must already have been set up with the operand type
12195 /// and the current alternative constraint selected.
12196 TargetLowering::ConstraintWeight
12197 PPCTargetLowering::getSingleConstraintMatchWeight(
12198     AsmOperandInfo &info, const char *constraint) const {
12199   ConstraintWeight weight = CW_Invalid;
12200   Value *CallOperandVal = info.CallOperandVal;
12201     // If we don't have a value, we can't do a match,
12202     // but allow it at the lowest weight.
12203   if (!CallOperandVal)
12204     return CW_Default;
12205   Type *type = CallOperandVal->getType();
12206
12207   // Look at the constraint type.
12208   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
12209     return CW_Register; // an individual CR bit.
12210   else if ((StringRef(constraint) == "wa" ||
12211             StringRef(constraint) == "wd" ||
12212             StringRef(constraint) == "wf") &&
12213            type->isVectorTy())
12214     return CW_Register;
12215   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
12216     return CW_Register;
12217
12218   switch (*constraint) {
12219   default:
12220     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12221     break;
12222   case 'b':
12223     if (type->isIntegerTy())
12224       weight = CW_Register;
12225     break;
12226   case 'f':
12227     if (type->isFloatTy())
12228       weight = CW_Register;
12229     break;
12230   case 'd':
12231     if (type->isDoubleTy())
12232       weight = CW_Register;
12233     break;
12234   case 'v':
12235     if (type->isVectorTy())
12236       weight = CW_Register;
12237     break;
12238   case 'y':
12239     weight = CW_Register;
12240     break;
12241   case 'Z':
12242     weight = CW_Memory;
12243     break;
12244   }
12245   return weight;
12246 }
12247
12248 std::pair<unsigned, const TargetRegisterClass *>
12249 PPCTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
12250                                                 StringRef Constraint,
12251                                                 MVT VT) const {
12252   if (Constraint.size() == 1) {
12253     // GCC RS6000 Constraint Letters
12254     switch (Constraint[0]) {
12255     case 'b':   // R1-R31
12256       if (VT == MVT::i64 && Subtarget.isPPC64())
12257         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
12258       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
12259     case 'r':   // R0-R31
12260       if (VT == MVT::i64 && Subtarget.isPPC64())
12261         return std::make_pair(0U, &PPC::G8RCRegClass);
12262       return std::make_pair(0U, &PPC::GPRCRegClass);
12263     // 'd' and 'f' constraints are both defined to be "the floating point
12264     // registers", where one is for 32-bit and the other for 64-bit. We don't
12265     // really care overly much here so just give them all the same reg classes.
12266     case 'd':
12267     case 'f':
12268       if (VT == MVT::f32 || VT == MVT::i32)
12269         return std::make_pair(0U, &PPC::F4RCRegClass);
12270       if (VT == MVT::f64 || VT == MVT::i64)
12271         return std::make_pair(0U, &PPC::F8RCRegClass);
12272       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12273         return std::make_pair(0U, &PPC::QFRCRegClass);
12274       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12275         return std::make_pair(0U, &PPC::QSRCRegClass);
12276       break;
12277     case 'v':
12278       if (VT == MVT::v4f64 && Subtarget.hasQPX())
12279         return std::make_pair(0U, &PPC::QFRCRegClass);
12280       if (VT == MVT::v4f32 && Subtarget.hasQPX())
12281         return std::make_pair(0U, &PPC::QSRCRegClass);
12282       if (Subtarget.hasAltivec())
12283         return std::make_pair(0U, &PPC::VRRCRegClass);
12284     case 'y':   // crrc
12285       return std::make_pair(0U, &PPC::CRRCRegClass);
12286     }
12287   } else if (Constraint == "wc" && Subtarget.useCRBits()) {
12288     // An individual CR bit.
12289     return std::make_pair(0U, &PPC::CRBITRCRegClass);
12290   } else if ((Constraint == "wa" || Constraint == "wd" ||
12291              Constraint == "wf") && Subtarget.hasVSX()) {
12292     return std::make_pair(0U, &PPC::VSRCRegClass);
12293   } else if (Constraint == "ws" && Subtarget.hasVSX()) {
12294     if (VT == MVT::f32 && Subtarget.hasP8Vector())
12295       return std::make_pair(0U, &PPC::VSSRCRegClass);
12296     else
12297       return std::make_pair(0U, &PPC::VSFRCRegClass);
12298   }
12299
12300   std::pair<unsigned, const TargetRegisterClass *> R =
12301       TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12302
12303   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
12304   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
12305   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
12306   // register.
12307   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
12308   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
12309   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
12310       PPC::GPRCRegClass.contains(R.first))
12311     return std::make_pair(TRI->getMatchingSuperReg(R.first,
12312                             PPC::sub_32, &PPC::G8RCRegClass),
12313                           &PPC::G8RCRegClass);
12314
12315   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
12316   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
12317     R.first = PPC::CR0;
12318     R.second = &PPC::CRRCRegClass;
12319   }
12320
12321   return R;
12322 }
12323
12324 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12325 /// vector.  If it is invalid, don't add anything to Ops.
12326 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12327                                                      std::string &Constraint,
12328                                                      std::vector<SDValue>&Ops,
12329                                                      SelectionDAG &DAG) const {
12330   SDValue Result;
12331
12332   // Only support length 1 constraints.
12333   if (Constraint.length() > 1) return;
12334
12335   char Letter = Constraint[0];
12336   switch (Letter) {
12337   default: break;
12338   case 'I':
12339   case 'J':
12340   case 'K':
12341   case 'L':
12342   case 'M':
12343   case 'N':
12344   case 'O':
12345   case 'P': {
12346     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
12347     if (!CST) return; // Must be an immediate to match.
12348     SDLoc dl(Op);
12349     int64_t Value = CST->getSExtValue();
12350     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
12351                          // numbers are printed as such.
12352     switch (Letter) {
12353     default: llvm_unreachable("Unknown constraint letter!");
12354     case 'I':  // "I" is a signed 16-bit constant.
12355       if (isInt<16>(Value))
12356         Result = DAG.getTargetConstant(Value, dl, TCVT);
12357       break;
12358     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
12359       if (isShiftedUInt<16, 16>(Value))
12360         Result = DAG.getTargetConstant(Value, dl, TCVT);
12361       break;
12362     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
12363       if (isShiftedInt<16, 16>(Value))
12364         Result = DAG.getTargetConstant(Value, dl, TCVT);
12365       break;
12366     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
12367       if (isUInt<16>(Value))
12368         Result = DAG.getTargetConstant(Value, dl, TCVT);
12369       break;
12370     case 'M':  // "M" is a constant that is greater than 31.
12371       if (Value > 31)
12372         Result = DAG.getTargetConstant(Value, dl, TCVT);
12373       break;
12374     case 'N':  // "N" is a positive constant that is an exact power of two.
12375       if (Value > 0 && isPowerOf2_64(Value))
12376         Result = DAG.getTargetConstant(Value, dl, TCVT);
12377       break;
12378     case 'O':  // "O" is the constant zero.
12379       if (Value == 0)
12380         Result = DAG.getTargetConstant(Value, dl, TCVT);
12381       break;
12382     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
12383       if (isInt<16>(-Value))
12384         Result = DAG.getTargetConstant(Value, dl, TCVT);
12385       break;
12386     }
12387     break;
12388   }
12389   }
12390
12391   if (Result.getNode()) {
12392     Ops.push_back(Result);
12393     return;
12394   }
12395
12396   // Handle standard constraint letters.
12397   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12398 }
12399
12400 // isLegalAddressingMode - Return true if the addressing mode represented
12401 // by AM is legal for this target, for a load/store of the specified type.
12402 bool PPCTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12403                                               const AddrMode &AM, Type *Ty,
12404                                               unsigned AS) const {
12405   // PPC does not allow r+i addressing modes for vectors!
12406   if (Ty->isVectorTy() && AM.BaseOffs != 0)
12407     return false;
12408
12409   // PPC allows a sign-extended 16-bit immediate field.
12410   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
12411     return false;
12412
12413   // No global is ever allowed as a base.
12414   if (AM.BaseGV)
12415     return false;
12416
12417   // PPC only support r+r,
12418   switch (AM.Scale) {
12419   case 0:  // "r+i" or just "i", depending on HasBaseReg.
12420     break;
12421   case 1:
12422     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
12423       return false;
12424     // Otherwise we have r+r or r+i.
12425     break;
12426   case 2:
12427     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
12428       return false;
12429     // Allow 2*r as r+r.
12430     break;
12431   default:
12432     // No other scales are supported.
12433     return false;
12434   }
12435
12436   return true;
12437 }
12438
12439 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
12440                                            SelectionDAG &DAG) const {
12441   MachineFunction &MF = DAG.getMachineFunction();
12442   MachineFrameInfo &MFI = MF.getFrameInfo();
12443   MFI.setReturnAddressIsTaken(true);
12444
12445   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12446     return SDValue();
12447
12448   SDLoc dl(Op);
12449   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12450
12451   // Make sure the function does not optimize away the store of the RA to
12452   // the stack.
12453   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
12454   FuncInfo->setLRStoreRequired();
12455   bool isPPC64 = Subtarget.isPPC64();
12456   auto PtrVT = getPointerTy(MF.getDataLayout());
12457
12458   if (Depth > 0) {
12459     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12460     SDValue Offset =
12461         DAG.getConstant(Subtarget.getFrameLowering()->getReturnSaveOffset(), dl,
12462                         isPPC64 ? MVT::i64 : MVT::i32);
12463     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12464                        DAG.getNode(ISD::ADD, dl, PtrVT, FrameAddr, Offset),
12465                        MachinePointerInfo());
12466   }
12467
12468   // Just load the return address off the stack.
12469   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
12470   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), RetAddrFI,
12471                      MachinePointerInfo());
12472 }
12473
12474 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
12475                                           SelectionDAG &DAG) const {
12476   SDLoc dl(Op);
12477   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12478
12479   MachineFunction &MF = DAG.getMachineFunction();
12480   MachineFrameInfo &MFI = MF.getFrameInfo();
12481   MFI.setFrameAddressIsTaken(true);
12482
12483   EVT PtrVT = getPointerTy(MF.getDataLayout());
12484   bool isPPC64 = PtrVT == MVT::i64;
12485
12486   // Naked functions never have a frame pointer, and so we use r1. For all
12487   // other functions, this decision must be delayed until during PEI.
12488   unsigned FrameReg;
12489   if (MF.getFunction()->hasFnAttribute(Attribute::Naked))
12490     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
12491   else
12492     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
12493
12494   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
12495                                          PtrVT);
12496   while (Depth--)
12497     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
12498                             FrameAddr, MachinePointerInfo());
12499   return FrameAddr;
12500 }
12501
12502 // FIXME? Maybe this could be a TableGen attribute on some registers and
12503 // this table could be generated automatically from RegInfo.
12504 unsigned PPCTargetLowering::getRegisterByName(const char* RegName, EVT VT,
12505                                               SelectionDAG &DAG) const {
12506   bool isPPC64 = Subtarget.isPPC64();
12507   bool isDarwinABI = Subtarget.isDarwinABI();
12508
12509   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
12510       (!isPPC64 && VT != MVT::i32))
12511     report_fatal_error("Invalid register global variable type");
12512
12513   bool is64Bit = isPPC64 && VT == MVT::i64;
12514   unsigned Reg = StringSwitch<unsigned>(RegName)
12515                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
12516                    .Case("r2", (isDarwinABI || isPPC64) ? 0 : PPC::R2)
12517                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
12518                                   (is64Bit ? PPC::X13 : PPC::R13))
12519                    .Default(0);
12520
12521   if (Reg)
12522     return Reg;
12523   report_fatal_error("Invalid register name global variable");
12524 }
12525
12526 bool
12527 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
12528   // The PowerPC target isn't yet aware of offsets.
12529   return false;
12530 }
12531
12532 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
12533                                            const CallInst &I,
12534                                            unsigned Intrinsic) const {
12535   switch (Intrinsic) {
12536   case Intrinsic::ppc_qpx_qvlfd:
12537   case Intrinsic::ppc_qpx_qvlfs:
12538   case Intrinsic::ppc_qpx_qvlfcd:
12539   case Intrinsic::ppc_qpx_qvlfcs:
12540   case Intrinsic::ppc_qpx_qvlfiwa:
12541   case Intrinsic::ppc_qpx_qvlfiwz:
12542   case Intrinsic::ppc_altivec_lvx:
12543   case Intrinsic::ppc_altivec_lvxl:
12544   case Intrinsic::ppc_altivec_lvebx:
12545   case Intrinsic::ppc_altivec_lvehx:
12546   case Intrinsic::ppc_altivec_lvewx:
12547   case Intrinsic::ppc_vsx_lxvd2x:
12548   case Intrinsic::ppc_vsx_lxvw4x: {
12549     EVT VT;
12550     switch (Intrinsic) {
12551     case Intrinsic::ppc_altivec_lvebx:
12552       VT = MVT::i8;
12553       break;
12554     case Intrinsic::ppc_altivec_lvehx:
12555       VT = MVT::i16;
12556       break;
12557     case Intrinsic::ppc_altivec_lvewx:
12558       VT = MVT::i32;
12559       break;
12560     case Intrinsic::ppc_vsx_lxvd2x:
12561       VT = MVT::v2f64;
12562       break;
12563     case Intrinsic::ppc_qpx_qvlfd:
12564       VT = MVT::v4f64;
12565       break;
12566     case Intrinsic::ppc_qpx_qvlfs:
12567       VT = MVT::v4f32;
12568       break;
12569     case Intrinsic::ppc_qpx_qvlfcd:
12570       VT = MVT::v2f64;
12571       break;
12572     case Intrinsic::ppc_qpx_qvlfcs:
12573       VT = MVT::v2f32;
12574       break;
12575     default:
12576       VT = MVT::v4i32;
12577       break;
12578     }
12579
12580     Info.opc = ISD::INTRINSIC_W_CHAIN;
12581     Info.memVT = VT;
12582     Info.ptrVal = I.getArgOperand(0);
12583     Info.offset = -VT.getStoreSize()+1;
12584     Info.size = 2*VT.getStoreSize()-1;
12585     Info.align = 1;
12586     Info.vol = false;
12587     Info.readMem = true;
12588     Info.writeMem = false;
12589     return true;
12590   }
12591   case Intrinsic::ppc_qpx_qvlfda:
12592   case Intrinsic::ppc_qpx_qvlfsa:
12593   case Intrinsic::ppc_qpx_qvlfcda:
12594   case Intrinsic::ppc_qpx_qvlfcsa:
12595   case Intrinsic::ppc_qpx_qvlfiwaa:
12596   case Intrinsic::ppc_qpx_qvlfiwza: {
12597     EVT VT;
12598     switch (Intrinsic) {
12599     case Intrinsic::ppc_qpx_qvlfda:
12600       VT = MVT::v4f64;
12601       break;
12602     case Intrinsic::ppc_qpx_qvlfsa:
12603       VT = MVT::v4f32;
12604       break;
12605     case Intrinsic::ppc_qpx_qvlfcda:
12606       VT = MVT::v2f64;
12607       break;
12608     case Intrinsic::ppc_qpx_qvlfcsa:
12609       VT = MVT::v2f32;
12610       break;
12611     default:
12612       VT = MVT::v4i32;
12613       break;
12614     }
12615
12616     Info.opc = ISD::INTRINSIC_W_CHAIN;
12617     Info.memVT = VT;
12618     Info.ptrVal = I.getArgOperand(0);
12619     Info.offset = 0;
12620     Info.size = VT.getStoreSize();
12621     Info.align = 1;
12622     Info.vol = false;
12623     Info.readMem = true;
12624     Info.writeMem = false;
12625     return true;
12626   }
12627   case Intrinsic::ppc_qpx_qvstfd:
12628   case Intrinsic::ppc_qpx_qvstfs:
12629   case Intrinsic::ppc_qpx_qvstfcd:
12630   case Intrinsic::ppc_qpx_qvstfcs:
12631   case Intrinsic::ppc_qpx_qvstfiw:
12632   case Intrinsic::ppc_altivec_stvx:
12633   case Intrinsic::ppc_altivec_stvxl:
12634   case Intrinsic::ppc_altivec_stvebx:
12635   case Intrinsic::ppc_altivec_stvehx:
12636   case Intrinsic::ppc_altivec_stvewx:
12637   case Intrinsic::ppc_vsx_stxvd2x:
12638   case Intrinsic::ppc_vsx_stxvw4x: {
12639     EVT VT;
12640     switch (Intrinsic) {
12641     case Intrinsic::ppc_altivec_stvebx:
12642       VT = MVT::i8;
12643       break;
12644     case Intrinsic::ppc_altivec_stvehx:
12645       VT = MVT::i16;
12646       break;
12647     case Intrinsic::ppc_altivec_stvewx:
12648       VT = MVT::i32;
12649       break;
12650     case Intrinsic::ppc_vsx_stxvd2x:
12651       VT = MVT::v2f64;
12652       break;
12653     case Intrinsic::ppc_qpx_qvstfd:
12654       VT = MVT::v4f64;
12655       break;
12656     case Intrinsic::ppc_qpx_qvstfs:
12657       VT = MVT::v4f32;
12658       break;
12659     case Intrinsic::ppc_qpx_qvstfcd:
12660       VT = MVT::v2f64;
12661       break;
12662     case Intrinsic::ppc_qpx_qvstfcs:
12663       VT = MVT::v2f32;
12664       break;
12665     default:
12666       VT = MVT::v4i32;
12667       break;
12668     }
12669
12670     Info.opc = ISD::INTRINSIC_VOID;
12671     Info.memVT = VT;
12672     Info.ptrVal = I.getArgOperand(1);
12673     Info.offset = -VT.getStoreSize()+1;
12674     Info.size = 2*VT.getStoreSize()-1;
12675     Info.align = 1;
12676     Info.vol = false;
12677     Info.readMem = false;
12678     Info.writeMem = true;
12679     return true;
12680   }
12681   case Intrinsic::ppc_qpx_qvstfda:
12682   case Intrinsic::ppc_qpx_qvstfsa:
12683   case Intrinsic::ppc_qpx_qvstfcda:
12684   case Intrinsic::ppc_qpx_qvstfcsa:
12685   case Intrinsic::ppc_qpx_qvstfiwa: {
12686     EVT VT;
12687     switch (Intrinsic) {
12688     case Intrinsic::ppc_qpx_qvstfda:
12689       VT = MVT::v4f64;
12690       break;
12691     case Intrinsic::ppc_qpx_qvstfsa:
12692       VT = MVT::v4f32;
12693       break;
12694     case Intrinsic::ppc_qpx_qvstfcda:
12695       VT = MVT::v2f64;
12696       break;
12697     case Intrinsic::ppc_qpx_qvstfcsa:
12698       VT = MVT::v2f32;
12699       break;
12700     default:
12701       VT = MVT::v4i32;
12702       break;
12703     }
12704
12705     Info.opc = ISD::INTRINSIC_VOID;
12706     Info.memVT = VT;
12707     Info.ptrVal = I.getArgOperand(1);
12708     Info.offset = 0;
12709     Info.size = VT.getStoreSize();
12710     Info.align = 1;
12711     Info.vol = false;
12712     Info.readMem = false;
12713     Info.writeMem = true;
12714     return true;
12715   }
12716   default:
12717     break;
12718   }
12719
12720   return false;
12721 }
12722
12723 /// getOptimalMemOpType - Returns the target specific optimal type for load
12724 /// and store operations as a result of memset, memcpy, and memmove
12725 /// lowering. If DstAlign is zero that means it's safe to destination
12726 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
12727 /// means there isn't a need to check it against alignment requirement,
12728 /// probably because the source does not need to be loaded. If 'IsMemset' is
12729 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
12730 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
12731 /// source is constant so it does not need to be loaded.
12732 /// It returns EVT::Other if the type should be determined using generic
12733 /// target-independent logic.
12734 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
12735                                            unsigned DstAlign, unsigned SrcAlign,
12736                                            bool IsMemset, bool ZeroMemset,
12737                                            bool MemcpyStrSrc,
12738                                            MachineFunction &MF) const {
12739   if (getTargetMachine().getOptLevel() != CodeGenOpt::None) {
12740     const Function *F = MF.getFunction();
12741     // When expanding a memset, require at least two QPX instructions to cover
12742     // the cost of loading the value to be stored from the constant pool.
12743     if (Subtarget.hasQPX() && Size >= 32 && (!IsMemset || Size >= 64) &&
12744        (!SrcAlign || SrcAlign >= 32) && (!DstAlign || DstAlign >= 32) &&
12745         !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12746       return MVT::v4f64;
12747     }
12748
12749     // We should use Altivec/VSX loads and stores when available. For unaligned
12750     // addresses, unaligned VSX loads are only fast starting with the P8.
12751     if (Subtarget.hasAltivec() && Size >= 16 &&
12752         (((!SrcAlign || SrcAlign >= 16) && (!DstAlign || DstAlign >= 16)) ||
12753          ((IsMemset && Subtarget.hasVSX()) || Subtarget.hasP8Vector())))
12754       return MVT::v4i32;
12755   }
12756
12757   if (Subtarget.isPPC64()) {
12758     return MVT::i64;
12759   }
12760
12761   return MVT::i32;
12762 }
12763
12764 /// \brief Returns true if it is beneficial to convert a load of a constant
12765 /// to just the constant itself.
12766 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
12767                                                           Type *Ty) const {
12768   assert(Ty->isIntegerTy());
12769
12770   unsigned BitSize = Ty->getPrimitiveSizeInBits();
12771   return !(BitSize == 0 || BitSize > 64);
12772 }
12773
12774 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
12775   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12776     return false;
12777   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
12778   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
12779   return NumBits1 == 64 && NumBits2 == 32;
12780 }
12781
12782 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
12783   if (!VT1.isInteger() || !VT2.isInteger())
12784     return false;
12785   unsigned NumBits1 = VT1.getSizeInBits();
12786   unsigned NumBits2 = VT2.getSizeInBits();
12787   return NumBits1 == 64 && NumBits2 == 32;
12788 }
12789
12790 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12791   // Generally speaking, zexts are not free, but they are free when they can be
12792   // folded with other operations.
12793   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
12794     EVT MemVT = LD->getMemoryVT();
12795     if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
12796          (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
12797         (LD->getExtensionType() == ISD::NON_EXTLOAD ||
12798          LD->getExtensionType() == ISD::ZEXTLOAD))
12799       return true;
12800   }
12801
12802   // FIXME: Add other cases...
12803   //  - 32-bit shifts with a zext to i64
12804   //  - zext after ctlz, bswap, etc.
12805   //  - zext after and by a constant mask
12806
12807   return TargetLowering::isZExtFree(Val, VT2);
12808 }
12809
12810 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
12811   assert(VT.isFloatingPoint());
12812   return true;
12813 }
12814
12815 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12816   return isInt<16>(Imm) || isUInt<16>(Imm);
12817 }
12818
12819 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12820   return isInt<16>(Imm) || isUInt<16>(Imm);
12821 }
12822
12823 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12824                                                        unsigned,
12825                                                        unsigned,
12826                                                        bool *Fast) const {
12827   if (DisablePPCUnaligned)
12828     return false;
12829
12830   // PowerPC supports unaligned memory access for simple non-vector types.
12831   // Although accessing unaligned addresses is not as efficient as accessing
12832   // aligned addresses, it is generally more efficient than manual expansion,
12833   // and generally only traps for software emulation when crossing page
12834   // boundaries.
12835
12836   if (!VT.isSimple())
12837     return false;
12838
12839   if (VT.getSimpleVT().isVector()) {
12840     if (Subtarget.hasVSX()) {
12841       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
12842           VT != MVT::v4f32 && VT != MVT::v4i32)
12843         return false;
12844     } else {
12845       return false;
12846     }
12847   }
12848
12849   if (VT == MVT::ppcf128)
12850     return false;
12851
12852   if (Fast)
12853     *Fast = true;
12854
12855   return true;
12856 }
12857
12858 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
12859   VT = VT.getScalarType();
12860
12861   if (!VT.isSimple())
12862     return false;
12863
12864   switch (VT.getSimpleVT().SimpleTy) {
12865   case MVT::f32:
12866   case MVT::f64:
12867     return true;
12868   default:
12869     break;
12870   }
12871
12872   return false;
12873 }
12874
12875 const MCPhysReg *
12876 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
12877   // LR is a callee-save register, but we must treat it as clobbered by any call
12878   // site. Hence we include LR in the scratch registers, which are in turn added
12879   // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
12880   // to CTR, which is used by any indirect call.
12881   static const MCPhysReg ScratchRegs[] = {
12882     PPC::X12, PPC::LR8, PPC::CTR8, 0
12883   };
12884
12885   return ScratchRegs;
12886 }
12887
12888 unsigned PPCTargetLowering::getExceptionPointerRegister(
12889     const Constant *PersonalityFn) const {
12890   return Subtarget.isPPC64() ? PPC::X3 : PPC::R3;
12891 }
12892
12893 unsigned PPCTargetLowering::getExceptionSelectorRegister(
12894     const Constant *PersonalityFn) const {
12895   return Subtarget.isPPC64() ? PPC::X4 : PPC::R4;
12896 }
12897
12898 bool
12899 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
12900                      EVT VT , unsigned DefinedValues) const {
12901   if (VT == MVT::v2i64)
12902     return Subtarget.hasDirectMove(); // Don't need stack ops with direct moves
12903
12904   if (Subtarget.hasVSX() || Subtarget.hasQPX())
12905     return true;
12906
12907   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
12908 }
12909
12910 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
12911   if (DisableILPPref || Subtarget.enableMachineScheduler())
12912     return TargetLowering::getSchedulingPreference(N);
12913
12914   return Sched::ILP;
12915 }
12916
12917 // Create a fast isel object.
12918 FastISel *
12919 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
12920                                   const TargetLibraryInfo *LibInfo) const {
12921   return PPC::createFastISel(FuncInfo, LibInfo);
12922 }
12923
12924 void PPCTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
12925   if (Subtarget.isDarwinABI()) return;
12926   if (!Subtarget.isPPC64()) return;
12927
12928   // Update IsSplitCSR in PPCFunctionInfo
12929   PPCFunctionInfo *PFI = Entry->getParent()->getInfo<PPCFunctionInfo>();
12930   PFI->setIsSplitCSR(true);
12931 }
12932
12933 void PPCTargetLowering::insertCopiesSplitCSR(
12934   MachineBasicBlock *Entry,
12935   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
12936   const PPCRegisterInfo *TRI = Subtarget.getRegisterInfo();
12937   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
12938   if (!IStart)
12939     return;
12940
12941   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
12942   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
12943   MachineBasicBlock::iterator MBBI = Entry->begin();
12944   for (const MCPhysReg *I = IStart; *I; ++I) {
12945     const TargetRegisterClass *RC = nullptr;
12946     if (PPC::G8RCRegClass.contains(*I))
12947       RC = &PPC::G8RCRegClass;
12948     else if (PPC::F8RCRegClass.contains(*I))
12949       RC = &PPC::F8RCRegClass;
12950     else if (PPC::CRRCRegClass.contains(*I))
12951       RC = &PPC::CRRCRegClass;
12952     else if (PPC::VRRCRegClass.contains(*I))
12953       RC = &PPC::VRRCRegClass;
12954     else
12955       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12956
12957     unsigned NewVR = MRI->createVirtualRegister(RC);
12958     // Create copy from CSR to a virtual register.
12959     // FIXME: this currently does not emit CFI pseudo-instructions, it works
12960     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12961     // nounwind. If we want to generalize this later, we may need to emit
12962     // CFI pseudo-instructions.
12963     assert(Entry->getParent()->getFunction()->hasFnAttribute(
12964              Attribute::NoUnwind) &&
12965            "Function should be nounwind in insertCopiesSplitCSR!");
12966     Entry->addLiveIn(*I);
12967     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
12968       .addReg(*I);
12969
12970     // Insert the copy-back instructions right before the terminator
12971     for (auto *Exit : Exits)
12972       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
12973               TII->get(TargetOpcode::COPY), *I)
12974         .addReg(NewVR);
12975   }
12976 }
12977
12978 // Override to enable LOAD_STACK_GUARD lowering on Linux.
12979 bool PPCTargetLowering::useLoadStackGuardNode() const {
12980   if (!Subtarget.isTargetLinux())
12981     return TargetLowering::useLoadStackGuardNode();
12982   return true;
12983 }
12984
12985 // Override to disable global variable loading on Linux.
12986 void PPCTargetLowering::insertSSPDeclarations(Module &M) const {
12987   if (!Subtarget.isTargetLinux())
12988     return TargetLowering::insertSSPDeclarations(M);
12989 }
12990
12991 bool PPCTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
12992   if (!VT.isSimple() || !Subtarget.hasVSX())
12993     return false;
12994
12995   switch(VT.getSimpleVT().SimpleTy) {
12996   default:
12997     // For FP types that are currently not supported by PPC backend, return
12998     // false. Examples: f16, f80.
12999     return false;
13000   case MVT::f32:
13001   case MVT::f64:
13002   case MVT::ppcf128:
13003     return Imm.isPosZero();
13004   }
13005 }
13006
13007 // For vector shift operation op, fold
13008 // (op x, (and y, ((1 << numbits(x)) - 1))) -> (target op x, y)
13009 static SDValue stripModuloOnShift(const TargetLowering &TLI, SDNode *N,
13010                                   SelectionDAG &DAG) {
13011   SDValue N0 = N->getOperand(0);
13012   SDValue N1 = N->getOperand(1);
13013   EVT VT = N0.getValueType();
13014   unsigned OpSizeInBits = VT.getScalarSizeInBits();
13015   unsigned Opcode = N->getOpcode();
13016   unsigned TargetOpcode;
13017
13018   switch (Opcode) {
13019   default:
13020     llvm_unreachable("Unexpected shift operation");
13021   case ISD::SHL:
13022     TargetOpcode = PPCISD::SHL;
13023     break;
13024   case ISD::SRL:
13025     TargetOpcode = PPCISD::SRL;
13026     break;
13027   case ISD::SRA:
13028     TargetOpcode = PPCISD::SRA;
13029     break;
13030   }
13031
13032   if (VT.isVector() && TLI.isOperationLegal(Opcode, VT) &&
13033       N1->getOpcode() == ISD::AND)
13034     if (ConstantSDNode *Mask = isConstOrConstSplat(N1->getOperand(1)))
13035       if (Mask->getZExtValue() == OpSizeInBits - 1)
13036         return DAG.getNode(TargetOpcode, SDLoc(N), VT, N0, N1->getOperand(0));
13037
13038   return SDValue();
13039 }
13040
13041 SDValue PPCTargetLowering::combineSHL(SDNode *N, DAGCombinerInfo &DCI) const {
13042   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13043     return Value;
13044
13045   return SDValue();
13046 }
13047
13048 SDValue PPCTargetLowering::combineSRA(SDNode *N, DAGCombinerInfo &DCI) const {
13049   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13050     return Value;
13051
13052   return SDValue();
13053 }
13054
13055 SDValue PPCTargetLowering::combineSRL(SDNode *N, DAGCombinerInfo &DCI) const {
13056   if (auto Value = stripModuloOnShift(*this, N, DCI.DAG))
13057     return Value;
13058
13059   return SDValue();
13060 }