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