[PowerPC] ELFv2 stack space reduction
[oota-llvm.git] / 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 "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
44
45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
50
51 // FIXME: Remove this once the bug has been fixed!
52 extern cl::opt<bool> ANDIGlueBug;
53
54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
55   // If it isn't a Mach-O file then it's going to be a linux ELF
56   // object file.
57   if (TT.isOSDarwin())
58     return new TargetLoweringObjectFileMachO();
59
60   return new PPC64LinuxTargetObjectFile();
61 }
62
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
65       Subtarget(*TM.getSubtargetImpl()) {
66   setPow2DivIsCheap();
67
68   // Use _setjmp/_longjmp instead of setjmp/longjmp.
69   setUseUnderscoreSetJmp(true);
70   setUseUnderscoreLongJmp(true);
71
72   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73   // arguments are at least 4/8 bytes aligned.
74   bool isPPC64 = Subtarget.isPPC64();
75   setMinStackArgumentAlignment(isPPC64 ? 8:4);
76
77   // Set up the register classes.
78   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
81
82   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
85
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // PowerPC has pre-inc load and store's.
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99
100   if (Subtarget.useCRBits()) {
101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
102
103     if (isPPC64 || Subtarget.hasFPCVT()) {
104       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106                          isPPC64 ? MVT::i64 : MVT::i32);
107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
109                          isPPC64 ? MVT::i64 : MVT::i32);
110     } else {
111       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
113     }
114
115     // PowerPC does not support direct load / store of condition registers
116     setOperationAction(ISD::LOAD, MVT::i1, Custom);
117     setOperationAction(ISD::STORE, MVT::i1, Custom);
118
119     // FIXME: Remove this once the ANDI glue bug is fixed:
120     if (ANDIGlueBug)
121       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
122
123     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath &&
180         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath &&
185         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget.hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget.hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget.hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget.useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget.isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget.isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget.has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (Subtarget.hasFPCVT()) {
371     if (Subtarget.has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget.use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget.hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
406
407       // add/sub are legal for all supported vector VT's.
408       setOperationAction(ISD::ADD , VT, Legal);
409       setOperationAction(ISD::SUB , VT, Legal);
410
411       // We promote all shuffles to v16i8.
412       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
414
415       // We promote all non-typed operations to v4i32.
416       setOperationAction(ISD::AND   , VT, Promote);
417       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
418       setOperationAction(ISD::OR    , VT, Promote);
419       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
420       setOperationAction(ISD::XOR   , VT, Promote);
421       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
422       setOperationAction(ISD::LOAD  , VT, Promote);
423       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
424       setOperationAction(ISD::SELECT, VT, Promote);
425       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426       setOperationAction(ISD::STORE, VT, Promote);
427       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
428
429       // No other operations are legal.
430       setOperationAction(ISD::MUL , VT, Expand);
431       setOperationAction(ISD::SDIV, VT, Expand);
432       setOperationAction(ISD::SREM, VT, Expand);
433       setOperationAction(ISD::UDIV, VT, Expand);
434       setOperationAction(ISD::UREM, VT, Expand);
435       setOperationAction(ISD::FDIV, VT, Expand);
436       setOperationAction(ISD::FREM, VT, Expand);
437       setOperationAction(ISD::FNEG, VT, Expand);
438       setOperationAction(ISD::FSQRT, VT, Expand);
439       setOperationAction(ISD::FLOG, VT, Expand);
440       setOperationAction(ISD::FLOG10, VT, Expand);
441       setOperationAction(ISD::FLOG2, VT, Expand);
442       setOperationAction(ISD::FEXP, VT, Expand);
443       setOperationAction(ISD::FEXP2, VT, Expand);
444       setOperationAction(ISD::FSIN, VT, Expand);
445       setOperationAction(ISD::FCOS, VT, Expand);
446       setOperationAction(ISD::FABS, VT, Expand);
447       setOperationAction(ISD::FPOWI, VT, Expand);
448       setOperationAction(ISD::FFLOOR, VT, Expand);
449       setOperationAction(ISD::FCEIL,  VT, Expand);
450       setOperationAction(ISD::FTRUNC, VT, Expand);
451       setOperationAction(ISD::FRINT,  VT, Expand);
452       setOperationAction(ISD::FNEARBYINT, VT, Expand);
453       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::UDIVREM, VT, Expand);
459       setOperationAction(ISD::SDIVREM, VT, Expand);
460       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461       setOperationAction(ISD::FPOW, VT, Expand);
462       setOperationAction(ISD::BSWAP, VT, Expand);
463       setOperationAction(ISD::CTPOP, VT, Expand);
464       setOperationAction(ISD::CTLZ, VT, Expand);
465       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466       setOperationAction(ISD::CTTZ, VT, Expand);
467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468       setOperationAction(ISD::VSELECT, VT, Expand);
469       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470
471       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
472            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
473         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
474         setTruncStoreAction(VT, InnerVT, Expand);
475       }
476       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
477       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
478       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
479     }
480
481     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
482     // with merges, splats, etc.
483     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484
485     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
486     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
487     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
488     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
489     setOperationAction(ISD::SELECT, MVT::v4i32,
490                        Subtarget.useCRBits() ? Legal : Expand);
491     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
492     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
493     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
494     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
495     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
497     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
498     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
499     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500
501     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
502     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
503     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
504     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505
506     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
507     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508
509     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
510       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
511       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
512     }
513
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517
518     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
519     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
522     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
523     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
524     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525
526     // Altivec does not contain unordered floating-point compare instructions
527     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
528     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
529     setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
530     setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
531     setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
532     setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
533
534     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
535     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
536
537     if (Subtarget.hasVSX()) {
538       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
539       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
540
541       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
542       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
543       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
544       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
545       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
548
549       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
550       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
551
552       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
553       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
554
555       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
556       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
558       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
559       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
560
561       // Share the Altivec comparison restrictions.
562       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
563       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETUGT, MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETUGE, MVT::v2f64, Expand);
566       setCondCodeAction(ISD::SETULT, MVT::v2f64, Expand);
567       setCondCodeAction(ISD::SETULE, MVT::v2f64, Expand);
568
569       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
570       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
571
572       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
573       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
574
575       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
576
577       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
578
579       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
580       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
581
582       // VSX v2i64 only supports non-arithmetic operations.
583       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
584       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
585
586       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
587       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
588       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
589
590       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
591
592       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
593       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
594       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
595       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
596
597       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
598
599       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
600       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
601       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
602       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
603
604       // Vector operation legalization checks the result type of
605       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
606       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
607       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
608       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
609       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
610
611       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
612     }
613   }
614
615   if (Subtarget.has64BitSupport()) {
616     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
617     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
618   }
619
620   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
621   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
622   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
623   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
624
625   setBooleanContents(ZeroOrOneBooleanContent);
626   // Altivec instructions set fields to all zeros or all ones.
627   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
628
629   if (isPPC64) {
630     setStackPointerRegisterToSaveRestore(PPC::X1);
631     setExceptionPointerRegister(PPC::X3);
632     setExceptionSelectorRegister(PPC::X4);
633   } else {
634     setStackPointerRegisterToSaveRestore(PPC::R1);
635     setExceptionPointerRegister(PPC::R3);
636     setExceptionSelectorRegister(PPC::R4);
637   }
638
639   // We have target-specific dag combine patterns for the following nodes:
640   setTargetDAGCombine(ISD::SINT_TO_FP);
641   setTargetDAGCombine(ISD::LOAD);
642   setTargetDAGCombine(ISD::STORE);
643   setTargetDAGCombine(ISD::BR_CC);
644   if (Subtarget.useCRBits())
645     setTargetDAGCombine(ISD::BRCOND);
646   setTargetDAGCombine(ISD::BSWAP);
647   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
648
649   setTargetDAGCombine(ISD::SIGN_EXTEND);
650   setTargetDAGCombine(ISD::ZERO_EXTEND);
651   setTargetDAGCombine(ISD::ANY_EXTEND);
652
653   if (Subtarget.useCRBits()) {
654     setTargetDAGCombine(ISD::TRUNCATE);
655     setTargetDAGCombine(ISD::SETCC);
656     setTargetDAGCombine(ISD::SELECT_CC);
657   }
658
659   // Use reciprocal estimates.
660   if (TM.Options.UnsafeFPMath) {
661     setTargetDAGCombine(ISD::FDIV);
662     setTargetDAGCombine(ISD::FSQRT);
663   }
664
665   // Darwin long double math library functions have $LDBL128 appended.
666   if (Subtarget.isDarwin()) {
667     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
668     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
669     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
670     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
671     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
672     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
673     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
674     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
675     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
676     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
677   }
678
679   // With 32 condition bits, we don't need to sink (and duplicate) compares
680   // aggressively in CodeGenPrep.
681   if (Subtarget.useCRBits())
682     setHasMultipleConditionRegisters();
683
684   setMinFunctionAlignment(2);
685   if (Subtarget.isDarwin())
686     setPrefFunctionAlignment(4);
687
688   if (isPPC64 && Subtarget.isJITCodeModel())
689     // Temporary workaround for the inability of PPC64 JIT to handle jump
690     // tables.
691     setSupportJumpTables(false);
692
693   setInsertFencesForAtomic(true);
694
695   if (Subtarget.enableMachineScheduler())
696     setSchedulingPreference(Sched::Source);
697   else
698     setSchedulingPreference(Sched::Hybrid);
699
700   computeRegisterProperties();
701
702   // The Freescale cores does better with aggressive inlining of memcpy and
703   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
704   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
705       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
706     MaxStoresPerMemset = 32;
707     MaxStoresPerMemsetOptSize = 16;
708     MaxStoresPerMemcpy = 32;
709     MaxStoresPerMemcpyOptSize = 8;
710     MaxStoresPerMemmove = 32;
711     MaxStoresPerMemmoveOptSize = 8;
712
713     setPrefFunctionAlignment(4);
714   }
715 }
716
717 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
718 /// the desired ByVal argument alignment.
719 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
720                              unsigned MaxMaxAlign) {
721   if (MaxAlign == MaxMaxAlign)
722     return;
723   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
724     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
725       MaxAlign = 32;
726     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
727       MaxAlign = 16;
728   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
729     unsigned EltAlign = 0;
730     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
731     if (EltAlign > MaxAlign)
732       MaxAlign = EltAlign;
733   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
734     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
735       unsigned EltAlign = 0;
736       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
737       if (EltAlign > MaxAlign)
738         MaxAlign = EltAlign;
739       if (MaxAlign == MaxMaxAlign)
740         break;
741     }
742   }
743 }
744
745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
746 /// function arguments in the caller parameter area.
747 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
748   // Darwin passes everything on 4 byte boundary.
749   if (Subtarget.isDarwin())
750     return 4;
751
752   // 16byte and wider vectors are passed on 16byte boundary.
753   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
754   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
755   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
756     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
757   return Align;
758 }
759
760 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
761   switch (Opcode) {
762   default: return nullptr;
763   case PPCISD::FSEL:            return "PPCISD::FSEL";
764   case PPCISD::FCFID:           return "PPCISD::FCFID";
765   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
766   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
767   case PPCISD::FRE:             return "PPCISD::FRE";
768   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
769   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
770   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
771   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
772   case PPCISD::VPERM:           return "PPCISD::VPERM";
773   case PPCISD::Hi:              return "PPCISD::Hi";
774   case PPCISD::Lo:              return "PPCISD::Lo";
775   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
776   case PPCISD::LOAD:            return "PPCISD::LOAD";
777   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
778   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
779   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
780   case PPCISD::SRL:             return "PPCISD::SRL";
781   case PPCISD::SRA:             return "PPCISD::SRA";
782   case PPCISD::SHL:             return "PPCISD::SHL";
783   case PPCISD::CALL:            return "PPCISD::CALL";
784   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
785   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
786   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
787   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
788   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
789   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
790   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
791   case PPCISD::VCMP:            return "PPCISD::VCMP";
792   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
793   case PPCISD::LBRX:            return "PPCISD::LBRX";
794   case PPCISD::STBRX:           return "PPCISD::STBRX";
795   case PPCISD::LARX:            return "PPCISD::LARX";
796   case PPCISD::STCX:            return "PPCISD::STCX";
797   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
798   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
799   case PPCISD::BDZ:             return "PPCISD::BDZ";
800   case PPCISD::MFFS:            return "PPCISD::MFFS";
801   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
802   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
803   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
804   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
805   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
806   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
807   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
808   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
809   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
810   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
811   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
812   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
813   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
814   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
815   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
816   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
817   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
818   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
819   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
820   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
821   case PPCISD::SC:              return "PPCISD::SC";
822   }
823 }
824
825 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
826   if (!VT.isVector())
827     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
828   return VT.changeVectorElementTypeToInteger();
829 }
830
831 //===----------------------------------------------------------------------===//
832 // Node matching predicates, for use by the tblgen matching code.
833 //===----------------------------------------------------------------------===//
834
835 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
836 static bool isFloatingPointZero(SDValue Op) {
837   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
838     return CFP->getValueAPF().isZero();
839   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
840     // Maybe this has already been legalized into the constant pool?
841     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
842       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
843         return CFP->getValueAPF().isZero();
844   }
845   return false;
846 }
847
848 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
849 /// true if Op is undef or if it matches the specified value.
850 static bool isConstantOrUndef(int Op, int Val) {
851   return Op < 0 || Op == Val;
852 }
853
854 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
855 /// VPKUHUM instruction.
856 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
857                                SelectionDAG &DAG) {
858   unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1;
859   if (!isUnary) {
860     for (unsigned i = 0; i != 16; ++i)
861       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+j))
862         return false;
863   } else {
864     for (unsigned i = 0; i != 8; ++i)
865       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
866           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
867         return false;
868   }
869   return true;
870 }
871
872 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
873 /// VPKUWUM instruction.
874 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
875                                SelectionDAG &DAG) {
876   unsigned j, k;
877   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
878     j = 0;
879     k = 1;
880   } else {
881     j = 2;
882     k = 3;
883   }
884   if (!isUnary) {
885     for (unsigned i = 0; i != 16; i += 2)
886       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
887           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k))
888         return false;
889   } else {
890     for (unsigned i = 0; i != 8; i += 2)
891       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
892           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k) ||
893           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j) ||
894           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+k))
895         return false;
896   }
897   return true;
898 }
899
900 /// isVMerge - Common function, used to match vmrg* shuffles.
901 ///
902 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
903                      unsigned LHSStart, unsigned RHSStart) {
904   if (N->getValueType(0) != MVT::v16i8)
905     return false;
906   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
907          "Unsupported merge size!");
908
909   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
910     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
911       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
912                              LHSStart+j+i*UnitSize) ||
913           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
914                              RHSStart+j+i*UnitSize))
915         return false;
916     }
917   return true;
918 }
919
920 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
921 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
922 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
923                              bool isUnary, SelectionDAG &DAG) {
924   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
925     if (!isUnary)
926       return isVMerge(N, UnitSize, 0, 16);
927     return isVMerge(N, UnitSize, 0, 0);
928   } else {
929     if (!isUnary)
930       return isVMerge(N, UnitSize, 8, 24);
931     return isVMerge(N, UnitSize, 8, 8);
932   }
933 }
934
935 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
936 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
937 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
938                              bool isUnary, SelectionDAG &DAG) {
939   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
940     if (!isUnary)
941       return isVMerge(N, UnitSize, 8, 24);
942     return isVMerge(N, UnitSize, 8, 8);
943   } else {
944     if (!isUnary)
945       return isVMerge(N, UnitSize, 0, 16);
946     return isVMerge(N, UnitSize, 0, 0);
947   }
948 }
949
950
951 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
952 /// amount, otherwise return -1.
953 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
954   if (N->getValueType(0) != MVT::v16i8)
955     return -1;
956
957   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
958
959   // Find the first non-undef value in the shuffle mask.
960   unsigned i;
961   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
962     /*search*/;
963
964   if (i == 16) return -1;  // all undef.
965
966   // Otherwise, check to see if the rest of the elements are consecutively
967   // numbered from this value.
968   unsigned ShiftAmt = SVOp->getMaskElt(i);
969   if (ShiftAmt < i) return -1;
970
971   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
972
973     ShiftAmt += i;
974
975     if (!isUnary) {
976       // Check the rest of the elements to see if they are consecutive.
977       for (++i; i != 16; ++i)
978         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt - i))
979           return -1;
980     } else {
981       // Check the rest of the elements to see if they are consecutive.
982       for (++i; i != 16; ++i)
983         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt - i) & 15))
984           return -1;
985     }
986
987   } else {  // Big Endian
988
989     ShiftAmt -= i;
990
991     if (!isUnary) {
992       // Check the rest of the elements to see if they are consecutive.
993       for (++i; i != 16; ++i)
994         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
995           return -1;
996     } else {
997       // Check the rest of the elements to see if they are consecutive.
998       for (++i; i != 16; ++i)
999         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1000           return -1;
1001     }
1002   }
1003   return ShiftAmt;
1004 }
1005
1006 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1007 /// specifies a splat of a single element that is suitable for input to
1008 /// VSPLTB/VSPLTH/VSPLTW.
1009 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1010   assert(N->getValueType(0) == MVT::v16i8 &&
1011          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1012
1013   // This is a splat operation if each element of the permute is the same, and
1014   // if the value doesn't reference the second vector.
1015   unsigned ElementBase = N->getMaskElt(0);
1016
1017   // FIXME: Handle UNDEF elements too!
1018   if (ElementBase >= 16)
1019     return false;
1020
1021   // Check that the indices are consecutive, in the case of a multi-byte element
1022   // splatted with a v16i8 mask.
1023   for (unsigned i = 1; i != EltSize; ++i)
1024     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1025       return false;
1026
1027   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1028     if (N->getMaskElt(i) < 0) continue;
1029     for (unsigned j = 0; j != EltSize; ++j)
1030       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1031         return false;
1032   }
1033   return true;
1034 }
1035
1036 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1037 /// are -0.0.
1038 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1039   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1040
1041   APInt APVal, APUndef;
1042   unsigned BitSize;
1043   bool HasAnyUndefs;
1044
1045   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1046     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1047       return CFP->getValueAPF().isNegZero();
1048
1049   return false;
1050 }
1051
1052 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1053 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1054 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1055                                 SelectionDAG &DAG) {
1056   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1057   assert(isSplatShuffleMask(SVOp, EltSize));
1058   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1059     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1060   else
1061     return SVOp->getMaskElt(0) / EltSize;
1062 }
1063
1064 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1065 /// by using a vspltis[bhw] instruction of the specified element size, return
1066 /// the constant being splatted.  The ByteSize field indicates the number of
1067 /// bytes of each element [124] -> [bhw].
1068 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1069   SDValue OpVal(nullptr, 0);
1070
1071   // If ByteSize of the splat is bigger than the element size of the
1072   // build_vector, then we have a case where we are checking for a splat where
1073   // multiple elements of the buildvector are folded together into a single
1074   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1075   unsigned EltSize = 16/N->getNumOperands();
1076   if (EltSize < ByteSize) {
1077     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1078     SDValue UniquedVals[4];
1079     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1080
1081     // See if all of the elements in the buildvector agree across.
1082     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1083       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1084       // If the element isn't a constant, bail fully out.
1085       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1086
1087
1088       if (!UniquedVals[i&(Multiple-1)].getNode())
1089         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1090       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1091         return SDValue();  // no match.
1092     }
1093
1094     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1095     // either constant or undef values that are identical for each chunk.  See
1096     // if these chunks can form into a larger vspltis*.
1097
1098     // Check to see if all of the leading entries are either 0 or -1.  If
1099     // neither, then this won't fit into the immediate field.
1100     bool LeadingZero = true;
1101     bool LeadingOnes = true;
1102     for (unsigned i = 0; i != Multiple-1; ++i) {
1103       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1104
1105       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1106       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1107     }
1108     // Finally, check the least significant entry.
1109     if (LeadingZero) {
1110       if (!UniquedVals[Multiple-1].getNode())
1111         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1112       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1113       if (Val < 16)
1114         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1115     }
1116     if (LeadingOnes) {
1117       if (!UniquedVals[Multiple-1].getNode())
1118         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1119       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1120       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1121         return DAG.getTargetConstant(Val, MVT::i32);
1122     }
1123
1124     return SDValue();
1125   }
1126
1127   // Check to see if this buildvec has a single non-undef value in its elements.
1128   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1129     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1130     if (!OpVal.getNode())
1131       OpVal = N->getOperand(i);
1132     else if (OpVal != N->getOperand(i))
1133       return SDValue();
1134   }
1135
1136   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1137
1138   unsigned ValSizeInBytes = EltSize;
1139   uint64_t Value = 0;
1140   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1141     Value = CN->getZExtValue();
1142   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1143     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1144     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1145   }
1146
1147   // If the splat value is larger than the element value, then we can never do
1148   // this splat.  The only case that we could fit the replicated bits into our
1149   // immediate field for would be zero, and we prefer to use vxor for it.
1150   if (ValSizeInBytes < ByteSize) return SDValue();
1151
1152   // If the element value is larger than the splat value, cut it in half and
1153   // check to see if the two halves are equal.  Continue doing this until we
1154   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1155   while (ValSizeInBytes > ByteSize) {
1156     ValSizeInBytes >>= 1;
1157
1158     // If the top half equals the bottom half, we're still ok.
1159     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1160          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1161       return SDValue();
1162   }
1163
1164   // Properly sign extend the value.
1165   int MaskVal = SignExtend32(Value, ByteSize * 8);
1166
1167   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1168   if (MaskVal == 0) return SDValue();
1169
1170   // Finally, if this value fits in a 5 bit sext field, return it
1171   if (SignExtend32<5>(MaskVal) == MaskVal)
1172     return DAG.getTargetConstant(MaskVal, MVT::i32);
1173   return SDValue();
1174 }
1175
1176 //===----------------------------------------------------------------------===//
1177 //  Addressing Mode Selection
1178 //===----------------------------------------------------------------------===//
1179
1180 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1181 /// or 64-bit immediate, and if the value can be accurately represented as a
1182 /// sign extension from a 16-bit value.  If so, this returns true and the
1183 /// immediate.
1184 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1185   if (!isa<ConstantSDNode>(N))
1186     return false;
1187
1188   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1189   if (N->getValueType(0) == MVT::i32)
1190     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1191   else
1192     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1193 }
1194 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1195   return isIntS16Immediate(Op.getNode(), Imm);
1196 }
1197
1198
1199 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1200 /// can be represented as an indexed [r+r] operation.  Returns false if it
1201 /// can be more efficiently represented with [r+imm].
1202 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1203                                             SDValue &Index,
1204                                             SelectionDAG &DAG) const {
1205   short imm = 0;
1206   if (N.getOpcode() == ISD::ADD) {
1207     if (isIntS16Immediate(N.getOperand(1), imm))
1208       return false;    // r+i
1209     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1210       return false;    // r+i
1211
1212     Base = N.getOperand(0);
1213     Index = N.getOperand(1);
1214     return true;
1215   } else if (N.getOpcode() == ISD::OR) {
1216     if (isIntS16Immediate(N.getOperand(1), imm))
1217       return false;    // r+i can fold it if we can.
1218
1219     // If this is an or of disjoint bitfields, we can codegen this as an add
1220     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1221     // disjoint.
1222     APInt LHSKnownZero, LHSKnownOne;
1223     APInt RHSKnownZero, RHSKnownOne;
1224     DAG.computeKnownBits(N.getOperand(0),
1225                          LHSKnownZero, LHSKnownOne);
1226
1227     if (LHSKnownZero.getBoolValue()) {
1228       DAG.computeKnownBits(N.getOperand(1),
1229                            RHSKnownZero, RHSKnownOne);
1230       // If all of the bits are known zero on the LHS or RHS, the add won't
1231       // carry.
1232       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1233         Base = N.getOperand(0);
1234         Index = N.getOperand(1);
1235         return true;
1236       }
1237     }
1238   }
1239
1240   return false;
1241 }
1242
1243 // If we happen to be doing an i64 load or store into a stack slot that has
1244 // less than a 4-byte alignment, then the frame-index elimination may need to
1245 // use an indexed load or store instruction (because the offset may not be a
1246 // multiple of 4). The extra register needed to hold the offset comes from the
1247 // register scavenger, and it is possible that the scavenger will need to use
1248 // an emergency spill slot. As a result, we need to make sure that a spill slot
1249 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1250 // stack slot.
1251 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1252   // FIXME: This does not handle the LWA case.
1253   if (VT != MVT::i64)
1254     return;
1255
1256   // NOTE: We'll exclude negative FIs here, which come from argument
1257   // lowering, because there are no known test cases triggering this problem
1258   // using packed structures (or similar). We can remove this exclusion if
1259   // we find such a test case. The reason why this is so test-case driven is
1260   // because this entire 'fixup' is only to prevent crashes (from the
1261   // register scavenger) on not-really-valid inputs. For example, if we have:
1262   //   %a = alloca i1
1263   //   %b = bitcast i1* %a to i64*
1264   //   store i64* a, i64 b
1265   // then the store should really be marked as 'align 1', but is not. If it
1266   // were marked as 'align 1' then the indexed form would have been
1267   // instruction-selected initially, and the problem this 'fixup' is preventing
1268   // won't happen regardless.
1269   if (FrameIdx < 0)
1270     return;
1271
1272   MachineFunction &MF = DAG.getMachineFunction();
1273   MachineFrameInfo *MFI = MF.getFrameInfo();
1274
1275   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1276   if (Align >= 4)
1277     return;
1278
1279   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1280   FuncInfo->setHasNonRISpills();
1281 }
1282
1283 /// Returns true if the address N can be represented by a base register plus
1284 /// a signed 16-bit displacement [r+imm], and if it is not better
1285 /// represented as reg+reg.  If Aligned is true, only accept displacements
1286 /// suitable for STD and friends, i.e. multiples of 4.
1287 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1288                                             SDValue &Base,
1289                                             SelectionDAG &DAG,
1290                                             bool Aligned) const {
1291   // FIXME dl should come from parent load or store, not from address
1292   SDLoc dl(N);
1293   // If this can be more profitably realized as r+r, fail.
1294   if (SelectAddressRegReg(N, Disp, Base, DAG))
1295     return false;
1296
1297   if (N.getOpcode() == ISD::ADD) {
1298     short imm = 0;
1299     if (isIntS16Immediate(N.getOperand(1), imm) &&
1300         (!Aligned || (imm & 3) == 0)) {
1301       Disp = DAG.getTargetConstant(imm, N.getValueType());
1302       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1303         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1304         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1305       } else {
1306         Base = N.getOperand(0);
1307       }
1308       return true; // [r+i]
1309     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1310       // Match LOAD (ADD (X, Lo(G))).
1311       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1312              && "Cannot handle constant offsets yet!");
1313       Disp = N.getOperand(1).getOperand(0);  // The global address.
1314       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1315              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1316              Disp.getOpcode() == ISD::TargetConstantPool ||
1317              Disp.getOpcode() == ISD::TargetJumpTable);
1318       Base = N.getOperand(0);
1319       return true;  // [&g+r]
1320     }
1321   } else if (N.getOpcode() == ISD::OR) {
1322     short imm = 0;
1323     if (isIntS16Immediate(N.getOperand(1), imm) &&
1324         (!Aligned || (imm & 3) == 0)) {
1325       // If this is an or of disjoint bitfields, we can codegen this as an add
1326       // (for better address arithmetic) if the LHS and RHS of the OR are
1327       // provably disjoint.
1328       APInt LHSKnownZero, LHSKnownOne;
1329       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1330
1331       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1332         // If all of the bits are known zero on the LHS or RHS, the add won't
1333         // carry.
1334         if (FrameIndexSDNode *FI =
1335               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1336           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1337           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1338         } else {
1339           Base = N.getOperand(0);
1340         }
1341         Disp = DAG.getTargetConstant(imm, N.getValueType());
1342         return true;
1343       }
1344     }
1345   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1346     // Loading from a constant address.
1347
1348     // If this address fits entirely in a 16-bit sext immediate field, codegen
1349     // this as "d, 0"
1350     short Imm;
1351     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1352       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1353       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1354                              CN->getValueType(0));
1355       return true;
1356     }
1357
1358     // Handle 32-bit sext immediates with LIS + addr mode.
1359     if ((CN->getValueType(0) == MVT::i32 ||
1360          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1361         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1362       int Addr = (int)CN->getZExtValue();
1363
1364       // Otherwise, break this down into an LIS + disp.
1365       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1366
1367       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1368       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1369       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1370       return true;
1371     }
1372   }
1373
1374   Disp = DAG.getTargetConstant(0, getPointerTy());
1375   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1376     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1377     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1378   } else
1379     Base = N;
1380   return true;      // [r+0]
1381 }
1382
1383 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1384 /// represented as an indexed [r+r] operation.
1385 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1386                                                 SDValue &Index,
1387                                                 SelectionDAG &DAG) const {
1388   // Check to see if we can easily represent this as an [r+r] address.  This
1389   // will fail if it thinks that the address is more profitably represented as
1390   // reg+imm, e.g. where imm = 0.
1391   if (SelectAddressRegReg(N, Base, Index, DAG))
1392     return true;
1393
1394   // If the operand is an addition, always emit this as [r+r], since this is
1395   // better (for code size, and execution, as the memop does the add for free)
1396   // than emitting an explicit add.
1397   if (N.getOpcode() == ISD::ADD) {
1398     Base = N.getOperand(0);
1399     Index = N.getOperand(1);
1400     return true;
1401   }
1402
1403   // Otherwise, do it the hard way, using R0 as the base register.
1404   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1405                          N.getValueType());
1406   Index = N;
1407   return true;
1408 }
1409
1410 /// getPreIndexedAddressParts - returns true by value, base pointer and
1411 /// offset pointer and addressing mode by reference if the node's address
1412 /// can be legally represented as pre-indexed load / store address.
1413 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1414                                                   SDValue &Offset,
1415                                                   ISD::MemIndexedMode &AM,
1416                                                   SelectionDAG &DAG) const {
1417   if (DisablePPCPreinc) return false;
1418
1419   bool isLoad = true;
1420   SDValue Ptr;
1421   EVT VT;
1422   unsigned Alignment;
1423   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1424     Ptr = LD->getBasePtr();
1425     VT = LD->getMemoryVT();
1426     Alignment = LD->getAlignment();
1427   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1428     Ptr = ST->getBasePtr();
1429     VT  = ST->getMemoryVT();
1430     Alignment = ST->getAlignment();
1431     isLoad = false;
1432   } else
1433     return false;
1434
1435   // PowerPC doesn't have preinc load/store instructions for vectors.
1436   if (VT.isVector())
1437     return false;
1438
1439   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1440
1441     // Common code will reject creating a pre-inc form if the base pointer
1442     // is a frame index, or if N is a store and the base pointer is either
1443     // the same as or a predecessor of the value being stored.  Check for
1444     // those situations here, and try with swapped Base/Offset instead.
1445     bool Swap = false;
1446
1447     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1448       Swap = true;
1449     else if (!isLoad) {
1450       SDValue Val = cast<StoreSDNode>(N)->getValue();
1451       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1452         Swap = true;
1453     }
1454
1455     if (Swap)
1456       std::swap(Base, Offset);
1457
1458     AM = ISD::PRE_INC;
1459     return true;
1460   }
1461
1462   // LDU/STU can only handle immediates that are a multiple of 4.
1463   if (VT != MVT::i64) {
1464     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1465       return false;
1466   } else {
1467     // LDU/STU need an address with at least 4-byte alignment.
1468     if (Alignment < 4)
1469       return false;
1470
1471     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1472       return false;
1473   }
1474
1475   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1476     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1477     // sext i32 to i64 when addr mode is r+i.
1478     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1479         LD->getExtensionType() == ISD::SEXTLOAD &&
1480         isa<ConstantSDNode>(Offset))
1481       return false;
1482   }
1483
1484   AM = ISD::PRE_INC;
1485   return true;
1486 }
1487
1488 //===----------------------------------------------------------------------===//
1489 //  LowerOperation implementation
1490 //===----------------------------------------------------------------------===//
1491
1492 /// GetLabelAccessInfo - Return true if we should reference labels using a
1493 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1494 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1495                                unsigned &LoOpFlags,
1496                                const GlobalValue *GV = nullptr) {
1497   HiOpFlags = PPCII::MO_HA;
1498   LoOpFlags = PPCII::MO_LO;
1499
1500   // Don't use the pic base if not in PIC relocation model.
1501   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1502
1503   if (isPIC) {
1504     HiOpFlags |= PPCII::MO_PIC_FLAG;
1505     LoOpFlags |= PPCII::MO_PIC_FLAG;
1506   }
1507
1508   // If this is a reference to a global value that requires a non-lazy-ptr, make
1509   // sure that instruction lowering adds it.
1510   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1511     HiOpFlags |= PPCII::MO_NLP_FLAG;
1512     LoOpFlags |= PPCII::MO_NLP_FLAG;
1513
1514     if (GV->hasHiddenVisibility()) {
1515       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1516       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1517     }
1518   }
1519
1520   return isPIC;
1521 }
1522
1523 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1524                              SelectionDAG &DAG) {
1525   EVT PtrVT = HiPart.getValueType();
1526   SDValue Zero = DAG.getConstant(0, PtrVT);
1527   SDLoc DL(HiPart);
1528
1529   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1530   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1531
1532   // With PIC, the first instruction is actually "GR+hi(&G)".
1533   if (isPIC)
1534     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1535                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1536
1537   // Generate non-pic code that has direct accesses to the constant pool.
1538   // The address of the global is just (hi(&g)+lo(&g)).
1539   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1540 }
1541
1542 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1543                                              SelectionDAG &DAG) const {
1544   EVT PtrVT = Op.getValueType();
1545   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1546   const Constant *C = CP->getConstVal();
1547
1548   // 64-bit SVR4 ABI code is always position-independent.
1549   // The actual address of the GlobalValue is stored in the TOC.
1550   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1551     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1552     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1553                        DAG.getRegister(PPC::X2, MVT::i64));
1554   }
1555
1556   unsigned MOHiFlag, MOLoFlag;
1557   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1558
1559   if (isPIC && Subtarget.isSVR4ABI()) {
1560     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1561                                            PPCII::MO_PIC_FLAG);
1562     SDLoc DL(CP);
1563     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1564                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1565   }
1566
1567   SDValue CPIHi =
1568     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1569   SDValue CPILo =
1570     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1571   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1572 }
1573
1574 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1575   EVT PtrVT = Op.getValueType();
1576   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1577
1578   // 64-bit SVR4 ABI code is always position-independent.
1579   // The actual address of the GlobalValue is stored in the TOC.
1580   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1581     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1582     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1583                        DAG.getRegister(PPC::X2, MVT::i64));
1584   }
1585
1586   unsigned MOHiFlag, MOLoFlag;
1587   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1588
1589   if (isPIC && Subtarget.isSVR4ABI()) {
1590     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1591                                         PPCII::MO_PIC_FLAG);
1592     SDLoc DL(GA);
1593     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1594                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1595   }
1596
1597   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1598   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1599   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1600 }
1601
1602 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1603                                              SelectionDAG &DAG) const {
1604   EVT PtrVT = Op.getValueType();
1605
1606   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1607
1608   unsigned MOHiFlag, MOLoFlag;
1609   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1610   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1611   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1612   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1613 }
1614
1615 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1616                                               SelectionDAG &DAG) const {
1617
1618   // FIXME: TLS addresses currently use medium model code sequences,
1619   // which is the most useful form.  Eventually support for small and
1620   // large models could be added if users need it, at the cost of
1621   // additional complexity.
1622   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1623   SDLoc dl(GA);
1624   const GlobalValue *GV = GA->getGlobal();
1625   EVT PtrVT = getPointerTy();
1626   bool is64bit = Subtarget.isPPC64();
1627
1628   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1629
1630   if (Model == TLSModel::LocalExec) {
1631     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1632                                                PPCII::MO_TPREL_HA);
1633     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1634                                                PPCII::MO_TPREL_LO);
1635     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1636                                      is64bit ? MVT::i64 : MVT::i32);
1637     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1638     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1639   }
1640
1641   if (Model == TLSModel::InitialExec) {
1642     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1643     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1644                                                 PPCII::MO_TLS);
1645     SDValue GOTPtr;
1646     if (is64bit) {
1647       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1648       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1649                            PtrVT, GOTReg, TGA);
1650     } else
1651       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1652     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1653                                    PtrVT, TGA, GOTPtr);
1654     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1655   }
1656
1657   if (Model == TLSModel::GeneralDynamic) {
1658     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1659     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1660     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1661                                      GOTReg, TGA);
1662     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1663                                    GOTEntryHi, TGA);
1664
1665     // We need a chain node, and don't have one handy.  The underlying
1666     // call has no side effects, so using the function entry node
1667     // suffices.
1668     SDValue Chain = DAG.getEntryNode();
1669     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1670     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1671     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1672                                   PtrVT, ParmReg, TGA);
1673     // The return value from GET_TLS_ADDR really is in X3 already, but
1674     // some hacks are needed here to tie everything together.  The extra
1675     // copies dissolve during subsequent transforms.
1676     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1677     return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1678   }
1679
1680   if (Model == TLSModel::LocalDynamic) {
1681     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1682     SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1683     SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1684                                      GOTReg, TGA);
1685     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1686                                    GOTEntryHi, TGA);
1687
1688     // We need a chain node, and don't have one handy.  The underlying
1689     // call has no side effects, so using the function entry node
1690     // suffices.
1691     SDValue Chain = DAG.getEntryNode();
1692     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1693     SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1694     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1695                                   PtrVT, ParmReg, TGA);
1696     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1697     // some hacks are needed here to tie everything together.  The extra
1698     // copies dissolve during subsequent transforms.
1699     Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1700     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1701                                       Chain, ParmReg, TGA);
1702     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1703   }
1704
1705   llvm_unreachable("Unknown TLS model!");
1706 }
1707
1708 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1709                                               SelectionDAG &DAG) const {
1710   EVT PtrVT = Op.getValueType();
1711   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1712   SDLoc DL(GSDN);
1713   const GlobalValue *GV = GSDN->getGlobal();
1714
1715   // 64-bit SVR4 ABI code is always position-independent.
1716   // The actual address of the GlobalValue is stored in the TOC.
1717   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1718     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1719     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1720                        DAG.getRegister(PPC::X2, MVT::i64));
1721   }
1722
1723   unsigned MOHiFlag, MOLoFlag;
1724   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1725
1726   if (isPIC && Subtarget.isSVR4ABI()) {
1727     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1728                                             GSDN->getOffset(),
1729                                             PPCII::MO_PIC_FLAG);
1730     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1731                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1732   }
1733
1734   SDValue GAHi =
1735     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1736   SDValue GALo =
1737     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1738
1739   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1740
1741   // If the global reference is actually to a non-lazy-pointer, we have to do an
1742   // extra load to get the address of the global.
1743   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1744     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1745                       false, false, false, 0);
1746   return Ptr;
1747 }
1748
1749 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1750   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1751   SDLoc dl(Op);
1752
1753   if (Op.getValueType() == MVT::v2i64) {
1754     // When the operands themselves are v2i64 values, we need to do something
1755     // special because VSX has no underlying comparison operations for these.
1756     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1757       // Equality can be handled by casting to the legal type for Altivec
1758       // comparisons, everything else needs to be expanded.
1759       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1760         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1761                  DAG.getSetCC(dl, MVT::v4i32,
1762                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1763                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1764                    CC));
1765       }
1766
1767       return SDValue();
1768     }
1769
1770     // We handle most of these in the usual way.
1771     return Op;
1772   }
1773
1774   // If we're comparing for equality to zero, expose the fact that this is
1775   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1776   // fold the new nodes.
1777   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1778     if (C->isNullValue() && CC == ISD::SETEQ) {
1779       EVT VT = Op.getOperand(0).getValueType();
1780       SDValue Zext = Op.getOperand(0);
1781       if (VT.bitsLT(MVT::i32)) {
1782         VT = MVT::i32;
1783         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1784       }
1785       unsigned Log2b = Log2_32(VT.getSizeInBits());
1786       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1787       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1788                                 DAG.getConstant(Log2b, MVT::i32));
1789       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1790     }
1791     // Leave comparisons against 0 and -1 alone for now, since they're usually
1792     // optimized.  FIXME: revisit this when we can custom lower all setcc
1793     // optimizations.
1794     if (C->isAllOnesValue() || C->isNullValue())
1795       return SDValue();
1796   }
1797
1798   // If we have an integer seteq/setne, turn it into a compare against zero
1799   // by xor'ing the rhs with the lhs, which is faster than setting a
1800   // condition register, reading it back out, and masking the correct bit.  The
1801   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1802   // the result to other bit-twiddling opportunities.
1803   EVT LHSVT = Op.getOperand(0).getValueType();
1804   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1805     EVT VT = Op.getValueType();
1806     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1807                                 Op.getOperand(1));
1808     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1809   }
1810   return SDValue();
1811 }
1812
1813 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1814                                       const PPCSubtarget &Subtarget) const {
1815   SDNode *Node = Op.getNode();
1816   EVT VT = Node->getValueType(0);
1817   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1818   SDValue InChain = Node->getOperand(0);
1819   SDValue VAListPtr = Node->getOperand(1);
1820   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1821   SDLoc dl(Node);
1822
1823   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1824
1825   // gpr_index
1826   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1827                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1828                                     false, false, 0);
1829   InChain = GprIndex.getValue(1);
1830
1831   if (VT == MVT::i64) {
1832     // Check if GprIndex is even
1833     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1834                                  DAG.getConstant(1, MVT::i32));
1835     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1836                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1837     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1838                                           DAG.getConstant(1, MVT::i32));
1839     // Align GprIndex to be even if it isn't
1840     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1841                            GprIndex);
1842   }
1843
1844   // fpr index is 1 byte after gpr
1845   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1846                                DAG.getConstant(1, MVT::i32));
1847
1848   // fpr
1849   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1850                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1851                                     false, false, 0);
1852   InChain = FprIndex.getValue(1);
1853
1854   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1855                                        DAG.getConstant(8, MVT::i32));
1856
1857   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1858                                         DAG.getConstant(4, MVT::i32));
1859
1860   // areas
1861   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1862                                      MachinePointerInfo(), false, false,
1863                                      false, 0);
1864   InChain = OverflowArea.getValue(1);
1865
1866   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1867                                     MachinePointerInfo(), false, false,
1868                                     false, 0);
1869   InChain = RegSaveArea.getValue(1);
1870
1871   // select overflow_area if index > 8
1872   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1873                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1874
1875   // adjustment constant gpr_index * 4/8
1876   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1877                                     VT.isInteger() ? GprIndex : FprIndex,
1878                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1879                                                     MVT::i32));
1880
1881   // OurReg = RegSaveArea + RegConstant
1882   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1883                                RegConstant);
1884
1885   // Floating types are 32 bytes into RegSaveArea
1886   if (VT.isFloatingPoint())
1887     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1888                          DAG.getConstant(32, MVT::i32));
1889
1890   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1891   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1892                                    VT.isInteger() ? GprIndex : FprIndex,
1893                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1894                                                    MVT::i32));
1895
1896   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1897                               VT.isInteger() ? VAListPtr : FprPtr,
1898                               MachinePointerInfo(SV),
1899                               MVT::i8, false, false, 0);
1900
1901   // determine if we should load from reg_save_area or overflow_area
1902   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1903
1904   // increase overflow_area by 4/8 if gpr/fpr > 8
1905   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1906                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1907                                           MVT::i32));
1908
1909   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1910                              OverflowAreaPlusN);
1911
1912   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1913                               OverflowAreaPtr,
1914                               MachinePointerInfo(),
1915                               MVT::i32, false, false, 0);
1916
1917   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1918                      false, false, false, 0);
1919 }
1920
1921 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1922                                        const PPCSubtarget &Subtarget) const {
1923   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1924
1925   // We have to copy the entire va_list struct:
1926   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1927   return DAG.getMemcpy(Op.getOperand(0), Op,
1928                        Op.getOperand(1), Op.getOperand(2),
1929                        DAG.getConstant(12, MVT::i32), 8, false, true,
1930                        MachinePointerInfo(), MachinePointerInfo());
1931 }
1932
1933 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1934                                                   SelectionDAG &DAG) const {
1935   return Op.getOperand(0);
1936 }
1937
1938 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1939                                                 SelectionDAG &DAG) const {
1940   SDValue Chain = Op.getOperand(0);
1941   SDValue Trmp = Op.getOperand(1); // trampoline
1942   SDValue FPtr = Op.getOperand(2); // nested function
1943   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1944   SDLoc dl(Op);
1945
1946   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1947   bool isPPC64 = (PtrVT == MVT::i64);
1948   Type *IntPtrTy =
1949     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1950                                                              *DAG.getContext());
1951
1952   TargetLowering::ArgListTy Args;
1953   TargetLowering::ArgListEntry Entry;
1954
1955   Entry.Ty = IntPtrTy;
1956   Entry.Node = Trmp; Args.push_back(Entry);
1957
1958   // TrampSize == (isPPC64 ? 48 : 40);
1959   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1960                                isPPC64 ? MVT::i64 : MVT::i32);
1961   Args.push_back(Entry);
1962
1963   Entry.Node = FPtr; Args.push_back(Entry);
1964   Entry.Node = Nest; Args.push_back(Entry);
1965
1966   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1967   TargetLowering::CallLoweringInfo CLI(DAG);
1968   CLI.setDebugLoc(dl).setChain(Chain)
1969     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
1970                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1971                std::move(Args), 0);
1972
1973   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1974   return CallResult.second;
1975 }
1976
1977 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1978                                         const PPCSubtarget &Subtarget) const {
1979   MachineFunction &MF = DAG.getMachineFunction();
1980   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1981
1982   SDLoc dl(Op);
1983
1984   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1985     // vastart just stores the address of the VarArgsFrameIndex slot into the
1986     // memory location argument.
1987     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1988     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1989     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1990     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1991                         MachinePointerInfo(SV),
1992                         false, false, 0);
1993   }
1994
1995   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1996   // We suppose the given va_list is already allocated.
1997   //
1998   // typedef struct {
1999   //  char gpr;     /* index into the array of 8 GPRs
2000   //                 * stored in the register save area
2001   //                 * gpr=0 corresponds to r3,
2002   //                 * gpr=1 to r4, etc.
2003   //                 */
2004   //  char fpr;     /* index into the array of 8 FPRs
2005   //                 * stored in the register save area
2006   //                 * fpr=0 corresponds to f1,
2007   //                 * fpr=1 to f2, etc.
2008   //                 */
2009   //  char *overflow_arg_area;
2010   //                /* location on stack that holds
2011   //                 * the next overflow argument
2012   //                 */
2013   //  char *reg_save_area;
2014   //               /* where r3:r10 and f1:f8 (if saved)
2015   //                * are stored
2016   //                */
2017   // } va_list[1];
2018
2019
2020   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2021   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2022
2023
2024   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2025
2026   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2027                                             PtrVT);
2028   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2029                                  PtrVT);
2030
2031   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2032   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2033
2034   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2035   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2036
2037   uint64_t FPROffset = 1;
2038   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2039
2040   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2041
2042   // Store first byte : number of int regs
2043   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2044                                          Op.getOperand(1),
2045                                          MachinePointerInfo(SV),
2046                                          MVT::i8, false, false, 0);
2047   uint64_t nextOffset = FPROffset;
2048   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2049                                   ConstFPROffset);
2050
2051   // Store second byte : number of float regs
2052   SDValue secondStore =
2053     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2054                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2055                       false, false, 0);
2056   nextOffset += StackOffset;
2057   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2058
2059   // Store second word : arguments given on stack
2060   SDValue thirdStore =
2061     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2062                  MachinePointerInfo(SV, nextOffset),
2063                  false, false, 0);
2064   nextOffset += FrameOffset;
2065   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2066
2067   // Store third word : arguments given in registers
2068   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2069                       MachinePointerInfo(SV, nextOffset),
2070                       false, false, 0);
2071
2072 }
2073
2074 #include "PPCGenCallingConv.inc"
2075
2076 // Function whose sole purpose is to kill compiler warnings 
2077 // stemming from unused functions included from PPCGenCallingConv.inc.
2078 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2079   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2080 }
2081
2082 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2083                                       CCValAssign::LocInfo &LocInfo,
2084                                       ISD::ArgFlagsTy &ArgFlags,
2085                                       CCState &State) {
2086   return true;
2087 }
2088
2089 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2090                                              MVT &LocVT,
2091                                              CCValAssign::LocInfo &LocInfo,
2092                                              ISD::ArgFlagsTy &ArgFlags,
2093                                              CCState &State) {
2094   static const MCPhysReg ArgRegs[] = {
2095     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2096     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2097   };
2098   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2099
2100   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2101
2102   // Skip one register if the first unallocated register has an even register
2103   // number and there are still argument registers available which have not been
2104   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2105   // need to skip a register if RegNum is odd.
2106   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2107     State.AllocateReg(ArgRegs[RegNum]);
2108   }
2109
2110   // Always return false here, as this function only makes sure that the first
2111   // unallocated register has an odd register number and does not actually
2112   // allocate a register for the current argument.
2113   return false;
2114 }
2115
2116 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2117                                                MVT &LocVT,
2118                                                CCValAssign::LocInfo &LocInfo,
2119                                                ISD::ArgFlagsTy &ArgFlags,
2120                                                CCState &State) {
2121   static const MCPhysReg ArgRegs[] = {
2122     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2123     PPC::F8
2124   };
2125
2126   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2127
2128   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2129
2130   // If there is only one Floating-point register left we need to put both f64
2131   // values of a split ppc_fp128 value on the stack.
2132   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2133     State.AllocateReg(ArgRegs[RegNum]);
2134   }
2135
2136   // Always return false here, as this function only makes sure that the two f64
2137   // values a ppc_fp128 value is split into are both passed in registers or both
2138   // passed on the stack and does not actually allocate a register for the
2139   // current argument.
2140   return false;
2141 }
2142
2143 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2144 /// on Darwin.
2145 static const MCPhysReg *GetFPR() {
2146   static const MCPhysReg FPR[] = {
2147     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2148     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2149   };
2150
2151   return FPR;
2152 }
2153
2154 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2155 /// the stack.
2156 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2157                                        unsigned PtrByteSize) {
2158   unsigned ArgSize = ArgVT.getStoreSize();
2159   if (Flags.isByVal())
2160     ArgSize = Flags.getByValSize();
2161   ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2162
2163   return ArgSize;
2164 }
2165
2166 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2167 /// on the stack.
2168 static unsigned CalculateStackSlotAlignment(EVT ArgVT, ISD::ArgFlagsTy Flags,
2169                                             unsigned PtrByteSize) {
2170   unsigned Align = PtrByteSize;
2171
2172   // Altivec parameters are padded to a 16 byte boundary.
2173   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2174       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2175       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2176     Align = 16;
2177
2178   // ByVal parameters are aligned as requested.
2179   if (Flags.isByVal()) {
2180     unsigned BVAlign = Flags.getByValAlign();
2181     if (BVAlign > PtrByteSize) {
2182       if (BVAlign % PtrByteSize != 0)
2183           llvm_unreachable(
2184             "ByVal alignment is not a multiple of the pointer size");
2185
2186       Align = BVAlign;
2187     }
2188   }
2189
2190   return Align;
2191 }
2192
2193 /// CalculateStackSlotUsed - Return whether this argument will use its
2194 /// stack slot (instead of being passed in registers).  ArgOffset,
2195 /// AvailableFPRs, and AvailableVRs must hold the current argument
2196 /// position, and will be updated to account for this argument.
2197 static bool CalculateStackSlotUsed(EVT ArgVT, ISD::ArgFlagsTy Flags,
2198                                    unsigned PtrByteSize,
2199                                    unsigned LinkageSize,
2200                                    unsigned ParamAreaSize,
2201                                    unsigned &ArgOffset,
2202                                    unsigned &AvailableFPRs,
2203                                    unsigned &AvailableVRs) {
2204   bool UseMemory = false;
2205
2206   // Respect alignment of argument on the stack.
2207   unsigned Align = CalculateStackSlotAlignment(ArgVT, Flags, PtrByteSize);
2208   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2209   // If there's no space left in the argument save area, we must
2210   // use memory (this check also catches zero-sized arguments).
2211   if (ArgOffset >= LinkageSize + ParamAreaSize)
2212     UseMemory = true;
2213
2214   // Allocate argument on the stack.
2215   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2216   // If we overran the argument save area, we must use memory
2217   // (this check catches arguments passed partially in memory)
2218   if (ArgOffset > LinkageSize + ParamAreaSize)
2219     UseMemory = true;
2220
2221   // However, if the argument is actually passed in an FPR or a VR,
2222   // we don't use memory after all.
2223   if (!Flags.isByVal()) {
2224     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2225       if (AvailableFPRs > 0) {
2226         --AvailableFPRs;
2227         return false;
2228       }
2229     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2230         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2231         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2232       if (AvailableVRs > 0) {
2233         --AvailableVRs;
2234         return false;
2235       }
2236   }
2237
2238   return UseMemory;
2239 }
2240
2241 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2242 /// ensure minimum alignment required for target.
2243 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2244                                      unsigned NumBytes) {
2245   unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment();
2246   unsigned AlignMask = TargetAlign - 1;
2247   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2248   return NumBytes;
2249 }
2250
2251 SDValue
2252 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2253                                         CallingConv::ID CallConv, bool isVarArg,
2254                                         const SmallVectorImpl<ISD::InputArg>
2255                                           &Ins,
2256                                         SDLoc dl, SelectionDAG &DAG,
2257                                         SmallVectorImpl<SDValue> &InVals)
2258                                           const {
2259   if (Subtarget.isSVR4ABI()) {
2260     if (Subtarget.isPPC64())
2261       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2262                                          dl, DAG, InVals);
2263     else
2264       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2265                                          dl, DAG, InVals);
2266   } else {
2267     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2268                                        dl, DAG, InVals);
2269   }
2270 }
2271
2272 SDValue
2273 PPCTargetLowering::LowerFormalArguments_32SVR4(
2274                                       SDValue Chain,
2275                                       CallingConv::ID CallConv, bool isVarArg,
2276                                       const SmallVectorImpl<ISD::InputArg>
2277                                         &Ins,
2278                                       SDLoc dl, SelectionDAG &DAG,
2279                                       SmallVectorImpl<SDValue> &InVals) const {
2280
2281   // 32-bit SVR4 ABI Stack Frame Layout:
2282   //              +-----------------------------------+
2283   //        +-->  |            Back chain             |
2284   //        |     +-----------------------------------+
2285   //        |     | Floating-point register save area |
2286   //        |     +-----------------------------------+
2287   //        |     |    General register save area     |
2288   //        |     +-----------------------------------+
2289   //        |     |          CR save word             |
2290   //        |     +-----------------------------------+
2291   //        |     |         VRSAVE save word          |
2292   //        |     +-----------------------------------+
2293   //        |     |         Alignment padding         |
2294   //        |     +-----------------------------------+
2295   //        |     |     Vector register save area     |
2296   //        |     +-----------------------------------+
2297   //        |     |       Local variable space        |
2298   //        |     +-----------------------------------+
2299   //        |     |        Parameter list area        |
2300   //        |     +-----------------------------------+
2301   //        |     |           LR save word            |
2302   //        |     +-----------------------------------+
2303   // SP-->  +---  |            Back chain             |
2304   //              +-----------------------------------+
2305   //
2306   // Specifications:
2307   //   System V Application Binary Interface PowerPC Processor Supplement
2308   //   AltiVec Technology Programming Interface Manual
2309
2310   MachineFunction &MF = DAG.getMachineFunction();
2311   MachineFrameInfo *MFI = MF.getFrameInfo();
2312   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2313
2314   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2315   // Potential tail calls could cause overwriting of argument stack slots.
2316   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2317                        (CallConv == CallingConv::Fast));
2318   unsigned PtrByteSize = 4;
2319
2320   // Assign locations to all of the incoming arguments.
2321   SmallVector<CCValAssign, 16> ArgLocs;
2322   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2323                  getTargetMachine(), ArgLocs, *DAG.getContext());
2324
2325   // Reserve space for the linkage area on the stack.
2326   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2327   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2328
2329   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2330
2331   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2332     CCValAssign &VA = ArgLocs[i];
2333
2334     // Arguments stored in registers.
2335     if (VA.isRegLoc()) {
2336       const TargetRegisterClass *RC;
2337       EVT ValVT = VA.getValVT();
2338
2339       switch (ValVT.getSimpleVT().SimpleTy) {
2340         default:
2341           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2342         case MVT::i1:
2343         case MVT::i32:
2344           RC = &PPC::GPRCRegClass;
2345           break;
2346         case MVT::f32:
2347           RC = &PPC::F4RCRegClass;
2348           break;
2349         case MVT::f64:
2350           if (Subtarget.hasVSX())
2351             RC = &PPC::VSFRCRegClass;
2352           else
2353             RC = &PPC::F8RCRegClass;
2354           break;
2355         case MVT::v16i8:
2356         case MVT::v8i16:
2357         case MVT::v4i32:
2358         case MVT::v4f32:
2359           RC = &PPC::VRRCRegClass;
2360           break;
2361         case MVT::v2f64:
2362         case MVT::v2i64:
2363           RC = &PPC::VSHRCRegClass;
2364           break;
2365       }
2366
2367       // Transform the arguments stored in physical registers into virtual ones.
2368       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2369       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2370                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2371
2372       if (ValVT == MVT::i1)
2373         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2374
2375       InVals.push_back(ArgValue);
2376     } else {
2377       // Argument stored in memory.
2378       assert(VA.isMemLoc());
2379
2380       unsigned ArgSize = VA.getLocVT().getStoreSize();
2381       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2382                                       isImmutable);
2383
2384       // Create load nodes to retrieve arguments from the stack.
2385       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2386       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2387                                    MachinePointerInfo(),
2388                                    false, false, false, 0));
2389     }
2390   }
2391
2392   // Assign locations to all of the incoming aggregate by value arguments.
2393   // Aggregates passed by value are stored in the local variable space of the
2394   // caller's stack frame, right above the parameter list area.
2395   SmallVector<CCValAssign, 16> ByValArgLocs;
2396   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2397                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2398
2399   // Reserve stack space for the allocations in CCInfo.
2400   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2401
2402   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2403
2404   // Area that is at least reserved in the caller of this function.
2405   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2406   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2407
2408   // Set the size that is at least reserved in caller of this function.  Tail
2409   // call optimized function's reserved stack space needs to be aligned so that
2410   // taking the difference between two stack areas will result in an aligned
2411   // stack.
2412   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2413   FuncInfo->setMinReservedArea(MinReservedArea);
2414
2415   SmallVector<SDValue, 8> MemOps;
2416
2417   // If the function takes variable number of arguments, make a frame index for
2418   // the start of the first vararg value... for expansion of llvm.va_start.
2419   if (isVarArg) {
2420     static const MCPhysReg GPArgRegs[] = {
2421       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2422       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2423     };
2424     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2425
2426     static const MCPhysReg FPArgRegs[] = {
2427       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2428       PPC::F8
2429     };
2430     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2431
2432     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2433                                                           NumGPArgRegs));
2434     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2435                                                           NumFPArgRegs));
2436
2437     // Make room for NumGPArgRegs and NumFPArgRegs.
2438     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2439                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2440
2441     FuncInfo->setVarArgsStackOffset(
2442       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2443                              CCInfo.getNextStackOffset(), true));
2444
2445     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2446     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2447
2448     // The fixed integer arguments of a variadic function are stored to the
2449     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2450     // the result of va_next.
2451     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2452       // Get an existing live-in vreg, or add a new one.
2453       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2454       if (!VReg)
2455         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2456
2457       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2458       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2459                                    MachinePointerInfo(), false, false, 0);
2460       MemOps.push_back(Store);
2461       // Increment the address by four for the next argument to store
2462       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2463       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2464     }
2465
2466     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2467     // is set.
2468     // The double arguments are stored to the VarArgsFrameIndex
2469     // on the stack.
2470     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2471       // Get an existing live-in vreg, or add a new one.
2472       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2473       if (!VReg)
2474         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2475
2476       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2477       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2478                                    MachinePointerInfo(), false, false, 0);
2479       MemOps.push_back(Store);
2480       // Increment the address by eight for the next argument to store
2481       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2482                                          PtrVT);
2483       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2484     }
2485   }
2486
2487   if (!MemOps.empty())
2488     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2489
2490   return Chain;
2491 }
2492
2493 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2494 // value to MVT::i64 and then truncate to the correct register size.
2495 SDValue
2496 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2497                                      SelectionDAG &DAG, SDValue ArgVal,
2498                                      SDLoc dl) const {
2499   if (Flags.isSExt())
2500     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2501                          DAG.getValueType(ObjectVT));
2502   else if (Flags.isZExt())
2503     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2504                          DAG.getValueType(ObjectVT));
2505
2506   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2507 }
2508
2509 SDValue
2510 PPCTargetLowering::LowerFormalArguments_64SVR4(
2511                                       SDValue Chain,
2512                                       CallingConv::ID CallConv, bool isVarArg,
2513                                       const SmallVectorImpl<ISD::InputArg>
2514                                         &Ins,
2515                                       SDLoc dl, SelectionDAG &DAG,
2516                                       SmallVectorImpl<SDValue> &InVals) const {
2517   // TODO: add description of PPC stack frame format, or at least some docs.
2518   //
2519   bool isELFv2ABI = Subtarget.isELFv2ABI();
2520   bool isLittleEndian = Subtarget.isLittleEndian();
2521   MachineFunction &MF = DAG.getMachineFunction();
2522   MachineFrameInfo *MFI = MF.getFrameInfo();
2523   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2524
2525   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2526   // Potential tail calls could cause overwriting of argument stack slots.
2527   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2528                        (CallConv == CallingConv::Fast));
2529   unsigned PtrByteSize = 8;
2530
2531   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2532                                                           isELFv2ABI);
2533
2534   static const MCPhysReg GPR[] = {
2535     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2536     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2537   };
2538
2539   static const MCPhysReg *FPR = GetFPR();
2540
2541   static const MCPhysReg VR[] = {
2542     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2543     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2544   };
2545   static const MCPhysReg VSRH[] = {
2546     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2547     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2548   };
2549
2550   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2551   const unsigned Num_FPR_Regs = 13;
2552   const unsigned Num_VR_Regs  = array_lengthof(VR);
2553
2554   // Do a first pass over the arguments to determine whether the ABI
2555   // guarantees that our caller has allocated the parameter save area
2556   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2557   // in the ELFv2 ABI, it is true if this is a vararg function or if
2558   // any parameter is located in a stack slot.
2559
2560   bool HasParameterArea = !isELFv2ABI || isVarArg;
2561   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2562   unsigned NumBytes = LinkageSize;
2563   unsigned AvailableFPRs = Num_FPR_Regs;
2564   unsigned AvailableVRs = Num_VR_Regs;
2565   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2566     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].Flags,
2567                                PtrByteSize, LinkageSize, ParamAreaSize,
2568                                NumBytes, AvailableFPRs, AvailableVRs))
2569       HasParameterArea = true;
2570
2571   // Add DAG nodes to load the arguments or copy them out of registers.  On
2572   // entry to a function on PPC, the arguments start after the linkage area,
2573   // although the first ones are often in registers.
2574
2575   unsigned ArgOffset = LinkageSize;
2576   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2577   SmallVector<SDValue, 8> MemOps;
2578   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2579   unsigned CurArgIdx = 0;
2580   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2581     SDValue ArgVal;
2582     bool needsLoad = false;
2583     EVT ObjectVT = Ins[ArgNo].VT;
2584     unsigned ObjSize = ObjectVT.getStoreSize();
2585     unsigned ArgSize = ObjSize;
2586     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2587     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2588     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2589
2590     /* Respect alignment of argument on the stack.  */
2591     unsigned Align =
2592       CalculateStackSlotAlignment(ObjectVT, Flags, PtrByteSize);
2593     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2594     unsigned CurArgOffset = ArgOffset;
2595
2596     /* Compute GPR index associated with argument offset.  */
2597     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2598     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2599
2600     // FIXME the codegen can be much improved in some cases.
2601     // We do not have to keep everything in memory.
2602     if (Flags.isByVal()) {
2603       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2604       ObjSize = Flags.getByValSize();
2605       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2606       // Empty aggregate parameters do not take up registers.  Examples:
2607       //   struct { } a;
2608       //   union  { } b;
2609       //   int c[0];
2610       // etc.  However, we have to provide a place-holder in InVals, so
2611       // pretend we have an 8-byte item at the current address for that
2612       // purpose.
2613       if (!ObjSize) {
2614         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2615         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2616         InVals.push_back(FIN);
2617         continue;
2618       }
2619
2620       // Create a stack object covering all stack doublewords occupied
2621       // by the argument.  If the argument is (fully or partially) on
2622       // the stack, or if the argument is fully in registers but the
2623       // caller has allocated the parameter save anyway, we can refer
2624       // directly to the caller's stack frame.  Otherwise, create a
2625       // local copy in our own frame.
2626       int FI;
2627       if (HasParameterArea ||
2628           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2629         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
2630       else
2631         FI = MFI->CreateStackObject(ArgSize, Align, false);
2632       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2633
2634       // Handle aggregates smaller than 8 bytes.
2635       if (ObjSize < PtrByteSize) {
2636         // The value of the object is its address, which differs from the
2637         // address of the enclosing doubleword on big-endian systems.
2638         SDValue Arg = FIN;
2639         if (!isLittleEndian) {
2640           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2641           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2642         }
2643         InVals.push_back(Arg);
2644
2645         if (GPR_idx != Num_GPR_Regs) {
2646           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2647           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2648           SDValue Store;
2649
2650           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2651             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2652                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2653             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2654                                       MachinePointerInfo(FuncArg),
2655                                       ObjType, false, false, 0);
2656           } else {
2657             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2658             // store the whole register as-is to the parameter save area
2659             // slot.
2660             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2661                                  MachinePointerInfo(FuncArg),
2662                                  false, false, 0);
2663           }
2664
2665           MemOps.push_back(Store);
2666         }
2667         // Whether we copied from a register or not, advance the offset
2668         // into the parameter save area by a full doubleword.
2669         ArgOffset += PtrByteSize;
2670         continue;
2671       }
2672
2673       // The value of the object is its address, which is the address of
2674       // its first stack doubleword.
2675       InVals.push_back(FIN);
2676
2677       // Store whatever pieces of the object are in registers to memory.
2678       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2679         if (GPR_idx == Num_GPR_Regs)
2680           break;
2681
2682         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2683         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2684         SDValue Addr = FIN;
2685         if (j) {
2686           SDValue Off = DAG.getConstant(j, PtrVT);
2687           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2688         }
2689         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2690                                      MachinePointerInfo(FuncArg, j),
2691                                      false, false, 0);
2692         MemOps.push_back(Store);
2693         ++GPR_idx;
2694       }
2695       ArgOffset += ArgSize;
2696       continue;
2697     }
2698
2699     switch (ObjectVT.getSimpleVT().SimpleTy) {
2700     default: llvm_unreachable("Unhandled argument type!");
2701     case MVT::i1:
2702     case MVT::i32:
2703     case MVT::i64:
2704       if (GPR_idx != Num_GPR_Regs) {
2705         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2706         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2707
2708         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2709           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2710           // value to MVT::i64 and then truncate to the correct register size.
2711           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2712       } else {
2713         needsLoad = true;
2714         ArgSize = PtrByteSize;
2715       }
2716       ArgOffset += 8;
2717       break;
2718
2719     case MVT::f32:
2720     case MVT::f64:
2721       if (FPR_idx != Num_FPR_Regs) {
2722         unsigned VReg;
2723
2724         if (ObjectVT == MVT::f32)
2725           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2726         else
2727           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2728                                             &PPC::VSFRCRegClass :
2729                                             &PPC::F8RCRegClass);
2730
2731         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2732         ++FPR_idx;
2733       } else {
2734         needsLoad = true;
2735         ArgSize = PtrByteSize;
2736       }
2737
2738       ArgOffset += 8;
2739       break;
2740     case MVT::v4f32:
2741     case MVT::v4i32:
2742     case MVT::v8i16:
2743     case MVT::v16i8:
2744     case MVT::v2f64:
2745     case MVT::v2i64:
2746       if (VR_idx != Num_VR_Regs) {
2747         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2748                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2749                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2750         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2751         ++VR_idx;
2752       } else {
2753         needsLoad = true;
2754       }
2755       ArgOffset += 16;
2756       break;
2757     }
2758
2759     // We need to load the argument to a virtual register if we determined
2760     // above that we ran out of physical registers of the appropriate type.
2761     if (needsLoad) {
2762       if (ObjSize < ArgSize && !isLittleEndian)
2763         CurArgOffset += ArgSize - ObjSize;
2764       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2765       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2766       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2767                            false, false, false, 0);
2768     }
2769
2770     InVals.push_back(ArgVal);
2771   }
2772
2773   // Area that is at least reserved in the caller of this function.
2774   unsigned MinReservedArea;
2775   if (HasParameterArea)
2776     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2777   else
2778     MinReservedArea = LinkageSize;
2779
2780   // Set the size that is at least reserved in caller of this function.  Tail
2781   // call optimized functions' reserved stack space needs to be aligned so that
2782   // taking the difference between two stack areas will result in an aligned
2783   // stack.
2784   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2785   FuncInfo->setMinReservedArea(MinReservedArea);
2786
2787   // If the function takes variable number of arguments, make a frame index for
2788   // the start of the first vararg value... for expansion of llvm.va_start.
2789   if (isVarArg) {
2790     int Depth = ArgOffset;
2791
2792     FuncInfo->setVarArgsFrameIndex(
2793       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2794     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2795
2796     // If this function is vararg, store any remaining integer argument regs
2797     // to their spots on the stack so that they may be loaded by deferencing the
2798     // result of va_next.
2799     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2800          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2801       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2802       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2803       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2804                                    MachinePointerInfo(), false, false, 0);
2805       MemOps.push_back(Store);
2806       // Increment the address by four for the next argument to store
2807       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2808       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2809     }
2810   }
2811
2812   if (!MemOps.empty())
2813     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2814
2815   return Chain;
2816 }
2817
2818 SDValue
2819 PPCTargetLowering::LowerFormalArguments_Darwin(
2820                                       SDValue Chain,
2821                                       CallingConv::ID CallConv, bool isVarArg,
2822                                       const SmallVectorImpl<ISD::InputArg>
2823                                         &Ins,
2824                                       SDLoc dl, SelectionDAG &DAG,
2825                                       SmallVectorImpl<SDValue> &InVals) const {
2826   // TODO: add description of PPC stack frame format, or at least some docs.
2827   //
2828   MachineFunction &MF = DAG.getMachineFunction();
2829   MachineFrameInfo *MFI = MF.getFrameInfo();
2830   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2831
2832   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2833   bool isPPC64 = PtrVT == MVT::i64;
2834   // Potential tail calls could cause overwriting of argument stack slots.
2835   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2836                        (CallConv == CallingConv::Fast));
2837   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2838
2839   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2840                                                           false);
2841   unsigned ArgOffset = LinkageSize;
2842   // Area that is at least reserved in caller of this function.
2843   unsigned MinReservedArea = ArgOffset;
2844
2845   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2846     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2847     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2848   };
2849   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2850     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2851     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2852   };
2853
2854   static const MCPhysReg *FPR = GetFPR();
2855
2856   static const MCPhysReg VR[] = {
2857     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2858     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2859   };
2860
2861   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2862   const unsigned Num_FPR_Regs = 13;
2863   const unsigned Num_VR_Regs  = array_lengthof( VR);
2864
2865   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2866
2867   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2868
2869   // In 32-bit non-varargs functions, the stack space for vectors is after the
2870   // stack space for non-vectors.  We do not use this space unless we have
2871   // too many vectors to fit in registers, something that only occurs in
2872   // constructed examples:), but we have to walk the arglist to figure
2873   // that out...for the pathological case, compute VecArgOffset as the
2874   // start of the vector parameter area.  Computing VecArgOffset is the
2875   // entire point of the following loop.
2876   unsigned VecArgOffset = ArgOffset;
2877   if (!isVarArg && !isPPC64) {
2878     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2879          ++ArgNo) {
2880       EVT ObjectVT = Ins[ArgNo].VT;
2881       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2882
2883       if (Flags.isByVal()) {
2884         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2885         unsigned ObjSize = Flags.getByValSize();
2886         unsigned ArgSize =
2887                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2888         VecArgOffset += ArgSize;
2889         continue;
2890       }
2891
2892       switch(ObjectVT.getSimpleVT().SimpleTy) {
2893       default: llvm_unreachable("Unhandled argument type!");
2894       case MVT::i1:
2895       case MVT::i32:
2896       case MVT::f32:
2897         VecArgOffset += 4;
2898         break;
2899       case MVT::i64:  // PPC64
2900       case MVT::f64:
2901         // FIXME: We are guaranteed to be !isPPC64 at this point.
2902         // Does MVT::i64 apply?
2903         VecArgOffset += 8;
2904         break;
2905       case MVT::v4f32:
2906       case MVT::v4i32:
2907       case MVT::v8i16:
2908       case MVT::v16i8:
2909         // Nothing to do, we're only looking at Nonvector args here.
2910         break;
2911       }
2912     }
2913   }
2914   // We've found where the vector parameter area in memory is.  Skip the
2915   // first 12 parameters; these don't use that memory.
2916   VecArgOffset = ((VecArgOffset+15)/16)*16;
2917   VecArgOffset += 12*16;
2918
2919   // Add DAG nodes to load the arguments or copy them out of registers.  On
2920   // entry to a function on PPC, the arguments start after the linkage area,
2921   // although the first ones are often in registers.
2922
2923   SmallVector<SDValue, 8> MemOps;
2924   unsigned nAltivecParamsAtEnd = 0;
2925   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2926   unsigned CurArgIdx = 0;
2927   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2928     SDValue ArgVal;
2929     bool needsLoad = false;
2930     EVT ObjectVT = Ins[ArgNo].VT;
2931     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2932     unsigned ArgSize = ObjSize;
2933     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2934     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2935     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2936
2937     unsigned CurArgOffset = ArgOffset;
2938
2939     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2940     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2941         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2942       if (isVarArg || isPPC64) {
2943         MinReservedArea = ((MinReservedArea+15)/16)*16;
2944         MinReservedArea += CalculateStackSlotSize(ObjectVT,
2945                                                   Flags,
2946                                                   PtrByteSize);
2947       } else  nAltivecParamsAtEnd++;
2948     } else
2949       // Calculate min reserved area.
2950       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2951                                                 Flags,
2952                                                 PtrByteSize);
2953
2954     // FIXME the codegen can be much improved in some cases.
2955     // We do not have to keep everything in memory.
2956     if (Flags.isByVal()) {
2957       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2958       ObjSize = Flags.getByValSize();
2959       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2960       // Objects of size 1 and 2 are right justified, everything else is
2961       // left justified.  This means the memory address is adjusted forwards.
2962       if (ObjSize==1 || ObjSize==2) {
2963         CurArgOffset = CurArgOffset + (4 - ObjSize);
2964       }
2965       // The value of the object is its address.
2966       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2967       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2968       InVals.push_back(FIN);
2969       if (ObjSize==1 || ObjSize==2) {
2970         if (GPR_idx != Num_GPR_Regs) {
2971           unsigned VReg;
2972           if (isPPC64)
2973             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2974           else
2975             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2976           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2977           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2978           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2979                                             MachinePointerInfo(FuncArg),
2980                                             ObjType, false, false, 0);
2981           MemOps.push_back(Store);
2982           ++GPR_idx;
2983         }
2984
2985         ArgOffset += PtrByteSize;
2986
2987         continue;
2988       }
2989       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2990         // Store whatever pieces of the object are in registers
2991         // to memory.  ArgOffset will be the address of the beginning
2992         // of the object.
2993         if (GPR_idx != Num_GPR_Regs) {
2994           unsigned VReg;
2995           if (isPPC64)
2996             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2997           else
2998             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2999           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3000           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3001           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3002           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3003                                        MachinePointerInfo(FuncArg, j),
3004                                        false, false, 0);
3005           MemOps.push_back(Store);
3006           ++GPR_idx;
3007           ArgOffset += PtrByteSize;
3008         } else {
3009           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3010           break;
3011         }
3012       }
3013       continue;
3014     }
3015
3016     switch (ObjectVT.getSimpleVT().SimpleTy) {
3017     default: llvm_unreachable("Unhandled argument type!");
3018     case MVT::i1:
3019     case MVT::i32:
3020       if (!isPPC64) {
3021         if (GPR_idx != Num_GPR_Regs) {
3022           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3023           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3024
3025           if (ObjectVT == MVT::i1)
3026             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3027
3028           ++GPR_idx;
3029         } else {
3030           needsLoad = true;
3031           ArgSize = PtrByteSize;
3032         }
3033         // All int arguments reserve stack space in the Darwin ABI.
3034         ArgOffset += PtrByteSize;
3035         break;
3036       }
3037       // FALLTHROUGH
3038     case MVT::i64:  // PPC64
3039       if (GPR_idx != Num_GPR_Regs) {
3040         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3041         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3042
3043         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3044           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3045           // value to MVT::i64 and then truncate to the correct register size.
3046           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3047
3048         ++GPR_idx;
3049       } else {
3050         needsLoad = true;
3051         ArgSize = PtrByteSize;
3052       }
3053       // All int arguments reserve stack space in the Darwin ABI.
3054       ArgOffset += 8;
3055       break;
3056
3057     case MVT::f32:
3058     case MVT::f64:
3059       // Every 4 bytes of argument space consumes one of the GPRs available for
3060       // argument passing.
3061       if (GPR_idx != Num_GPR_Regs) {
3062         ++GPR_idx;
3063         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3064           ++GPR_idx;
3065       }
3066       if (FPR_idx != Num_FPR_Regs) {
3067         unsigned VReg;
3068
3069         if (ObjectVT == MVT::f32)
3070           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3071         else
3072           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3073
3074         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3075         ++FPR_idx;
3076       } else {
3077         needsLoad = true;
3078       }
3079
3080       // All FP arguments reserve stack space in the Darwin ABI.
3081       ArgOffset += isPPC64 ? 8 : ObjSize;
3082       break;
3083     case MVT::v4f32:
3084     case MVT::v4i32:
3085     case MVT::v8i16:
3086     case MVT::v16i8:
3087       // Note that vector arguments in registers don't reserve stack space,
3088       // except in varargs functions.
3089       if (VR_idx != Num_VR_Regs) {
3090         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3091         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3092         if (isVarArg) {
3093           while ((ArgOffset % 16) != 0) {
3094             ArgOffset += PtrByteSize;
3095             if (GPR_idx != Num_GPR_Regs)
3096               GPR_idx++;
3097           }
3098           ArgOffset += 16;
3099           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3100         }
3101         ++VR_idx;
3102       } else {
3103         if (!isVarArg && !isPPC64) {
3104           // Vectors go after all the nonvectors.
3105           CurArgOffset = VecArgOffset;
3106           VecArgOffset += 16;
3107         } else {
3108           // Vectors are aligned.
3109           ArgOffset = ((ArgOffset+15)/16)*16;
3110           CurArgOffset = ArgOffset;
3111           ArgOffset += 16;
3112         }
3113         needsLoad = true;
3114       }
3115       break;
3116     }
3117
3118     // We need to load the argument to a virtual register if we determined above
3119     // that we ran out of physical registers of the appropriate type.
3120     if (needsLoad) {
3121       int FI = MFI->CreateFixedObject(ObjSize,
3122                                       CurArgOffset + (ArgSize - ObjSize),
3123                                       isImmutable);
3124       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3125       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3126                            false, false, false, 0);
3127     }
3128
3129     InVals.push_back(ArgVal);
3130   }
3131
3132   // Allow for Altivec parameters at the end, if needed.
3133   if (nAltivecParamsAtEnd) {
3134     MinReservedArea = ((MinReservedArea+15)/16)*16;
3135     MinReservedArea += 16*nAltivecParamsAtEnd;
3136   }
3137
3138   // Area that is at least reserved in the caller of this function.
3139   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3140
3141   // Set the size that is at least reserved in caller of this function.  Tail
3142   // call optimized functions' reserved stack space needs to be aligned so that
3143   // taking the difference between two stack areas will result in an aligned
3144   // stack.
3145   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3146   FuncInfo->setMinReservedArea(MinReservedArea);
3147
3148   // If the function takes variable number of arguments, make a frame index for
3149   // the start of the first vararg value... for expansion of llvm.va_start.
3150   if (isVarArg) {
3151     int Depth = ArgOffset;
3152
3153     FuncInfo->setVarArgsFrameIndex(
3154       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3155                              Depth, true));
3156     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3157
3158     // If this function is vararg, store any remaining integer argument regs
3159     // to their spots on the stack so that they may be loaded by deferencing the
3160     // result of va_next.
3161     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3162       unsigned VReg;
3163
3164       if (isPPC64)
3165         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3166       else
3167         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3168
3169       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3170       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3171                                    MachinePointerInfo(), false, false, 0);
3172       MemOps.push_back(Store);
3173       // Increment the address by four for the next argument to store
3174       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3175       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3176     }
3177   }
3178
3179   if (!MemOps.empty())
3180     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3181
3182   return Chain;
3183 }
3184
3185 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3186 /// adjusted to accommodate the arguments for the tailcall.
3187 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3188                                    unsigned ParamSize) {
3189
3190   if (!isTailCall) return 0;
3191
3192   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3193   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3194   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3195   // Remember only if the new adjustement is bigger.
3196   if (SPDiff < FI->getTailCallSPDelta())
3197     FI->setTailCallSPDelta(SPDiff);
3198
3199   return SPDiff;
3200 }
3201
3202 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3203 /// for tail call optimization. Targets which want to do tail call
3204 /// optimization should implement this function.
3205 bool
3206 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3207                                                      CallingConv::ID CalleeCC,
3208                                                      bool isVarArg,
3209                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3210                                                      SelectionDAG& DAG) const {
3211   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3212     return false;
3213
3214   // Variable argument functions are not supported.
3215   if (isVarArg)
3216     return false;
3217
3218   MachineFunction &MF = DAG.getMachineFunction();
3219   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3220   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3221     // Functions containing by val parameters are not supported.
3222     for (unsigned i = 0; i != Ins.size(); i++) {
3223        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3224        if (Flags.isByVal()) return false;
3225     }
3226
3227     // Non-PIC/GOT tail calls are supported.
3228     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3229       return true;
3230
3231     // At the moment we can only do local tail calls (in same module, hidden
3232     // or protected) if we are generating PIC.
3233     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3234       return G->getGlobal()->hasHiddenVisibility()
3235           || G->getGlobal()->hasProtectedVisibility();
3236   }
3237
3238   return false;
3239 }
3240
3241 /// isCallCompatibleAddress - Return the immediate to use if the specified
3242 /// 32-bit value is representable in the immediate field of a BxA instruction.
3243 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3244   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3245   if (!C) return nullptr;
3246
3247   int Addr = C->getZExtValue();
3248   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3249       SignExtend32<26>(Addr) != Addr)
3250     return nullptr;  // Top 6 bits have to be sext of immediate.
3251
3252   return DAG.getConstant((int)C->getZExtValue() >> 2,
3253                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3254 }
3255
3256 namespace {
3257
3258 struct TailCallArgumentInfo {
3259   SDValue Arg;
3260   SDValue FrameIdxOp;
3261   int       FrameIdx;
3262
3263   TailCallArgumentInfo() : FrameIdx(0) {}
3264 };
3265
3266 }
3267
3268 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3269 static void
3270 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3271                                            SDValue Chain,
3272                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3273                    SmallVectorImpl<SDValue> &MemOpChains,
3274                    SDLoc dl) {
3275   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3276     SDValue Arg = TailCallArgs[i].Arg;
3277     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3278     int FI = TailCallArgs[i].FrameIdx;
3279     // Store relative to framepointer.
3280     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3281                                        MachinePointerInfo::getFixedStack(FI),
3282                                        false, false, 0));
3283   }
3284 }
3285
3286 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3287 /// the appropriate stack slot for the tail call optimized function call.
3288 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3289                                                MachineFunction &MF,
3290                                                SDValue Chain,
3291                                                SDValue OldRetAddr,
3292                                                SDValue OldFP,
3293                                                int SPDiff,
3294                                                bool isPPC64,
3295                                                bool isDarwinABI,
3296                                                SDLoc dl) {
3297   if (SPDiff) {
3298     // Calculate the new stack slot for the return address.
3299     int SlotSize = isPPC64 ? 8 : 4;
3300     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3301                                                                    isDarwinABI);
3302     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3303                                                           NewRetAddrLoc, true);
3304     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3305     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3306     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3307                          MachinePointerInfo::getFixedStack(NewRetAddr),
3308                          false, false, 0);
3309
3310     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3311     // slot as the FP is never overwritten.
3312     if (isDarwinABI) {
3313       int NewFPLoc =
3314         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3315       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3316                                                           true);
3317       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3318       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3319                            MachinePointerInfo::getFixedStack(NewFPIdx),
3320                            false, false, 0);
3321     }
3322   }
3323   return Chain;
3324 }
3325
3326 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3327 /// the position of the argument.
3328 static void
3329 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3330                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3331                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3332   int Offset = ArgOffset + SPDiff;
3333   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3334   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3335   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3336   SDValue FIN = DAG.getFrameIndex(FI, VT);
3337   TailCallArgumentInfo Info;
3338   Info.Arg = Arg;
3339   Info.FrameIdxOp = FIN;
3340   Info.FrameIdx = FI;
3341   TailCallArguments.push_back(Info);
3342 }
3343
3344 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3345 /// stack slot. Returns the chain as result and the loaded frame pointers in
3346 /// LROpOut/FPOpout. Used when tail calling.
3347 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3348                                                         int SPDiff,
3349                                                         SDValue Chain,
3350                                                         SDValue &LROpOut,
3351                                                         SDValue &FPOpOut,
3352                                                         bool isDarwinABI,
3353                                                         SDLoc dl) const {
3354   if (SPDiff) {
3355     // Load the LR and FP stack slot for later adjusting.
3356     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3357     LROpOut = getReturnAddrFrameIndex(DAG);
3358     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3359                           false, false, false, 0);
3360     Chain = SDValue(LROpOut.getNode(), 1);
3361
3362     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3363     // slot as the FP is never overwritten.
3364     if (isDarwinABI) {
3365       FPOpOut = getFramePointerFrameIndex(DAG);
3366       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3367                             false, false, false, 0);
3368       Chain = SDValue(FPOpOut.getNode(), 1);
3369     }
3370   }
3371   return Chain;
3372 }
3373
3374 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3375 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3376 /// specified by the specific parameter attribute. The copy will be passed as
3377 /// a byval function parameter.
3378 /// Sometimes what we are copying is the end of a larger object, the part that
3379 /// does not fit in registers.
3380 static SDValue
3381 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3382                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3383                           SDLoc dl) {
3384   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3385   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3386                        false, false, MachinePointerInfo(),
3387                        MachinePointerInfo());
3388 }
3389
3390 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3391 /// tail calls.
3392 static void
3393 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3394                  SDValue Arg, SDValue PtrOff, int SPDiff,
3395                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3396                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3397                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3398                  SDLoc dl) {
3399   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3400   if (!isTailCall) {
3401     if (isVector) {
3402       SDValue StackPtr;
3403       if (isPPC64)
3404         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3405       else
3406         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3407       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3408                            DAG.getConstant(ArgOffset, PtrVT));
3409     }
3410     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3411                                        MachinePointerInfo(), false, false, 0));
3412   // Calculate and remember argument location.
3413   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3414                                   TailCallArguments);
3415 }
3416
3417 static
3418 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3419                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3420                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3421                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3422   MachineFunction &MF = DAG.getMachineFunction();
3423
3424   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3425   // might overwrite each other in case of tail call optimization.
3426   SmallVector<SDValue, 8> MemOpChains2;
3427   // Do not flag preceding copytoreg stuff together with the following stuff.
3428   InFlag = SDValue();
3429   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3430                                     MemOpChains2, dl);
3431   if (!MemOpChains2.empty())
3432     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3433
3434   // Store the return address to the appropriate stack slot.
3435   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3436                                         isPPC64, isDarwinABI, dl);
3437
3438   // Emit callseq_end just before tailcall node.
3439   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3440                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3441   InFlag = Chain.getValue(1);
3442 }
3443
3444 static
3445 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3446                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3447                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3448                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3449                      const PPCSubtarget &Subtarget) {
3450
3451   bool isPPC64 = Subtarget.isPPC64();
3452   bool isSVR4ABI = Subtarget.isSVR4ABI();
3453   bool isELFv2ABI = Subtarget.isELFv2ABI();
3454
3455   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3456   NodeTys.push_back(MVT::Other);   // Returns a chain
3457   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3458
3459   unsigned CallOpc = PPCISD::CALL;
3460
3461   bool needIndirectCall = true;
3462   if (!isSVR4ABI || !isPPC64)
3463     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3464       // If this is an absolute destination address, use the munged value.
3465       Callee = SDValue(Dest, 0);
3466       needIndirectCall = false;
3467     }
3468
3469   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3470     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3471     // Use indirect calls for ALL functions calls in JIT mode, since the
3472     // far-call stubs may be outside relocation limits for a BL instruction.
3473     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3474       unsigned OpFlags = 0;
3475       if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3476           (Subtarget.getTargetTriple().isMacOSX() &&
3477            Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3478           (G->getGlobal()->isDeclaration() ||
3479            G->getGlobal()->isWeakForLinker())) ||
3480           (Subtarget.isTargetELF() && !isPPC64 &&
3481            !G->getGlobal()->hasLocalLinkage() &&
3482            DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3483         // PC-relative references to external symbols should go through $stub,
3484         // unless we're building with the leopard linker or later, which
3485         // automatically synthesizes these stubs.
3486         OpFlags = PPCII::MO_PLT_OR_STUB;
3487       }
3488
3489       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3490       // every direct call is) turn it into a TargetGlobalAddress /
3491       // TargetExternalSymbol node so that legalize doesn't hack it.
3492       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3493                                           Callee.getValueType(),
3494                                           0, OpFlags);
3495       needIndirectCall = false;
3496     }
3497   }
3498
3499   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3500     unsigned char OpFlags = 0;
3501
3502     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3503          (Subtarget.getTargetTriple().isMacOSX() &&
3504           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3505         (Subtarget.isTargetELF() && !isPPC64 &&
3506          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3507       // PC-relative references to external symbols should go through $stub,
3508       // unless we're building with the leopard linker or later, which
3509       // automatically synthesizes these stubs.
3510       OpFlags = PPCII::MO_PLT_OR_STUB;
3511     }
3512
3513     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3514                                          OpFlags);
3515     needIndirectCall = false;
3516   }
3517
3518   if (needIndirectCall) {
3519     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3520     // to do the call, we can't use PPCISD::CALL.
3521     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3522
3523     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3524       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3525       // entry point, but to the function descriptor (the function entry point
3526       // address is part of the function descriptor though).
3527       // The function descriptor is a three doubleword structure with the
3528       // following fields: function entry point, TOC base address and
3529       // environment pointer.
3530       // Thus for a call through a function pointer, the following actions need
3531       // to be performed:
3532       //   1. Save the TOC of the caller in the TOC save area of its stack
3533       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3534       //   2. Load the address of the function entry point from the function
3535       //      descriptor.
3536       //   3. Load the TOC of the callee from the function descriptor into r2.
3537       //   4. Load the environment pointer from the function descriptor into
3538       //      r11.
3539       //   5. Branch to the function entry point address.
3540       //   6. On return of the callee, the TOC of the caller needs to be
3541       //      restored (this is done in FinishCall()).
3542       //
3543       // All those operations are flagged together to ensure that no other
3544       // operations can be scheduled in between. E.g. without flagging the
3545       // operations together, a TOC access in the caller could be scheduled
3546       // between the load of the callee TOC and the branch to the callee, which
3547       // results in the TOC access going through the TOC of the callee instead
3548       // of going through the TOC of the caller, which leads to incorrect code.
3549
3550       // Load the address of the function entry point from the function
3551       // descriptor.
3552       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3553       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3554                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3555       Chain = LoadFuncPtr.getValue(1);
3556       InFlag = LoadFuncPtr.getValue(2);
3557
3558       // Load environment pointer into r11.
3559       // Offset of the environment pointer within the function descriptor.
3560       SDValue PtrOff = DAG.getIntPtrConstant(16);
3561
3562       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3563       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3564                                        InFlag);
3565       Chain = LoadEnvPtr.getValue(1);
3566       InFlag = LoadEnvPtr.getValue(2);
3567
3568       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3569                                         InFlag);
3570       Chain = EnvVal.getValue(0);
3571       InFlag = EnvVal.getValue(1);
3572
3573       // Load TOC of the callee into r2. We are using a target-specific load
3574       // with r2 hard coded, because the result of a target-independent load
3575       // would never go directly into r2, since r2 is a reserved register (which
3576       // prevents the register allocator from allocating it), resulting in an
3577       // additional register being allocated and an unnecessary move instruction
3578       // being generated.
3579       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3580       SDValue TOCOff = DAG.getIntPtrConstant(8);
3581       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3582       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3583                                        AddTOC, InFlag);
3584       Chain = LoadTOCPtr.getValue(0);
3585       InFlag = LoadTOCPtr.getValue(1);
3586
3587       MTCTROps[0] = Chain;
3588       MTCTROps[1] = LoadFuncPtr;
3589       MTCTROps[2] = InFlag;
3590     }
3591
3592     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3593                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3594     InFlag = Chain.getValue(1);
3595
3596     NodeTys.clear();
3597     NodeTys.push_back(MVT::Other);
3598     NodeTys.push_back(MVT::Glue);
3599     Ops.push_back(Chain);
3600     CallOpc = PPCISD::BCTRL;
3601     Callee.setNode(nullptr);
3602     // Add use of X11 (holding environment pointer)
3603     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3604       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3605     // Add CTR register as callee so a bctr can be emitted later.
3606     if (isTailCall)
3607       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3608   }
3609
3610   // If this is a direct call, pass the chain and the callee.
3611   if (Callee.getNode()) {
3612     Ops.push_back(Chain);
3613     Ops.push_back(Callee);
3614   }
3615   // If this is a tail call add stack pointer delta.
3616   if (isTailCall)
3617     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3618
3619   // Add argument registers to the end of the list so that they are known live
3620   // into the call.
3621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3622     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3623                                   RegsToPass[i].second.getValueType()));
3624
3625   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3626   if (Callee.getNode() && isELFv2ABI)
3627     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3628
3629   return CallOpc;
3630 }
3631
3632 static
3633 bool isLocalCall(const SDValue &Callee)
3634 {
3635   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3636     return !G->getGlobal()->isDeclaration() &&
3637            !G->getGlobal()->isWeakForLinker();
3638   return false;
3639 }
3640
3641 SDValue
3642 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3643                                    CallingConv::ID CallConv, bool isVarArg,
3644                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3645                                    SDLoc dl, SelectionDAG &DAG,
3646                                    SmallVectorImpl<SDValue> &InVals) const {
3647
3648   SmallVector<CCValAssign, 16> RVLocs;
3649   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3650                     getTargetMachine(), RVLocs, *DAG.getContext());
3651   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3652
3653   // Copy all of the result registers out of their specified physreg.
3654   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3655     CCValAssign &VA = RVLocs[i];
3656     assert(VA.isRegLoc() && "Can only return in registers!");
3657
3658     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3659                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3660     Chain = Val.getValue(1);
3661     InFlag = Val.getValue(2);
3662
3663     switch (VA.getLocInfo()) {
3664     default: llvm_unreachable("Unknown loc info!");
3665     case CCValAssign::Full: break;
3666     case CCValAssign::AExt:
3667       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3668       break;
3669     case CCValAssign::ZExt:
3670       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3671                         DAG.getValueType(VA.getValVT()));
3672       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3673       break;
3674     case CCValAssign::SExt:
3675       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3676                         DAG.getValueType(VA.getValVT()));
3677       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3678       break;
3679     }
3680
3681     InVals.push_back(Val);
3682   }
3683
3684   return Chain;
3685 }
3686
3687 SDValue
3688 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3689                               bool isTailCall, bool isVarArg,
3690                               SelectionDAG &DAG,
3691                               SmallVector<std::pair<unsigned, SDValue>, 8>
3692                                 &RegsToPass,
3693                               SDValue InFlag, SDValue Chain,
3694                               SDValue &Callee,
3695                               int SPDiff, unsigned NumBytes,
3696                               const SmallVectorImpl<ISD::InputArg> &Ins,
3697                               SmallVectorImpl<SDValue> &InVals) const {
3698
3699   bool isELFv2ABI = Subtarget.isELFv2ABI();
3700   std::vector<EVT> NodeTys;
3701   SmallVector<SDValue, 8> Ops;
3702   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3703                                  isTailCall, RegsToPass, Ops, NodeTys,
3704                                  Subtarget);
3705
3706   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3707   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3708     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3709
3710   // When performing tail call optimization the callee pops its arguments off
3711   // the stack. Account for this here so these bytes can be pushed back on in
3712   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3713   int BytesCalleePops =
3714     (CallConv == CallingConv::Fast &&
3715      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3716
3717   // Add a register mask operand representing the call-preserved registers.
3718   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3719   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3720   assert(Mask && "Missing call preserved mask for calling convention");
3721   Ops.push_back(DAG.getRegisterMask(Mask));
3722
3723   if (InFlag.getNode())
3724     Ops.push_back(InFlag);
3725
3726   // Emit tail call.
3727   if (isTailCall) {
3728     assert(((Callee.getOpcode() == ISD::Register &&
3729              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3730             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3731             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3732             isa<ConstantSDNode>(Callee)) &&
3733     "Expecting an global address, external symbol, absolute value or register");
3734
3735     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3736   }
3737
3738   // Add a NOP immediately after the branch instruction when using the 64-bit
3739   // SVR4 ABI. At link time, if caller and callee are in a different module and
3740   // thus have a different TOC, the call will be replaced with a call to a stub
3741   // function which saves the current TOC, loads the TOC of the callee and
3742   // branches to the callee. The NOP will be replaced with a load instruction
3743   // which restores the TOC of the caller from the TOC save slot of the current
3744   // stack frame. If caller and callee belong to the same module (and have the
3745   // same TOC), the NOP will remain unchanged.
3746
3747   bool needsTOCRestore = false;
3748   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3749     if (CallOpc == PPCISD::BCTRL) {
3750       // This is a call through a function pointer.
3751       // Restore the caller TOC from the save area into R2.
3752       // See PrepareCall() for more information about calls through function
3753       // pointers in the 64-bit SVR4 ABI.
3754       // We are using a target-specific load with r2 hard coded, because the
3755       // result of a target-independent load would never go directly into r2,
3756       // since r2 is a reserved register (which prevents the register allocator
3757       // from allocating it), resulting in an additional register being
3758       // allocated and an unnecessary move instruction being generated.
3759       needsTOCRestore = true;
3760     } else if ((CallOpc == PPCISD::CALL) &&
3761                (!isLocalCall(Callee) ||
3762                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3763       // Otherwise insert NOP for non-local calls.
3764       CallOpc = PPCISD::CALL_NOP;
3765     }
3766   }
3767
3768   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3769   InFlag = Chain.getValue(1);
3770
3771   if (needsTOCRestore) {
3772     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3773     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3774     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3775     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3776     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3777     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3778     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3779     InFlag = Chain.getValue(1);
3780   }
3781
3782   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3783                              DAG.getIntPtrConstant(BytesCalleePops, true),
3784                              InFlag, dl);
3785   if (!Ins.empty())
3786     InFlag = Chain.getValue(1);
3787
3788   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3789                          Ins, dl, DAG, InVals);
3790 }
3791
3792 SDValue
3793 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3794                              SmallVectorImpl<SDValue> &InVals) const {
3795   SelectionDAG &DAG                     = CLI.DAG;
3796   SDLoc &dl                             = CLI.DL;
3797   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3798   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3799   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3800   SDValue Chain                         = CLI.Chain;
3801   SDValue Callee                        = CLI.Callee;
3802   bool &isTailCall                      = CLI.IsTailCall;
3803   CallingConv::ID CallConv              = CLI.CallConv;
3804   bool isVarArg                         = CLI.IsVarArg;
3805
3806   if (isTailCall)
3807     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3808                                                    Ins, DAG);
3809
3810   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3811     report_fatal_error("failed to perform tail call elimination on a call "
3812                        "site marked musttail");
3813
3814   if (Subtarget.isSVR4ABI()) {
3815     if (Subtarget.isPPC64())
3816       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3817                               isTailCall, Outs, OutVals, Ins,
3818                               dl, DAG, InVals);
3819     else
3820       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3821                               isTailCall, Outs, OutVals, Ins,
3822                               dl, DAG, InVals);
3823   }
3824
3825   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3826                           isTailCall, Outs, OutVals, Ins,
3827                           dl, DAG, InVals);
3828 }
3829
3830 SDValue
3831 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3832                                     CallingConv::ID CallConv, bool isVarArg,
3833                                     bool isTailCall,
3834                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3835                                     const SmallVectorImpl<SDValue> &OutVals,
3836                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3837                                     SDLoc dl, SelectionDAG &DAG,
3838                                     SmallVectorImpl<SDValue> &InVals) const {
3839   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3840   // of the 32-bit SVR4 ABI stack frame layout.
3841
3842   assert((CallConv == CallingConv::C ||
3843           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3844
3845   unsigned PtrByteSize = 4;
3846
3847   MachineFunction &MF = DAG.getMachineFunction();
3848
3849   // Mark this function as potentially containing a function that contains a
3850   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3851   // and restoring the callers stack pointer in this functions epilog. This is
3852   // done because by tail calling the called function might overwrite the value
3853   // in this function's (MF) stack pointer stack slot 0(SP).
3854   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3855       CallConv == CallingConv::Fast)
3856     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3857
3858   // Count how many bytes are to be pushed on the stack, including the linkage
3859   // area, parameter list area and the part of the local variable space which
3860   // contains copies of aggregates which are passed by value.
3861
3862   // Assign locations to all of the outgoing arguments.
3863   SmallVector<CCValAssign, 16> ArgLocs;
3864   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3865                  getTargetMachine(), ArgLocs, *DAG.getContext());
3866
3867   // Reserve space for the linkage area on the stack.
3868   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3869                        PtrByteSize);
3870
3871   if (isVarArg) {
3872     // Handle fixed and variable vector arguments differently.
3873     // Fixed vector arguments go into registers as long as registers are
3874     // available. Variable vector arguments always go into memory.
3875     unsigned NumArgs = Outs.size();
3876
3877     for (unsigned i = 0; i != NumArgs; ++i) {
3878       MVT ArgVT = Outs[i].VT;
3879       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3880       bool Result;
3881
3882       if (Outs[i].IsFixed) {
3883         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3884                                CCInfo);
3885       } else {
3886         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3887                                       ArgFlags, CCInfo);
3888       }
3889
3890       if (Result) {
3891 #ifndef NDEBUG
3892         errs() << "Call operand #" << i << " has unhandled type "
3893              << EVT(ArgVT).getEVTString() << "\n";
3894 #endif
3895         llvm_unreachable(nullptr);
3896       }
3897     }
3898   } else {
3899     // All arguments are treated the same.
3900     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3901   }
3902
3903   // Assign locations to all of the outgoing aggregate by value arguments.
3904   SmallVector<CCValAssign, 16> ByValArgLocs;
3905   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3906                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3907
3908   // Reserve stack space for the allocations in CCInfo.
3909   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3910
3911   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3912
3913   // Size of the linkage area, parameter list area and the part of the local
3914   // space variable where copies of aggregates which are passed by value are
3915   // stored.
3916   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3917
3918   // Calculate by how many bytes the stack has to be adjusted in case of tail
3919   // call optimization.
3920   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3921
3922   // Adjust the stack pointer for the new arguments...
3923   // These operations are automatically eliminated by the prolog/epilog pass
3924   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3925                                dl);
3926   SDValue CallSeqStart = Chain;
3927
3928   // Load the return address and frame pointer so it can be moved somewhere else
3929   // later.
3930   SDValue LROp, FPOp;
3931   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3932                                        dl);
3933
3934   // Set up a copy of the stack pointer for use loading and storing any
3935   // arguments that may not fit in the registers available for argument
3936   // passing.
3937   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3938
3939   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3940   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3941   SmallVector<SDValue, 8> MemOpChains;
3942
3943   bool seenFloatArg = false;
3944   // Walk the register/memloc assignments, inserting copies/loads.
3945   for (unsigned i = 0, j = 0, e = ArgLocs.size();
3946        i != e;
3947        ++i) {
3948     CCValAssign &VA = ArgLocs[i];
3949     SDValue Arg = OutVals[i];
3950     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3951
3952     if (Flags.isByVal()) {
3953       // Argument is an aggregate which is passed by value, thus we need to
3954       // create a copy of it in the local variable space of the current stack
3955       // frame (which is the stack frame of the caller) and pass the address of
3956       // this copy to the callee.
3957       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3958       CCValAssign &ByValVA = ByValArgLocs[j++];
3959       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3960
3961       // Memory reserved in the local variable space of the callers stack frame.
3962       unsigned LocMemOffset = ByValVA.getLocMemOffset();
3963
3964       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3965       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3966
3967       // Create a copy of the argument in the local area of the current
3968       // stack frame.
3969       SDValue MemcpyCall =
3970         CreateCopyOfByValArgument(Arg, PtrOff,
3971                                   CallSeqStart.getNode()->getOperand(0),
3972                                   Flags, DAG, dl);
3973
3974       // This must go outside the CALLSEQ_START..END.
3975       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3976                            CallSeqStart.getNode()->getOperand(1),
3977                            SDLoc(MemcpyCall));
3978       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3979                              NewCallSeqStart.getNode());
3980       Chain = CallSeqStart = NewCallSeqStart;
3981
3982       // Pass the address of the aggregate copy on the stack either in a
3983       // physical register or in the parameter list area of the current stack
3984       // frame to the callee.
3985       Arg = PtrOff;
3986     }
3987
3988     if (VA.isRegLoc()) {
3989       if (Arg.getValueType() == MVT::i1)
3990         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
3991
3992       seenFloatArg |= VA.getLocVT().isFloatingPoint();
3993       // Put argument in a physical register.
3994       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3995     } else {
3996       // Put argument in the parameter list area of the current stack frame.
3997       assert(VA.isMemLoc());
3998       unsigned LocMemOffset = VA.getLocMemOffset();
3999
4000       if (!isTailCall) {
4001         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4002         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4003
4004         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4005                                            MachinePointerInfo(),
4006                                            false, false, 0));
4007       } else {
4008         // Calculate and remember argument location.
4009         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4010                                  TailCallArguments);
4011       }
4012     }
4013   }
4014
4015   if (!MemOpChains.empty())
4016     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4017
4018   // Build a sequence of copy-to-reg nodes chained together with token chain
4019   // and flag operands which copy the outgoing args into the appropriate regs.
4020   SDValue InFlag;
4021   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4022     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4023                              RegsToPass[i].second, InFlag);
4024     InFlag = Chain.getValue(1);
4025   }
4026
4027   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4028   // registers.
4029   if (isVarArg) {
4030     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4031     SDValue Ops[] = { Chain, InFlag };
4032
4033     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4034                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4035
4036     InFlag = Chain.getValue(1);
4037   }
4038
4039   if (isTailCall)
4040     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4041                     false, TailCallArguments);
4042
4043   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4044                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4045                     Ins, InVals);
4046 }
4047
4048 // Copy an argument into memory, being careful to do this outside the
4049 // call sequence for the call to which the argument belongs.
4050 SDValue
4051 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4052                                               SDValue CallSeqStart,
4053                                               ISD::ArgFlagsTy Flags,
4054                                               SelectionDAG &DAG,
4055                                               SDLoc dl) const {
4056   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4057                         CallSeqStart.getNode()->getOperand(0),
4058                         Flags, DAG, dl);
4059   // The MEMCPY must go outside the CALLSEQ_START..END.
4060   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4061                              CallSeqStart.getNode()->getOperand(1),
4062                              SDLoc(MemcpyCall));
4063   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4064                          NewCallSeqStart.getNode());
4065   return NewCallSeqStart;
4066 }
4067
4068 SDValue
4069 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4070                                     CallingConv::ID CallConv, bool isVarArg,
4071                                     bool isTailCall,
4072                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4073                                     const SmallVectorImpl<SDValue> &OutVals,
4074                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4075                                     SDLoc dl, SelectionDAG &DAG,
4076                                     SmallVectorImpl<SDValue> &InVals) const {
4077
4078   bool isELFv2ABI = Subtarget.isELFv2ABI();
4079   bool isLittleEndian = Subtarget.isLittleEndian();
4080   unsigned NumOps = Outs.size();
4081
4082   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4083   unsigned PtrByteSize = 8;
4084
4085   MachineFunction &MF = DAG.getMachineFunction();
4086
4087   // Mark this function as potentially containing a function that contains a
4088   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4089   // and restoring the callers stack pointer in this functions epilog. This is
4090   // done because by tail calling the called function might overwrite the value
4091   // in this function's (MF) stack pointer stack slot 0(SP).
4092   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4093       CallConv == CallingConv::Fast)
4094     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4095
4096   // Count how many bytes are to be pushed on the stack, including the linkage
4097   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4098   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4099   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4100   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4101                                                           isELFv2ABI);
4102   unsigned NumBytes = LinkageSize;
4103
4104   // Add up all the space actually used.
4105   for (unsigned i = 0; i != NumOps; ++i) {
4106     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4107     EVT ArgVT = Outs[i].VT;
4108
4109     /* Respect alignment of argument on the stack.  */
4110     unsigned Align = CalculateStackSlotAlignment(ArgVT, Flags, PtrByteSize);
4111     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4112
4113     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4114   }
4115
4116   unsigned NumBytesActuallyUsed = NumBytes;
4117
4118   // The prolog code of the callee may store up to 8 GPR argument registers to
4119   // the stack, allowing va_start to index over them in memory if its varargs.
4120   // Because we cannot tell if this is needed on the caller side, we have to
4121   // conservatively assume that it is needed.  As such, make sure we have at
4122   // least enough stack space for the caller to store the 8 GPRs.
4123   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4124   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4125
4126   // Tail call needs the stack to be aligned.
4127   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4128       CallConv == CallingConv::Fast)
4129     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4130
4131   // Calculate by how many bytes the stack has to be adjusted in case of tail
4132   // call optimization.
4133   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4134
4135   // To protect arguments on the stack from being clobbered in a tail call,
4136   // force all the loads to happen before doing any other lowering.
4137   if (isTailCall)
4138     Chain = DAG.getStackArgumentTokenFactor(Chain);
4139
4140   // Adjust the stack pointer for the new arguments...
4141   // These operations are automatically eliminated by the prolog/epilog pass
4142   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4143                                dl);
4144   SDValue CallSeqStart = Chain;
4145
4146   // Load the return address and frame pointer so it can be move somewhere else
4147   // later.
4148   SDValue LROp, FPOp;
4149   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4150                                        dl);
4151
4152   // Set up a copy of the stack pointer for use loading and storing any
4153   // arguments that may not fit in the registers available for argument
4154   // passing.
4155   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4156
4157   // Figure out which arguments are going to go in registers, and which in
4158   // memory.  Also, if this is a vararg function, floating point operations
4159   // must be stored to our stack, and loaded into integer regs as well, if
4160   // any integer regs are available for argument passing.
4161   unsigned ArgOffset = LinkageSize;
4162   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4163
4164   static const MCPhysReg GPR[] = {
4165     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4166     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4167   };
4168   static const MCPhysReg *FPR = GetFPR();
4169
4170   static const MCPhysReg VR[] = {
4171     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4172     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4173   };
4174   static const MCPhysReg VSRH[] = {
4175     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4176     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4177   };
4178
4179   const unsigned NumGPRs = array_lengthof(GPR);
4180   const unsigned NumFPRs = 13;
4181   const unsigned NumVRs  = array_lengthof(VR);
4182
4183   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4184   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4185
4186   SmallVector<SDValue, 8> MemOpChains;
4187   for (unsigned i = 0; i != NumOps; ++i) {
4188     SDValue Arg = OutVals[i];
4189     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4190
4191     /* Respect alignment of argument on the stack.  */
4192     unsigned Align =
4193       CalculateStackSlotAlignment(Outs[i].VT, Flags, PtrByteSize);
4194     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4195
4196     /* Compute GPR index associated with argument offset.  */
4197     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4198     GPR_idx = std::min(GPR_idx, NumGPRs);
4199
4200     // PtrOff will be used to store the current argument to the stack if a
4201     // register cannot be found for it.
4202     SDValue PtrOff;
4203
4204     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4205
4206     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4207
4208     // Promote integers to 64-bit values.
4209     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4210       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4211       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4212       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4213     }
4214
4215     // FIXME memcpy is used way more than necessary.  Correctness first.
4216     // Note: "by value" is code for passing a structure by value, not
4217     // basic types.
4218     if (Flags.isByVal()) {
4219       // Note: Size includes alignment padding, so
4220       //   struct x { short a; char b; }
4221       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4222       // These are the proper values we need for right-justifying the
4223       // aggregate in a parameter register.
4224       unsigned Size = Flags.getByValSize();
4225
4226       // An empty aggregate parameter takes up no storage and no
4227       // registers.
4228       if (Size == 0)
4229         continue;
4230
4231       // All aggregates smaller than 8 bytes must be passed right-justified.
4232       if (Size==1 || Size==2 || Size==4) {
4233         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4234         if (GPR_idx != NumGPRs) {
4235           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4236                                         MachinePointerInfo(), VT,
4237                                         false, false, 0);
4238           MemOpChains.push_back(Load.getValue(1));
4239           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4240
4241           ArgOffset += PtrByteSize;
4242           continue;
4243         }
4244       }
4245
4246       if (GPR_idx == NumGPRs && Size < 8) {
4247         SDValue AddPtr = PtrOff;
4248         if (!isLittleEndian) {
4249           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4250                                           PtrOff.getValueType());
4251           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4252         }
4253         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4254                                                           CallSeqStart,
4255                                                           Flags, DAG, dl);
4256         ArgOffset += PtrByteSize;
4257         continue;
4258       }
4259       // Copy entire object into memory.  There are cases where gcc-generated
4260       // code assumes it is there, even if it could be put entirely into
4261       // registers.  (This is not what the doc says.)
4262
4263       // FIXME: The above statement is likely due to a misunderstanding of the
4264       // documents.  All arguments must be copied into the parameter area BY
4265       // THE CALLEE in the event that the callee takes the address of any
4266       // formal argument.  That has not yet been implemented.  However, it is
4267       // reasonable to use the stack area as a staging area for the register
4268       // load.
4269
4270       // Skip this for small aggregates, as we will use the same slot for a
4271       // right-justified copy, below.
4272       if (Size >= 8)
4273         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4274                                                           CallSeqStart,
4275                                                           Flags, DAG, dl);
4276
4277       // When a register is available, pass a small aggregate right-justified.
4278       if (Size < 8 && GPR_idx != NumGPRs) {
4279         // The easiest way to get this right-justified in a register
4280         // is to copy the structure into the rightmost portion of a
4281         // local variable slot, then load the whole slot into the
4282         // register.
4283         // FIXME: The memcpy seems to produce pretty awful code for
4284         // small aggregates, particularly for packed ones.
4285         // FIXME: It would be preferable to use the slot in the
4286         // parameter save area instead of a new local variable.
4287         SDValue AddPtr = PtrOff;
4288         if (!isLittleEndian) {
4289           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4290           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4291         }
4292         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4293                                                           CallSeqStart,
4294                                                           Flags, DAG, dl);
4295
4296         // Load the slot into the register.
4297         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4298                                    MachinePointerInfo(),
4299                                    false, false, false, 0);
4300         MemOpChains.push_back(Load.getValue(1));
4301         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4302
4303         // Done with this argument.
4304         ArgOffset += PtrByteSize;
4305         continue;
4306       }
4307
4308       // For aggregates larger than PtrByteSize, copy the pieces of the
4309       // object that fit into registers from the parameter save area.
4310       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4311         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4312         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4313         if (GPR_idx != NumGPRs) {
4314           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4315                                      MachinePointerInfo(),
4316                                      false, false, false, 0);
4317           MemOpChains.push_back(Load.getValue(1));
4318           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4319           ArgOffset += PtrByteSize;
4320         } else {
4321           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4322           break;
4323         }
4324       }
4325       continue;
4326     }
4327
4328     switch (Arg.getSimpleValueType().SimpleTy) {
4329     default: llvm_unreachable("Unexpected ValueType for argument!");
4330     case MVT::i1:
4331     case MVT::i32:
4332     case MVT::i64:
4333       if (GPR_idx != NumGPRs) {
4334         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4335       } else {
4336         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4337                          true, isTailCall, false, MemOpChains,
4338                          TailCallArguments, dl);
4339       }
4340       ArgOffset += PtrByteSize;
4341       break;
4342     case MVT::f32:
4343     case MVT::f64:
4344       if (FPR_idx != NumFPRs) {
4345         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4346
4347         if (isVarArg) {
4348           // A single float or an aggregate containing only a single float
4349           // must be passed right-justified in the stack doubleword, and
4350           // in the GPR, if one is available.
4351           SDValue StoreOff;
4352           if (Arg.getSimpleValueType().SimpleTy == MVT::f32 &&
4353               !isLittleEndian) {
4354             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4355             StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4356           } else
4357             StoreOff = PtrOff;
4358
4359           SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4360                                        MachinePointerInfo(), false, false, 0);
4361           MemOpChains.push_back(Store);
4362
4363           // Float varargs are always shadowed in available integer registers
4364           if (GPR_idx != NumGPRs) {
4365             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4366                                        MachinePointerInfo(), false, false,
4367                                        false, 0);
4368             MemOpChains.push_back(Load.getValue(1));
4369             RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4370           }
4371         }
4372       } else {
4373         // Single-precision floating-point values are mapped to the
4374         // second (rightmost) word of the stack doubleword.
4375         if (Arg.getValueType() == MVT::f32 && !isLittleEndian) {
4376           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4377           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4378         }
4379
4380         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4381                          true, isTailCall, false, MemOpChains,
4382                          TailCallArguments, dl);
4383       }
4384       ArgOffset += 8;
4385       break;
4386     case MVT::v4f32:
4387     case MVT::v4i32:
4388     case MVT::v8i16:
4389     case MVT::v16i8:
4390     case MVT::v2f64:
4391     case MVT::v2i64:
4392       // For a varargs call, named arguments go into VRs or on the stack as
4393       // usual; unnamed arguments always go to the stack or the corresponding
4394       // GPRs when within range.  For now, we always put the value in both
4395       // locations (or even all three).
4396       if (isVarArg) {
4397         // We could elide this store in the case where the object fits
4398         // entirely in R registers.  Maybe later.
4399         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4400                                      MachinePointerInfo(), false, false, 0);
4401         MemOpChains.push_back(Store);
4402         if (VR_idx != NumVRs) {
4403           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4404                                      MachinePointerInfo(),
4405                                      false, false, false, 0);
4406           MemOpChains.push_back(Load.getValue(1));
4407
4408           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4409                            Arg.getSimpleValueType() == MVT::v2i64) ?
4410                           VSRH[VR_idx] : VR[VR_idx];
4411           ++VR_idx;
4412
4413           RegsToPass.push_back(std::make_pair(VReg, Load));
4414         }
4415         ArgOffset += 16;
4416         for (unsigned i=0; i<16; i+=PtrByteSize) {
4417           if (GPR_idx == NumGPRs)
4418             break;
4419           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4420                                   DAG.getConstant(i, PtrVT));
4421           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4422                                      false, false, false, 0);
4423           MemOpChains.push_back(Load.getValue(1));
4424           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4425         }
4426         break;
4427       }
4428
4429       // Non-varargs Altivec params go into VRs or on the stack.
4430       if (VR_idx != NumVRs) {
4431         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4432                          Arg.getSimpleValueType() == MVT::v2i64) ?
4433                         VSRH[VR_idx] : VR[VR_idx];
4434         ++VR_idx;
4435
4436         RegsToPass.push_back(std::make_pair(VReg, Arg));
4437       } else {
4438         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4439                          true, isTailCall, true, MemOpChains,
4440                          TailCallArguments, dl);
4441       }
4442       ArgOffset += 16;
4443       break;
4444     }
4445   }
4446
4447   assert(NumBytesActuallyUsed == ArgOffset);
4448   (void)NumBytesActuallyUsed;
4449
4450   if (!MemOpChains.empty())
4451     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4452
4453   // Check if this is an indirect call (MTCTR/BCTRL).
4454   // See PrepareCall() for more information about calls through function
4455   // pointers in the 64-bit SVR4 ABI.
4456   if (!isTailCall &&
4457       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4458       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4459     // Load r2 into a virtual register and store it to the TOC save area.
4460     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4461     // TOC save area offset.
4462     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4463     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4464     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4465     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4466                          false, false, 0);
4467     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4468     // This does not mean the MTCTR instruction must use R12; it's easier
4469     // to model this as an extra parameter, so do that.
4470     if (isELFv2ABI)
4471       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4472   }
4473
4474   // Build a sequence of copy-to-reg nodes chained together with token chain
4475   // and flag operands which copy the outgoing args into the appropriate regs.
4476   SDValue InFlag;
4477   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4478     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4479                              RegsToPass[i].second, InFlag);
4480     InFlag = Chain.getValue(1);
4481   }
4482
4483   if (isTailCall)
4484     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4485                     FPOp, true, TailCallArguments);
4486
4487   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4488                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4489                     Ins, InVals);
4490 }
4491
4492 SDValue
4493 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4494                                     CallingConv::ID CallConv, bool isVarArg,
4495                                     bool isTailCall,
4496                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4497                                     const SmallVectorImpl<SDValue> &OutVals,
4498                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4499                                     SDLoc dl, SelectionDAG &DAG,
4500                                     SmallVectorImpl<SDValue> &InVals) const {
4501
4502   unsigned NumOps = Outs.size();
4503
4504   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4505   bool isPPC64 = PtrVT == MVT::i64;
4506   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4507
4508   MachineFunction &MF = DAG.getMachineFunction();
4509
4510   // Mark this function as potentially containing a function that contains a
4511   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4512   // and restoring the callers stack pointer in this functions epilog. This is
4513   // done because by tail calling the called function might overwrite the value
4514   // in this function's (MF) stack pointer stack slot 0(SP).
4515   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4516       CallConv == CallingConv::Fast)
4517     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4518
4519   // Count how many bytes are to be pushed on the stack, including the linkage
4520   // area, and parameter passing area.  We start with 24/48 bytes, which is
4521   // prereserved space for [SP][CR][LR][3 x unused].
4522   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4523                                                           false);
4524   unsigned NumBytes = LinkageSize;
4525
4526   // Add up all the space actually used.
4527   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4528   // they all go in registers, but we must reserve stack space for them for
4529   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4530   // assigned stack space in order, with padding so Altivec parameters are
4531   // 16-byte aligned.
4532   unsigned nAltivecParamsAtEnd = 0;
4533   for (unsigned i = 0; i != NumOps; ++i) {
4534     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4535     EVT ArgVT = Outs[i].VT;
4536     // Varargs Altivec parameters are padded to a 16 byte boundary.
4537     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4538         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4539         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4540       if (!isVarArg && !isPPC64) {
4541         // Non-varargs Altivec parameters go after all the non-Altivec
4542         // parameters; handle those later so we know how much padding we need.
4543         nAltivecParamsAtEnd++;
4544         continue;
4545       }
4546       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4547       NumBytes = ((NumBytes+15)/16)*16;
4548     }
4549     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4550   }
4551
4552   // Allow for Altivec parameters at the end, if needed.
4553   if (nAltivecParamsAtEnd) {
4554     NumBytes = ((NumBytes+15)/16)*16;
4555     NumBytes += 16*nAltivecParamsAtEnd;
4556   }
4557
4558   // The prolog code of the callee may store up to 8 GPR argument registers to
4559   // the stack, allowing va_start to index over them in memory if its varargs.
4560   // Because we cannot tell if this is needed on the caller side, we have to
4561   // conservatively assume that it is needed.  As such, make sure we have at
4562   // least enough stack space for the caller to store the 8 GPRs.
4563   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4564
4565   // Tail call needs the stack to be aligned.
4566   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4567       CallConv == CallingConv::Fast)
4568     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4569
4570   // Calculate by how many bytes the stack has to be adjusted in case of tail
4571   // call optimization.
4572   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4573
4574   // To protect arguments on the stack from being clobbered in a tail call,
4575   // force all the loads to happen before doing any other lowering.
4576   if (isTailCall)
4577     Chain = DAG.getStackArgumentTokenFactor(Chain);
4578
4579   // Adjust the stack pointer for the new arguments...
4580   // These operations are automatically eliminated by the prolog/epilog pass
4581   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4582                                dl);
4583   SDValue CallSeqStart = Chain;
4584
4585   // Load the return address and frame pointer so it can be move somewhere else
4586   // later.
4587   SDValue LROp, FPOp;
4588   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4589                                        dl);
4590
4591   // Set up a copy of the stack pointer for use loading and storing any
4592   // arguments that may not fit in the registers available for argument
4593   // passing.
4594   SDValue StackPtr;
4595   if (isPPC64)
4596     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4597   else
4598     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4599
4600   // Figure out which arguments are going to go in registers, and which in
4601   // memory.  Also, if this is a vararg function, floating point operations
4602   // must be stored to our stack, and loaded into integer regs as well, if
4603   // any integer regs are available for argument passing.
4604   unsigned ArgOffset = LinkageSize;
4605   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4606
4607   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4608     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4609     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4610   };
4611   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4612     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4613     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4614   };
4615   static const MCPhysReg *FPR = GetFPR();
4616
4617   static const MCPhysReg VR[] = {
4618     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4619     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4620   };
4621   const unsigned NumGPRs = array_lengthof(GPR_32);
4622   const unsigned NumFPRs = 13;
4623   const unsigned NumVRs  = array_lengthof(VR);
4624
4625   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4626
4627   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4628   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4629
4630   SmallVector<SDValue, 8> MemOpChains;
4631   for (unsigned i = 0; i != NumOps; ++i) {
4632     SDValue Arg = OutVals[i];
4633     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4634
4635     // PtrOff will be used to store the current argument to the stack if a
4636     // register cannot be found for it.
4637     SDValue PtrOff;
4638
4639     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4640
4641     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4642
4643     // On PPC64, promote integers to 64-bit values.
4644     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4645       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4646       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4647       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4648     }
4649
4650     // FIXME memcpy is used way more than necessary.  Correctness first.
4651     // Note: "by value" is code for passing a structure by value, not
4652     // basic types.
4653     if (Flags.isByVal()) {
4654       unsigned Size = Flags.getByValSize();
4655       // Very small objects are passed right-justified.  Everything else is
4656       // passed left-justified.
4657       if (Size==1 || Size==2) {
4658         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4659         if (GPR_idx != NumGPRs) {
4660           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4661                                         MachinePointerInfo(), VT,
4662                                         false, false, 0);
4663           MemOpChains.push_back(Load.getValue(1));
4664           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4665
4666           ArgOffset += PtrByteSize;
4667         } else {
4668           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4669                                           PtrOff.getValueType());
4670           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4671           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4672                                                             CallSeqStart,
4673                                                             Flags, DAG, dl);
4674           ArgOffset += PtrByteSize;
4675         }
4676         continue;
4677       }
4678       // Copy entire object into memory.  There are cases where gcc-generated
4679       // code assumes it is there, even if it could be put entirely into
4680       // registers.  (This is not what the doc says.)
4681       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4682                                                         CallSeqStart,
4683                                                         Flags, DAG, dl);
4684
4685       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4686       // copy the pieces of the object that fit into registers from the
4687       // parameter save area.
4688       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4689         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4690         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4691         if (GPR_idx != NumGPRs) {
4692           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4693                                      MachinePointerInfo(),
4694                                      false, false, false, 0);
4695           MemOpChains.push_back(Load.getValue(1));
4696           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4697           ArgOffset += PtrByteSize;
4698         } else {
4699           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4700           break;
4701         }
4702       }
4703       continue;
4704     }
4705
4706     switch (Arg.getSimpleValueType().SimpleTy) {
4707     default: llvm_unreachable("Unexpected ValueType for argument!");
4708     case MVT::i1:
4709     case MVT::i32:
4710     case MVT::i64:
4711       if (GPR_idx != NumGPRs) {
4712         if (Arg.getValueType() == MVT::i1)
4713           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4714
4715         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4716       } else {
4717         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4718                          isPPC64, isTailCall, false, MemOpChains,
4719                          TailCallArguments, dl);
4720       }
4721       ArgOffset += PtrByteSize;
4722       break;
4723     case MVT::f32:
4724     case MVT::f64:
4725       if (FPR_idx != NumFPRs) {
4726         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4727
4728         if (isVarArg) {
4729           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4730                                        MachinePointerInfo(), false, false, 0);
4731           MemOpChains.push_back(Store);
4732
4733           // Float varargs are always shadowed in available integer registers
4734           if (GPR_idx != NumGPRs) {
4735             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4736                                        MachinePointerInfo(), false, false,
4737                                        false, 0);
4738             MemOpChains.push_back(Load.getValue(1));
4739             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4740           }
4741           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4742             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4743             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4744             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4745                                        MachinePointerInfo(),
4746                                        false, false, false, 0);
4747             MemOpChains.push_back(Load.getValue(1));
4748             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4749           }
4750         } else {
4751           // If we have any FPRs remaining, we may also have GPRs remaining.
4752           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4753           // GPRs.
4754           if (GPR_idx != NumGPRs)
4755             ++GPR_idx;
4756           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4757               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4758             ++GPR_idx;
4759         }
4760       } else
4761         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4762                          isPPC64, isTailCall, false, MemOpChains,
4763                          TailCallArguments, dl);
4764       if (isPPC64)
4765         ArgOffset += 8;
4766       else
4767         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4768       break;
4769     case MVT::v4f32:
4770     case MVT::v4i32:
4771     case MVT::v8i16:
4772     case MVT::v16i8:
4773       if (isVarArg) {
4774         // These go aligned on the stack, or in the corresponding R registers
4775         // when within range.  The Darwin PPC ABI doc claims they also go in
4776         // V registers; in fact gcc does this only for arguments that are
4777         // prototyped, not for those that match the ...  We do it for all
4778         // arguments, seems to work.
4779         while (ArgOffset % 16 !=0) {
4780           ArgOffset += PtrByteSize;
4781           if (GPR_idx != NumGPRs)
4782             GPR_idx++;
4783         }
4784         // We could elide this store in the case where the object fits
4785         // entirely in R registers.  Maybe later.
4786         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4787                             DAG.getConstant(ArgOffset, PtrVT));
4788         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4789                                      MachinePointerInfo(), false, false, 0);
4790         MemOpChains.push_back(Store);
4791         if (VR_idx != NumVRs) {
4792           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4793                                      MachinePointerInfo(),
4794                                      false, false, false, 0);
4795           MemOpChains.push_back(Load.getValue(1));
4796           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4797         }
4798         ArgOffset += 16;
4799         for (unsigned i=0; i<16; i+=PtrByteSize) {
4800           if (GPR_idx == NumGPRs)
4801             break;
4802           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4803                                   DAG.getConstant(i, PtrVT));
4804           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4805                                      false, false, false, 0);
4806           MemOpChains.push_back(Load.getValue(1));
4807           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4808         }
4809         break;
4810       }
4811
4812       // Non-varargs Altivec params generally go in registers, but have
4813       // stack space allocated at the end.
4814       if (VR_idx != NumVRs) {
4815         // Doesn't have GPR space allocated.
4816         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4817       } else if (nAltivecParamsAtEnd==0) {
4818         // We are emitting Altivec params in order.
4819         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4820                          isPPC64, isTailCall, true, MemOpChains,
4821                          TailCallArguments, dl);
4822         ArgOffset += 16;
4823       }
4824       break;
4825     }
4826   }
4827   // If all Altivec parameters fit in registers, as they usually do,
4828   // they get stack space following the non-Altivec parameters.  We
4829   // don't track this here because nobody below needs it.
4830   // If there are more Altivec parameters than fit in registers emit
4831   // the stores here.
4832   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4833     unsigned j = 0;
4834     // Offset is aligned; skip 1st 12 params which go in V registers.
4835     ArgOffset = ((ArgOffset+15)/16)*16;
4836     ArgOffset += 12*16;
4837     for (unsigned i = 0; i != NumOps; ++i) {
4838       SDValue Arg = OutVals[i];
4839       EVT ArgType = Outs[i].VT;
4840       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4841           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4842         if (++j > NumVRs) {
4843           SDValue PtrOff;
4844           // We are emitting Altivec params in order.
4845           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4846                            isPPC64, isTailCall, true, MemOpChains,
4847                            TailCallArguments, dl);
4848           ArgOffset += 16;
4849         }
4850       }
4851     }
4852   }
4853
4854   if (!MemOpChains.empty())
4855     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4856
4857   // On Darwin, R12 must contain the address of an indirect callee.  This does
4858   // not mean the MTCTR instruction must use R12; it's easier to model this as
4859   // an extra parameter, so do that.
4860   if (!isTailCall &&
4861       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4862       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4863       !isBLACompatibleAddress(Callee, DAG))
4864     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4865                                                    PPC::R12), Callee));
4866
4867   // Build a sequence of copy-to-reg nodes chained together with token chain
4868   // and flag operands which copy the outgoing args into the appropriate regs.
4869   SDValue InFlag;
4870   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4871     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4872                              RegsToPass[i].second, InFlag);
4873     InFlag = Chain.getValue(1);
4874   }
4875
4876   if (isTailCall)
4877     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4878                     FPOp, true, TailCallArguments);
4879
4880   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4881                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4882                     Ins, InVals);
4883 }
4884
4885 bool
4886 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4887                                   MachineFunction &MF, bool isVarArg,
4888                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
4889                                   LLVMContext &Context) const {
4890   SmallVector<CCValAssign, 16> RVLocs;
4891   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4892                  RVLocs, Context);
4893   return CCInfo.CheckReturn(Outs, RetCC_PPC);
4894 }
4895
4896 SDValue
4897 PPCTargetLowering::LowerReturn(SDValue Chain,
4898                                CallingConv::ID CallConv, bool isVarArg,
4899                                const SmallVectorImpl<ISD::OutputArg> &Outs,
4900                                const SmallVectorImpl<SDValue> &OutVals,
4901                                SDLoc dl, SelectionDAG &DAG) const {
4902
4903   SmallVector<CCValAssign, 16> RVLocs;
4904   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4905                  getTargetMachine(), RVLocs, *DAG.getContext());
4906   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4907
4908   SDValue Flag;
4909   SmallVector<SDValue, 4> RetOps(1, Chain);
4910
4911   // Copy the result values into the output registers.
4912   for (unsigned i = 0; i != RVLocs.size(); ++i) {
4913     CCValAssign &VA = RVLocs[i];
4914     assert(VA.isRegLoc() && "Can only return in registers!");
4915
4916     SDValue Arg = OutVals[i];
4917
4918     switch (VA.getLocInfo()) {
4919     default: llvm_unreachable("Unknown loc info!");
4920     case CCValAssign::Full: break;
4921     case CCValAssign::AExt:
4922       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4923       break;
4924     case CCValAssign::ZExt:
4925       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4926       break;
4927     case CCValAssign::SExt:
4928       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4929       break;
4930     }
4931
4932     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4933     Flag = Chain.getValue(1);
4934     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4935   }
4936
4937   RetOps[0] = Chain;  // Update chain.
4938
4939   // Add the flag if we have it.
4940   if (Flag.getNode())
4941     RetOps.push_back(Flag);
4942
4943   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
4944 }
4945
4946 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4947                                    const PPCSubtarget &Subtarget) const {
4948   // When we pop the dynamic allocation we need to restore the SP link.
4949   SDLoc dl(Op);
4950
4951   // Get the corect type for pointers.
4952   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4953
4954   // Construct the stack pointer operand.
4955   bool isPPC64 = Subtarget.isPPC64();
4956   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4957   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4958
4959   // Get the operands for the STACKRESTORE.
4960   SDValue Chain = Op.getOperand(0);
4961   SDValue SaveSP = Op.getOperand(1);
4962
4963   // Load the old link SP.
4964   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4965                                    MachinePointerInfo(),
4966                                    false, false, false, 0);
4967
4968   // Restore the stack pointer.
4969   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4970
4971   // Store the old link SP.
4972   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4973                       false, false, 0);
4974 }
4975
4976
4977
4978 SDValue
4979 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4980   MachineFunction &MF = DAG.getMachineFunction();
4981   bool isPPC64 = Subtarget.isPPC64();
4982   bool isDarwinABI = Subtarget.isDarwinABI();
4983   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4984
4985   // Get current frame pointer save index.  The users of this index will be
4986   // primarily DYNALLOC instructions.
4987   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4988   int RASI = FI->getReturnAddrSaveIndex();
4989
4990   // If the frame pointer save index hasn't been defined yet.
4991   if (!RASI) {
4992     // Find out what the fix offset of the frame pointer save area.
4993     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4994     // Allocate the frame index for frame pointer save area.
4995     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4996     // Save the result.
4997     FI->setReturnAddrSaveIndex(RASI);
4998   }
4999   return DAG.getFrameIndex(RASI, PtrVT);
5000 }
5001
5002 SDValue
5003 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5004   MachineFunction &MF = DAG.getMachineFunction();
5005   bool isPPC64 = Subtarget.isPPC64();
5006   bool isDarwinABI = Subtarget.isDarwinABI();
5007   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5008
5009   // Get current frame pointer save index.  The users of this index will be
5010   // primarily DYNALLOC instructions.
5011   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5012   int FPSI = FI->getFramePointerSaveIndex();
5013
5014   // If the frame pointer save index hasn't been defined yet.
5015   if (!FPSI) {
5016     // Find out what the fix offset of the frame pointer save area.
5017     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5018                                                            isDarwinABI);
5019
5020     // Allocate the frame index for frame pointer save area.
5021     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5022     // Save the result.
5023     FI->setFramePointerSaveIndex(FPSI);
5024   }
5025   return DAG.getFrameIndex(FPSI, PtrVT);
5026 }
5027
5028 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5029                                          SelectionDAG &DAG,
5030                                          const PPCSubtarget &Subtarget) const {
5031   // Get the inputs.
5032   SDValue Chain = Op.getOperand(0);
5033   SDValue Size  = Op.getOperand(1);
5034   SDLoc dl(Op);
5035
5036   // Get the corect type for pointers.
5037   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5038   // Negate the size.
5039   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5040                                   DAG.getConstant(0, PtrVT), Size);
5041   // Construct a node for the frame pointer save index.
5042   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5043   // Build a DYNALLOC node.
5044   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5045   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5046   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5047 }
5048
5049 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5050                                                SelectionDAG &DAG) const {
5051   SDLoc DL(Op);
5052   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5053                      DAG.getVTList(MVT::i32, MVT::Other),
5054                      Op.getOperand(0), Op.getOperand(1));
5055 }
5056
5057 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5058                                                 SelectionDAG &DAG) const {
5059   SDLoc DL(Op);
5060   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5061                      Op.getOperand(0), Op.getOperand(1));
5062 }
5063
5064 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5065   assert(Op.getValueType() == MVT::i1 &&
5066          "Custom lowering only for i1 loads");
5067
5068   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5069
5070   SDLoc dl(Op);
5071   LoadSDNode *LD = cast<LoadSDNode>(Op);
5072
5073   SDValue Chain = LD->getChain();
5074   SDValue BasePtr = LD->getBasePtr();
5075   MachineMemOperand *MMO = LD->getMemOperand();
5076
5077   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5078                                  BasePtr, MVT::i8, MMO);
5079   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5080
5081   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5082   return DAG.getMergeValues(Ops, dl);
5083 }
5084
5085 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5086   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5087          "Custom lowering only for i1 stores");
5088
5089   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5090
5091   SDLoc dl(Op);
5092   StoreSDNode *ST = cast<StoreSDNode>(Op);
5093
5094   SDValue Chain = ST->getChain();
5095   SDValue BasePtr = ST->getBasePtr();
5096   SDValue Value = ST->getValue();
5097   MachineMemOperand *MMO = ST->getMemOperand();
5098
5099   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5100   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5101 }
5102
5103 // FIXME: Remove this once the ANDI glue bug is fixed:
5104 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5105   assert(Op.getValueType() == MVT::i1 &&
5106          "Custom lowering only for i1 results");
5107
5108   SDLoc DL(Op);
5109   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5110                      Op.getOperand(0));
5111 }
5112
5113 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5114 /// possible.
5115 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5116   // Not FP? Not a fsel.
5117   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5118       !Op.getOperand(2).getValueType().isFloatingPoint())
5119     return Op;
5120
5121   // We might be able to do better than this under some circumstances, but in
5122   // general, fsel-based lowering of select is a finite-math-only optimization.
5123   // For more information, see section F.3 of the 2.06 ISA specification.
5124   if (!DAG.getTarget().Options.NoInfsFPMath ||
5125       !DAG.getTarget().Options.NoNaNsFPMath)
5126     return Op;
5127
5128   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5129
5130   EVT ResVT = Op.getValueType();
5131   EVT CmpVT = Op.getOperand(0).getValueType();
5132   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5133   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5134   SDLoc dl(Op);
5135
5136   // If the RHS of the comparison is a 0.0, we don't need to do the
5137   // subtraction at all.
5138   SDValue Sel1;
5139   if (isFloatingPointZero(RHS))
5140     switch (CC) {
5141     default: break;       // SETUO etc aren't handled by fsel.
5142     case ISD::SETNE:
5143       std::swap(TV, FV);
5144     case ISD::SETEQ:
5145       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5146         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5147       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5148       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5149         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5150       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5151                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5152     case ISD::SETULT:
5153     case ISD::SETLT:
5154       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5155     case ISD::SETOGE:
5156     case ISD::SETGE:
5157       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5158         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5159       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5160     case ISD::SETUGT:
5161     case ISD::SETGT:
5162       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5163     case ISD::SETOLE:
5164     case ISD::SETLE:
5165       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5166         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5167       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5168                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5169     }
5170
5171   SDValue Cmp;
5172   switch (CC) {
5173   default: break;       // SETUO etc aren't handled by fsel.
5174   case ISD::SETNE:
5175     std::swap(TV, FV);
5176   case ISD::SETEQ:
5177     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5178     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5179       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5180     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5181     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5182       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5183     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5184                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5185   case ISD::SETULT:
5186   case ISD::SETLT:
5187     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5188     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5189       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5190     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5191   case ISD::SETOGE:
5192   case ISD::SETGE:
5193     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5194     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5195       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5196     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5197   case ISD::SETUGT:
5198   case ISD::SETGT:
5199     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5200     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5201       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5202     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5203   case ISD::SETOLE:
5204   case ISD::SETLE:
5205     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5206     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5207       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5208     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5209   }
5210   return Op;
5211 }
5212
5213 // FIXME: Split this code up when LegalizeDAGTypes lands.
5214 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5215                                            SDLoc dl) const {
5216   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5217   SDValue Src = Op.getOperand(0);
5218   if (Src.getValueType() == MVT::f32)
5219     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5220
5221   SDValue Tmp;
5222   switch (Op.getSimpleValueType().SimpleTy) {
5223   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5224   case MVT::i32:
5225     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5226                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5227                                                    PPCISD::FCTIDZ),
5228                       dl, MVT::f64, Src);
5229     break;
5230   case MVT::i64:
5231     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5232            "i64 FP_TO_UINT is supported only with FPCVT");
5233     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5234                                                         PPCISD::FCTIDUZ,
5235                       dl, MVT::f64, Src);
5236     break;
5237   }
5238
5239   // Convert the FP value to an int value through memory.
5240   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5241     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5242   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5243   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5244   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5245
5246   // Emit a store to the stack slot.
5247   SDValue Chain;
5248   if (i32Stack) {
5249     MachineFunction &MF = DAG.getMachineFunction();
5250     MachineMemOperand *MMO =
5251       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5252     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5253     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5254               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5255   } else
5256     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5257                          MPI, false, false, 0);
5258
5259   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5260   // add in a bias.
5261   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5262     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5263                         DAG.getConstant(4, FIPtr.getValueType()));
5264     MPI = MachinePointerInfo();
5265   }
5266
5267   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5268                      false, false, false, 0);
5269 }
5270
5271 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5272                                            SelectionDAG &DAG) const {
5273   SDLoc dl(Op);
5274   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5275   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5276     return SDValue();
5277
5278   if (Op.getOperand(0).getValueType() == MVT::i1)
5279     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5280                        DAG.getConstantFP(1.0, Op.getValueType()),
5281                        DAG.getConstantFP(0.0, Op.getValueType()));
5282
5283   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5284          "UINT_TO_FP is supported only with FPCVT");
5285
5286   // If we have FCFIDS, then use it when converting to single-precision.
5287   // Otherwise, convert to double-precision and then round.
5288   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5289                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5290                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5291                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5292                     PPCISD::FCFIDU : PPCISD::FCFID);
5293   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5294                    MVT::f32 : MVT::f64;
5295
5296   if (Op.getOperand(0).getValueType() == MVT::i64) {
5297     SDValue SINT = Op.getOperand(0);
5298     // When converting to single-precision, we actually need to convert
5299     // to double-precision first and then round to single-precision.
5300     // To avoid double-rounding effects during that operation, we have
5301     // to prepare the input operand.  Bits that might be truncated when
5302     // converting to double-precision are replaced by a bit that won't
5303     // be lost at this stage, but is below the single-precision rounding
5304     // position.
5305     //
5306     // However, if -enable-unsafe-fp-math is in effect, accept double
5307     // rounding to avoid the extra overhead.
5308     if (Op.getValueType() == MVT::f32 &&
5309         !Subtarget.hasFPCVT() &&
5310         !DAG.getTarget().Options.UnsafeFPMath) {
5311
5312       // Twiddle input to make sure the low 11 bits are zero.  (If this
5313       // is the case, we are guaranteed the value will fit into the 53 bit
5314       // mantissa of an IEEE double-precision value without rounding.)
5315       // If any of those low 11 bits were not zero originally, make sure
5316       // bit 12 (value 2048) is set instead, so that the final rounding
5317       // to single-precision gets the correct result.
5318       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5319                                   SINT, DAG.getConstant(2047, MVT::i64));
5320       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5321                           Round, DAG.getConstant(2047, MVT::i64));
5322       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5323       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5324                           Round, DAG.getConstant(-2048, MVT::i64));
5325
5326       // However, we cannot use that value unconditionally: if the magnitude
5327       // of the input value is small, the bit-twiddling we did above might
5328       // end up visibly changing the output.  Fortunately, in that case, we
5329       // don't need to twiddle bits since the original input will convert
5330       // exactly to double-precision floating-point already.  Therefore,
5331       // construct a conditional to use the original value if the top 11
5332       // bits are all sign-bit copies, and use the rounded value computed
5333       // above otherwise.
5334       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5335                                  SINT, DAG.getConstant(53, MVT::i32));
5336       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5337                          Cond, DAG.getConstant(1, MVT::i64));
5338       Cond = DAG.getSetCC(dl, MVT::i32,
5339                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5340
5341       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5342     }
5343
5344     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5345     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5346
5347     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5348       FP = DAG.getNode(ISD::FP_ROUND, dl,
5349                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5350     return FP;
5351   }
5352
5353   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5354          "Unhandled INT_TO_FP type in custom expander!");
5355   // Since we only generate this in 64-bit mode, we can take advantage of
5356   // 64-bit registers.  In particular, sign extend the input value into the
5357   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5358   // then lfd it and fcfid it.
5359   MachineFunction &MF = DAG.getMachineFunction();
5360   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5361   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5362
5363   SDValue Ld;
5364   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5365     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5366     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5367
5368     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5369                                  MachinePointerInfo::getFixedStack(FrameIdx),
5370                                  false, false, 0);
5371
5372     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5373            "Expected an i32 store");
5374     MachineMemOperand *MMO =
5375       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5376                               MachineMemOperand::MOLoad, 4, 4);
5377     SDValue Ops[] = { Store, FIdx };
5378     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5379                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5380                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5381                                  Ops, MVT::i32, MMO);
5382   } else {
5383     assert(Subtarget.isPPC64() &&
5384            "i32->FP without LFIWAX supported only on PPC64");
5385
5386     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5387     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5388
5389     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5390                                 Op.getOperand(0));
5391
5392     // STD the extended value into the stack slot.
5393     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5394                                  MachinePointerInfo::getFixedStack(FrameIdx),
5395                                  false, false, 0);
5396
5397     // Load the value as a double.
5398     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5399                      MachinePointerInfo::getFixedStack(FrameIdx),
5400                      false, false, false, 0);
5401   }
5402
5403   // FCFID it and return it.
5404   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5405   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5406     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5407   return FP;
5408 }
5409
5410 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5411                                             SelectionDAG &DAG) const {
5412   SDLoc dl(Op);
5413   /*
5414    The rounding mode is in bits 30:31 of FPSR, and has the following
5415    settings:
5416      00 Round to nearest
5417      01 Round to 0
5418      10 Round to +inf
5419      11 Round to -inf
5420
5421   FLT_ROUNDS, on the other hand, expects the following:
5422     -1 Undefined
5423      0 Round to 0
5424      1 Round to nearest
5425      2 Round to +inf
5426      3 Round to -inf
5427
5428   To perform the conversion, we do:
5429     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5430   */
5431
5432   MachineFunction &MF = DAG.getMachineFunction();
5433   EVT VT = Op.getValueType();
5434   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5435
5436   // Save FP Control Word to register
5437   EVT NodeTys[] = {
5438     MVT::f64,    // return register
5439     MVT::Glue    // unused in this context
5440   };
5441   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5442
5443   // Save FP register to stack slot
5444   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5445   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5446   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5447                                StackSlot, MachinePointerInfo(), false, false,0);
5448
5449   // Load FP Control Word from low 32 bits of stack slot.
5450   SDValue Four = DAG.getConstant(4, PtrVT);
5451   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5452   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5453                             false, false, false, 0);
5454
5455   // Transform as necessary
5456   SDValue CWD1 =
5457     DAG.getNode(ISD::AND, dl, MVT::i32,
5458                 CWD, DAG.getConstant(3, MVT::i32));
5459   SDValue CWD2 =
5460     DAG.getNode(ISD::SRL, dl, MVT::i32,
5461                 DAG.getNode(ISD::AND, dl, MVT::i32,
5462                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5463                                         CWD, DAG.getConstant(3, MVT::i32)),
5464                             DAG.getConstant(3, MVT::i32)),
5465                 DAG.getConstant(1, MVT::i32));
5466
5467   SDValue RetVal =
5468     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5469
5470   return DAG.getNode((VT.getSizeInBits() < 16 ?
5471                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5472 }
5473
5474 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5475   EVT VT = Op.getValueType();
5476   unsigned BitWidth = VT.getSizeInBits();
5477   SDLoc dl(Op);
5478   assert(Op.getNumOperands() == 3 &&
5479          VT == Op.getOperand(1).getValueType() &&
5480          "Unexpected SHL!");
5481
5482   // Expand into a bunch of logical ops.  Note that these ops
5483   // depend on the PPC behavior for oversized shift amounts.
5484   SDValue Lo = Op.getOperand(0);
5485   SDValue Hi = Op.getOperand(1);
5486   SDValue Amt = Op.getOperand(2);
5487   EVT AmtVT = Amt.getValueType();
5488
5489   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5490                              DAG.getConstant(BitWidth, AmtVT), Amt);
5491   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5492   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5493   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5494   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5495                              DAG.getConstant(-BitWidth, AmtVT));
5496   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5497   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5498   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5499   SDValue OutOps[] = { OutLo, OutHi };
5500   return DAG.getMergeValues(OutOps, dl);
5501 }
5502
5503 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5504   EVT VT = Op.getValueType();
5505   SDLoc dl(Op);
5506   unsigned BitWidth = VT.getSizeInBits();
5507   assert(Op.getNumOperands() == 3 &&
5508          VT == Op.getOperand(1).getValueType() &&
5509          "Unexpected SRL!");
5510
5511   // Expand into a bunch of logical ops.  Note that these ops
5512   // depend on the PPC behavior for oversized shift amounts.
5513   SDValue Lo = Op.getOperand(0);
5514   SDValue Hi = Op.getOperand(1);
5515   SDValue Amt = Op.getOperand(2);
5516   EVT AmtVT = Amt.getValueType();
5517
5518   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5519                              DAG.getConstant(BitWidth, AmtVT), Amt);
5520   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5521   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5522   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5523   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5524                              DAG.getConstant(-BitWidth, AmtVT));
5525   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5526   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5527   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5528   SDValue OutOps[] = { OutLo, OutHi };
5529   return DAG.getMergeValues(OutOps, dl);
5530 }
5531
5532 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5533   SDLoc dl(Op);
5534   EVT VT = Op.getValueType();
5535   unsigned BitWidth = VT.getSizeInBits();
5536   assert(Op.getNumOperands() == 3 &&
5537          VT == Op.getOperand(1).getValueType() &&
5538          "Unexpected SRA!");
5539
5540   // Expand into a bunch of logical ops, followed by a select_cc.
5541   SDValue Lo = Op.getOperand(0);
5542   SDValue Hi = Op.getOperand(1);
5543   SDValue Amt = Op.getOperand(2);
5544   EVT AmtVT = Amt.getValueType();
5545
5546   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5547                              DAG.getConstant(BitWidth, AmtVT), Amt);
5548   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5549   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5550   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5551   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5552                              DAG.getConstant(-BitWidth, AmtVT));
5553   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5554   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5555   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5556                                   Tmp4, Tmp6, ISD::SETLE);
5557   SDValue OutOps[] = { OutLo, OutHi };
5558   return DAG.getMergeValues(OutOps, dl);
5559 }
5560
5561 //===----------------------------------------------------------------------===//
5562 // Vector related lowering.
5563 //
5564
5565 /// BuildSplatI - Build a canonical splati of Val with an element size of
5566 /// SplatSize.  Cast the result to VT.
5567 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5568                              SelectionDAG &DAG, SDLoc dl) {
5569   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5570
5571   static const EVT VTys[] = { // canonical VT to use for each size.
5572     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5573   };
5574
5575   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5576
5577   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5578   if (Val == -1)
5579     SplatSize = 1;
5580
5581   EVT CanonicalVT = VTys[SplatSize-1];
5582
5583   // Build a canonical splat for this value.
5584   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5585   SmallVector<SDValue, 8> Ops;
5586   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5587   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5588   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5589 }
5590
5591 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5592 /// specified intrinsic ID.
5593 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5594                                 SelectionDAG &DAG, SDLoc dl,
5595                                 EVT DestVT = MVT::Other) {
5596   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5597   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5598                      DAG.getConstant(IID, MVT::i32), Op);
5599 }
5600
5601 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5602 /// specified intrinsic ID.
5603 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5604                                 SelectionDAG &DAG, SDLoc dl,
5605                                 EVT DestVT = MVT::Other) {
5606   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5607   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5608                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5609 }
5610
5611 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5612 /// specified intrinsic ID.
5613 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5614                                 SDValue Op2, SelectionDAG &DAG,
5615                                 SDLoc dl, EVT DestVT = MVT::Other) {
5616   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5617   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5618                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5619 }
5620
5621
5622 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5623 /// amount.  The result has the specified value type.
5624 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5625                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5626   // Force LHS/RHS to be the right type.
5627   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5628   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5629
5630   int Ops[16];
5631   for (unsigned i = 0; i != 16; ++i)
5632     Ops[i] = i + Amt;
5633   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5634   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5635 }
5636
5637 // If this is a case we can't handle, return null and let the default
5638 // expansion code take care of it.  If we CAN select this case, and if it
5639 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5640 // this case more efficiently than a constant pool load, lower it to the
5641 // sequence of ops that should be used.
5642 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5643                                              SelectionDAG &DAG) const {
5644   SDLoc dl(Op);
5645   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5646   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5647
5648   // Check if this is a splat of a constant value.
5649   APInt APSplatBits, APSplatUndef;
5650   unsigned SplatBitSize;
5651   bool HasAnyUndefs;
5652   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5653                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5654     return SDValue();
5655
5656   unsigned SplatBits = APSplatBits.getZExtValue();
5657   unsigned SplatUndef = APSplatUndef.getZExtValue();
5658   unsigned SplatSize = SplatBitSize / 8;
5659
5660   // First, handle single instruction cases.
5661
5662   // All zeros?
5663   if (SplatBits == 0) {
5664     // Canonicalize all zero vectors to be v4i32.
5665     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5666       SDValue Z = DAG.getConstant(0, MVT::i32);
5667       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5668       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5669     }
5670     return Op;
5671   }
5672
5673   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5674   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5675                     (32-SplatBitSize));
5676   if (SextVal >= -16 && SextVal <= 15)
5677     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5678
5679
5680   // Two instruction sequences.
5681
5682   // If this value is in the range [-32,30] and is even, use:
5683   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5684   // If this value is in the range [17,31] and is odd, use:
5685   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5686   // If this value is in the range [-31,-17] and is odd, use:
5687   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5688   // Note the last two are three-instruction sequences.
5689   if (SextVal >= -32 && SextVal <= 31) {
5690     // To avoid having these optimizations undone by constant folding,
5691     // we convert to a pseudo that will be expanded later into one of
5692     // the above forms.
5693     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5694     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5695               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5696     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5697     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5698     if (VT == Op.getValueType())
5699       return RetVal;
5700     else
5701       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5702   }
5703
5704   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5705   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5706   // for fneg/fabs.
5707   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5708     // Make -1 and vspltisw -1:
5709     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5710
5711     // Make the VSLW intrinsic, computing 0x8000_0000.
5712     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5713                                    OnesV, DAG, dl);
5714
5715     // xor by OnesV to invert it.
5716     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5717     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5718   }
5719
5720   // The remaining cases assume either big endian element order or
5721   // a splat-size that equates to the element size of the vector
5722   // to be built.  An example that doesn't work for little endian is
5723   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5724   // and a vector element size of 16 bits.  The code below will
5725   // produce the vector in big endian element order, which for little
5726   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5727
5728   // For now, just avoid these optimizations in that case.
5729   // FIXME: Develop correct optimizations for LE with mismatched
5730   // splat and element sizes.
5731
5732   if (Subtarget.isLittleEndian() &&
5733       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5734     return SDValue();
5735
5736   // Check to see if this is a wide variety of vsplti*, binop self cases.
5737   static const signed char SplatCsts[] = {
5738     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5739     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5740   };
5741
5742   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5743     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5744     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5745     int i = SplatCsts[idx];
5746
5747     // Figure out what shift amount will be used by altivec if shifted by i in
5748     // this splat size.
5749     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5750
5751     // vsplti + shl self.
5752     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5753       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5754       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5755         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5756         Intrinsic::ppc_altivec_vslw
5757       };
5758       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5759       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5760     }
5761
5762     // vsplti + srl self.
5763     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5764       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5765       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5766         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5767         Intrinsic::ppc_altivec_vsrw
5768       };
5769       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5770       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5771     }
5772
5773     // vsplti + sra self.
5774     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5775       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5776       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5777         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5778         Intrinsic::ppc_altivec_vsraw
5779       };
5780       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5781       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5782     }
5783
5784     // vsplti + rol self.
5785     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5786                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5787       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5788       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5789         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5790         Intrinsic::ppc_altivec_vrlw
5791       };
5792       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5793       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5794     }
5795
5796     // t = vsplti c, result = vsldoi t, t, 1
5797     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5798       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5799       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5800     }
5801     // t = vsplti c, result = vsldoi t, t, 2
5802     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5803       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5804       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5805     }
5806     // t = vsplti c, result = vsldoi t, t, 3
5807     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5808       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5809       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5810     }
5811   }
5812
5813   return SDValue();
5814 }
5815
5816 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5817 /// the specified operations to build the shuffle.
5818 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5819                                       SDValue RHS, SelectionDAG &DAG,
5820                                       SDLoc dl) {
5821   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5822   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5823   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5824
5825   enum {
5826     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5827     OP_VMRGHW,
5828     OP_VMRGLW,
5829     OP_VSPLTISW0,
5830     OP_VSPLTISW1,
5831     OP_VSPLTISW2,
5832     OP_VSPLTISW3,
5833     OP_VSLDOI4,
5834     OP_VSLDOI8,
5835     OP_VSLDOI12
5836   };
5837
5838   if (OpNum == OP_COPY) {
5839     if (LHSID == (1*9+2)*9+3) return LHS;
5840     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5841     return RHS;
5842   }
5843
5844   SDValue OpLHS, OpRHS;
5845   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5846   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5847
5848   int ShufIdxs[16];
5849   switch (OpNum) {
5850   default: llvm_unreachable("Unknown i32 permute!");
5851   case OP_VMRGHW:
5852     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5853     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5854     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5855     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5856     break;
5857   case OP_VMRGLW:
5858     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5859     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5860     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5861     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5862     break;
5863   case OP_VSPLTISW0:
5864     for (unsigned i = 0; i != 16; ++i)
5865       ShufIdxs[i] = (i&3)+0;
5866     break;
5867   case OP_VSPLTISW1:
5868     for (unsigned i = 0; i != 16; ++i)
5869       ShufIdxs[i] = (i&3)+4;
5870     break;
5871   case OP_VSPLTISW2:
5872     for (unsigned i = 0; i != 16; ++i)
5873       ShufIdxs[i] = (i&3)+8;
5874     break;
5875   case OP_VSPLTISW3:
5876     for (unsigned i = 0; i != 16; ++i)
5877       ShufIdxs[i] = (i&3)+12;
5878     break;
5879   case OP_VSLDOI4:
5880     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5881   case OP_VSLDOI8:
5882     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5883   case OP_VSLDOI12:
5884     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5885   }
5886   EVT VT = OpLHS.getValueType();
5887   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5888   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5889   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5890   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5891 }
5892
5893 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
5894 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
5895 /// return the code it can be lowered into.  Worst case, it can always be
5896 /// lowered into a vperm.
5897 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5898                                                SelectionDAG &DAG) const {
5899   SDLoc dl(Op);
5900   SDValue V1 = Op.getOperand(0);
5901   SDValue V2 = Op.getOperand(1);
5902   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5903   EVT VT = Op.getValueType();
5904   bool isLittleEndian = Subtarget.isLittleEndian();
5905
5906   // Cases that are handled by instructions that take permute immediates
5907   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5908   // selected by the instruction selector.
5909   if (V2.getOpcode() == ISD::UNDEF) {
5910     if (PPC::isSplatShuffleMask(SVOp, 1) ||
5911         PPC::isSplatShuffleMask(SVOp, 2) ||
5912         PPC::isSplatShuffleMask(SVOp, 4) ||
5913         PPC::isVPKUWUMShuffleMask(SVOp, true, DAG) ||
5914         PPC::isVPKUHUMShuffleMask(SVOp, true, DAG) ||
5915         PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
5916         PPC::isVMRGLShuffleMask(SVOp, 1, true, DAG) ||
5917         PPC::isVMRGLShuffleMask(SVOp, 2, true, DAG) ||
5918         PPC::isVMRGLShuffleMask(SVOp, 4, true, DAG) ||
5919         PPC::isVMRGHShuffleMask(SVOp, 1, true, DAG) ||
5920         PPC::isVMRGHShuffleMask(SVOp, 2, true, DAG) ||
5921         PPC::isVMRGHShuffleMask(SVOp, 4, true, DAG)) {
5922       return Op;
5923     }
5924   }
5925
5926   // Altivec has a variety of "shuffle immediates" that take two vector inputs
5927   // and produce a fixed permutation.  If any of these match, do not lower to
5928   // VPERM.
5929   if (PPC::isVPKUWUMShuffleMask(SVOp, false, DAG) ||
5930       PPC::isVPKUHUMShuffleMask(SVOp, false, DAG) ||
5931       PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
5932       PPC::isVMRGLShuffleMask(SVOp, 1, false, DAG) ||
5933       PPC::isVMRGLShuffleMask(SVOp, 2, false, DAG) ||
5934       PPC::isVMRGLShuffleMask(SVOp, 4, false, DAG) ||
5935       PPC::isVMRGHShuffleMask(SVOp, 1, false, DAG) ||
5936       PPC::isVMRGHShuffleMask(SVOp, 2, false, DAG) ||
5937       PPC::isVMRGHShuffleMask(SVOp, 4, false, DAG))
5938     return Op;
5939
5940   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
5941   // perfect shuffle table to emit an optimal matching sequence.
5942   ArrayRef<int> PermMask = SVOp->getMask();
5943
5944   unsigned PFIndexes[4];
5945   bool isFourElementShuffle = true;
5946   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5947     unsigned EltNo = 8;   // Start out undef.
5948     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
5949       if (PermMask[i*4+j] < 0)
5950         continue;   // Undef, ignore it.
5951
5952       unsigned ByteSource = PermMask[i*4+j];
5953       if ((ByteSource & 3) != j) {
5954         isFourElementShuffle = false;
5955         break;
5956       }
5957
5958       if (EltNo == 8) {
5959         EltNo = ByteSource/4;
5960       } else if (EltNo != ByteSource/4) {
5961         isFourElementShuffle = false;
5962         break;
5963       }
5964     }
5965     PFIndexes[i] = EltNo;
5966   }
5967
5968   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5969   // perfect shuffle vector to determine if it is cost effective to do this as
5970   // discrete instructions, or whether we should use a vperm.
5971   // For now, we skip this for little endian until such time as we have a
5972   // little-endian perfect shuffle table.
5973   if (isFourElementShuffle && !isLittleEndian) {
5974     // Compute the index in the perfect shuffle table.
5975     unsigned PFTableIndex =
5976       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5977
5978     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5979     unsigned Cost  = (PFEntry >> 30);
5980
5981     // Determining when to avoid vperm is tricky.  Many things affect the cost
5982     // of vperm, particularly how many times the perm mask needs to be computed.
5983     // For example, if the perm mask can be hoisted out of a loop or is already
5984     // used (perhaps because there are multiple permutes with the same shuffle
5985     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
5986     // the loop requires an extra register.
5987     //
5988     // As a compromise, we only emit discrete instructions if the shuffle can be
5989     // generated in 3 or fewer operations.  When we have loop information
5990     // available, if this block is within a loop, we should avoid using vperm
5991     // for 3-operation perms and use a constant pool load instead.
5992     if (Cost < 3)
5993       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5994   }
5995
5996   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5997   // vector that will get spilled to the constant pool.
5998   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5999
6000   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6001   // that it is in input element units, not in bytes.  Convert now.
6002
6003   // For little endian, the order of the input vectors is reversed, and
6004   // the permutation mask is complemented with respect to 31.  This is
6005   // necessary to produce proper semantics with the big-endian-biased vperm
6006   // instruction.
6007   EVT EltVT = V1.getValueType().getVectorElementType();
6008   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6009
6010   SmallVector<SDValue, 16> ResultMask;
6011   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6012     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6013
6014     for (unsigned j = 0; j != BytesPerElement; ++j)
6015       if (isLittleEndian)
6016         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6017                                              MVT::i32));
6018       else
6019         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6020                                              MVT::i32));
6021   }
6022
6023   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6024                                   ResultMask);
6025   if (isLittleEndian)
6026     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6027                        V2, V1, VPermMask);
6028   else
6029     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6030                        V1, V2, VPermMask);
6031 }
6032
6033 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6034 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6035 /// information about the intrinsic.
6036 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6037                                   bool &isDot) {
6038   unsigned IntrinsicID =
6039     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6040   CompareOpc = -1;
6041   isDot = false;
6042   switch (IntrinsicID) {
6043   default: return false;
6044     // Comparison predicates.
6045   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6046   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6047   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6048   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6049   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6050   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6051   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6052   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6053   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6054   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6055   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6056   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6057   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6058
6059     // Normal Comparisons.
6060   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6061   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6062   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6063   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6064   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6065   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6066   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6067   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6068   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6069   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6070   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6071   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6072   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6073   }
6074   return true;
6075 }
6076
6077 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6078 /// lower, do it, otherwise return null.
6079 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6080                                                    SelectionDAG &DAG) const {
6081   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6082   // opcode number of the comparison.
6083   SDLoc dl(Op);
6084   int CompareOpc;
6085   bool isDot;
6086   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6087     return SDValue();    // Don't custom lower most intrinsics.
6088
6089   // If this is a non-dot comparison, make the VCMP node and we are done.
6090   if (!isDot) {
6091     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6092                               Op.getOperand(1), Op.getOperand(2),
6093                               DAG.getConstant(CompareOpc, MVT::i32));
6094     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6095   }
6096
6097   // Create the PPCISD altivec 'dot' comparison node.
6098   SDValue Ops[] = {
6099     Op.getOperand(2),  // LHS
6100     Op.getOperand(3),  // RHS
6101     DAG.getConstant(CompareOpc, MVT::i32)
6102   };
6103   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6104   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6105
6106   // Now that we have the comparison, emit a copy from the CR to a GPR.
6107   // This is flagged to the above dot comparison.
6108   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6109                                 DAG.getRegister(PPC::CR6, MVT::i32),
6110                                 CompNode.getValue(1));
6111
6112   // Unpack the result based on how the target uses it.
6113   unsigned BitNo;   // Bit # of CR6.
6114   bool InvertBit;   // Invert result?
6115   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6116   default:  // Can't happen, don't crash on invalid number though.
6117   case 0:   // Return the value of the EQ bit of CR6.
6118     BitNo = 0; InvertBit = false;
6119     break;
6120   case 1:   // Return the inverted value of the EQ bit of CR6.
6121     BitNo = 0; InvertBit = true;
6122     break;
6123   case 2:   // Return the value of the LT bit of CR6.
6124     BitNo = 2; InvertBit = false;
6125     break;
6126   case 3:   // Return the inverted value of the LT bit of CR6.
6127     BitNo = 2; InvertBit = true;
6128     break;
6129   }
6130
6131   // Shift the bit into the low position.
6132   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6133                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6134   // Isolate the bit.
6135   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6136                       DAG.getConstant(1, MVT::i32));
6137
6138   // If we are supposed to, toggle the bit.
6139   if (InvertBit)
6140     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6141                         DAG.getConstant(1, MVT::i32));
6142   return Flags;
6143 }
6144
6145 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6146                                                   SelectionDAG &DAG) const {
6147   SDLoc dl(Op);
6148   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6149   // instructions), but for smaller types, we need to first extend up to v2i32
6150   // before doing going farther.
6151   if (Op.getValueType() == MVT::v2i64) {
6152     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6153     if (ExtVT != MVT::v2i32) {
6154       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6155       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6156                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6157                                         ExtVT.getVectorElementType(), 4)));
6158       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6159       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6160                        DAG.getValueType(MVT::v2i32));
6161     }
6162
6163     return Op;
6164   }
6165
6166   return SDValue();
6167 }
6168
6169 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6170                                                    SelectionDAG &DAG) const {
6171   SDLoc dl(Op);
6172   // Create a stack slot that is 16-byte aligned.
6173   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6174   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6175   EVT PtrVT = getPointerTy();
6176   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6177
6178   // Store the input value into Value#0 of the stack slot.
6179   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6180                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6181                                false, false, 0);
6182   // Load it out.
6183   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6184                      false, false, false, 0);
6185 }
6186
6187 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6188   SDLoc dl(Op);
6189   if (Op.getValueType() == MVT::v4i32) {
6190     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6191
6192     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6193     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6194
6195     SDValue RHSSwap =   // = vrlw RHS, 16
6196       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6197
6198     // Shrinkify inputs to v8i16.
6199     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6200     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6201     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6202
6203     // Low parts multiplied together, generating 32-bit results (we ignore the
6204     // top parts).
6205     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6206                                         LHS, RHS, DAG, dl, MVT::v4i32);
6207
6208     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6209                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6210     // Shift the high parts up 16 bits.
6211     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6212                               Neg16, DAG, dl);
6213     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6214   } else if (Op.getValueType() == MVT::v8i16) {
6215     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6216
6217     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6218
6219     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6220                             LHS, RHS, Zero, DAG, dl);
6221   } else if (Op.getValueType() == MVT::v16i8) {
6222     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6223     bool isLittleEndian = Subtarget.isLittleEndian();
6224
6225     // Multiply the even 8-bit parts, producing 16-bit sums.
6226     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6227                                            LHS, RHS, DAG, dl, MVT::v8i16);
6228     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6229
6230     // Multiply the odd 8-bit parts, producing 16-bit sums.
6231     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6232                                           LHS, RHS, DAG, dl, MVT::v8i16);
6233     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6234
6235     // Merge the results together.  Because vmuleub and vmuloub are
6236     // instructions with a big-endian bias, we must reverse the
6237     // element numbering and reverse the meaning of "odd" and "even"
6238     // when generating little endian code.
6239     int Ops[16];
6240     for (unsigned i = 0; i != 8; ++i) {
6241       if (isLittleEndian) {
6242         Ops[i*2  ] = 2*i;
6243         Ops[i*2+1] = 2*i+16;
6244       } else {
6245         Ops[i*2  ] = 2*i+1;
6246         Ops[i*2+1] = 2*i+1+16;
6247       }
6248     }
6249     if (isLittleEndian)
6250       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6251     else
6252       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6253   } else {
6254     llvm_unreachable("Unknown mul to lower!");
6255   }
6256 }
6257
6258 /// LowerOperation - Provide custom lowering hooks for some operations.
6259 ///
6260 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6261   switch (Op.getOpcode()) {
6262   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6263   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6264   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6265   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6266   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6267   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6268   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6269   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6270   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6271   case ISD::VASTART:
6272     return LowerVASTART(Op, DAG, Subtarget);
6273
6274   case ISD::VAARG:
6275     return LowerVAARG(Op, DAG, Subtarget);
6276
6277   case ISD::VACOPY:
6278     return LowerVACOPY(Op, DAG, Subtarget);
6279
6280   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6281   case ISD::DYNAMIC_STACKALLOC:
6282     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6283
6284   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6285   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6286
6287   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6288   case ISD::STORE:              return LowerSTORE(Op, DAG);
6289   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6290   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6291   case ISD::FP_TO_UINT:
6292   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6293                                                        SDLoc(Op));
6294   case ISD::UINT_TO_FP:
6295   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6296   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6297
6298   // Lower 64-bit shifts.
6299   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6300   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6301   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6302
6303   // Vector-related lowering.
6304   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6305   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6306   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6307   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6308   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6309   case ISD::MUL:                return LowerMUL(Op, DAG);
6310
6311   // For counter-based loop handling.
6312   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6313
6314   // Frame & Return address.
6315   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6316   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6317   }
6318 }
6319
6320 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6321                                            SmallVectorImpl<SDValue>&Results,
6322                                            SelectionDAG &DAG) const {
6323   const TargetMachine &TM = getTargetMachine();
6324   SDLoc dl(N);
6325   switch (N->getOpcode()) {
6326   default:
6327     llvm_unreachable("Do not know how to custom type legalize this operation!");
6328   case ISD::INTRINSIC_W_CHAIN: {
6329     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6330         Intrinsic::ppc_is_decremented_ctr_nonzero)
6331       break;
6332
6333     assert(N->getValueType(0) == MVT::i1 &&
6334            "Unexpected result type for CTR decrement intrinsic");
6335     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6336     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6337     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6338                                  N->getOperand(1)); 
6339
6340     Results.push_back(NewInt);
6341     Results.push_back(NewInt.getValue(1));
6342     break;
6343   }
6344   case ISD::VAARG: {
6345     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6346         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6347       return;
6348
6349     EVT VT = N->getValueType(0);
6350
6351     if (VT == MVT::i64) {
6352       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6353
6354       Results.push_back(NewNode);
6355       Results.push_back(NewNode.getValue(1));
6356     }
6357     return;
6358   }
6359   case ISD::FP_ROUND_INREG: {
6360     assert(N->getValueType(0) == MVT::ppcf128);
6361     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6362     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6363                              MVT::f64, N->getOperand(0),
6364                              DAG.getIntPtrConstant(0));
6365     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6366                              MVT::f64, N->getOperand(0),
6367                              DAG.getIntPtrConstant(1));
6368
6369     // Add the two halves of the long double in round-to-zero mode.
6370     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6371
6372     // We know the low half is about to be thrown away, so just use something
6373     // convenient.
6374     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6375                                 FPreg, FPreg));
6376     return;
6377   }
6378   case ISD::FP_TO_SINT:
6379     // LowerFP_TO_INT() can only handle f32 and f64.
6380     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6381       return;
6382     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6383     return;
6384   }
6385 }
6386
6387
6388 //===----------------------------------------------------------------------===//
6389 //  Other Lowering Code
6390 //===----------------------------------------------------------------------===//
6391
6392 MachineBasicBlock *
6393 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6394                                     bool is64bit, unsigned BinOpcode) const {
6395   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6396   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6397
6398   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6399   MachineFunction *F = BB->getParent();
6400   MachineFunction::iterator It = BB;
6401   ++It;
6402
6403   unsigned dest = MI->getOperand(0).getReg();
6404   unsigned ptrA = MI->getOperand(1).getReg();
6405   unsigned ptrB = MI->getOperand(2).getReg();
6406   unsigned incr = MI->getOperand(3).getReg();
6407   DebugLoc dl = MI->getDebugLoc();
6408
6409   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6410   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6411   F->insert(It, loopMBB);
6412   F->insert(It, exitMBB);
6413   exitMBB->splice(exitMBB->begin(), BB,
6414                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6415   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6416
6417   MachineRegisterInfo &RegInfo = F->getRegInfo();
6418   unsigned TmpReg = (!BinOpcode) ? incr :
6419     RegInfo.createVirtualRegister(
6420        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6421                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6422
6423   //  thisMBB:
6424   //   ...
6425   //   fallthrough --> loopMBB
6426   BB->addSuccessor(loopMBB);
6427
6428   //  loopMBB:
6429   //   l[wd]arx dest, ptr
6430   //   add r0, dest, incr
6431   //   st[wd]cx. r0, ptr
6432   //   bne- loopMBB
6433   //   fallthrough --> exitMBB
6434   BB = loopMBB;
6435   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6436     .addReg(ptrA).addReg(ptrB);
6437   if (BinOpcode)
6438     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6439   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6440     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6441   BuildMI(BB, dl, TII->get(PPC::BCC))
6442     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6443   BB->addSuccessor(loopMBB);
6444   BB->addSuccessor(exitMBB);
6445
6446   //  exitMBB:
6447   //   ...
6448   BB = exitMBB;
6449   return BB;
6450 }
6451
6452 MachineBasicBlock *
6453 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6454                                             MachineBasicBlock *BB,
6455                                             bool is8bit,    // operation
6456                                             unsigned BinOpcode) const {
6457   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6458   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6459   // In 64 bit mode we have to use 64 bits for addresses, even though the
6460   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6461   // registers without caring whether they're 32 or 64, but here we're
6462   // doing actual arithmetic on the addresses.
6463   bool is64bit = Subtarget.isPPC64();
6464   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6465
6466   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6467   MachineFunction *F = BB->getParent();
6468   MachineFunction::iterator It = BB;
6469   ++It;
6470
6471   unsigned dest = MI->getOperand(0).getReg();
6472   unsigned ptrA = MI->getOperand(1).getReg();
6473   unsigned ptrB = MI->getOperand(2).getReg();
6474   unsigned incr = MI->getOperand(3).getReg();
6475   DebugLoc dl = MI->getDebugLoc();
6476
6477   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6478   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6479   F->insert(It, loopMBB);
6480   F->insert(It, exitMBB);
6481   exitMBB->splice(exitMBB->begin(), BB,
6482                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6483   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6484
6485   MachineRegisterInfo &RegInfo = F->getRegInfo();
6486   const TargetRegisterClass *RC =
6487     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6488               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6489   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6490   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6491   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6492   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6493   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6494   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6495   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6496   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6497   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6498   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6499   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6500   unsigned Ptr1Reg;
6501   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6502
6503   //  thisMBB:
6504   //   ...
6505   //   fallthrough --> loopMBB
6506   BB->addSuccessor(loopMBB);
6507
6508   // The 4-byte load must be aligned, while a char or short may be
6509   // anywhere in the word.  Hence all this nasty bookkeeping code.
6510   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6511   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6512   //   xori shift, shift1, 24 [16]
6513   //   rlwinm ptr, ptr1, 0, 0, 29
6514   //   slw incr2, incr, shift
6515   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6516   //   slw mask, mask2, shift
6517   //  loopMBB:
6518   //   lwarx tmpDest, ptr
6519   //   add tmp, tmpDest, incr2
6520   //   andc tmp2, tmpDest, mask
6521   //   and tmp3, tmp, mask
6522   //   or tmp4, tmp3, tmp2
6523   //   stwcx. tmp4, ptr
6524   //   bne- loopMBB
6525   //   fallthrough --> exitMBB
6526   //   srw dest, tmpDest, shift
6527   if (ptrA != ZeroReg) {
6528     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6529     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6530       .addReg(ptrA).addReg(ptrB);
6531   } else {
6532     Ptr1Reg = ptrB;
6533   }
6534   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6535       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6536   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6537       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6538   if (is64bit)
6539     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6540       .addReg(Ptr1Reg).addImm(0).addImm(61);
6541   else
6542     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6543       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6544   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6545       .addReg(incr).addReg(ShiftReg);
6546   if (is8bit)
6547     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6548   else {
6549     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6550     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6551   }
6552   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6553       .addReg(Mask2Reg).addReg(ShiftReg);
6554
6555   BB = loopMBB;
6556   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6557     .addReg(ZeroReg).addReg(PtrReg);
6558   if (BinOpcode)
6559     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6560       .addReg(Incr2Reg).addReg(TmpDestReg);
6561   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6562     .addReg(TmpDestReg).addReg(MaskReg);
6563   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6564     .addReg(TmpReg).addReg(MaskReg);
6565   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6566     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6567   BuildMI(BB, dl, TII->get(PPC::STWCX))
6568     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6569   BuildMI(BB, dl, TII->get(PPC::BCC))
6570     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6571   BB->addSuccessor(loopMBB);
6572   BB->addSuccessor(exitMBB);
6573
6574   //  exitMBB:
6575   //   ...
6576   BB = exitMBB;
6577   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6578     .addReg(ShiftReg);
6579   return BB;
6580 }
6581
6582 llvm::MachineBasicBlock*
6583 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6584                                     MachineBasicBlock *MBB) const {
6585   DebugLoc DL = MI->getDebugLoc();
6586   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6587
6588   MachineFunction *MF = MBB->getParent();
6589   MachineRegisterInfo &MRI = MF->getRegInfo();
6590
6591   const BasicBlock *BB = MBB->getBasicBlock();
6592   MachineFunction::iterator I = MBB;
6593   ++I;
6594
6595   // Memory Reference
6596   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6597   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6598
6599   unsigned DstReg = MI->getOperand(0).getReg();
6600   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6601   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6602   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6603   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6604
6605   MVT PVT = getPointerTy();
6606   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6607          "Invalid Pointer Size!");
6608   // For v = setjmp(buf), we generate
6609   //
6610   // thisMBB:
6611   //  SjLjSetup mainMBB
6612   //  bl mainMBB
6613   //  v_restore = 1
6614   //  b sinkMBB
6615   //
6616   // mainMBB:
6617   //  buf[LabelOffset] = LR
6618   //  v_main = 0
6619   //
6620   // sinkMBB:
6621   //  v = phi(main, restore)
6622   //
6623
6624   MachineBasicBlock *thisMBB = MBB;
6625   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6626   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6627   MF->insert(I, mainMBB);
6628   MF->insert(I, sinkMBB);
6629
6630   MachineInstrBuilder MIB;
6631
6632   // Transfer the remainder of BB and its successor edges to sinkMBB.
6633   sinkMBB->splice(sinkMBB->begin(), MBB,
6634                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6635   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6636
6637   // Note that the structure of the jmp_buf used here is not compatible
6638   // with that used by libc, and is not designed to be. Specifically, it
6639   // stores only those 'reserved' registers that LLVM does not otherwise
6640   // understand how to spill. Also, by convention, by the time this
6641   // intrinsic is called, Clang has already stored the frame address in the
6642   // first slot of the buffer and stack address in the third. Following the
6643   // X86 target code, we'll store the jump address in the second slot. We also
6644   // need to save the TOC pointer (R2) to handle jumps between shared
6645   // libraries, and that will be stored in the fourth slot. The thread
6646   // identifier (R13) is not affected.
6647
6648   // thisMBB:
6649   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6650   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6651   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6652
6653   // Prepare IP either in reg.
6654   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6655   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6656   unsigned BufReg = MI->getOperand(1).getReg();
6657
6658   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6659     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6660             .addReg(PPC::X2)
6661             .addImm(TOCOffset)
6662             .addReg(BufReg);
6663     MIB.setMemRefs(MMOBegin, MMOEnd);
6664   }
6665
6666   // Naked functions never have a base pointer, and so we use r1. For all
6667   // other functions, this decision must be delayed until during PEI.
6668   unsigned BaseReg;
6669   if (MF->getFunction()->getAttributes().hasAttribute(
6670           AttributeSet::FunctionIndex, Attribute::Naked))
6671     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6672   else
6673     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6674
6675   MIB = BuildMI(*thisMBB, MI, DL,
6676                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6677           .addReg(BaseReg)
6678           .addImm(BPOffset)
6679           .addReg(BufReg);
6680   MIB.setMemRefs(MMOBegin, MMOEnd);
6681
6682   // Setup
6683   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6684   const PPCRegisterInfo *TRI =
6685     static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6686   MIB.addRegMask(TRI->getNoPreservedMask());
6687
6688   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6689
6690   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6691           .addMBB(mainMBB);
6692   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6693
6694   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6695   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6696
6697   // mainMBB:
6698   //  mainDstReg = 0
6699   MIB = BuildMI(mainMBB, DL,
6700     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6701
6702   // Store IP
6703   if (Subtarget.isPPC64()) {
6704     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6705             .addReg(LabelReg)
6706             .addImm(LabelOffset)
6707             .addReg(BufReg);
6708   } else {
6709     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6710             .addReg(LabelReg)
6711             .addImm(LabelOffset)
6712             .addReg(BufReg);
6713   }
6714
6715   MIB.setMemRefs(MMOBegin, MMOEnd);
6716
6717   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6718   mainMBB->addSuccessor(sinkMBB);
6719
6720   // sinkMBB:
6721   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6722           TII->get(PPC::PHI), DstReg)
6723     .addReg(mainDstReg).addMBB(mainMBB)
6724     .addReg(restoreDstReg).addMBB(thisMBB);
6725
6726   MI->eraseFromParent();
6727   return sinkMBB;
6728 }
6729
6730 MachineBasicBlock *
6731 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6732                                      MachineBasicBlock *MBB) const {
6733   DebugLoc DL = MI->getDebugLoc();
6734   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6735
6736   MachineFunction *MF = MBB->getParent();
6737   MachineRegisterInfo &MRI = MF->getRegInfo();
6738
6739   // Memory Reference
6740   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6741   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6742
6743   MVT PVT = getPointerTy();
6744   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6745          "Invalid Pointer Size!");
6746
6747   const TargetRegisterClass *RC =
6748     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6749   unsigned Tmp = MRI.createVirtualRegister(RC);
6750   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6751   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6752   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6753   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6754                   (Subtarget.isSVR4ABI() &&
6755                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6756                      PPC::R29 : PPC::R30);
6757
6758   MachineInstrBuilder MIB;
6759
6760   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6761   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6762   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6763   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6764
6765   unsigned BufReg = MI->getOperand(0).getReg();
6766
6767   // Reload FP (the jumped-to function may not have had a
6768   // frame pointer, and if so, then its r31 will be restored
6769   // as necessary).
6770   if (PVT == MVT::i64) {
6771     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6772             .addImm(0)
6773             .addReg(BufReg);
6774   } else {
6775     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6776             .addImm(0)
6777             .addReg(BufReg);
6778   }
6779   MIB.setMemRefs(MMOBegin, MMOEnd);
6780
6781   // Reload IP
6782   if (PVT == MVT::i64) {
6783     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6784             .addImm(LabelOffset)
6785             .addReg(BufReg);
6786   } else {
6787     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6788             .addImm(LabelOffset)
6789             .addReg(BufReg);
6790   }
6791   MIB.setMemRefs(MMOBegin, MMOEnd);
6792
6793   // Reload SP
6794   if (PVT == MVT::i64) {
6795     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6796             .addImm(SPOffset)
6797             .addReg(BufReg);
6798   } else {
6799     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6800             .addImm(SPOffset)
6801             .addReg(BufReg);
6802   }
6803   MIB.setMemRefs(MMOBegin, MMOEnd);
6804
6805   // Reload BP
6806   if (PVT == MVT::i64) {
6807     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6808             .addImm(BPOffset)
6809             .addReg(BufReg);
6810   } else {
6811     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6812             .addImm(BPOffset)
6813             .addReg(BufReg);
6814   }
6815   MIB.setMemRefs(MMOBegin, MMOEnd);
6816
6817   // Reload TOC
6818   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6819     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6820             .addImm(TOCOffset)
6821             .addReg(BufReg);
6822
6823     MIB.setMemRefs(MMOBegin, MMOEnd);
6824   }
6825
6826   // Jump
6827   BuildMI(*MBB, MI, DL,
6828           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6829   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6830
6831   MI->eraseFromParent();
6832   return MBB;
6833 }
6834
6835 MachineBasicBlock *
6836 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6837                                                MachineBasicBlock *BB) const {
6838   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6839       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6840     return emitEHSjLjSetJmp(MI, BB);
6841   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6842              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6843     return emitEHSjLjLongJmp(MI, BB);
6844   }
6845
6846   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6847
6848   // To "insert" these instructions we actually have to insert their
6849   // control-flow patterns.
6850   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6851   MachineFunction::iterator It = BB;
6852   ++It;
6853
6854   MachineFunction *F = BB->getParent();
6855
6856   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6857                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
6858                                  MI->getOpcode() == PPC::SELECT_I4 ||
6859                                  MI->getOpcode() == PPC::SELECT_I8)) {
6860     SmallVector<MachineOperand, 2> Cond;
6861     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6862         MI->getOpcode() == PPC::SELECT_CC_I8)
6863       Cond.push_back(MI->getOperand(4));
6864     else
6865       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6866     Cond.push_back(MI->getOperand(1));
6867
6868     DebugLoc dl = MI->getDebugLoc();
6869     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6870     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6871                       Cond, MI->getOperand(2).getReg(),
6872                       MI->getOperand(3).getReg());
6873   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6874              MI->getOpcode() == PPC::SELECT_CC_I8 ||
6875              MI->getOpcode() == PPC::SELECT_CC_F4 ||
6876              MI->getOpcode() == PPC::SELECT_CC_F8 ||
6877              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
6878              MI->getOpcode() == PPC::SELECT_I4 ||
6879              MI->getOpcode() == PPC::SELECT_I8 ||
6880              MI->getOpcode() == PPC::SELECT_F4 ||
6881              MI->getOpcode() == PPC::SELECT_F8 ||
6882              MI->getOpcode() == PPC::SELECT_VRRC) {
6883     // The incoming instruction knows the destination vreg to set, the
6884     // condition code register to branch on, the true/false values to
6885     // select between, and a branch opcode to use.
6886
6887     //  thisMBB:
6888     //  ...
6889     //   TrueVal = ...
6890     //   cmpTY ccX, r1, r2
6891     //   bCC copy1MBB
6892     //   fallthrough --> copy0MBB
6893     MachineBasicBlock *thisMBB = BB;
6894     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6895     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6896     DebugLoc dl = MI->getDebugLoc();
6897     F->insert(It, copy0MBB);
6898     F->insert(It, sinkMBB);
6899
6900     // Transfer the remainder of BB and its successor edges to sinkMBB.
6901     sinkMBB->splice(sinkMBB->begin(), BB,
6902                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
6903     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6904
6905     // Next, add the true and fallthrough blocks as its successors.
6906     BB->addSuccessor(copy0MBB);
6907     BB->addSuccessor(sinkMBB);
6908
6909     if (MI->getOpcode() == PPC::SELECT_I4 ||
6910         MI->getOpcode() == PPC::SELECT_I8 ||
6911         MI->getOpcode() == PPC::SELECT_F4 ||
6912         MI->getOpcode() == PPC::SELECT_F8 ||
6913         MI->getOpcode() == PPC::SELECT_VRRC) {
6914       BuildMI(BB, dl, TII->get(PPC::BC))
6915         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6916     } else {
6917       unsigned SelectPred = MI->getOperand(4).getImm();
6918       BuildMI(BB, dl, TII->get(PPC::BCC))
6919         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6920     }
6921
6922     //  copy0MBB:
6923     //   %FalseValue = ...
6924     //   # fallthrough to sinkMBB
6925     BB = copy0MBB;
6926
6927     // Update machine-CFG edges
6928     BB->addSuccessor(sinkMBB);
6929
6930     //  sinkMBB:
6931     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6932     //  ...
6933     BB = sinkMBB;
6934     BuildMI(*BB, BB->begin(), dl,
6935             TII->get(PPC::PHI), MI->getOperand(0).getReg())
6936       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6937       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6938   }
6939   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6940     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6941   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6942     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6943   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6944     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6945   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6946     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6947
6948   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6949     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6950   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6951     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6952   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6953     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6954   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6955     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6956
6957   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6958     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6959   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6960     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6961   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6962     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6963   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6964     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6965
6966   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6967     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6968   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6969     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6970   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6971     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6972   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6973     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6974
6975   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6976     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
6977   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6978     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
6979   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6980     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
6981   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6982     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
6983
6984   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6985     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6986   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6987     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6988   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6989     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6990   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6991     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6992
6993   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6994     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6995   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6996     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6997   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6998     BB = EmitAtomicBinary(MI, BB, false, 0);
6999   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7000     BB = EmitAtomicBinary(MI, BB, true, 0);
7001
7002   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7003            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7004     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7005
7006     unsigned dest   = MI->getOperand(0).getReg();
7007     unsigned ptrA   = MI->getOperand(1).getReg();
7008     unsigned ptrB   = MI->getOperand(2).getReg();
7009     unsigned oldval = MI->getOperand(3).getReg();
7010     unsigned newval = MI->getOperand(4).getReg();
7011     DebugLoc dl     = MI->getDebugLoc();
7012
7013     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7014     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7015     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7016     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7017     F->insert(It, loop1MBB);
7018     F->insert(It, loop2MBB);
7019     F->insert(It, midMBB);
7020     F->insert(It, exitMBB);
7021     exitMBB->splice(exitMBB->begin(), BB,
7022                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7023     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7024
7025     //  thisMBB:
7026     //   ...
7027     //   fallthrough --> loopMBB
7028     BB->addSuccessor(loop1MBB);
7029
7030     // loop1MBB:
7031     //   l[wd]arx dest, ptr
7032     //   cmp[wd] dest, oldval
7033     //   bne- midMBB
7034     // loop2MBB:
7035     //   st[wd]cx. newval, ptr
7036     //   bne- loopMBB
7037     //   b exitBB
7038     // midMBB:
7039     //   st[wd]cx. dest, ptr
7040     // exitBB:
7041     BB = loop1MBB;
7042     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7043       .addReg(ptrA).addReg(ptrB);
7044     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7045       .addReg(oldval).addReg(dest);
7046     BuildMI(BB, dl, TII->get(PPC::BCC))
7047       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7048     BB->addSuccessor(loop2MBB);
7049     BB->addSuccessor(midMBB);
7050
7051     BB = loop2MBB;
7052     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7053       .addReg(newval).addReg(ptrA).addReg(ptrB);
7054     BuildMI(BB, dl, TII->get(PPC::BCC))
7055       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7056     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7057     BB->addSuccessor(loop1MBB);
7058     BB->addSuccessor(exitMBB);
7059
7060     BB = midMBB;
7061     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7062       .addReg(dest).addReg(ptrA).addReg(ptrB);
7063     BB->addSuccessor(exitMBB);
7064
7065     //  exitMBB:
7066     //   ...
7067     BB = exitMBB;
7068   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7069              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7070     // We must use 64-bit registers for addresses when targeting 64-bit,
7071     // since we're actually doing arithmetic on them.  Other registers
7072     // can be 32-bit.
7073     bool is64bit = Subtarget.isPPC64();
7074     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7075
7076     unsigned dest   = MI->getOperand(0).getReg();
7077     unsigned ptrA   = MI->getOperand(1).getReg();
7078     unsigned ptrB   = MI->getOperand(2).getReg();
7079     unsigned oldval = MI->getOperand(3).getReg();
7080     unsigned newval = MI->getOperand(4).getReg();
7081     DebugLoc dl     = MI->getDebugLoc();
7082
7083     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7084     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7085     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7086     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7087     F->insert(It, loop1MBB);
7088     F->insert(It, loop2MBB);
7089     F->insert(It, midMBB);
7090     F->insert(It, exitMBB);
7091     exitMBB->splice(exitMBB->begin(), BB,
7092                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7093     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7094
7095     MachineRegisterInfo &RegInfo = F->getRegInfo();
7096     const TargetRegisterClass *RC =
7097       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7098                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7099     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7100     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7101     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7102     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7103     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7104     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7105     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7106     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7107     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7108     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7109     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7110     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7111     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7112     unsigned Ptr1Reg;
7113     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7114     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7115     //  thisMBB:
7116     //   ...
7117     //   fallthrough --> loopMBB
7118     BB->addSuccessor(loop1MBB);
7119
7120     // The 4-byte load must be aligned, while a char or short may be
7121     // anywhere in the word.  Hence all this nasty bookkeeping code.
7122     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7123     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7124     //   xori shift, shift1, 24 [16]
7125     //   rlwinm ptr, ptr1, 0, 0, 29
7126     //   slw newval2, newval, shift
7127     //   slw oldval2, oldval,shift
7128     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7129     //   slw mask, mask2, shift
7130     //   and newval3, newval2, mask
7131     //   and oldval3, oldval2, mask
7132     // loop1MBB:
7133     //   lwarx tmpDest, ptr
7134     //   and tmp, tmpDest, mask
7135     //   cmpw tmp, oldval3
7136     //   bne- midMBB
7137     // loop2MBB:
7138     //   andc tmp2, tmpDest, mask
7139     //   or tmp4, tmp2, newval3
7140     //   stwcx. tmp4, ptr
7141     //   bne- loop1MBB
7142     //   b exitBB
7143     // midMBB:
7144     //   stwcx. tmpDest, ptr
7145     // exitBB:
7146     //   srw dest, tmpDest, shift
7147     if (ptrA != ZeroReg) {
7148       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7149       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7150         .addReg(ptrA).addReg(ptrB);
7151     } else {
7152       Ptr1Reg = ptrB;
7153     }
7154     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7155         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7156     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7157         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7158     if (is64bit)
7159       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7160         .addReg(Ptr1Reg).addImm(0).addImm(61);
7161     else
7162       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7163         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7164     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7165         .addReg(newval).addReg(ShiftReg);
7166     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7167         .addReg(oldval).addReg(ShiftReg);
7168     if (is8bit)
7169       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7170     else {
7171       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7172       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7173         .addReg(Mask3Reg).addImm(65535);
7174     }
7175     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7176         .addReg(Mask2Reg).addReg(ShiftReg);
7177     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7178         .addReg(NewVal2Reg).addReg(MaskReg);
7179     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7180         .addReg(OldVal2Reg).addReg(MaskReg);
7181
7182     BB = loop1MBB;
7183     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7184         .addReg(ZeroReg).addReg(PtrReg);
7185     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7186         .addReg(TmpDestReg).addReg(MaskReg);
7187     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7188         .addReg(TmpReg).addReg(OldVal3Reg);
7189     BuildMI(BB, dl, TII->get(PPC::BCC))
7190         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7191     BB->addSuccessor(loop2MBB);
7192     BB->addSuccessor(midMBB);
7193
7194     BB = loop2MBB;
7195     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7196         .addReg(TmpDestReg).addReg(MaskReg);
7197     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7198         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7199     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7200         .addReg(ZeroReg).addReg(PtrReg);
7201     BuildMI(BB, dl, TII->get(PPC::BCC))
7202       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7203     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7204     BB->addSuccessor(loop1MBB);
7205     BB->addSuccessor(exitMBB);
7206
7207     BB = midMBB;
7208     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7209       .addReg(ZeroReg).addReg(PtrReg);
7210     BB->addSuccessor(exitMBB);
7211
7212     //  exitMBB:
7213     //   ...
7214     BB = exitMBB;
7215     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7216       .addReg(ShiftReg);
7217   } else if (MI->getOpcode() == PPC::FADDrtz) {
7218     // This pseudo performs an FADD with rounding mode temporarily forced
7219     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7220     // is not modeled at the SelectionDAG level.
7221     unsigned Dest = MI->getOperand(0).getReg();
7222     unsigned Src1 = MI->getOperand(1).getReg();
7223     unsigned Src2 = MI->getOperand(2).getReg();
7224     DebugLoc dl   = MI->getDebugLoc();
7225
7226     MachineRegisterInfo &RegInfo = F->getRegInfo();
7227     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7228
7229     // Save FPSCR value.
7230     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7231
7232     // Set rounding mode to round-to-zero.
7233     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7234     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7235
7236     // Perform addition.
7237     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7238
7239     // Restore FPSCR value.
7240     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7241   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7242              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7243              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7244              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7245     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7246                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7247                       PPC::ANDIo8 : PPC::ANDIo;
7248     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7249                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7250
7251     MachineRegisterInfo &RegInfo = F->getRegInfo();
7252     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7253                                                   &PPC::GPRCRegClass :
7254                                                   &PPC::G8RCRegClass);
7255
7256     DebugLoc dl   = MI->getDebugLoc();
7257     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7258       .addReg(MI->getOperand(1).getReg()).addImm(1);
7259     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7260             MI->getOperand(0).getReg())
7261       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7262   } else {
7263     llvm_unreachable("Unexpected instr type to insert");
7264   }
7265
7266   MI->eraseFromParent();   // The pseudo instruction is gone now.
7267   return BB;
7268 }
7269
7270 //===----------------------------------------------------------------------===//
7271 // Target Optimization Hooks
7272 //===----------------------------------------------------------------------===//
7273
7274 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7275                                                DAGCombinerInfo &DCI) const {
7276   if (DCI.isAfterLegalizeVectorOps())
7277     return SDValue();
7278
7279   EVT VT = Op.getValueType();
7280
7281   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7282       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7283       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7284       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7285
7286     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7287     // For the reciprocal, we need to find the zero of the function:
7288     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7289     //     =>
7290     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7291     //     does not require additional intermediate precision]
7292
7293     // Convergence is quadratic, so we essentially double the number of digits
7294     // correct after every iteration. The minimum architected relative
7295     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7296     // 23 digits and double has 52 digits.
7297     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7298     if (VT.getScalarType() == MVT::f64)
7299       ++Iterations;
7300
7301     SelectionDAG &DAG = DCI.DAG;
7302     SDLoc dl(Op);
7303
7304     SDValue FPOne =
7305       DAG.getConstantFP(1.0, VT.getScalarType());
7306     if (VT.isVector()) {
7307       assert(VT.getVectorNumElements() == 4 &&
7308              "Unknown vector type");
7309       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7310                           FPOne, FPOne, FPOne, FPOne);
7311     }
7312
7313     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7314     DCI.AddToWorklist(Est.getNode());
7315
7316     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7317     for (int i = 0; i < Iterations; ++i) {
7318       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7319       DCI.AddToWorklist(NewEst.getNode());
7320
7321       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7322       DCI.AddToWorklist(NewEst.getNode());
7323
7324       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7325       DCI.AddToWorklist(NewEst.getNode());
7326
7327       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7328       DCI.AddToWorklist(Est.getNode());
7329     }
7330
7331     return Est;
7332   }
7333
7334   return SDValue();
7335 }
7336
7337 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7338                                              DAGCombinerInfo &DCI) const {
7339   if (DCI.isAfterLegalizeVectorOps())
7340     return SDValue();
7341
7342   EVT VT = Op.getValueType();
7343
7344   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7345       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7346       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7347       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7348
7349     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7350     // For the reciprocal sqrt, we need to find the zero of the function:
7351     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7352     //     =>
7353     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7354     // As a result, we precompute A/2 prior to the iteration loop.
7355
7356     // Convergence is quadratic, so we essentially double the number of digits
7357     // correct after every iteration. The minimum architected relative
7358     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7359     // 23 digits and double has 52 digits.
7360     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7361     if (VT.getScalarType() == MVT::f64)
7362       ++Iterations;
7363
7364     SelectionDAG &DAG = DCI.DAG;
7365     SDLoc dl(Op);
7366
7367     SDValue FPThreeHalves =
7368       DAG.getConstantFP(1.5, VT.getScalarType());
7369     if (VT.isVector()) {
7370       assert(VT.getVectorNumElements() == 4 &&
7371              "Unknown vector type");
7372       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7373                                   FPThreeHalves, FPThreeHalves,
7374                                   FPThreeHalves, FPThreeHalves);
7375     }
7376
7377     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7378     DCI.AddToWorklist(Est.getNode());
7379
7380     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7381     // this entire sequence requires only one FP constant.
7382     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7383     DCI.AddToWorklist(HalfArg.getNode());
7384
7385     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7386     DCI.AddToWorklist(HalfArg.getNode());
7387
7388     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7389     for (int i = 0; i < Iterations; ++i) {
7390       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7391       DCI.AddToWorklist(NewEst.getNode());
7392
7393       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7394       DCI.AddToWorklist(NewEst.getNode());
7395
7396       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7397       DCI.AddToWorklist(NewEst.getNode());
7398
7399       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7400       DCI.AddToWorklist(Est.getNode());
7401     }
7402
7403     return Est;
7404   }
7405
7406   return SDValue();
7407 }
7408
7409 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7410 // not enforce equality of the chain operands.
7411 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
7412                             unsigned Bytes, int Dist,
7413                             SelectionDAG &DAG) {
7414   EVT VT = LS->getMemoryVT();
7415   if (VT.getSizeInBits() / 8 != Bytes)
7416     return false;
7417
7418   SDValue Loc = LS->getBasePtr();
7419   SDValue BaseLoc = Base->getBasePtr();
7420   if (Loc.getOpcode() == ISD::FrameIndex) {
7421     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7422       return false;
7423     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7424     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7425     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7426     int FS  = MFI->getObjectSize(FI);
7427     int BFS = MFI->getObjectSize(BFI);
7428     if (FS != BFS || FS != (int)Bytes) return false;
7429     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7430   }
7431
7432   // Handle X+C
7433   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7434       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7435     return true;
7436
7437   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7438   const GlobalValue *GV1 = nullptr;
7439   const GlobalValue *GV2 = nullptr;
7440   int64_t Offset1 = 0;
7441   int64_t Offset2 = 0;
7442   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7443   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7444   if (isGA1 && isGA2 && GV1 == GV2)
7445     return Offset1 == (Offset2 + Dist*Bytes);
7446   return false;
7447 }
7448
7449 // Return true is there is a nearyby consecutive load to the one provided
7450 // (regardless of alignment). We search up and down the chain, looking though
7451 // token factors and other loads (but nothing else). As a result, a true
7452 // results indicates that it is safe to create a new consecutive load adjacent
7453 // to the load provided.
7454 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7455   SDValue Chain = LD->getChain();
7456   EVT VT = LD->getMemoryVT();
7457
7458   SmallSet<SDNode *, 16> LoadRoots;
7459   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7460   SmallSet<SDNode *, 16> Visited;
7461
7462   // First, search up the chain, branching to follow all token-factor operands.
7463   // If we find a consecutive load, then we're done, otherwise, record all
7464   // nodes just above the top-level loads and token factors.
7465   while (!Queue.empty()) {
7466     SDNode *ChainNext = Queue.pop_back_val();
7467     if (!Visited.insert(ChainNext))
7468       continue;
7469
7470     if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
7471       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7472         return true;
7473
7474       if (!Visited.count(ChainLD->getChain().getNode()))
7475         Queue.push_back(ChainLD->getChain().getNode());
7476     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7477       for (const SDUse &O : ChainNext->ops())
7478         if (!Visited.count(O.getNode()))
7479           Queue.push_back(O.getNode());
7480     } else
7481       LoadRoots.insert(ChainNext);
7482   }
7483
7484   // Second, search down the chain, starting from the top-level nodes recorded
7485   // in the first phase. These top-level nodes are the nodes just above all
7486   // loads and token factors. Starting with their uses, recursively look though
7487   // all loads (just the chain uses) and token factors to find a consecutive
7488   // load.
7489   Visited.clear();
7490   Queue.clear();
7491
7492   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7493        IE = LoadRoots.end(); I != IE; ++I) {
7494     Queue.push_back(*I);
7495        
7496     while (!Queue.empty()) {
7497       SDNode *LoadRoot = Queue.pop_back_val();
7498       if (!Visited.insert(LoadRoot))
7499         continue;
7500
7501       if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
7502         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7503           return true;
7504
7505       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7506            UE = LoadRoot->use_end(); UI != UE; ++UI)
7507         if (((isa<LoadSDNode>(*UI) &&
7508             cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7509             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7510           Queue.push_back(*UI);
7511     }
7512   }
7513
7514   return false;
7515 }
7516
7517 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7518                                                   DAGCombinerInfo &DCI) const {
7519   SelectionDAG &DAG = DCI.DAG;
7520   SDLoc dl(N);
7521
7522   assert(Subtarget.useCRBits() &&
7523          "Expecting to be tracking CR bits");
7524   // If we're tracking CR bits, we need to be careful that we don't have:
7525   //   trunc(binary-ops(zext(x), zext(y)))
7526   // or
7527   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7528   // such that we're unnecessarily moving things into GPRs when it would be
7529   // better to keep them in CR bits.
7530
7531   // Note that trunc here can be an actual i1 trunc, or can be the effective
7532   // truncation that comes from a setcc or select_cc.
7533   if (N->getOpcode() == ISD::TRUNCATE &&
7534       N->getValueType(0) != MVT::i1)
7535     return SDValue();
7536
7537   if (N->getOperand(0).getValueType() != MVT::i32 &&
7538       N->getOperand(0).getValueType() != MVT::i64)
7539     return SDValue();
7540
7541   if (N->getOpcode() == ISD::SETCC ||
7542       N->getOpcode() == ISD::SELECT_CC) {
7543     // If we're looking at a comparison, then we need to make sure that the
7544     // high bits (all except for the first) don't matter the result.
7545     ISD::CondCode CC =
7546       cast<CondCodeSDNode>(N->getOperand(
7547         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7548     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7549
7550     if (ISD::isSignedIntSetCC(CC)) {
7551       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7552           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7553         return SDValue();
7554     } else if (ISD::isUnsignedIntSetCC(CC)) {
7555       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7556                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7557           !DAG.MaskedValueIsZero(N->getOperand(1),
7558                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7559         return SDValue();
7560     } else {
7561       // This is neither a signed nor an unsigned comparison, just make sure
7562       // that the high bits are equal.
7563       APInt Op1Zero, Op1One;
7564       APInt Op2Zero, Op2One;
7565       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7566       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7567
7568       // We don't really care about what is known about the first bit (if
7569       // anything), so clear it in all masks prior to comparing them.
7570       Op1Zero.clearBit(0); Op1One.clearBit(0);
7571       Op2Zero.clearBit(0); Op2One.clearBit(0);
7572
7573       if (Op1Zero != Op2Zero || Op1One != Op2One)
7574         return SDValue();
7575     }
7576   }
7577
7578   // We now know that the higher-order bits are irrelevant, we just need to
7579   // make sure that all of the intermediate operations are bit operations, and
7580   // all inputs are extensions.
7581   if (N->getOperand(0).getOpcode() != ISD::AND &&
7582       N->getOperand(0).getOpcode() != ISD::OR  &&
7583       N->getOperand(0).getOpcode() != ISD::XOR &&
7584       N->getOperand(0).getOpcode() != ISD::SELECT &&
7585       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7586       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7587       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7588       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7589       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7590     return SDValue();
7591
7592   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7593       N->getOperand(1).getOpcode() != ISD::AND &&
7594       N->getOperand(1).getOpcode() != ISD::OR  &&
7595       N->getOperand(1).getOpcode() != ISD::XOR &&
7596       N->getOperand(1).getOpcode() != ISD::SELECT &&
7597       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7598       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7599       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7600       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7601       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7602     return SDValue();
7603
7604   SmallVector<SDValue, 4> Inputs;
7605   SmallVector<SDValue, 8> BinOps, PromOps;
7606   SmallPtrSet<SDNode *, 16> Visited;
7607
7608   for (unsigned i = 0; i < 2; ++i) {
7609     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7610           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7611           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7612           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7613         isa<ConstantSDNode>(N->getOperand(i)))
7614       Inputs.push_back(N->getOperand(i));
7615     else
7616       BinOps.push_back(N->getOperand(i));
7617
7618     if (N->getOpcode() == ISD::TRUNCATE)
7619       break;
7620   }
7621
7622   // Visit all inputs, collect all binary operations (and, or, xor and
7623   // select) that are all fed by extensions. 
7624   while (!BinOps.empty()) {
7625     SDValue BinOp = BinOps.back();
7626     BinOps.pop_back();
7627
7628     if (!Visited.insert(BinOp.getNode()))
7629       continue;
7630
7631     PromOps.push_back(BinOp);
7632
7633     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7634       // The condition of the select is not promoted.
7635       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7636         continue;
7637       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7638         continue;
7639
7640       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7641             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7642             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7643            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7644           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7645         Inputs.push_back(BinOp.getOperand(i)); 
7646       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7647                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7648                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7649                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7650                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7651                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7652                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7653                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7654                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7655         BinOps.push_back(BinOp.getOperand(i));
7656       } else {
7657         // We have an input that is not an extension or another binary
7658         // operation; we'll abort this transformation.
7659         return SDValue();
7660       }
7661     }
7662   }
7663
7664   // Make sure that this is a self-contained cluster of operations (which
7665   // is not quite the same thing as saying that everything has only one
7666   // use).
7667   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7668     if (isa<ConstantSDNode>(Inputs[i]))
7669       continue;
7670
7671     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7672                               UE = Inputs[i].getNode()->use_end();
7673          UI != UE; ++UI) {
7674       SDNode *User = *UI;
7675       if (User != N && !Visited.count(User))
7676         return SDValue();
7677
7678       // Make sure that we're not going to promote the non-output-value
7679       // operand(s) or SELECT or SELECT_CC.
7680       // FIXME: Although we could sometimes handle this, and it does occur in
7681       // practice that one of the condition inputs to the select is also one of
7682       // the outputs, we currently can't deal with this.
7683       if (User->getOpcode() == ISD::SELECT) {
7684         if (User->getOperand(0) == Inputs[i])
7685           return SDValue();
7686       } else if (User->getOpcode() == ISD::SELECT_CC) {
7687         if (User->getOperand(0) == Inputs[i] ||
7688             User->getOperand(1) == Inputs[i])
7689           return SDValue();
7690       }
7691     }
7692   }
7693
7694   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7695     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7696                               UE = PromOps[i].getNode()->use_end();
7697          UI != UE; ++UI) {
7698       SDNode *User = *UI;
7699       if (User != N && !Visited.count(User))
7700         return SDValue();
7701
7702       // Make sure that we're not going to promote the non-output-value
7703       // operand(s) or SELECT or SELECT_CC.
7704       // FIXME: Although we could sometimes handle this, and it does occur in
7705       // practice that one of the condition inputs to the select is also one of
7706       // the outputs, we currently can't deal with this.
7707       if (User->getOpcode() == ISD::SELECT) {
7708         if (User->getOperand(0) == PromOps[i])
7709           return SDValue();
7710       } else if (User->getOpcode() == ISD::SELECT_CC) {
7711         if (User->getOperand(0) == PromOps[i] ||
7712             User->getOperand(1) == PromOps[i])
7713           return SDValue();
7714       }
7715     }
7716   }
7717
7718   // Replace all inputs with the extension operand.
7719   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7720     // Constants may have users outside the cluster of to-be-promoted nodes,
7721     // and so we need to replace those as we do the promotions.
7722     if (isa<ConstantSDNode>(Inputs[i]))
7723       continue;
7724     else
7725       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7726   }
7727
7728   // Replace all operations (these are all the same, but have a different
7729   // (i1) return type). DAG.getNode will validate that the types of
7730   // a binary operator match, so go through the list in reverse so that
7731   // we've likely promoted both operands first. Any intermediate truncations or
7732   // extensions disappear.
7733   while (!PromOps.empty()) {
7734     SDValue PromOp = PromOps.back();
7735     PromOps.pop_back();
7736
7737     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7738         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7739         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7740         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7741       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7742           PromOp.getOperand(0).getValueType() != MVT::i1) {
7743         // The operand is not yet ready (see comment below).
7744         PromOps.insert(PromOps.begin(), PromOp);
7745         continue;
7746       }
7747
7748       SDValue RepValue = PromOp.getOperand(0);
7749       if (isa<ConstantSDNode>(RepValue))
7750         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7751
7752       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7753       continue;
7754     }
7755
7756     unsigned C;
7757     switch (PromOp.getOpcode()) {
7758     default:             C = 0; break;
7759     case ISD::SELECT:    C = 1; break;
7760     case ISD::SELECT_CC: C = 2; break;
7761     }
7762
7763     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7764          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7765         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7766          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7767       // The to-be-promoted operands of this node have not yet been
7768       // promoted (this should be rare because we're going through the
7769       // list backward, but if one of the operands has several users in
7770       // this cluster of to-be-promoted nodes, it is possible).
7771       PromOps.insert(PromOps.begin(), PromOp);
7772       continue;
7773     }
7774
7775     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7776                                 PromOp.getNode()->op_end());
7777
7778     // If there are any constant inputs, make sure they're replaced now.
7779     for (unsigned i = 0; i < 2; ++i)
7780       if (isa<ConstantSDNode>(Ops[C+i]))
7781         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7782
7783     DAG.ReplaceAllUsesOfValueWith(PromOp,
7784       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7785   }
7786
7787   // Now we're left with the initial truncation itself.
7788   if (N->getOpcode() == ISD::TRUNCATE)
7789     return N->getOperand(0);
7790
7791   // Otherwise, this is a comparison. The operands to be compared have just
7792   // changed type (to i1), but everything else is the same.
7793   return SDValue(N, 0);
7794 }
7795
7796 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7797                                                   DAGCombinerInfo &DCI) const {
7798   SelectionDAG &DAG = DCI.DAG;
7799   SDLoc dl(N);
7800
7801   // If we're tracking CR bits, we need to be careful that we don't have:
7802   //   zext(binary-ops(trunc(x), trunc(y)))
7803   // or
7804   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7805   // such that we're unnecessarily moving things into CR bits that can more
7806   // efficiently stay in GPRs. Note that if we're not certain that the high
7807   // bits are set as required by the final extension, we still may need to do
7808   // some masking to get the proper behavior.
7809
7810   // This same functionality is important on PPC64 when dealing with
7811   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7812   // the return values of functions. Because it is so similar, it is handled
7813   // here as well.
7814
7815   if (N->getValueType(0) != MVT::i32 &&
7816       N->getValueType(0) != MVT::i64)
7817     return SDValue();
7818
7819   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
7820         Subtarget.useCRBits()) ||
7821        (N->getOperand(0).getValueType() == MVT::i32 &&
7822         Subtarget.isPPC64())))
7823     return SDValue();
7824
7825   if (N->getOperand(0).getOpcode() != ISD::AND &&
7826       N->getOperand(0).getOpcode() != ISD::OR  &&
7827       N->getOperand(0).getOpcode() != ISD::XOR &&
7828       N->getOperand(0).getOpcode() != ISD::SELECT &&
7829       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
7830     return SDValue();
7831
7832   SmallVector<SDValue, 4> Inputs;
7833   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
7834   SmallPtrSet<SDNode *, 16> Visited;
7835
7836   // Visit all inputs, collect all binary operations (and, or, xor and
7837   // select) that are all fed by truncations. 
7838   while (!BinOps.empty()) {
7839     SDValue BinOp = BinOps.back();
7840     BinOps.pop_back();
7841
7842     if (!Visited.insert(BinOp.getNode()))
7843       continue;
7844
7845     PromOps.push_back(BinOp);
7846
7847     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7848       // The condition of the select is not promoted.
7849       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7850         continue;
7851       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7852         continue;
7853
7854       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7855           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7856         Inputs.push_back(BinOp.getOperand(i)); 
7857       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7858                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7859                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7860                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7861                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
7862         BinOps.push_back(BinOp.getOperand(i));
7863       } else {
7864         // We have an input that is not a truncation or another binary
7865         // operation; we'll abort this transformation.
7866         return SDValue();
7867       }
7868     }
7869   }
7870
7871   // Make sure that this is a self-contained cluster of operations (which
7872   // is not quite the same thing as saying that everything has only one
7873   // use).
7874   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7875     if (isa<ConstantSDNode>(Inputs[i]))
7876       continue;
7877
7878     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7879                               UE = Inputs[i].getNode()->use_end();
7880          UI != UE; ++UI) {
7881       SDNode *User = *UI;
7882       if (User != N && !Visited.count(User))
7883         return SDValue();
7884
7885       // Make sure that we're not going to promote the non-output-value
7886       // operand(s) or SELECT or SELECT_CC.
7887       // FIXME: Although we could sometimes handle this, and it does occur in
7888       // practice that one of the condition inputs to the select is also one of
7889       // the outputs, we currently can't deal with this.
7890       if (User->getOpcode() == ISD::SELECT) {
7891         if (User->getOperand(0) == Inputs[i])
7892           return SDValue();
7893       } else if (User->getOpcode() == ISD::SELECT_CC) {
7894         if (User->getOperand(0) == Inputs[i] ||
7895             User->getOperand(1) == Inputs[i])
7896           return SDValue();
7897       }
7898     }
7899   }
7900
7901   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7902     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7903                               UE = PromOps[i].getNode()->use_end();
7904          UI != UE; ++UI) {
7905       SDNode *User = *UI;
7906       if (User != N && !Visited.count(User))
7907         return SDValue();
7908
7909       // Make sure that we're not going to promote the non-output-value
7910       // operand(s) or SELECT or SELECT_CC.
7911       // FIXME: Although we could sometimes handle this, and it does occur in
7912       // practice that one of the condition inputs to the select is also one of
7913       // the outputs, we currently can't deal with this.
7914       if (User->getOpcode() == ISD::SELECT) {
7915         if (User->getOperand(0) == PromOps[i])
7916           return SDValue();
7917       } else if (User->getOpcode() == ISD::SELECT_CC) {
7918         if (User->getOperand(0) == PromOps[i] ||
7919             User->getOperand(1) == PromOps[i])
7920           return SDValue();
7921       }
7922     }
7923   }
7924
7925   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
7926   bool ReallyNeedsExt = false;
7927   if (N->getOpcode() != ISD::ANY_EXTEND) {
7928     // If all of the inputs are not already sign/zero extended, then
7929     // we'll still need to do that at the end.
7930     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7931       if (isa<ConstantSDNode>(Inputs[i]))
7932         continue;
7933
7934       unsigned OpBits =
7935         Inputs[i].getOperand(0).getValueSizeInBits();
7936       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
7937
7938       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
7939            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
7940                                   APInt::getHighBitsSet(OpBits,
7941                                                         OpBits-PromBits))) ||
7942           (N->getOpcode() == ISD::SIGN_EXTEND &&
7943            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
7944              (OpBits-(PromBits-1)))) {
7945         ReallyNeedsExt = true;
7946         break;
7947       }
7948     }
7949   }
7950
7951   // Replace all inputs, either with the truncation operand, or a
7952   // truncation or extension to the final output type.
7953   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7954     // Constant inputs need to be replaced with the to-be-promoted nodes that
7955     // use them because they might have users outside of the cluster of
7956     // promoted nodes.
7957     if (isa<ConstantSDNode>(Inputs[i]))
7958       continue;
7959
7960     SDValue InSrc = Inputs[i].getOperand(0);
7961     if (Inputs[i].getValueType() == N->getValueType(0))
7962       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
7963     else if (N->getOpcode() == ISD::SIGN_EXTEND)
7964       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7965         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
7966     else if (N->getOpcode() == ISD::ZERO_EXTEND)
7967       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7968         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
7969     else
7970       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
7971         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
7972   }
7973
7974   // Replace all operations (these are all the same, but have a different
7975   // (promoted) return type). DAG.getNode will validate that the types of
7976   // a binary operator match, so go through the list in reverse so that
7977   // we've likely promoted both operands first.
7978   while (!PromOps.empty()) {
7979     SDValue PromOp = PromOps.back();
7980     PromOps.pop_back();
7981
7982     unsigned C;
7983     switch (PromOp.getOpcode()) {
7984     default:             C = 0; break;
7985     case ISD::SELECT:    C = 1; break;
7986     case ISD::SELECT_CC: C = 2; break;
7987     }
7988
7989     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7990          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
7991         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7992          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
7993       // The to-be-promoted operands of this node have not yet been
7994       // promoted (this should be rare because we're going through the
7995       // list backward, but if one of the operands has several users in
7996       // this cluster of to-be-promoted nodes, it is possible).
7997       PromOps.insert(PromOps.begin(), PromOp);
7998       continue;
7999     }
8000
8001     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8002                                 PromOp.getNode()->op_end());
8003
8004     // If this node has constant inputs, then they'll need to be promoted here.
8005     for (unsigned i = 0; i < 2; ++i) {
8006       if (!isa<ConstantSDNode>(Ops[C+i]))
8007         continue;
8008       if (Ops[C+i].getValueType() == N->getValueType(0))
8009         continue;
8010
8011       if (N->getOpcode() == ISD::SIGN_EXTEND)
8012         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8013       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8014         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8015       else
8016         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8017     }
8018
8019     DAG.ReplaceAllUsesOfValueWith(PromOp,
8020       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8021   }
8022
8023   // Now we're left with the initial extension itself.
8024   if (!ReallyNeedsExt)
8025     return N->getOperand(0);
8026
8027   // To zero extend, just mask off everything except for the first bit (in the
8028   // i1 case).
8029   if (N->getOpcode() == ISD::ZERO_EXTEND)
8030     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8031                        DAG.getConstant(APInt::getLowBitsSet(
8032                                          N->getValueSizeInBits(0), PromBits),
8033                                        N->getValueType(0)));
8034
8035   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8036          "Invalid extension type");
8037   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8038   SDValue ShiftCst =
8039     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8040   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8041                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8042                                  N->getOperand(0), ShiftCst), ShiftCst);
8043 }
8044
8045 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8046                                              DAGCombinerInfo &DCI) const {
8047   const TargetMachine &TM = getTargetMachine();
8048   SelectionDAG &DAG = DCI.DAG;
8049   SDLoc dl(N);
8050   switch (N->getOpcode()) {
8051   default: break;
8052   case PPCISD::SHL:
8053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8054       if (C->isNullValue())   // 0 << V -> 0.
8055         return N->getOperand(0);
8056     }
8057     break;
8058   case PPCISD::SRL:
8059     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8060       if (C->isNullValue())   // 0 >>u V -> 0.
8061         return N->getOperand(0);
8062     }
8063     break;
8064   case PPCISD::SRA:
8065     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8066       if (C->isNullValue() ||   //  0 >>s V -> 0.
8067           C->isAllOnesValue())    // -1 >>s V -> -1.
8068         return N->getOperand(0);
8069     }
8070     break;
8071   case ISD::SIGN_EXTEND:
8072   case ISD::ZERO_EXTEND:
8073   case ISD::ANY_EXTEND: 
8074     return DAGCombineExtBoolTrunc(N, DCI);
8075   case ISD::TRUNCATE:
8076   case ISD::SETCC:
8077   case ISD::SELECT_CC:
8078     return DAGCombineTruncBoolExt(N, DCI);
8079   case ISD::FDIV: {
8080     assert(TM.Options.UnsafeFPMath &&
8081            "Reciprocal estimates require UnsafeFPMath");
8082
8083     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8084       SDValue RV =
8085         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8086       if (RV.getNode()) {
8087         DCI.AddToWorklist(RV.getNode());
8088         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8089                            N->getOperand(0), RV);
8090       }
8091     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8092                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8093       SDValue RV =
8094         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8095                                  DCI);
8096       if (RV.getNode()) {
8097         DCI.AddToWorklist(RV.getNode());
8098         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8099                          N->getValueType(0), RV);
8100         DCI.AddToWorklist(RV.getNode());
8101         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8102                            N->getOperand(0), RV);
8103       }
8104     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8105                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8106       SDValue RV =
8107         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8108                                  DCI);
8109       if (RV.getNode()) {
8110         DCI.AddToWorklist(RV.getNode());
8111         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8112                          N->getValueType(0), RV,
8113                          N->getOperand(1).getOperand(1));
8114         DCI.AddToWorklist(RV.getNode());
8115         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8116                            N->getOperand(0), RV);
8117       }
8118     }
8119
8120     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8121     if (RV.getNode()) {
8122       DCI.AddToWorklist(RV.getNode());
8123       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8124                          N->getOperand(0), RV);
8125     }
8126
8127     }
8128     break;
8129   case ISD::FSQRT: {
8130     assert(TM.Options.UnsafeFPMath &&
8131            "Reciprocal estimates require UnsafeFPMath");
8132
8133     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8134     // reciprocal sqrt.
8135     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8136     if (RV.getNode()) {
8137       DCI.AddToWorklist(RV.getNode());
8138       RV = DAGCombineFastRecip(RV, DCI);
8139       if (RV.getNode()) {
8140         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8141         // this case and force the answer to 0.
8142
8143         EVT VT = RV.getValueType();
8144
8145         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8146         if (VT.isVector()) {
8147           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8148           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8149         }
8150
8151         SDValue ZeroCmp =
8152           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8153                        N->getOperand(0), Zero, ISD::SETEQ);
8154         DCI.AddToWorklist(ZeroCmp.getNode());
8155         DCI.AddToWorklist(RV.getNode());
8156
8157         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8158                          ZeroCmp, Zero, RV);
8159         return RV;
8160       }
8161     }
8162
8163     }
8164     break;
8165   case ISD::SINT_TO_FP:
8166     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8167       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8168         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8169         // We allow the src/dst to be either f32/f64, but the intermediate
8170         // type must be i64.
8171         if (N->getOperand(0).getValueType() == MVT::i64 &&
8172             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8173           SDValue Val = N->getOperand(0).getOperand(0);
8174           if (Val.getValueType() == MVT::f32) {
8175             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8176             DCI.AddToWorklist(Val.getNode());
8177           }
8178
8179           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8180           DCI.AddToWorklist(Val.getNode());
8181           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8182           DCI.AddToWorklist(Val.getNode());
8183           if (N->getValueType(0) == MVT::f32) {
8184             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8185                               DAG.getIntPtrConstant(0));
8186             DCI.AddToWorklist(Val.getNode());
8187           }
8188           return Val;
8189         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8190           // If the intermediate type is i32, we can avoid the load/store here
8191           // too.
8192         }
8193       }
8194     }
8195     break;
8196   case ISD::STORE:
8197     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8198     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8199         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8200         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8201         N->getOperand(1).getValueType() == MVT::i32 &&
8202         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8203       SDValue Val = N->getOperand(1).getOperand(0);
8204       if (Val.getValueType() == MVT::f32) {
8205         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8206         DCI.AddToWorklist(Val.getNode());
8207       }
8208       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8209       DCI.AddToWorklist(Val.getNode());
8210
8211       SDValue Ops[] = {
8212         N->getOperand(0), Val, N->getOperand(2),
8213         DAG.getValueType(N->getOperand(1).getValueType())
8214       };
8215
8216       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8217               DAG.getVTList(MVT::Other), Ops,
8218               cast<StoreSDNode>(N)->getMemoryVT(),
8219               cast<StoreSDNode>(N)->getMemOperand());
8220       DCI.AddToWorklist(Val.getNode());
8221       return Val;
8222     }
8223
8224     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8225     if (cast<StoreSDNode>(N)->isUnindexed() &&
8226         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8227         N->getOperand(1).getNode()->hasOneUse() &&
8228         (N->getOperand(1).getValueType() == MVT::i32 ||
8229          N->getOperand(1).getValueType() == MVT::i16 ||
8230          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8231           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8232           N->getOperand(1).getValueType() == MVT::i64))) {
8233       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8234       // Do an any-extend to 32-bits if this is a half-word input.
8235       if (BSwapOp.getValueType() == MVT::i16)
8236         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8237
8238       SDValue Ops[] = {
8239         N->getOperand(0), BSwapOp, N->getOperand(2),
8240         DAG.getValueType(N->getOperand(1).getValueType())
8241       };
8242       return
8243         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8244                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8245                                 cast<StoreSDNode>(N)->getMemOperand());
8246     }
8247     break;
8248   case ISD::LOAD: {
8249     LoadSDNode *LD = cast<LoadSDNode>(N);
8250     EVT VT = LD->getValueType(0);
8251     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8252     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8253     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8254         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8255         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8256          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8257         LD->getAlignment() < ABIAlignment) {
8258       // This is a type-legal unaligned Altivec load.
8259       SDValue Chain = LD->getChain();
8260       SDValue Ptr = LD->getBasePtr();
8261       bool isLittleEndian = Subtarget.isLittleEndian();
8262
8263       // This implements the loading of unaligned vectors as described in
8264       // the venerable Apple Velocity Engine overview. Specifically:
8265       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8266       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8267       //
8268       // The general idea is to expand a sequence of one or more unaligned
8269       // loads into an alignment-based permutation-control instruction (lvsl
8270       // or lvsr), a series of regular vector loads (which always truncate
8271       // their input address to an aligned address), and a series of
8272       // permutations.  The results of these permutations are the requested
8273       // loaded values.  The trick is that the last "extra" load is not taken
8274       // from the address you might suspect (sizeof(vector) bytes after the
8275       // last requested load), but rather sizeof(vector) - 1 bytes after the
8276       // last requested vector. The point of this is to avoid a page fault if
8277       // the base address happened to be aligned. This works because if the
8278       // base address is aligned, then adding less than a full vector length
8279       // will cause the last vector in the sequence to be (re)loaded.
8280       // Otherwise, the next vector will be fetched as you might suspect was
8281       // necessary.
8282
8283       // We might be able to reuse the permutation generation from
8284       // a different base address offset from this one by an aligned amount.
8285       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8286       // optimization later.
8287       Intrinsic::ID Intr = (isLittleEndian ?
8288                             Intrinsic::ppc_altivec_lvsr :
8289                             Intrinsic::ppc_altivec_lvsl);
8290       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8291
8292       // Refine the alignment of the original load (a "new" load created here
8293       // which was identical to the first except for the alignment would be
8294       // merged with the existing node regardless).
8295       MachineFunction &MF = DAG.getMachineFunction();
8296       MachineMemOperand *MMO =
8297         MF.getMachineMemOperand(LD->getPointerInfo(),
8298                                 LD->getMemOperand()->getFlags(),
8299                                 LD->getMemoryVT().getStoreSize(),
8300                                 ABIAlignment);
8301       LD->refineAlignment(MMO);
8302       SDValue BaseLoad = SDValue(LD, 0);
8303
8304       // Note that the value of IncOffset (which is provided to the next
8305       // load's pointer info offset value, and thus used to calculate the
8306       // alignment), and the value of IncValue (which is actually used to
8307       // increment the pointer value) are different! This is because we
8308       // require the next load to appear to be aligned, even though it
8309       // is actually offset from the base pointer by a lesser amount.
8310       int IncOffset = VT.getSizeInBits() / 8;
8311       int IncValue = IncOffset;
8312
8313       // Walk (both up and down) the chain looking for another load at the real
8314       // (aligned) offset (the alignment of the other load does not matter in
8315       // this case). If found, then do not use the offset reduction trick, as
8316       // that will prevent the loads from being later combined (as they would
8317       // otherwise be duplicates).
8318       if (!findConsecutiveLoad(LD, DAG))
8319         --IncValue;
8320
8321       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8322       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8323
8324       SDValue ExtraLoad =
8325         DAG.getLoad(VT, dl, Chain, Ptr,
8326                     LD->getPointerInfo().getWithOffset(IncOffset),
8327                     LD->isVolatile(), LD->isNonTemporal(),
8328                     LD->isInvariant(), ABIAlignment);
8329
8330       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8331         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8332
8333       if (BaseLoad.getValueType() != MVT::v4i32)
8334         BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
8335
8336       if (ExtraLoad.getValueType() != MVT::v4i32)
8337         ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
8338
8339       // Because vperm has a big-endian bias, we must reverse the order
8340       // of the input vectors and complement the permute control vector
8341       // when generating little endian code.  We have already handled the
8342       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8343       // and ExtraLoad here.
8344       SDValue Perm;
8345       if (isLittleEndian)
8346         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8347                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8348       else
8349         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8350                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8351
8352       if (VT != MVT::v4i32)
8353         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8354
8355       // Now we need to be really careful about how we update the users of the
8356       // original load. We cannot just call DCI.CombineTo (or
8357       // DAG.ReplaceAllUsesWith for that matter), because the load still has
8358       // uses created here (the permutation for example) that need to stay.
8359       SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8360       while (UI != UE) {
8361         SDUse &Use = UI.getUse();
8362         SDNode *User = *UI;
8363         // Note: BaseLoad is checked here because it might not be N, but a
8364         // bitcast of N.
8365         if (User == Perm.getNode() || User == BaseLoad.getNode() ||
8366             User == TF.getNode() || Use.getResNo() > 1) {
8367           ++UI;
8368           continue;
8369         }
8370
8371         SDValue To = Use.getResNo() ? TF : Perm;
8372         ++UI;
8373
8374         SmallVector<SDValue, 8> Ops;
8375         for (const SDUse &O : User->ops()) {
8376           if (O == Use)
8377             Ops.push_back(To);
8378           else
8379             Ops.push_back(O);
8380         }
8381
8382         DAG.UpdateNodeOperands(User, Ops);
8383       }
8384
8385       return SDValue(N, 0);
8386     }
8387     }
8388     break;
8389   case ISD::INTRINSIC_WO_CHAIN: {
8390     bool isLittleEndian = Subtarget.isLittleEndian();
8391     Intrinsic::ID Intr = (isLittleEndian ?
8392                           Intrinsic::ppc_altivec_lvsr :
8393                           Intrinsic::ppc_altivec_lvsl);
8394     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8395         N->getOperand(1)->getOpcode() == ISD::ADD) {
8396       SDValue Add = N->getOperand(1);
8397
8398       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8399             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8400               Add.getValueType().getScalarType().getSizeInBits()))) {
8401         SDNode *BasePtr = Add->getOperand(0).getNode();
8402         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8403              UE = BasePtr->use_end(); UI != UE; ++UI) {
8404           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8405               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8406                 Intr) {
8407             // We've found another LVSL/LVSR, and this address is an aligned
8408             // multiple of that one. The results will be the same, so use the
8409             // one we've just found instead.
8410
8411             return SDValue(*UI, 0);
8412           }
8413         }
8414       }
8415     }
8416     }
8417
8418     break;
8419   case ISD::BSWAP:
8420     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8421     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8422         N->getOperand(0).hasOneUse() &&
8423         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8424          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8425           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8426           N->getValueType(0) == MVT::i64))) {
8427       SDValue Load = N->getOperand(0);
8428       LoadSDNode *LD = cast<LoadSDNode>(Load);
8429       // Create the byte-swapping load.
8430       SDValue Ops[] = {
8431         LD->getChain(),    // Chain
8432         LD->getBasePtr(),  // Ptr
8433         DAG.getValueType(N->getValueType(0)) // VT
8434       };
8435       SDValue BSLoad =
8436         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8437                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8438                                               MVT::i64 : MVT::i32, MVT::Other),
8439                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8440
8441       // If this is an i16 load, insert the truncate.
8442       SDValue ResVal = BSLoad;
8443       if (N->getValueType(0) == MVT::i16)
8444         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8445
8446       // First, combine the bswap away.  This makes the value produced by the
8447       // load dead.
8448       DCI.CombineTo(N, ResVal);
8449
8450       // Next, combine the load away, we give it a bogus result value but a real
8451       // chain result.  The result value is dead because the bswap is dead.
8452       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8453
8454       // Return N so it doesn't get rechecked!
8455       return SDValue(N, 0);
8456     }
8457
8458     break;
8459   case PPCISD::VCMP: {
8460     // If a VCMPo node already exists with exactly the same operands as this
8461     // node, use its result instead of this node (VCMPo computes both a CR6 and
8462     // a normal output).
8463     //
8464     if (!N->getOperand(0).hasOneUse() &&
8465         !N->getOperand(1).hasOneUse() &&
8466         !N->getOperand(2).hasOneUse()) {
8467
8468       // Scan all of the users of the LHS, looking for VCMPo's that match.
8469       SDNode *VCMPoNode = nullptr;
8470
8471       SDNode *LHSN = N->getOperand(0).getNode();
8472       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8473            UI != E; ++UI)
8474         if (UI->getOpcode() == PPCISD::VCMPo &&
8475             UI->getOperand(1) == N->getOperand(1) &&
8476             UI->getOperand(2) == N->getOperand(2) &&
8477             UI->getOperand(0) == N->getOperand(0)) {
8478           VCMPoNode = *UI;
8479           break;
8480         }
8481
8482       // If there is no VCMPo node, or if the flag value has a single use, don't
8483       // transform this.
8484       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8485         break;
8486
8487       // Look at the (necessarily single) use of the flag value.  If it has a
8488       // chain, this transformation is more complex.  Note that multiple things
8489       // could use the value result, which we should ignore.
8490       SDNode *FlagUser = nullptr;
8491       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8492            FlagUser == nullptr; ++UI) {
8493         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8494         SDNode *User = *UI;
8495         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8496           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8497             FlagUser = User;
8498             break;
8499           }
8500         }
8501       }
8502
8503       // If the user is a MFOCRF instruction, we know this is safe.
8504       // Otherwise we give up for right now.
8505       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8506         return SDValue(VCMPoNode, 0);
8507     }
8508     break;
8509   }
8510   case ISD::BRCOND: {
8511     SDValue Cond = N->getOperand(1);
8512     SDValue Target = N->getOperand(2);
8513  
8514     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8515         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8516           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8517
8518       // We now need to make the intrinsic dead (it cannot be instruction
8519       // selected).
8520       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8521       assert(Cond.getNode()->hasOneUse() &&
8522              "Counter decrement has more than one use");
8523
8524       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8525                          N->getOperand(0), Target);
8526     }
8527   }
8528   break;
8529   case ISD::BR_CC: {
8530     // If this is a branch on an altivec predicate comparison, lower this so
8531     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8532     // lowering is done pre-legalize, because the legalizer lowers the predicate
8533     // compare down to code that is difficult to reassemble.
8534     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8535     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8536
8537     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8538     // value. If so, pass-through the AND to get to the intrinsic.
8539     if (LHS.getOpcode() == ISD::AND &&
8540         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8541         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8542           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8543         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8544         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8545           isZero())
8546       LHS = LHS.getOperand(0);
8547
8548     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8549         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8550           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8551         isa<ConstantSDNode>(RHS)) {
8552       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8553              "Counter decrement comparison is not EQ or NE");
8554
8555       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8556       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8557                     (CC == ISD::SETNE && !Val);
8558
8559       // We now need to make the intrinsic dead (it cannot be instruction
8560       // selected).
8561       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8562       assert(LHS.getNode()->hasOneUse() &&
8563              "Counter decrement has more than one use");
8564
8565       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8566                          N->getOperand(0), N->getOperand(4));
8567     }
8568
8569     int CompareOpc;
8570     bool isDot;
8571
8572     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8573         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8574         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8575       assert(isDot && "Can't compare against a vector result!");
8576
8577       // If this is a comparison against something other than 0/1, then we know
8578       // that the condition is never/always true.
8579       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8580       if (Val != 0 && Val != 1) {
8581         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8582           return N->getOperand(0);
8583         // Always !=, turn it into an unconditional branch.
8584         return DAG.getNode(ISD::BR, dl, MVT::Other,
8585                            N->getOperand(0), N->getOperand(4));
8586       }
8587
8588       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8589
8590       // Create the PPCISD altivec 'dot' comparison node.
8591       SDValue Ops[] = {
8592         LHS.getOperand(2),  // LHS of compare
8593         LHS.getOperand(3),  // RHS of compare
8594         DAG.getConstant(CompareOpc, MVT::i32)
8595       };
8596       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8597       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8598
8599       // Unpack the result based on how the target uses it.
8600       PPC::Predicate CompOpc;
8601       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8602       default:  // Can't happen, don't crash on invalid number though.
8603       case 0:   // Branch on the value of the EQ bit of CR6.
8604         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8605         break;
8606       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8607         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8608         break;
8609       case 2:   // Branch on the value of the LT bit of CR6.
8610         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8611         break;
8612       case 3:   // Branch on the inverted value of the LT bit of CR6.
8613         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8614         break;
8615       }
8616
8617       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8618                          DAG.getConstant(CompOpc, MVT::i32),
8619                          DAG.getRegister(PPC::CR6, MVT::i32),
8620                          N->getOperand(4), CompNode.getValue(1));
8621     }
8622     break;
8623   }
8624   }
8625
8626   return SDValue();
8627 }
8628
8629 //===----------------------------------------------------------------------===//
8630 // Inline Assembly Support
8631 //===----------------------------------------------------------------------===//
8632
8633 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8634                                                       APInt &KnownZero,
8635                                                       APInt &KnownOne,
8636                                                       const SelectionDAG &DAG,
8637                                                       unsigned Depth) const {
8638   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8639   switch (Op.getOpcode()) {
8640   default: break;
8641   case PPCISD::LBRX: {
8642     // lhbrx is known to have the top bits cleared out.
8643     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8644       KnownZero = 0xFFFF0000;
8645     break;
8646   }
8647   case ISD::INTRINSIC_WO_CHAIN: {
8648     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8649     default: break;
8650     case Intrinsic::ppc_altivec_vcmpbfp_p:
8651     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8652     case Intrinsic::ppc_altivec_vcmpequb_p:
8653     case Intrinsic::ppc_altivec_vcmpequh_p:
8654     case Intrinsic::ppc_altivec_vcmpequw_p:
8655     case Intrinsic::ppc_altivec_vcmpgefp_p:
8656     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8657     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8658     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8659     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8660     case Intrinsic::ppc_altivec_vcmpgtub_p:
8661     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8662     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8663       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8664       break;
8665     }
8666   }
8667   }
8668 }
8669
8670
8671 /// getConstraintType - Given a constraint, return the type of
8672 /// constraint it is for this target.
8673 PPCTargetLowering::ConstraintType
8674 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8675   if (Constraint.size() == 1) {
8676     switch (Constraint[0]) {
8677     default: break;
8678     case 'b':
8679     case 'r':
8680     case 'f':
8681     case 'v':
8682     case 'y':
8683       return C_RegisterClass;
8684     case 'Z':
8685       // FIXME: While Z does indicate a memory constraint, it specifically
8686       // indicates an r+r address (used in conjunction with the 'y' modifier
8687       // in the replacement string). Currently, we're forcing the base
8688       // register to be r0 in the asm printer (which is interpreted as zero)
8689       // and forming the complete address in the second register. This is
8690       // suboptimal.
8691       return C_Memory;
8692     }
8693   } else if (Constraint == "wc") { // individual CR bits.
8694     return C_RegisterClass;
8695   } else if (Constraint == "wa" || Constraint == "wd" ||
8696              Constraint == "wf" || Constraint == "ws") {
8697     return C_RegisterClass; // VSX registers.
8698   }
8699   return TargetLowering::getConstraintType(Constraint);
8700 }
8701
8702 /// Examine constraint type and operand type and determine a weight value.
8703 /// This object must already have been set up with the operand type
8704 /// and the current alternative constraint selected.
8705 TargetLowering::ConstraintWeight
8706 PPCTargetLowering::getSingleConstraintMatchWeight(
8707     AsmOperandInfo &info, const char *constraint) const {
8708   ConstraintWeight weight = CW_Invalid;
8709   Value *CallOperandVal = info.CallOperandVal;
8710     // If we don't have a value, we can't do a match,
8711     // but allow it at the lowest weight.
8712   if (!CallOperandVal)
8713     return CW_Default;
8714   Type *type = CallOperandVal->getType();
8715
8716   // Look at the constraint type.
8717   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8718     return CW_Register; // an individual CR bit.
8719   else if ((StringRef(constraint) == "wa" ||
8720             StringRef(constraint) == "wd" ||
8721             StringRef(constraint) == "wf") &&
8722            type->isVectorTy())
8723     return CW_Register;
8724   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8725     return CW_Register;
8726
8727   switch (*constraint) {
8728   default:
8729     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8730     break;
8731   case 'b':
8732     if (type->isIntegerTy())
8733       weight = CW_Register;
8734     break;
8735   case 'f':
8736     if (type->isFloatTy())
8737       weight = CW_Register;
8738     break;
8739   case 'd':
8740     if (type->isDoubleTy())
8741       weight = CW_Register;
8742     break;
8743   case 'v':
8744     if (type->isVectorTy())
8745       weight = CW_Register;
8746     break;
8747   case 'y':
8748     weight = CW_Register;
8749     break;
8750   case 'Z':
8751     weight = CW_Memory;
8752     break;
8753   }
8754   return weight;
8755 }
8756
8757 std::pair<unsigned, const TargetRegisterClass*>
8758 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8759                                                 MVT VT) const {
8760   if (Constraint.size() == 1) {
8761     // GCC RS6000 Constraint Letters
8762     switch (Constraint[0]) {
8763     case 'b':   // R1-R31
8764       if (VT == MVT::i64 && Subtarget.isPPC64())
8765         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8766       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8767     case 'r':   // R0-R31
8768       if (VT == MVT::i64 && Subtarget.isPPC64())
8769         return std::make_pair(0U, &PPC::G8RCRegClass);
8770       return std::make_pair(0U, &PPC::GPRCRegClass);
8771     case 'f':
8772       if (VT == MVT::f32 || VT == MVT::i32)
8773         return std::make_pair(0U, &PPC::F4RCRegClass);
8774       if (VT == MVT::f64 || VT == MVT::i64)
8775         return std::make_pair(0U, &PPC::F8RCRegClass);
8776       break;
8777     case 'v':
8778       return std::make_pair(0U, &PPC::VRRCRegClass);
8779     case 'y':   // crrc
8780       return std::make_pair(0U, &PPC::CRRCRegClass);
8781     }
8782   } else if (Constraint == "wc") { // an individual CR bit.
8783     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8784   } else if (Constraint == "wa" || Constraint == "wd" ||
8785              Constraint == "wf") {
8786     return std::make_pair(0U, &PPC::VSRCRegClass);
8787   } else if (Constraint == "ws") {
8788     return std::make_pair(0U, &PPC::VSFRCRegClass);
8789   }
8790
8791   std::pair<unsigned, const TargetRegisterClass*> R =
8792     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8793
8794   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8795   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8796   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8797   // register.
8798   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8799   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8800   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8801       PPC::GPRCRegClass.contains(R.first)) {
8802     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8803     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8804                             PPC::sub_32, &PPC::G8RCRegClass),
8805                           &PPC::G8RCRegClass);
8806   }
8807
8808   return R;
8809 }
8810
8811
8812 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8813 /// vector.  If it is invalid, don't add anything to Ops.
8814 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8815                                                      std::string &Constraint,
8816                                                      std::vector<SDValue>&Ops,
8817                                                      SelectionDAG &DAG) const {
8818   SDValue Result;
8819
8820   // Only support length 1 constraints.
8821   if (Constraint.length() > 1) return;
8822
8823   char Letter = Constraint[0];
8824   switch (Letter) {
8825   default: break;
8826   case 'I':
8827   case 'J':
8828   case 'K':
8829   case 'L':
8830   case 'M':
8831   case 'N':
8832   case 'O':
8833   case 'P': {
8834     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
8835     if (!CST) return; // Must be an immediate to match.
8836     unsigned Value = CST->getZExtValue();
8837     switch (Letter) {
8838     default: llvm_unreachable("Unknown constraint letter!");
8839     case 'I':  // "I" is a signed 16-bit constant.
8840       if ((short)Value == (int)Value)
8841         Result = DAG.getTargetConstant(Value, Op.getValueType());
8842       break;
8843     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
8844     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
8845       if ((short)Value == 0)
8846         Result = DAG.getTargetConstant(Value, Op.getValueType());
8847       break;
8848     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
8849       if ((Value >> 16) == 0)
8850         Result = DAG.getTargetConstant(Value, Op.getValueType());
8851       break;
8852     case 'M':  // "M" is a constant that is greater than 31.
8853       if (Value > 31)
8854         Result = DAG.getTargetConstant(Value, Op.getValueType());
8855       break;
8856     case 'N':  // "N" is a positive constant that is an exact power of two.
8857       if ((int)Value > 0 && isPowerOf2_32(Value))
8858         Result = DAG.getTargetConstant(Value, Op.getValueType());
8859       break;
8860     case 'O':  // "O" is the constant zero.
8861       if (Value == 0)
8862         Result = DAG.getTargetConstant(Value, Op.getValueType());
8863       break;
8864     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
8865       if ((short)-Value == (int)-Value)
8866         Result = DAG.getTargetConstant(Value, Op.getValueType());
8867       break;
8868     }
8869     break;
8870   }
8871   }
8872
8873   if (Result.getNode()) {
8874     Ops.push_back(Result);
8875     return;
8876   }
8877
8878   // Handle standard constraint letters.
8879   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
8880 }
8881
8882 // isLegalAddressingMode - Return true if the addressing mode represented
8883 // by AM is legal for this target, for a load/store of the specified type.
8884 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
8885                                               Type *Ty) const {
8886   // FIXME: PPC does not allow r+i addressing modes for vectors!
8887
8888   // PPC allows a sign-extended 16-bit immediate field.
8889   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
8890     return false;
8891
8892   // No global is ever allowed as a base.
8893   if (AM.BaseGV)
8894     return false;
8895
8896   // PPC only support r+r,
8897   switch (AM.Scale) {
8898   case 0:  // "r+i" or just "i", depending on HasBaseReg.
8899     break;
8900   case 1:
8901     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
8902       return false;
8903     // Otherwise we have r+r or r+i.
8904     break;
8905   case 2:
8906     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
8907       return false;
8908     // Allow 2*r as r+r.
8909     break;
8910   default:
8911     // No other scales are supported.
8912     return false;
8913   }
8914
8915   return true;
8916 }
8917
8918 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
8919                                            SelectionDAG &DAG) const {
8920   MachineFunction &MF = DAG.getMachineFunction();
8921   MachineFrameInfo *MFI = MF.getFrameInfo();
8922   MFI->setReturnAddressIsTaken(true);
8923
8924   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
8925     return SDValue();
8926
8927   SDLoc dl(Op);
8928   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8929
8930   // Make sure the function does not optimize away the store of the RA to
8931   // the stack.
8932   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
8933   FuncInfo->setLRStoreRequired();
8934   bool isPPC64 = Subtarget.isPPC64();
8935   bool isDarwinABI = Subtarget.isDarwinABI();
8936
8937   if (Depth > 0) {
8938     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
8939     SDValue Offset =
8940
8941       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
8942                       isPPC64? MVT::i64 : MVT::i32);
8943     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8944                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
8945                                    FrameAddr, Offset),
8946                        MachinePointerInfo(), false, false, false, 0);
8947   }
8948
8949   // Just load the return address off the stack.
8950   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
8951   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
8952                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
8953 }
8954
8955 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
8956                                           SelectionDAG &DAG) const {
8957   SDLoc dl(Op);
8958   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8959
8960   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
8961   bool isPPC64 = PtrVT == MVT::i64;
8962
8963   MachineFunction &MF = DAG.getMachineFunction();
8964   MachineFrameInfo *MFI = MF.getFrameInfo();
8965   MFI->setFrameAddressIsTaken(true);
8966
8967   // Naked functions never have a frame pointer, and so we use r1. For all
8968   // other functions, this decision must be delayed until during PEI.
8969   unsigned FrameReg;
8970   if (MF.getFunction()->getAttributes().hasAttribute(
8971         AttributeSet::FunctionIndex, Attribute::Naked))
8972     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
8973   else
8974     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
8975
8976   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
8977                                          PtrVT);
8978   while (Depth--)
8979     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
8980                             FrameAddr, MachinePointerInfo(), false, false,
8981                             false, 0);
8982   return FrameAddr;
8983 }
8984
8985 // FIXME? Maybe this could be a TableGen attribute on some registers and
8986 // this table could be generated automatically from RegInfo.
8987 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
8988                                               EVT VT) const {
8989   bool isPPC64 = Subtarget.isPPC64();
8990   bool isDarwinABI = Subtarget.isDarwinABI();
8991
8992   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
8993       (!isPPC64 && VT != MVT::i32))
8994     report_fatal_error("Invalid register global variable type");
8995
8996   bool is64Bit = isPPC64 && VT == MVT::i64;
8997   unsigned Reg = StringSwitch<unsigned>(RegName)
8998                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
8999                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9000                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9001                                   (is64Bit ? PPC::X13 : PPC::R13))
9002                    .Default(0);
9003
9004   if (Reg)
9005     return Reg;
9006   report_fatal_error("Invalid register name global variable");
9007 }
9008
9009 bool
9010 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9011   // The PowerPC target isn't yet aware of offsets.
9012   return false;
9013 }
9014
9015 /// getOptimalMemOpType - Returns the target specific optimal type for load
9016 /// and store operations as a result of memset, memcpy, and memmove
9017 /// lowering. If DstAlign is zero that means it's safe to destination
9018 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9019 /// means there isn't a need to check it against alignment requirement,
9020 /// probably because the source does not need to be loaded. If 'IsMemset' is
9021 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9022 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9023 /// source is constant so it does not need to be loaded.
9024 /// It returns EVT::Other if the type should be determined using generic
9025 /// target-independent logic.
9026 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9027                                            unsigned DstAlign, unsigned SrcAlign,
9028                                            bool IsMemset, bool ZeroMemset,
9029                                            bool MemcpyStrSrc,
9030                                            MachineFunction &MF) const {
9031   if (Subtarget.isPPC64()) {
9032     return MVT::i64;
9033   } else {
9034     return MVT::i32;
9035   }
9036 }
9037
9038 /// \brief Returns true if it is beneficial to convert a load of a constant
9039 /// to just the constant itself.
9040 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9041                                                           Type *Ty) const {
9042   assert(Ty->isIntegerTy());
9043
9044   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9045   if (BitSize == 0 || BitSize > 64)
9046     return false;
9047   return true;
9048 }
9049
9050 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9051   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9052     return false;
9053   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9054   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9055   return NumBits1 == 64 && NumBits2 == 32;
9056 }
9057
9058 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9059   if (!VT1.isInteger() || !VT2.isInteger())
9060     return false;
9061   unsigned NumBits1 = VT1.getSizeInBits();
9062   unsigned NumBits2 = VT2.getSizeInBits();
9063   return NumBits1 == 64 && NumBits2 == 32;
9064 }
9065
9066 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9067   return isInt<16>(Imm) || isUInt<16>(Imm);
9068 }
9069
9070 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9071   return isInt<16>(Imm) || isUInt<16>(Imm);
9072 }
9073
9074 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
9075                                                       unsigned,
9076                                                       bool *Fast) const {
9077   if (DisablePPCUnaligned)
9078     return false;
9079
9080   // PowerPC supports unaligned memory access for simple non-vector types.
9081   // Although accessing unaligned addresses is not as efficient as accessing
9082   // aligned addresses, it is generally more efficient than manual expansion,
9083   // and generally only traps for software emulation when crossing page
9084   // boundaries.
9085
9086   if (!VT.isSimple())
9087     return false;
9088
9089   if (VT.getSimpleVT().isVector()) {
9090     if (Subtarget.hasVSX()) {
9091       if (VT != MVT::v2f64 && VT != MVT::v2i64)
9092         return false;
9093     } else {
9094       return false;
9095     }
9096   }
9097
9098   if (VT == MVT::ppcf128)
9099     return false;
9100
9101   if (Fast)
9102     *Fast = true;
9103
9104   return true;
9105 }
9106
9107 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9108   VT = VT.getScalarType();
9109
9110   if (!VT.isSimple())
9111     return false;
9112
9113   switch (VT.getSimpleVT().SimpleTy) {
9114   case MVT::f32:
9115   case MVT::f64:
9116     return true;
9117   default:
9118     break;
9119   }
9120
9121   return false;
9122 }
9123
9124 bool
9125 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9126                      EVT VT , unsigned DefinedValues) const {
9127   if (VT == MVT::v2i64)
9128     return false;
9129
9130   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9131 }
9132
9133 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9134   if (DisableILPPref || Subtarget.enableMachineScheduler())
9135     return TargetLowering::getSchedulingPreference(N);
9136
9137   return Sched::ILP;
9138 }
9139
9140 // Create a fast isel object.
9141 FastISel *
9142 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9143                                   const TargetLibraryInfo *LibInfo) const {
9144   return PPC::createFastISel(FuncInfo, LibInfo);
9145 }