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