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