Reinstate "Nuke the old JIT."
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 // FIXME: Remove this once soft-float is supported.
43 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
44 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
45
46 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
47 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
48
49 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
50 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
51
52 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
53 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
54
55 // FIXME: Remove this once the bug has been fixed!
56 extern cl::opt<bool> ANDIGlueBug;
57
58 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
59   // If it isn't a Mach-O file then it's going to be a linux ELF
60   // object file.
61   if (TT.isOSDarwin())
62     return new TargetLoweringObjectFileMachO();
63
64   return new PPC64LinuxTargetObjectFile();
65 }
66
67 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
68     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
69       Subtarget(*TM.getSubtargetImpl()) {
70   setPow2SDivIsCheap();
71
72   // Use _setjmp/_longjmp instead of setjmp/longjmp.
73   setUseUnderscoreSetJmp(true);
74   setUseUnderscoreLongJmp(true);
75
76   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77   // arguments are at least 4/8 bytes aligned.
78   bool isPPC64 = Subtarget.isPPC64();
79   setMinStackArgumentAlignment(isPPC64 ? 8:4);
80
81   // Set up the register classes.
82   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
83   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
84   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
85
86   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
87   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
88   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
89
90   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
91
92   // PowerPC has pre-inc load and store's.
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
94   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
95   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
96   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
97   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
99   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
100   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
101   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
102   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
103
104   if (Subtarget.useCRBits()) {
105     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
106
107     if (isPPC64 || Subtarget.hasFPCVT()) {
108       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
109       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
110                          isPPC64 ? MVT::i64 : MVT::i32);
111       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
112       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
113                          isPPC64 ? MVT::i64 : MVT::i32);
114     } else {
115       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
116       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
117     }
118
119     // PowerPC does not support direct load / store of condition registers
120     setOperationAction(ISD::LOAD, MVT::i1, Custom);
121     setOperationAction(ISD::STORE, MVT::i1, Custom);
122
123     // FIXME: Remove this once the ANDI glue bug is fixed:
124     if (ANDIGlueBug)
125       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
126
127     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
128     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
129     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
130     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
131     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
132     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
133
134     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
135   }
136
137   // This is used in the ppcf128->int sequence.  Note it has different semantics
138   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
139   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
140
141   // We do not currently implement these libm ops for PowerPC.
142   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
144   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
145   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
146   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
147   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
148
149   // PowerPC has no SREM/UREM instructions
150   setOperationAction(ISD::SREM, MVT::i32, Expand);
151   setOperationAction(ISD::UREM, MVT::i32, Expand);
152   setOperationAction(ISD::SREM, MVT::i64, Expand);
153   setOperationAction(ISD::UREM, MVT::i64, Expand);
154
155   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
156   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
157   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
158   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
159   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
160   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
161   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
162   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
163   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
164
165   // We don't support sin/cos/sqrt/fmod/pow
166   setOperationAction(ISD::FSIN , MVT::f64, Expand);
167   setOperationAction(ISD::FCOS , MVT::f64, Expand);
168   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
169   setOperationAction(ISD::FREM , MVT::f64, Expand);
170   setOperationAction(ISD::FPOW , MVT::f64, Expand);
171   setOperationAction(ISD::FMA  , MVT::f64, Legal);
172   setOperationAction(ISD::FSIN , MVT::f32, Expand);
173   setOperationAction(ISD::FCOS , MVT::f32, Expand);
174   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
175   setOperationAction(ISD::FREM , MVT::f32, Expand);
176   setOperationAction(ISD::FPOW , MVT::f32, Expand);
177   setOperationAction(ISD::FMA  , MVT::f32, Legal);
178
179   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
180
181   // If we're enabling GP optimizations, use hardware square root
182   if (!Subtarget.hasFSQRT() &&
183       !(TM.Options.UnsafeFPMath &&
184         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
185     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
186
187   if (!Subtarget.hasFSQRT() &&
188       !(TM.Options.UnsafeFPMath &&
189         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
190     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
191
192   if (Subtarget.hasFCPSGN()) {
193     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
194     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
195   } else {
196     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
197     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
198   }
199
200   if (Subtarget.hasFPRND()) {
201     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
202     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
203     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
204     setOperationAction(ISD::FROUND, MVT::f64, Legal);
205
206     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
207     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
208     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
209     setOperationAction(ISD::FROUND, MVT::f32, Legal);
210   }
211
212   // PowerPC does not have BSWAP, CTPOP or CTTZ
213   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
217   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
218   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
219   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
220   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
221
222   if (Subtarget.hasPOPCNTD()) {
223     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
224     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
225   } else {
226     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
227     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
228   }
229
230   // PowerPC does not have ROTR
231   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
232   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
233
234   if (!Subtarget.useCRBits()) {
235     // PowerPC does not have Select
236     setOperationAction(ISD::SELECT, MVT::i32, Expand);
237     setOperationAction(ISD::SELECT, MVT::i64, Expand);
238     setOperationAction(ISD::SELECT, MVT::f32, Expand);
239     setOperationAction(ISD::SELECT, MVT::f64, Expand);
240   }
241
242   // PowerPC wants to turn select_cc of FP into fsel when possible.
243   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
244   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
245
246   // PowerPC wants to optimize integer setcc a bit
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::SETCC, MVT::i32, Custom);
249
250   // PowerPC does not have BRCOND which requires SetCC
251   if (!Subtarget.useCRBits())
252     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
253
254   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
255
256   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
257   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
258
259   // PowerPC does not have [U|S]INT_TO_FP
260   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
261   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
262
263   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
264   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
265   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
266   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
267
268   // We cannot sextinreg(i1).  Expand to shifts.
269   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
270
271   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
272   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
273   // support continuation, user-level threading, and etc.. As a result, no
274   // other SjLj exception interfaces are implemented and please don't build
275   // your own exception handling based on them.
276   // LLVM/Clang supports zero-cost DWARF exception handling.
277   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
278   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
279
280   // We want to legalize GlobalAddress and ConstantPool nodes into the
281   // appropriate instructions to materialize the address.
282   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
283   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
284   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
285   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
286   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
287   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
288   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
289   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
290   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
291   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
292
293   // TRAP is legal.
294   setOperationAction(ISD::TRAP, MVT::Other, Legal);
295
296   // TRAMPOLINE is custom lowered.
297   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
298   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
299
300   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
301   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
302
303   if (Subtarget.isSVR4ABI()) {
304     if (isPPC64) {
305       // VAARG always uses double-word chunks, so promote anything smaller.
306       setOperationAction(ISD::VAARG, MVT::i1, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i8, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::i16, Promote);
311       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
312       setOperationAction(ISD::VAARG, MVT::i32, Promote);
313       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
314       setOperationAction(ISD::VAARG, MVT::Other, Expand);
315     } else {
316       // VAARG is custom lowered with the 32-bit SVR4 ABI.
317       setOperationAction(ISD::VAARG, MVT::Other, Custom);
318       setOperationAction(ISD::VAARG, MVT::i64, Custom);
319     }
320   } else
321     setOperationAction(ISD::VAARG, MVT::Other, Expand);
322
323   if (Subtarget.isSVR4ABI() && !isPPC64)
324     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
325     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
326   else
327     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
328
329   // Use the default implementation.
330   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
331   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
332   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
333   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
334   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
335
336   // We want to custom lower some of our intrinsics.
337   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
338
339   // To handle counter-based loop conditions.
340   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
341
342   // Comparisons that require checking two conditions.
343   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
351   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
352   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
353   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
354   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
355
356   if (Subtarget.has64BitSupport()) {
357     // They also have instructions for converting between i64 and fp.
358     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
359     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
360     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
361     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
362     // This is just the low 32 bits of a (signed) fp->i64 conversion.
363     // We cannot do this with Promote because i64 is not a legal type.
364     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
365
366     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
367       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
368   } else {
369     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
370     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
371   }
372
373   // With the instructions enabled under FPCVT, we can do everything.
374   if (Subtarget.hasFPCVT()) {
375     if (Subtarget.has64BitSupport()) {
376       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
377       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
378       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
379       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
380     }
381
382     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
383     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
384     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
385     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
386   }
387
388   if (Subtarget.use64BitRegs()) {
389     // 64-bit PowerPC implementations can support i64 types directly
390     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
391     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
392     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
393     // 64-bit PowerPC wants to expand i128 shifts itself.
394     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
395     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
396     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
397   } else {
398     // 32-bit PowerPC wants to expand i64 shifts itself.
399     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
400     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
401     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
402   }
403
404   if (Subtarget.hasAltivec()) {
405     // First set operation action for all vector types to expand. Then we
406     // will selectively turn on ones that can be effectively codegen'd.
407     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
408          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
409       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
410
411       // add/sub are legal for all supported vector VT's.
412       setOperationAction(ISD::ADD , VT, Legal);
413       setOperationAction(ISD::SUB , VT, Legal);
414
415       // We promote all shuffles to v16i8.
416       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
417       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
418
419       // We promote all non-typed operations to v4i32.
420       setOperationAction(ISD::AND   , VT, Promote);
421       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
422       setOperationAction(ISD::OR    , VT, Promote);
423       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
424       setOperationAction(ISD::XOR   , VT, Promote);
425       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
426       setOperationAction(ISD::LOAD  , VT, Promote);
427       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
428       setOperationAction(ISD::SELECT, VT, Promote);
429       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
430       setOperationAction(ISD::STORE, VT, Promote);
431       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
432
433       // No other operations are legal.
434       setOperationAction(ISD::MUL , VT, Expand);
435       setOperationAction(ISD::SDIV, VT, Expand);
436       setOperationAction(ISD::SREM, VT, Expand);
437       setOperationAction(ISD::UDIV, VT, Expand);
438       setOperationAction(ISD::UREM, VT, Expand);
439       setOperationAction(ISD::FDIV, VT, Expand);
440       setOperationAction(ISD::FREM, VT, Expand);
441       setOperationAction(ISD::FNEG, VT, Expand);
442       setOperationAction(ISD::FSQRT, VT, Expand);
443       setOperationAction(ISD::FLOG, VT, Expand);
444       setOperationAction(ISD::FLOG10, VT, Expand);
445       setOperationAction(ISD::FLOG2, VT, Expand);
446       setOperationAction(ISD::FEXP, VT, Expand);
447       setOperationAction(ISD::FEXP2, VT, Expand);
448       setOperationAction(ISD::FSIN, VT, Expand);
449       setOperationAction(ISD::FCOS, VT, Expand);
450       setOperationAction(ISD::FABS, VT, Expand);
451       setOperationAction(ISD::FPOWI, VT, Expand);
452       setOperationAction(ISD::FFLOOR, VT, Expand);
453       setOperationAction(ISD::FCEIL,  VT, Expand);
454       setOperationAction(ISD::FTRUNC, VT, Expand);
455       setOperationAction(ISD::FRINT,  VT, Expand);
456       setOperationAction(ISD::FNEARBYINT, VT, Expand);
457       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
458       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
459       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
460       setOperationAction(ISD::MULHU, VT, Expand);
461       setOperationAction(ISD::MULHS, VT, Expand);
462       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
463       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
464       setOperationAction(ISD::UDIVREM, VT, Expand);
465       setOperationAction(ISD::SDIVREM, VT, Expand);
466       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
467       setOperationAction(ISD::FPOW, VT, Expand);
468       setOperationAction(ISD::BSWAP, VT, Expand);
469       setOperationAction(ISD::CTPOP, VT, Expand);
470       setOperationAction(ISD::CTLZ, VT, Expand);
471       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
472       setOperationAction(ISD::CTTZ, VT, Expand);
473       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
474       setOperationAction(ISD::VSELECT, VT, Expand);
475       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
476
477       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
478            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
479         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
480         setTruncStoreAction(VT, InnerVT, Expand);
481       }
482       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
483       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
484       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
485     }
486
487     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
488     // with merges, splats, etc.
489     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
490
491     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
492     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
493     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
494     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
495     setOperationAction(ISD::SELECT, MVT::v4i32,
496                        Subtarget.useCRBits() ? Legal : Expand);
497     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
498     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
499     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
500     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
501     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
502     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
503     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
504     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
505     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
506
507     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
508     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
509     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
510     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
511
512     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
513     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
514
515     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
516       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
517       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
518     }
519
520     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
521     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
522     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
523
524     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
525     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
526
527     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
528     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
529     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
530     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
531
532     // Altivec does not contain unordered floating-point compare instructions
533     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
534     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
535     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
536     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
537
538     if (Subtarget.hasVSX()) {
539       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
540       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
541
542       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
543       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
544       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
545       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
546       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
547
548       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
549
550       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
551       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
552
553       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
554       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
555
556       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
557       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
558       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
559       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
560       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
561
562       // Share the Altivec comparison restrictions.
563       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
564       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
565       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
566       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
567
568       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
569       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
570
571       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
572
573       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
574
575       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
576       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
577
578       // VSX v2i64 only supports non-arithmetic operations.
579       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
580       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
581
582       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
583       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
584       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
585
586       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
587
588       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
589       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
590       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
591       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
592
593       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
594
595       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
596       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
597       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
598       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
599
600       // Vector operation legalization checks the result type of
601       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
602       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
603       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
604       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
605       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
606
607       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
608     }
609   }
610
611   if (Subtarget.has64BitSupport()) {
612     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
613     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
614   }
615
616   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
617   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
618   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
619   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
620
621   setBooleanContents(ZeroOrOneBooleanContent);
622   // Altivec instructions set fields to all zeros or all ones.
623   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
624
625   if (!isPPC64) {
626     // These libcalls are not available in 32-bit.
627     setLibcallName(RTLIB::SHL_I128, nullptr);
628     setLibcallName(RTLIB::SRL_I128, nullptr);
629     setLibcallName(RTLIB::SRA_I128, nullptr);
630   }
631
632   if (isPPC64) {
633     setStackPointerRegisterToSaveRestore(PPC::X1);
634     setExceptionPointerRegister(PPC::X3);
635     setExceptionSelectorRegister(PPC::X4);
636   } else {
637     setStackPointerRegisterToSaveRestore(PPC::R1);
638     setExceptionPointerRegister(PPC::R3);
639     setExceptionSelectorRegister(PPC::R4);
640   }
641
642   // We have target-specific dag combine patterns for the following nodes:
643   setTargetDAGCombine(ISD::SINT_TO_FP);
644   setTargetDAGCombine(ISD::LOAD);
645   setTargetDAGCombine(ISD::STORE);
646   setTargetDAGCombine(ISD::BR_CC);
647   if (Subtarget.useCRBits())
648     setTargetDAGCombine(ISD::BRCOND);
649   setTargetDAGCombine(ISD::BSWAP);
650   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
651
652   setTargetDAGCombine(ISD::SIGN_EXTEND);
653   setTargetDAGCombine(ISD::ZERO_EXTEND);
654   setTargetDAGCombine(ISD::ANY_EXTEND);
655
656   if (Subtarget.useCRBits()) {
657     setTargetDAGCombine(ISD::TRUNCATE);
658     setTargetDAGCombine(ISD::SETCC);
659     setTargetDAGCombine(ISD::SELECT_CC);
660   }
661
662   // Use reciprocal estimates.
663   if (TM.Options.UnsafeFPMath) {
664     setTargetDAGCombine(ISD::FDIV);
665     setTargetDAGCombine(ISD::FSQRT);
666   }
667
668   // Darwin long double math library functions have $LDBL128 appended.
669   if (Subtarget.isDarwin()) {
670     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
671     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
672     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
673     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
674     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
675     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
676     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
677     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
678     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
679     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
680   }
681
682   // With 32 condition bits, we don't need to sink (and duplicate) compares
683   // aggressively in CodeGenPrep.
684   if (Subtarget.useCRBits())
685     setHasMultipleConditionRegisters();
686
687   setMinFunctionAlignment(2);
688   if (Subtarget.isDarwin())
689     setPrefFunctionAlignment(4);
690
691   setInsertFencesForAtomic(true);
692
693   if (Subtarget.enableMachineScheduler())
694     setSchedulingPreference(Sched::Source);
695   else
696     setSchedulingPreference(Sched::Hybrid);
697
698   computeRegisterProperties();
699
700   // The Freescale cores does better with aggressive inlining of memcpy and
701   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
702   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
703       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
704     MaxStoresPerMemset = 32;
705     MaxStoresPerMemsetOptSize = 16;
706     MaxStoresPerMemcpy = 32;
707     MaxStoresPerMemcpyOptSize = 8;
708     MaxStoresPerMemmove = 32;
709     MaxStoresPerMemmoveOptSize = 8;
710
711     setPrefFunctionAlignment(4);
712   }
713 }
714
715 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
716 /// the desired ByVal argument alignment.
717 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
718                              unsigned MaxMaxAlign) {
719   if (MaxAlign == MaxMaxAlign)
720     return;
721   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
722     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
723       MaxAlign = 32;
724     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
725       MaxAlign = 16;
726   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
727     unsigned EltAlign = 0;
728     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
729     if (EltAlign > MaxAlign)
730       MaxAlign = EltAlign;
731   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
732     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
733       unsigned EltAlign = 0;
734       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
735       if (EltAlign > MaxAlign)
736         MaxAlign = EltAlign;
737       if (MaxAlign == MaxMaxAlign)
738         break;
739     }
740   }
741 }
742
743 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
744 /// function arguments in the caller parameter area.
745 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
746   // Darwin passes everything on 4 byte boundary.
747   if (Subtarget.isDarwin())
748     return 4;
749
750   // 16byte and wider vectors are passed on 16byte boundary.
751   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
752   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
753   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
754     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
755   return Align;
756 }
757
758 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
759   switch (Opcode) {
760   default: return nullptr;
761   case PPCISD::FSEL:            return "PPCISD::FSEL";
762   case PPCISD::FCFID:           return "PPCISD::FCFID";
763   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
764   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
765   case PPCISD::FRE:             return "PPCISD::FRE";
766   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
767   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
768   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
769   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
770   case PPCISD::VPERM:           return "PPCISD::VPERM";
771   case PPCISD::Hi:              return "PPCISD::Hi";
772   case PPCISD::Lo:              return "PPCISD::Lo";
773   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
774   case PPCISD::LOAD:            return "PPCISD::LOAD";
775   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
776   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
777   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
778   case PPCISD::SRL:             return "PPCISD::SRL";
779   case PPCISD::SRA:             return "PPCISD::SRA";
780   case PPCISD::SHL:             return "PPCISD::SHL";
781   case PPCISD::CALL:            return "PPCISD::CALL";
782   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
783   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
784   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
785   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
786   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
787   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
788   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
789   case PPCISD::VCMP:            return "PPCISD::VCMP";
790   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
791   case PPCISD::LBRX:            return "PPCISD::LBRX";
792   case PPCISD::STBRX:           return "PPCISD::STBRX";
793   case PPCISD::LARX:            return "PPCISD::LARX";
794   case PPCISD::STCX:            return "PPCISD::STCX";
795   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
796   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
797   case PPCISD::BDZ:             return "PPCISD::BDZ";
798   case PPCISD::MFFS:            return "PPCISD::MFFS";
799   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
800   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
801   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
802   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
803   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
804   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
805   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
806   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
807   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
808   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
809   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
810   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
811   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
812   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
813   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
814   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
815   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
816   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
817   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
818   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
819   case PPCISD::SC:              return "PPCISD::SC";
820   }
821 }
822
823 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
824   if (!VT.isVector())
825     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
826   return VT.changeVectorElementTypeToInteger();
827 }
828
829 //===----------------------------------------------------------------------===//
830 // Node matching predicates, for use by the tblgen matching code.
831 //===----------------------------------------------------------------------===//
832
833 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
834 static bool isFloatingPointZero(SDValue Op) {
835   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
836     return CFP->getValueAPF().isZero();
837   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
838     // Maybe this has already been legalized into the constant pool?
839     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
840       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
841         return CFP->getValueAPF().isZero();
842   }
843   return false;
844 }
845
846 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
847 /// true if Op is undef or if it matches the specified value.
848 static bool isConstantOrUndef(int Op, int Val) {
849   return Op < 0 || Op == Val;
850 }
851
852 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
853 /// VPKUHUM instruction.
854 /// The ShuffleKind distinguishes between big-endian operations with
855 /// two different inputs (0), either-endian operations with two identical
856 /// inputs (1), and little-endian operantion with two different inputs (2).
857 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
858 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
859                                SelectionDAG &DAG) {
860   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
861   if (ShuffleKind == 0) {
862     if (IsLE)
863       return false;
864     for (unsigned i = 0; i != 16; ++i)
865       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
866         return false;
867   } else if (ShuffleKind == 2) {
868     if (!IsLE)
869       return false;
870     for (unsigned i = 0; i != 16; ++i)
871       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
872         return false;
873   } else if (ShuffleKind == 1) {
874     unsigned j = IsLE ? 0 : 1;
875     for (unsigned i = 0; i != 8; ++i)
876       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
877           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
878         return false;
879   }
880   return true;
881 }
882
883 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
884 /// VPKUWUM instruction.
885 /// The ShuffleKind distinguishes between big-endian operations with
886 /// two different inputs (0), either-endian operations with two identical
887 /// inputs (1), and little-endian operantion with two different inputs (2).
888 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
889 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
890                                SelectionDAG &DAG) {
891   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
892   if (ShuffleKind == 0) {
893     if (IsLE)
894       return false;
895     for (unsigned i = 0; i != 16; i += 2)
896       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
897           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
898         return false;
899   } else if (ShuffleKind == 2) {
900     if (!IsLE)
901       return false;
902     for (unsigned i = 0; i != 16; i += 2)
903       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
904           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
905         return false;
906   } else if (ShuffleKind == 1) {
907     unsigned j = IsLE ? 0 : 2;
908     for (unsigned i = 0; i != 8; i += 2)
909       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
910           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
911           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
912           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
913         return false;
914   }
915   return true;
916 }
917
918 /// isVMerge - Common function, used to match vmrg* shuffles.
919 ///
920 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
921                      unsigned LHSStart, unsigned RHSStart) {
922   if (N->getValueType(0) != MVT::v16i8)
923     return false;
924   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
925          "Unsupported merge size!");
926
927   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
928     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
929       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
930                              LHSStart+j+i*UnitSize) ||
931           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
932                              RHSStart+j+i*UnitSize))
933         return false;
934     }
935   return true;
936 }
937
938 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
939 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
940 /// The ShuffleKind distinguishes between big-endian merges with two 
941 /// different inputs (0), either-endian merges with two identical inputs (1),
942 /// and little-endian merges with two different inputs (2).  For the latter,
943 /// the input operands are swapped (see PPCInstrAltivec.td).
944 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
945                              unsigned ShuffleKind, SelectionDAG &DAG) {
946   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
947     if (ShuffleKind == 1) // unary
948       return isVMerge(N, UnitSize, 0, 0);
949     else if (ShuffleKind == 2) // swapped
950       return isVMerge(N, UnitSize, 0, 16);
951     else
952       return false;
953   } else {
954     if (ShuffleKind == 1) // unary
955       return isVMerge(N, UnitSize, 8, 8);
956     else if (ShuffleKind == 0) // normal
957       return isVMerge(N, UnitSize, 8, 24);
958     else
959       return false;
960   }
961 }
962
963 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
964 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
965 /// The ShuffleKind distinguishes between big-endian merges with two 
966 /// different inputs (0), either-endian merges with two identical inputs (1),
967 /// and little-endian merges with two different inputs (2).  For the latter,
968 /// the input operands are swapped (see PPCInstrAltivec.td).
969 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
970                              unsigned ShuffleKind, SelectionDAG &DAG) {
971   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
972     if (ShuffleKind == 1) // unary
973       return isVMerge(N, UnitSize, 8, 8);
974     else if (ShuffleKind == 2) // swapped
975       return isVMerge(N, UnitSize, 8, 24);
976     else
977       return false;
978   } else {
979     if (ShuffleKind == 1) // unary
980       return isVMerge(N, UnitSize, 0, 0);
981     else if (ShuffleKind == 0) // normal
982       return isVMerge(N, UnitSize, 0, 16);
983     else
984       return false;
985   }
986 }
987
988
989 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
990 /// amount, otherwise return -1.
991 /// The ShuffleKind distinguishes between big-endian operations with two 
992 /// different inputs (0), either-endian operations with two identical inputs
993 /// (1), and little-endian operations with two different inputs (2).  For the
994 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
995 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
996                              SelectionDAG &DAG) {
997   if (N->getValueType(0) != MVT::v16i8)
998     return -1;
999
1000   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1001
1002   // Find the first non-undef value in the shuffle mask.
1003   unsigned i;
1004   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1005     /*search*/;
1006
1007   if (i == 16) return -1;  // all undef.
1008
1009   // Otherwise, check to see if the rest of the elements are consecutively
1010   // numbered from this value.
1011   unsigned ShiftAmt = SVOp->getMaskElt(i);
1012   if (ShiftAmt < i) return -1;
1013
1014   ShiftAmt -= i;
1015   bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1016     isLittleEndian();
1017
1018   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1019     // Check the rest of the elements to see if they are consecutive.
1020     for (++i; i != 16; ++i)
1021       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1022         return -1;
1023   } else if (ShuffleKind == 1) {
1024     // Check the rest of the elements to see if they are consecutive.
1025     for (++i; i != 16; ++i)
1026       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1027         return -1;
1028   } else
1029     return -1;
1030
1031   if (ShuffleKind == 2 && isLE)
1032     ShiftAmt = 16 - ShiftAmt;
1033
1034   return ShiftAmt;
1035 }
1036
1037 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1038 /// specifies a splat of a single element that is suitable for input to
1039 /// VSPLTB/VSPLTH/VSPLTW.
1040 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1041   assert(N->getValueType(0) == MVT::v16i8 &&
1042          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1043
1044   // This is a splat operation if each element of the permute is the same, and
1045   // if the value doesn't reference the second vector.
1046   unsigned ElementBase = N->getMaskElt(0);
1047
1048   // FIXME: Handle UNDEF elements too!
1049   if (ElementBase >= 16)
1050     return false;
1051
1052   // Check that the indices are consecutive, in the case of a multi-byte element
1053   // splatted with a v16i8 mask.
1054   for (unsigned i = 1; i != EltSize; ++i)
1055     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1056       return false;
1057
1058   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1059     if (N->getMaskElt(i) < 0) continue;
1060     for (unsigned j = 0; j != EltSize; ++j)
1061       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1062         return false;
1063   }
1064   return true;
1065 }
1066
1067 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1068 /// are -0.0.
1069 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1070   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1071
1072   APInt APVal, APUndef;
1073   unsigned BitSize;
1074   bool HasAnyUndefs;
1075
1076   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1077     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1078       return CFP->getValueAPF().isNegZero();
1079
1080   return false;
1081 }
1082
1083 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1084 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1085 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1086                                 SelectionDAG &DAG) {
1087   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1088   assert(isSplatShuffleMask(SVOp, EltSize));
1089   if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1090     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1091   else
1092     return SVOp->getMaskElt(0) / EltSize;
1093 }
1094
1095 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1096 /// by using a vspltis[bhw] instruction of the specified element size, return
1097 /// the constant being splatted.  The ByteSize field indicates the number of
1098 /// bytes of each element [124] -> [bhw].
1099 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1100   SDValue OpVal(nullptr, 0);
1101
1102   // If ByteSize of the splat is bigger than the element size of the
1103   // build_vector, then we have a case where we are checking for a splat where
1104   // multiple elements of the buildvector are folded together into a single
1105   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1106   unsigned EltSize = 16/N->getNumOperands();
1107   if (EltSize < ByteSize) {
1108     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1109     SDValue UniquedVals[4];
1110     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1111
1112     // See if all of the elements in the buildvector agree across.
1113     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1114       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1115       // If the element isn't a constant, bail fully out.
1116       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1117
1118
1119       if (!UniquedVals[i&(Multiple-1)].getNode())
1120         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1121       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1122         return SDValue();  // no match.
1123     }
1124
1125     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1126     // either constant or undef values that are identical for each chunk.  See
1127     // if these chunks can form into a larger vspltis*.
1128
1129     // Check to see if all of the leading entries are either 0 or -1.  If
1130     // neither, then this won't fit into the immediate field.
1131     bool LeadingZero = true;
1132     bool LeadingOnes = true;
1133     for (unsigned i = 0; i != Multiple-1; ++i) {
1134       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1135
1136       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1137       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1138     }
1139     // Finally, check the least significant entry.
1140     if (LeadingZero) {
1141       if (!UniquedVals[Multiple-1].getNode())
1142         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1143       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1144       if (Val < 16)
1145         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1146     }
1147     if (LeadingOnes) {
1148       if (!UniquedVals[Multiple-1].getNode())
1149         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1150       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1151       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1152         return DAG.getTargetConstant(Val, MVT::i32);
1153     }
1154
1155     return SDValue();
1156   }
1157
1158   // Check to see if this buildvec has a single non-undef value in its elements.
1159   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1160     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1161     if (!OpVal.getNode())
1162       OpVal = N->getOperand(i);
1163     else if (OpVal != N->getOperand(i))
1164       return SDValue();
1165   }
1166
1167   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1168
1169   unsigned ValSizeInBytes = EltSize;
1170   uint64_t Value = 0;
1171   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1172     Value = CN->getZExtValue();
1173   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1174     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1175     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1176   }
1177
1178   // If the splat value is larger than the element value, then we can never do
1179   // this splat.  The only case that we could fit the replicated bits into our
1180   // immediate field for would be zero, and we prefer to use vxor for it.
1181   if (ValSizeInBytes < ByteSize) return SDValue();
1182
1183   // If the element value is larger than the splat value, cut it in half and
1184   // check to see if the two halves are equal.  Continue doing this until we
1185   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1186   while (ValSizeInBytes > ByteSize) {
1187     ValSizeInBytes >>= 1;
1188
1189     // If the top half equals the bottom half, we're still ok.
1190     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1191          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1192       return SDValue();
1193   }
1194
1195   // Properly sign extend the value.
1196   int MaskVal = SignExtend32(Value, ByteSize * 8);
1197
1198   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1199   if (MaskVal == 0) return SDValue();
1200
1201   // Finally, if this value fits in a 5 bit sext field, return it
1202   if (SignExtend32<5>(MaskVal) == MaskVal)
1203     return DAG.getTargetConstant(MaskVal, MVT::i32);
1204   return SDValue();
1205 }
1206
1207 //===----------------------------------------------------------------------===//
1208 //  Addressing Mode Selection
1209 //===----------------------------------------------------------------------===//
1210
1211 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1212 /// or 64-bit immediate, and if the value can be accurately represented as a
1213 /// sign extension from a 16-bit value.  If so, this returns true and the
1214 /// immediate.
1215 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1216   if (!isa<ConstantSDNode>(N))
1217     return false;
1218
1219   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1220   if (N->getValueType(0) == MVT::i32)
1221     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1222   else
1223     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1224 }
1225 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1226   return isIntS16Immediate(Op.getNode(), Imm);
1227 }
1228
1229
1230 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1231 /// can be represented as an indexed [r+r] operation.  Returns false if it
1232 /// can be more efficiently represented with [r+imm].
1233 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1234                                             SDValue &Index,
1235                                             SelectionDAG &DAG) const {
1236   short imm = 0;
1237   if (N.getOpcode() == ISD::ADD) {
1238     if (isIntS16Immediate(N.getOperand(1), imm))
1239       return false;    // r+i
1240     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1241       return false;    // r+i
1242
1243     Base = N.getOperand(0);
1244     Index = N.getOperand(1);
1245     return true;
1246   } else if (N.getOpcode() == ISD::OR) {
1247     if (isIntS16Immediate(N.getOperand(1), imm))
1248       return false;    // r+i can fold it if we can.
1249
1250     // If this is an or of disjoint bitfields, we can codegen this as an add
1251     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1252     // disjoint.
1253     APInt LHSKnownZero, LHSKnownOne;
1254     APInt RHSKnownZero, RHSKnownOne;
1255     DAG.computeKnownBits(N.getOperand(0),
1256                          LHSKnownZero, LHSKnownOne);
1257
1258     if (LHSKnownZero.getBoolValue()) {
1259       DAG.computeKnownBits(N.getOperand(1),
1260                            RHSKnownZero, RHSKnownOne);
1261       // If all of the bits are known zero on the LHS or RHS, the add won't
1262       // carry.
1263       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1264         Base = N.getOperand(0);
1265         Index = N.getOperand(1);
1266         return true;
1267       }
1268     }
1269   }
1270
1271   return false;
1272 }
1273
1274 // If we happen to be doing an i64 load or store into a stack slot that has
1275 // less than a 4-byte alignment, then the frame-index elimination may need to
1276 // use an indexed load or store instruction (because the offset may not be a
1277 // multiple of 4). The extra register needed to hold the offset comes from the
1278 // register scavenger, and it is possible that the scavenger will need to use
1279 // an emergency spill slot. As a result, we need to make sure that a spill slot
1280 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1281 // stack slot.
1282 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1283   // FIXME: This does not handle the LWA case.
1284   if (VT != MVT::i64)
1285     return;
1286
1287   // NOTE: We'll exclude negative FIs here, which come from argument
1288   // lowering, because there are no known test cases triggering this problem
1289   // using packed structures (or similar). We can remove this exclusion if
1290   // we find such a test case. The reason why this is so test-case driven is
1291   // because this entire 'fixup' is only to prevent crashes (from the
1292   // register scavenger) on not-really-valid inputs. For example, if we have:
1293   //   %a = alloca i1
1294   //   %b = bitcast i1* %a to i64*
1295   //   store i64* a, i64 b
1296   // then the store should really be marked as 'align 1', but is not. If it
1297   // were marked as 'align 1' then the indexed form would have been
1298   // instruction-selected initially, and the problem this 'fixup' is preventing
1299   // won't happen regardless.
1300   if (FrameIdx < 0)
1301     return;
1302
1303   MachineFunction &MF = DAG.getMachineFunction();
1304   MachineFrameInfo *MFI = MF.getFrameInfo();
1305
1306   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1307   if (Align >= 4)
1308     return;
1309
1310   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1311   FuncInfo->setHasNonRISpills();
1312 }
1313
1314 /// Returns true if the address N can be represented by a base register plus
1315 /// a signed 16-bit displacement [r+imm], and if it is not better
1316 /// represented as reg+reg.  If Aligned is true, only accept displacements
1317 /// suitable for STD and friends, i.e. multiples of 4.
1318 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1319                                             SDValue &Base,
1320                                             SelectionDAG &DAG,
1321                                             bool Aligned) const {
1322   // FIXME dl should come from parent load or store, not from address
1323   SDLoc dl(N);
1324   // If this can be more profitably realized as r+r, fail.
1325   if (SelectAddressRegReg(N, Disp, Base, DAG))
1326     return false;
1327
1328   if (N.getOpcode() == ISD::ADD) {
1329     short imm = 0;
1330     if (isIntS16Immediate(N.getOperand(1), imm) &&
1331         (!Aligned || (imm & 3) == 0)) {
1332       Disp = DAG.getTargetConstant(imm, N.getValueType());
1333       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1334         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1335         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1336       } else {
1337         Base = N.getOperand(0);
1338       }
1339       return true; // [r+i]
1340     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1341       // Match LOAD (ADD (X, Lo(G))).
1342       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1343              && "Cannot handle constant offsets yet!");
1344       Disp = N.getOperand(1).getOperand(0);  // The global address.
1345       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1346              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1347              Disp.getOpcode() == ISD::TargetConstantPool ||
1348              Disp.getOpcode() == ISD::TargetJumpTable);
1349       Base = N.getOperand(0);
1350       return true;  // [&g+r]
1351     }
1352   } else if (N.getOpcode() == ISD::OR) {
1353     short imm = 0;
1354     if (isIntS16Immediate(N.getOperand(1), imm) &&
1355         (!Aligned || (imm & 3) == 0)) {
1356       // If this is an or of disjoint bitfields, we can codegen this as an add
1357       // (for better address arithmetic) if the LHS and RHS of the OR are
1358       // provably disjoint.
1359       APInt LHSKnownZero, LHSKnownOne;
1360       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1361
1362       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1363         // If all of the bits are known zero on the LHS or RHS, the add won't
1364         // carry.
1365         if (FrameIndexSDNode *FI =
1366               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1367           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1368           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1369         } else {
1370           Base = N.getOperand(0);
1371         }
1372         Disp = DAG.getTargetConstant(imm, N.getValueType());
1373         return true;
1374       }
1375     }
1376   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1377     // Loading from a constant address.
1378
1379     // If this address fits entirely in a 16-bit sext immediate field, codegen
1380     // this as "d, 0"
1381     short Imm;
1382     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1383       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1384       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1385                              CN->getValueType(0));
1386       return true;
1387     }
1388
1389     // Handle 32-bit sext immediates with LIS + addr mode.
1390     if ((CN->getValueType(0) == MVT::i32 ||
1391          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1392         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1393       int Addr = (int)CN->getZExtValue();
1394
1395       // Otherwise, break this down into an LIS + disp.
1396       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1397
1398       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1399       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1400       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1401       return true;
1402     }
1403   }
1404
1405   Disp = DAG.getTargetConstant(0, getPointerTy());
1406   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1407     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1408     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1409   } else
1410     Base = N;
1411   return true;      // [r+0]
1412 }
1413
1414 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1415 /// represented as an indexed [r+r] operation.
1416 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1417                                                 SDValue &Index,
1418                                                 SelectionDAG &DAG) const {
1419   // Check to see if we can easily represent this as an [r+r] address.  This
1420   // will fail if it thinks that the address is more profitably represented as
1421   // reg+imm, e.g. where imm = 0.
1422   if (SelectAddressRegReg(N, Base, Index, DAG))
1423     return true;
1424
1425   // If the operand is an addition, always emit this as [r+r], since this is
1426   // better (for code size, and execution, as the memop does the add for free)
1427   // than emitting an explicit add.
1428   if (N.getOpcode() == ISD::ADD) {
1429     Base = N.getOperand(0);
1430     Index = N.getOperand(1);
1431     return true;
1432   }
1433
1434   // Otherwise, do it the hard way, using R0 as the base register.
1435   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1436                          N.getValueType());
1437   Index = N;
1438   return true;
1439 }
1440
1441 /// getPreIndexedAddressParts - returns true by value, base pointer and
1442 /// offset pointer and addressing mode by reference if the node's address
1443 /// can be legally represented as pre-indexed load / store address.
1444 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1445                                                   SDValue &Offset,
1446                                                   ISD::MemIndexedMode &AM,
1447                                                   SelectionDAG &DAG) const {
1448   if (DisablePPCPreinc) return false;
1449
1450   bool isLoad = true;
1451   SDValue Ptr;
1452   EVT VT;
1453   unsigned Alignment;
1454   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1455     Ptr = LD->getBasePtr();
1456     VT = LD->getMemoryVT();
1457     Alignment = LD->getAlignment();
1458   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1459     Ptr = ST->getBasePtr();
1460     VT  = ST->getMemoryVT();
1461     Alignment = ST->getAlignment();
1462     isLoad = false;
1463   } else
1464     return false;
1465
1466   // PowerPC doesn't have preinc load/store instructions for vectors.
1467   if (VT.isVector())
1468     return false;
1469
1470   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1471
1472     // Common code will reject creating a pre-inc form if the base pointer
1473     // is a frame index, or if N is a store and the base pointer is either
1474     // the same as or a predecessor of the value being stored.  Check for
1475     // those situations here, and try with swapped Base/Offset instead.
1476     bool Swap = false;
1477
1478     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1479       Swap = true;
1480     else if (!isLoad) {
1481       SDValue Val = cast<StoreSDNode>(N)->getValue();
1482       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1483         Swap = true;
1484     }
1485
1486     if (Swap)
1487       std::swap(Base, Offset);
1488
1489     AM = ISD::PRE_INC;
1490     return true;
1491   }
1492
1493   // LDU/STU can only handle immediates that are a multiple of 4.
1494   if (VT != MVT::i64) {
1495     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1496       return false;
1497   } else {
1498     // LDU/STU need an address with at least 4-byte alignment.
1499     if (Alignment < 4)
1500       return false;
1501
1502     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1503       return false;
1504   }
1505
1506   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1507     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1508     // sext i32 to i64 when addr mode is r+i.
1509     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1510         LD->getExtensionType() == ISD::SEXTLOAD &&
1511         isa<ConstantSDNode>(Offset))
1512       return false;
1513   }
1514
1515   AM = ISD::PRE_INC;
1516   return true;
1517 }
1518
1519 //===----------------------------------------------------------------------===//
1520 //  LowerOperation implementation
1521 //===----------------------------------------------------------------------===//
1522
1523 /// GetLabelAccessInfo - Return true if we should reference labels using a
1524 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1525 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1526                                unsigned &LoOpFlags,
1527                                const GlobalValue *GV = nullptr) {
1528   HiOpFlags = PPCII::MO_HA;
1529   LoOpFlags = PPCII::MO_LO;
1530
1531   // Don't use the pic base if not in PIC relocation model.
1532   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1533
1534   if (isPIC) {
1535     HiOpFlags |= PPCII::MO_PIC_FLAG;
1536     LoOpFlags |= PPCII::MO_PIC_FLAG;
1537   }
1538
1539   // If this is a reference to a global value that requires a non-lazy-ptr, make
1540   // sure that instruction lowering adds it.
1541   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1542     HiOpFlags |= PPCII::MO_NLP_FLAG;
1543     LoOpFlags |= PPCII::MO_NLP_FLAG;
1544
1545     if (GV->hasHiddenVisibility()) {
1546       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1547       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1548     }
1549   }
1550
1551   return isPIC;
1552 }
1553
1554 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1555                              SelectionDAG &DAG) {
1556   EVT PtrVT = HiPart.getValueType();
1557   SDValue Zero = DAG.getConstant(0, PtrVT);
1558   SDLoc DL(HiPart);
1559
1560   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1561   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1562
1563   // With PIC, the first instruction is actually "GR+hi(&G)".
1564   if (isPIC)
1565     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1566                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1567
1568   // Generate non-pic code that has direct accesses to the constant pool.
1569   // The address of the global is just (hi(&g)+lo(&g)).
1570   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1571 }
1572
1573 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1574                                              SelectionDAG &DAG) const {
1575   EVT PtrVT = Op.getValueType();
1576   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1577   const Constant *C = CP->getConstVal();
1578
1579   // 64-bit SVR4 ABI code is always position-independent.
1580   // The actual address of the GlobalValue is stored in the TOC.
1581   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1582     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1583     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1584                        DAG.getRegister(PPC::X2, MVT::i64));
1585   }
1586
1587   unsigned MOHiFlag, MOLoFlag;
1588   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1589
1590   if (isPIC && Subtarget.isSVR4ABI()) {
1591     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1592                                            PPCII::MO_PIC_FLAG);
1593     SDLoc DL(CP);
1594     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1595                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1596   }
1597
1598   SDValue CPIHi =
1599     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1600   SDValue CPILo =
1601     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1602   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1603 }
1604
1605 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1606   EVT PtrVT = Op.getValueType();
1607   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1608
1609   // 64-bit SVR4 ABI code is always position-independent.
1610   // The actual address of the GlobalValue is stored in the TOC.
1611   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1612     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1613     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1614                        DAG.getRegister(PPC::X2, MVT::i64));
1615   }
1616
1617   unsigned MOHiFlag, MOLoFlag;
1618   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1619
1620   if (isPIC && Subtarget.isSVR4ABI()) {
1621     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1622                                         PPCII::MO_PIC_FLAG);
1623     SDLoc DL(GA);
1624     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1625                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1626   }
1627
1628   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1629   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1630   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1631 }
1632
1633 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1634                                              SelectionDAG &DAG) const {
1635   EVT PtrVT = Op.getValueType();
1636
1637   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1638
1639   unsigned MOHiFlag, MOLoFlag;
1640   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1641   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1642   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1643   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1644 }
1645
1646 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1647                                               SelectionDAG &DAG) const {
1648
1649   // FIXME: TLS addresses currently use medium model code sequences,
1650   // which is the most useful form.  Eventually support for small and
1651   // large models could be added if users need it, at the cost of
1652   // additional complexity.
1653   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1654   SDLoc dl(GA);
1655   const GlobalValue *GV = GA->getGlobal();
1656   EVT PtrVT = getPointerTy();
1657   bool is64bit = Subtarget.isPPC64();
1658
1659   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1660
1661   if (Model == TLSModel::LocalExec) {
1662     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1663                                                PPCII::MO_TPREL_HA);
1664     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1665                                                PPCII::MO_TPREL_LO);
1666     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1667                                      is64bit ? MVT::i64 : MVT::i32);
1668     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1669     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1670   }
1671
1672   if (Model == TLSModel::InitialExec) {
1673     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1674     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1675                                                 PPCII::MO_TLS);
1676     SDValue GOTPtr;
1677     if (is64bit) {
1678       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1679       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1680                            PtrVT, GOTReg, TGA);
1681     } else
1682       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1683     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1684                                    PtrVT, TGA, GOTPtr);
1685     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1686   }
1687
1688   if (Model == TLSModel::GeneralDynamic) {
1689     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1690     SDValue GOTPtr;
1691     if (is64bit) {
1692       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1693       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1694                                    GOTReg, TGA);
1695     } else {
1696       GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1697     }
1698     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1699                                    GOTPtr, TGA);
1700
1701     // We need a chain node, and don't have one handy.  The underlying
1702     // call has no side effects, so using the function entry node
1703     // suffices.
1704     SDValue Chain = DAG.getEntryNode();
1705     Chain = DAG.getCopyToReg(Chain, dl,
1706                              is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1707     SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1708                                       is64bit ? MVT::i64 : MVT::i32);
1709     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1710                                   PtrVT, ParmReg, TGA);
1711     // The return value from GET_TLS_ADDR really is in X3 already, but
1712     // some hacks are needed here to tie everything together.  The extra
1713     // copies dissolve during subsequent transforms.
1714     Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1715     return DAG.getCopyFromReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, PtrVT);
1716   }
1717
1718   if (Model == TLSModel::LocalDynamic) {
1719     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1720     SDValue GOTPtr;
1721     if (is64bit) {
1722       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1723       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1724                            GOTReg, TGA);
1725     } else {
1726       GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1727     }
1728     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1729                                    GOTPtr, TGA);
1730
1731     // We need a chain node, and don't have one handy.  The underlying
1732     // call has no side effects, so using the function entry node
1733     // suffices.
1734     SDValue Chain = DAG.getEntryNode();
1735     Chain = DAG.getCopyToReg(Chain, dl,
1736                              is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1737     SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1738                                       is64bit ? MVT::i64 : MVT::i32);
1739     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1740                                   PtrVT, ParmReg, TGA);
1741     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1742     // some hacks are needed here to tie everything together.  The extra
1743     // copies dissolve during subsequent transforms.
1744     Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1745     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1746                                       Chain, ParmReg, TGA);
1747     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1748   }
1749
1750   llvm_unreachable("Unknown TLS model!");
1751 }
1752
1753 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1754                                               SelectionDAG &DAG) const {
1755   EVT PtrVT = Op.getValueType();
1756   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1757   SDLoc DL(GSDN);
1758   const GlobalValue *GV = GSDN->getGlobal();
1759
1760   // 64-bit SVR4 ABI code is always position-independent.
1761   // The actual address of the GlobalValue is stored in the TOC.
1762   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1763     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1764     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1765                        DAG.getRegister(PPC::X2, MVT::i64));
1766   }
1767
1768   unsigned MOHiFlag, MOLoFlag;
1769   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1770
1771   if (isPIC && Subtarget.isSVR4ABI()) {
1772     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1773                                             GSDN->getOffset(),
1774                                             PPCII::MO_PIC_FLAG);
1775     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1776                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1777   }
1778
1779   SDValue GAHi =
1780     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1781   SDValue GALo =
1782     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1783
1784   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1785
1786   // If the global reference is actually to a non-lazy-pointer, we have to do an
1787   // extra load to get the address of the global.
1788   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1789     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1790                       false, false, false, 0);
1791   return Ptr;
1792 }
1793
1794 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1795   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1796   SDLoc dl(Op);
1797
1798   if (Op.getValueType() == MVT::v2i64) {
1799     // When the operands themselves are v2i64 values, we need to do something
1800     // special because VSX has no underlying comparison operations for these.
1801     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1802       // Equality can be handled by casting to the legal type for Altivec
1803       // comparisons, everything else needs to be expanded.
1804       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1805         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1806                  DAG.getSetCC(dl, MVT::v4i32,
1807                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1808                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1809                    CC));
1810       }
1811
1812       return SDValue();
1813     }
1814
1815     // We handle most of these in the usual way.
1816     return Op;
1817   }
1818
1819   // If we're comparing for equality to zero, expose the fact that this is
1820   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1821   // fold the new nodes.
1822   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1823     if (C->isNullValue() && CC == ISD::SETEQ) {
1824       EVT VT = Op.getOperand(0).getValueType();
1825       SDValue Zext = Op.getOperand(0);
1826       if (VT.bitsLT(MVT::i32)) {
1827         VT = MVT::i32;
1828         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1829       }
1830       unsigned Log2b = Log2_32(VT.getSizeInBits());
1831       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1832       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1833                                 DAG.getConstant(Log2b, MVT::i32));
1834       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1835     }
1836     // Leave comparisons against 0 and -1 alone for now, since they're usually
1837     // optimized.  FIXME: revisit this when we can custom lower all setcc
1838     // optimizations.
1839     if (C->isAllOnesValue() || C->isNullValue())
1840       return SDValue();
1841   }
1842
1843   // If we have an integer seteq/setne, turn it into a compare against zero
1844   // by xor'ing the rhs with the lhs, which is faster than setting a
1845   // condition register, reading it back out, and masking the correct bit.  The
1846   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1847   // the result to other bit-twiddling opportunities.
1848   EVT LHSVT = Op.getOperand(0).getValueType();
1849   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1850     EVT VT = Op.getValueType();
1851     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1852                                 Op.getOperand(1));
1853     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1854   }
1855   return SDValue();
1856 }
1857
1858 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1859                                       const PPCSubtarget &Subtarget) const {
1860   SDNode *Node = Op.getNode();
1861   EVT VT = Node->getValueType(0);
1862   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1863   SDValue InChain = Node->getOperand(0);
1864   SDValue VAListPtr = Node->getOperand(1);
1865   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1866   SDLoc dl(Node);
1867
1868   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1869
1870   // gpr_index
1871   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1872                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1873                                     false, false, false, 0);
1874   InChain = GprIndex.getValue(1);
1875
1876   if (VT == MVT::i64) {
1877     // Check if GprIndex is even
1878     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1879                                  DAG.getConstant(1, MVT::i32));
1880     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1881                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1882     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1883                                           DAG.getConstant(1, MVT::i32));
1884     // Align GprIndex to be even if it isn't
1885     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1886                            GprIndex);
1887   }
1888
1889   // fpr index is 1 byte after gpr
1890   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1891                                DAG.getConstant(1, MVT::i32));
1892
1893   // fpr
1894   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1895                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1896                                     false, false, false, 0);
1897   InChain = FprIndex.getValue(1);
1898
1899   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1900                                        DAG.getConstant(8, MVT::i32));
1901
1902   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1903                                         DAG.getConstant(4, MVT::i32));
1904
1905   // areas
1906   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1907                                      MachinePointerInfo(), false, false,
1908                                      false, 0);
1909   InChain = OverflowArea.getValue(1);
1910
1911   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1912                                     MachinePointerInfo(), false, false,
1913                                     false, 0);
1914   InChain = RegSaveArea.getValue(1);
1915
1916   // select overflow_area if index > 8
1917   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1918                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1919
1920   // adjustment constant gpr_index * 4/8
1921   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1922                                     VT.isInteger() ? GprIndex : FprIndex,
1923                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1924                                                     MVT::i32));
1925
1926   // OurReg = RegSaveArea + RegConstant
1927   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1928                                RegConstant);
1929
1930   // Floating types are 32 bytes into RegSaveArea
1931   if (VT.isFloatingPoint())
1932     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1933                          DAG.getConstant(32, MVT::i32));
1934
1935   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1936   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1937                                    VT.isInteger() ? GprIndex : FprIndex,
1938                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1939                                                    MVT::i32));
1940
1941   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1942                               VT.isInteger() ? VAListPtr : FprPtr,
1943                               MachinePointerInfo(SV),
1944                               MVT::i8, false, false, 0);
1945
1946   // determine if we should load from reg_save_area or overflow_area
1947   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1948
1949   // increase overflow_area by 4/8 if gpr/fpr > 8
1950   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1951                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1952                                           MVT::i32));
1953
1954   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1955                              OverflowAreaPlusN);
1956
1957   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1958                               OverflowAreaPtr,
1959                               MachinePointerInfo(),
1960                               MVT::i32, false, false, 0);
1961
1962   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1963                      false, false, false, 0);
1964 }
1965
1966 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1967                                        const PPCSubtarget &Subtarget) const {
1968   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1969
1970   // We have to copy the entire va_list struct:
1971   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1972   return DAG.getMemcpy(Op.getOperand(0), Op,
1973                        Op.getOperand(1), Op.getOperand(2),
1974                        DAG.getConstant(12, MVT::i32), 8, false, true,
1975                        MachinePointerInfo(), MachinePointerInfo());
1976 }
1977
1978 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1979                                                   SelectionDAG &DAG) const {
1980   return Op.getOperand(0);
1981 }
1982
1983 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1984                                                 SelectionDAG &DAG) const {
1985   SDValue Chain = Op.getOperand(0);
1986   SDValue Trmp = Op.getOperand(1); // trampoline
1987   SDValue FPtr = Op.getOperand(2); // nested function
1988   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1989   SDLoc dl(Op);
1990
1991   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1992   bool isPPC64 = (PtrVT == MVT::i64);
1993   Type *IntPtrTy =
1994     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1995                                                              *DAG.getContext());
1996
1997   TargetLowering::ArgListTy Args;
1998   TargetLowering::ArgListEntry Entry;
1999
2000   Entry.Ty = IntPtrTy;
2001   Entry.Node = Trmp; Args.push_back(Entry);
2002
2003   // TrampSize == (isPPC64 ? 48 : 40);
2004   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2005                                isPPC64 ? MVT::i64 : MVT::i32);
2006   Args.push_back(Entry);
2007
2008   Entry.Node = FPtr; Args.push_back(Entry);
2009   Entry.Node = Nest; Args.push_back(Entry);
2010
2011   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2012   TargetLowering::CallLoweringInfo CLI(DAG);
2013   CLI.setDebugLoc(dl).setChain(Chain)
2014     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2015                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2016                std::move(Args), 0);
2017
2018   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2019   return CallResult.second;
2020 }
2021
2022 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2023                                         const PPCSubtarget &Subtarget) const {
2024   MachineFunction &MF = DAG.getMachineFunction();
2025   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2026
2027   SDLoc dl(Op);
2028
2029   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2030     // vastart just stores the address of the VarArgsFrameIndex slot into the
2031     // memory location argument.
2032     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2033     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2034     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2035     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2036                         MachinePointerInfo(SV),
2037                         false, false, 0);
2038   }
2039
2040   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2041   // We suppose the given va_list is already allocated.
2042   //
2043   // typedef struct {
2044   //  char gpr;     /* index into the array of 8 GPRs
2045   //                 * stored in the register save area
2046   //                 * gpr=0 corresponds to r3,
2047   //                 * gpr=1 to r4, etc.
2048   //                 */
2049   //  char fpr;     /* index into the array of 8 FPRs
2050   //                 * stored in the register save area
2051   //                 * fpr=0 corresponds to f1,
2052   //                 * fpr=1 to f2, etc.
2053   //                 */
2054   //  char *overflow_arg_area;
2055   //                /* location on stack that holds
2056   //                 * the next overflow argument
2057   //                 */
2058   //  char *reg_save_area;
2059   //               /* where r3:r10 and f1:f8 (if saved)
2060   //                * are stored
2061   //                */
2062   // } va_list[1];
2063
2064
2065   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2066   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2067
2068
2069   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2070
2071   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2072                                             PtrVT);
2073   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2074                                  PtrVT);
2075
2076   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2077   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2078
2079   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2080   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2081
2082   uint64_t FPROffset = 1;
2083   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2084
2085   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2086
2087   // Store first byte : number of int regs
2088   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2089                                          Op.getOperand(1),
2090                                          MachinePointerInfo(SV),
2091                                          MVT::i8, false, false, 0);
2092   uint64_t nextOffset = FPROffset;
2093   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2094                                   ConstFPROffset);
2095
2096   // Store second byte : number of float regs
2097   SDValue secondStore =
2098     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2099                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2100                       false, false, 0);
2101   nextOffset += StackOffset;
2102   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2103
2104   // Store second word : arguments given on stack
2105   SDValue thirdStore =
2106     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2107                  MachinePointerInfo(SV, nextOffset),
2108                  false, false, 0);
2109   nextOffset += FrameOffset;
2110   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2111
2112   // Store third word : arguments given in registers
2113   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2114                       MachinePointerInfo(SV, nextOffset),
2115                       false, false, 0);
2116
2117 }
2118
2119 #include "PPCGenCallingConv.inc"
2120
2121 // Function whose sole purpose is to kill compiler warnings 
2122 // stemming from unused functions included from PPCGenCallingConv.inc.
2123 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2124   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2125 }
2126
2127 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2128                                       CCValAssign::LocInfo &LocInfo,
2129                                       ISD::ArgFlagsTy &ArgFlags,
2130                                       CCState &State) {
2131   return true;
2132 }
2133
2134 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2135                                              MVT &LocVT,
2136                                              CCValAssign::LocInfo &LocInfo,
2137                                              ISD::ArgFlagsTy &ArgFlags,
2138                                              CCState &State) {
2139   static const MCPhysReg ArgRegs[] = {
2140     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2141     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2142   };
2143   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2144
2145   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2146
2147   // Skip one register if the first unallocated register has an even register
2148   // number and there are still argument registers available which have not been
2149   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2150   // need to skip a register if RegNum is odd.
2151   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2152     State.AllocateReg(ArgRegs[RegNum]);
2153   }
2154
2155   // Always return false here, as this function only makes sure that the first
2156   // unallocated register has an odd register number and does not actually
2157   // allocate a register for the current argument.
2158   return false;
2159 }
2160
2161 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2162                                                MVT &LocVT,
2163                                                CCValAssign::LocInfo &LocInfo,
2164                                                ISD::ArgFlagsTy &ArgFlags,
2165                                                CCState &State) {
2166   static const MCPhysReg ArgRegs[] = {
2167     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2168     PPC::F8
2169   };
2170
2171   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2172
2173   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2174
2175   // If there is only one Floating-point register left we need to put both f64
2176   // values of a split ppc_fp128 value on the stack.
2177   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2178     State.AllocateReg(ArgRegs[RegNum]);
2179   }
2180
2181   // Always return false here, as this function only makes sure that the two f64
2182   // values a ppc_fp128 value is split into are both passed in registers or both
2183   // passed on the stack and does not actually allocate a register for the
2184   // current argument.
2185   return false;
2186 }
2187
2188 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2189 /// on Darwin.
2190 static const MCPhysReg *GetFPR() {
2191   static const MCPhysReg FPR[] = {
2192     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2193     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2194   };
2195
2196   return FPR;
2197 }
2198
2199 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2200 /// the stack.
2201 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2202                                        unsigned PtrByteSize) {
2203   unsigned ArgSize = ArgVT.getStoreSize();
2204   if (Flags.isByVal())
2205     ArgSize = Flags.getByValSize();
2206
2207   // Round up to multiples of the pointer size, except for array members,
2208   // which are always packed.
2209   if (!Flags.isInConsecutiveRegs())
2210     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2211
2212   return ArgSize;
2213 }
2214
2215 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2216 /// on the stack.
2217 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2218                                             ISD::ArgFlagsTy Flags,
2219                                             unsigned PtrByteSize) {
2220   unsigned Align = PtrByteSize;
2221
2222   // Altivec parameters are padded to a 16 byte boundary.
2223   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2224       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2225       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2226     Align = 16;
2227
2228   // ByVal parameters are aligned as requested.
2229   if (Flags.isByVal()) {
2230     unsigned BVAlign = Flags.getByValAlign();
2231     if (BVAlign > PtrByteSize) {
2232       if (BVAlign % PtrByteSize != 0)
2233           llvm_unreachable(
2234             "ByVal alignment is not a multiple of the pointer size");
2235
2236       Align = BVAlign;
2237     }
2238   }
2239
2240   // Array members are always packed to their original alignment.
2241   if (Flags.isInConsecutiveRegs()) {
2242     // If the array member was split into multiple registers, the first
2243     // needs to be aligned to the size of the full type.  (Except for
2244     // ppcf128, which is only aligned as its f64 components.)
2245     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2246       Align = OrigVT.getStoreSize();
2247     else
2248       Align = ArgVT.getStoreSize();
2249   }
2250
2251   return Align;
2252 }
2253
2254 /// CalculateStackSlotUsed - Return whether this argument will use its
2255 /// stack slot (instead of being passed in registers).  ArgOffset,
2256 /// AvailableFPRs, and AvailableVRs must hold the current argument
2257 /// position, and will be updated to account for this argument.
2258 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2259                                    ISD::ArgFlagsTy Flags,
2260                                    unsigned PtrByteSize,
2261                                    unsigned LinkageSize,
2262                                    unsigned ParamAreaSize,
2263                                    unsigned &ArgOffset,
2264                                    unsigned &AvailableFPRs,
2265                                    unsigned &AvailableVRs) {
2266   bool UseMemory = false;
2267
2268   // Respect alignment of argument on the stack.
2269   unsigned Align =
2270     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2271   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2272   // If there's no space left in the argument save area, we must
2273   // use memory (this check also catches zero-sized arguments).
2274   if (ArgOffset >= LinkageSize + ParamAreaSize)
2275     UseMemory = true;
2276
2277   // Allocate argument on the stack.
2278   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2279   if (Flags.isInConsecutiveRegsLast())
2280     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2281   // If we overran the argument save area, we must use memory
2282   // (this check catches arguments passed partially in memory)
2283   if (ArgOffset > LinkageSize + ParamAreaSize)
2284     UseMemory = true;
2285
2286   // However, if the argument is actually passed in an FPR or a VR,
2287   // we don't use memory after all.
2288   if (!Flags.isByVal()) {
2289     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2290       if (AvailableFPRs > 0) {
2291         --AvailableFPRs;
2292         return false;
2293       }
2294     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2295         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2296         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2297       if (AvailableVRs > 0) {
2298         --AvailableVRs;
2299         return false;
2300       }
2301   }
2302
2303   return UseMemory;
2304 }
2305
2306 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2307 /// ensure minimum alignment required for target.
2308 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2309                                      unsigned NumBytes) {
2310   unsigned TargetAlign =
2311       Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2312   unsigned AlignMask = TargetAlign - 1;
2313   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2314   return NumBytes;
2315 }
2316
2317 SDValue
2318 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2319                                         CallingConv::ID CallConv, bool isVarArg,
2320                                         const SmallVectorImpl<ISD::InputArg>
2321                                           &Ins,
2322                                         SDLoc dl, SelectionDAG &DAG,
2323                                         SmallVectorImpl<SDValue> &InVals)
2324                                           const {
2325   if (Subtarget.isSVR4ABI()) {
2326     if (Subtarget.isPPC64())
2327       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2328                                          dl, DAG, InVals);
2329     else
2330       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2331                                          dl, DAG, InVals);
2332   } else {
2333     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2334                                        dl, DAG, InVals);
2335   }
2336 }
2337
2338 SDValue
2339 PPCTargetLowering::LowerFormalArguments_32SVR4(
2340                                       SDValue Chain,
2341                                       CallingConv::ID CallConv, bool isVarArg,
2342                                       const SmallVectorImpl<ISD::InputArg>
2343                                         &Ins,
2344                                       SDLoc dl, SelectionDAG &DAG,
2345                                       SmallVectorImpl<SDValue> &InVals) const {
2346
2347   // 32-bit SVR4 ABI Stack Frame Layout:
2348   //              +-----------------------------------+
2349   //        +-->  |            Back chain             |
2350   //        |     +-----------------------------------+
2351   //        |     | Floating-point register save area |
2352   //        |     +-----------------------------------+
2353   //        |     |    General register save area     |
2354   //        |     +-----------------------------------+
2355   //        |     |          CR save word             |
2356   //        |     +-----------------------------------+
2357   //        |     |         VRSAVE save word          |
2358   //        |     +-----------------------------------+
2359   //        |     |         Alignment padding         |
2360   //        |     +-----------------------------------+
2361   //        |     |     Vector register save area     |
2362   //        |     +-----------------------------------+
2363   //        |     |       Local variable space        |
2364   //        |     +-----------------------------------+
2365   //        |     |        Parameter list area        |
2366   //        |     +-----------------------------------+
2367   //        |     |           LR save word            |
2368   //        |     +-----------------------------------+
2369   // SP-->  +---  |            Back chain             |
2370   //              +-----------------------------------+
2371   //
2372   // Specifications:
2373   //   System V Application Binary Interface PowerPC Processor Supplement
2374   //   AltiVec Technology Programming Interface Manual
2375
2376   MachineFunction &MF = DAG.getMachineFunction();
2377   MachineFrameInfo *MFI = MF.getFrameInfo();
2378   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2379
2380   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2381   // Potential tail calls could cause overwriting of argument stack slots.
2382   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2383                        (CallConv == CallingConv::Fast));
2384   unsigned PtrByteSize = 4;
2385
2386   // Assign locations to all of the incoming arguments.
2387   SmallVector<CCValAssign, 16> ArgLocs;
2388   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2389                  *DAG.getContext());
2390
2391   // Reserve space for the linkage area on the stack.
2392   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2393   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2394
2395   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2396
2397   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2398     CCValAssign &VA = ArgLocs[i];
2399
2400     // Arguments stored in registers.
2401     if (VA.isRegLoc()) {
2402       const TargetRegisterClass *RC;
2403       EVT ValVT = VA.getValVT();
2404
2405       switch (ValVT.getSimpleVT().SimpleTy) {
2406         default:
2407           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2408         case MVT::i1:
2409         case MVT::i32:
2410           RC = &PPC::GPRCRegClass;
2411           break;
2412         case MVT::f32:
2413           RC = &PPC::F4RCRegClass;
2414           break;
2415         case MVT::f64:
2416           if (Subtarget.hasVSX())
2417             RC = &PPC::VSFRCRegClass;
2418           else
2419             RC = &PPC::F8RCRegClass;
2420           break;
2421         case MVT::v16i8:
2422         case MVT::v8i16:
2423         case MVT::v4i32:
2424         case MVT::v4f32:
2425           RC = &PPC::VRRCRegClass;
2426           break;
2427         case MVT::v2f64:
2428         case MVT::v2i64:
2429           RC = &PPC::VSHRCRegClass;
2430           break;
2431       }
2432
2433       // Transform the arguments stored in physical registers into virtual ones.
2434       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2435       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2436                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2437
2438       if (ValVT == MVT::i1)
2439         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2440
2441       InVals.push_back(ArgValue);
2442     } else {
2443       // Argument stored in memory.
2444       assert(VA.isMemLoc());
2445
2446       unsigned ArgSize = VA.getLocVT().getStoreSize();
2447       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2448                                       isImmutable);
2449
2450       // Create load nodes to retrieve arguments from the stack.
2451       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2452       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2453                                    MachinePointerInfo(),
2454                                    false, false, false, 0));
2455     }
2456   }
2457
2458   // Assign locations to all of the incoming aggregate by value arguments.
2459   // Aggregates passed by value are stored in the local variable space of the
2460   // caller's stack frame, right above the parameter list area.
2461   SmallVector<CCValAssign, 16> ByValArgLocs;
2462   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2463                       ByValArgLocs, *DAG.getContext());
2464
2465   // Reserve stack space for the allocations in CCInfo.
2466   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2467
2468   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2469
2470   // Area that is at least reserved in the caller of this function.
2471   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2472   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2473
2474   // Set the size that is at least reserved in caller of this function.  Tail
2475   // call optimized function's reserved stack space needs to be aligned so that
2476   // taking the difference between two stack areas will result in an aligned
2477   // stack.
2478   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2479   FuncInfo->setMinReservedArea(MinReservedArea);
2480
2481   SmallVector<SDValue, 8> MemOps;
2482
2483   // If the function takes variable number of arguments, make a frame index for
2484   // the start of the first vararg value... for expansion of llvm.va_start.
2485   if (isVarArg) {
2486     static const MCPhysReg GPArgRegs[] = {
2487       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2488       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2489     };
2490     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2491
2492     static const MCPhysReg FPArgRegs[] = {
2493       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2494       PPC::F8
2495     };
2496     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2497     if (DisablePPCFloatInVariadic)
2498       NumFPArgRegs = 0;
2499
2500     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2501                                                           NumGPArgRegs));
2502     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2503                                                           NumFPArgRegs));
2504
2505     // Make room for NumGPArgRegs and NumFPArgRegs.
2506     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2507                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2508
2509     FuncInfo->setVarArgsStackOffset(
2510       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2511                              CCInfo.getNextStackOffset(), true));
2512
2513     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2514     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2515
2516     // The fixed integer arguments of a variadic function are stored to the
2517     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2518     // the result of va_next.
2519     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2520       // Get an existing live-in vreg, or add a new one.
2521       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2522       if (!VReg)
2523         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2524
2525       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2526       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2527                                    MachinePointerInfo(), false, false, 0);
2528       MemOps.push_back(Store);
2529       // Increment the address by four for the next argument to store
2530       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2531       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2532     }
2533
2534     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2535     // is set.
2536     // The double arguments are stored to the VarArgsFrameIndex
2537     // on the stack.
2538     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2539       // Get an existing live-in vreg, or add a new one.
2540       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2541       if (!VReg)
2542         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2543
2544       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2545       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2546                                    MachinePointerInfo(), false, false, 0);
2547       MemOps.push_back(Store);
2548       // Increment the address by eight for the next argument to store
2549       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2550                                          PtrVT);
2551       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2552     }
2553   }
2554
2555   if (!MemOps.empty())
2556     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2557
2558   return Chain;
2559 }
2560
2561 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2562 // value to MVT::i64 and then truncate to the correct register size.
2563 SDValue
2564 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2565                                      SelectionDAG &DAG, SDValue ArgVal,
2566                                      SDLoc dl) const {
2567   if (Flags.isSExt())
2568     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2569                          DAG.getValueType(ObjectVT));
2570   else if (Flags.isZExt())
2571     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2572                          DAG.getValueType(ObjectVT));
2573
2574   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2575 }
2576
2577 SDValue
2578 PPCTargetLowering::LowerFormalArguments_64SVR4(
2579                                       SDValue Chain,
2580                                       CallingConv::ID CallConv, bool isVarArg,
2581                                       const SmallVectorImpl<ISD::InputArg>
2582                                         &Ins,
2583                                       SDLoc dl, SelectionDAG &DAG,
2584                                       SmallVectorImpl<SDValue> &InVals) const {
2585   // TODO: add description of PPC stack frame format, or at least some docs.
2586   //
2587   bool isELFv2ABI = Subtarget.isELFv2ABI();
2588   bool isLittleEndian = Subtarget.isLittleEndian();
2589   MachineFunction &MF = DAG.getMachineFunction();
2590   MachineFrameInfo *MFI = MF.getFrameInfo();
2591   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2592
2593   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2594   // Potential tail calls could cause overwriting of argument stack slots.
2595   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2596                        (CallConv == CallingConv::Fast));
2597   unsigned PtrByteSize = 8;
2598
2599   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2600                                                           isELFv2ABI);
2601
2602   static const MCPhysReg GPR[] = {
2603     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2604     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2605   };
2606
2607   static const MCPhysReg *FPR = GetFPR();
2608
2609   static const MCPhysReg VR[] = {
2610     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2611     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2612   };
2613   static const MCPhysReg VSRH[] = {
2614     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2615     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2616   };
2617
2618   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2619   const unsigned Num_FPR_Regs = 13;
2620   const unsigned Num_VR_Regs  = array_lengthof(VR);
2621
2622   // Do a first pass over the arguments to determine whether the ABI
2623   // guarantees that our caller has allocated the parameter save area
2624   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2625   // in the ELFv2 ABI, it is true if this is a vararg function or if
2626   // any parameter is located in a stack slot.
2627
2628   bool HasParameterArea = !isELFv2ABI || isVarArg;
2629   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2630   unsigned NumBytes = LinkageSize;
2631   unsigned AvailableFPRs = Num_FPR_Regs;
2632   unsigned AvailableVRs = Num_VR_Regs;
2633   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2634     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2635                                PtrByteSize, LinkageSize, ParamAreaSize,
2636                                NumBytes, AvailableFPRs, AvailableVRs))
2637       HasParameterArea = true;
2638
2639   // Add DAG nodes to load the arguments or copy them out of registers.  On
2640   // entry to a function on PPC, the arguments start after the linkage area,
2641   // although the first ones are often in registers.
2642
2643   unsigned ArgOffset = LinkageSize;
2644   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2645   SmallVector<SDValue, 8> MemOps;
2646   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2647   unsigned CurArgIdx = 0;
2648   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2649     SDValue ArgVal;
2650     bool needsLoad = false;
2651     EVT ObjectVT = Ins[ArgNo].VT;
2652     EVT OrigVT = Ins[ArgNo].ArgVT;
2653     unsigned ObjSize = ObjectVT.getStoreSize();
2654     unsigned ArgSize = ObjSize;
2655     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2656     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2657     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2658
2659     /* Respect alignment of argument on the stack.  */
2660     unsigned Align =
2661       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2662     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2663     unsigned CurArgOffset = ArgOffset;
2664
2665     /* Compute GPR index associated with argument offset.  */
2666     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2667     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2668
2669     // FIXME the codegen can be much improved in some cases.
2670     // We do not have to keep everything in memory.
2671     if (Flags.isByVal()) {
2672       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2673       ObjSize = Flags.getByValSize();
2674       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2675       // Empty aggregate parameters do not take up registers.  Examples:
2676       //   struct { } a;
2677       //   union  { } b;
2678       //   int c[0];
2679       // etc.  However, we have to provide a place-holder in InVals, so
2680       // pretend we have an 8-byte item at the current address for that
2681       // purpose.
2682       if (!ObjSize) {
2683         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2684         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2685         InVals.push_back(FIN);
2686         continue;
2687       }
2688
2689       // Create a stack object covering all stack doublewords occupied
2690       // by the argument.  If the argument is (fully or partially) on
2691       // the stack, or if the argument is fully in registers but the
2692       // caller has allocated the parameter save anyway, we can refer
2693       // directly to the caller's stack frame.  Otherwise, create a
2694       // local copy in our own frame.
2695       int FI;
2696       if (HasParameterArea ||
2697           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2698         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2699       else
2700         FI = MFI->CreateStackObject(ArgSize, Align, false);
2701       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2702
2703       // Handle aggregates smaller than 8 bytes.
2704       if (ObjSize < PtrByteSize) {
2705         // The value of the object is its address, which differs from the
2706         // address of the enclosing doubleword on big-endian systems.
2707         SDValue Arg = FIN;
2708         if (!isLittleEndian) {
2709           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2710           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2711         }
2712         InVals.push_back(Arg);
2713
2714         if (GPR_idx != Num_GPR_Regs) {
2715           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2716           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2717           SDValue Store;
2718
2719           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2720             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2721                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2722             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2723                                       MachinePointerInfo(FuncArg),
2724                                       ObjType, false, false, 0);
2725           } else {
2726             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2727             // store the whole register as-is to the parameter save area
2728             // slot.
2729             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2730                                  MachinePointerInfo(FuncArg),
2731                                  false, false, 0);
2732           }
2733
2734           MemOps.push_back(Store);
2735         }
2736         // Whether we copied from a register or not, advance the offset
2737         // into the parameter save area by a full doubleword.
2738         ArgOffset += PtrByteSize;
2739         continue;
2740       }
2741
2742       // The value of the object is its address, which is the address of
2743       // its first stack doubleword.
2744       InVals.push_back(FIN);
2745
2746       // Store whatever pieces of the object are in registers to memory.
2747       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2748         if (GPR_idx == Num_GPR_Regs)
2749           break;
2750
2751         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2752         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2753         SDValue Addr = FIN;
2754         if (j) {
2755           SDValue Off = DAG.getConstant(j, PtrVT);
2756           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2757         }
2758         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2759                                      MachinePointerInfo(FuncArg, j),
2760                                      false, false, 0);
2761         MemOps.push_back(Store);
2762         ++GPR_idx;
2763       }
2764       ArgOffset += ArgSize;
2765       continue;
2766     }
2767
2768     switch (ObjectVT.getSimpleVT().SimpleTy) {
2769     default: llvm_unreachable("Unhandled argument type!");
2770     case MVT::i1:
2771     case MVT::i32:
2772     case MVT::i64:
2773       // These can be scalar arguments or elements of an integer array type
2774       // passed directly.  Clang may use those instead of "byval" aggregate
2775       // types to avoid forcing arguments to memory unnecessarily.
2776       if (GPR_idx != Num_GPR_Regs) {
2777         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2778         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2779
2780         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2781           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2782           // value to MVT::i64 and then truncate to the correct register size.
2783           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2784       } else {
2785         needsLoad = true;
2786         ArgSize = PtrByteSize;
2787       }
2788       ArgOffset += 8;
2789       break;
2790
2791     case MVT::f32:
2792     case MVT::f64:
2793       // These can be scalar arguments or elements of a float array type
2794       // passed directly.  The latter are used to implement ELFv2 homogenous
2795       // float aggregates.
2796       if (FPR_idx != Num_FPR_Regs) {
2797         unsigned VReg;
2798
2799         if (ObjectVT == MVT::f32)
2800           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2801         else
2802           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2803                                             &PPC::VSFRCRegClass :
2804                                             &PPC::F8RCRegClass);
2805
2806         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2807         ++FPR_idx;
2808       } else if (GPR_idx != Num_GPR_Regs) {
2809         // This can only ever happen in the presence of f32 array types,
2810         // since otherwise we never run out of FPRs before running out
2811         // of GPRs.
2812         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2813         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2814
2815         if (ObjectVT == MVT::f32) {
2816           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2817             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2818                                  DAG.getConstant(32, MVT::i32));
2819           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2820         }
2821
2822         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2823       } else {
2824         needsLoad = true;
2825       }
2826
2827       // When passing an array of floats, the array occupies consecutive
2828       // space in the argument area; only round up to the next doubleword
2829       // at the end of the array.  Otherwise, each float takes 8 bytes.
2830       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2831       ArgOffset += ArgSize;
2832       if (Flags.isInConsecutiveRegsLast())
2833         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2834       break;
2835     case MVT::v4f32:
2836     case MVT::v4i32:
2837     case MVT::v8i16:
2838     case MVT::v16i8:
2839     case MVT::v2f64:
2840     case MVT::v2i64:
2841       // These can be scalar arguments or elements of a vector array type
2842       // passed directly.  The latter are used to implement ELFv2 homogenous
2843       // vector aggregates.
2844       if (VR_idx != Num_VR_Regs) {
2845         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2846                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2847                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2848         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2849         ++VR_idx;
2850       } else {
2851         needsLoad = true;
2852       }
2853       ArgOffset += 16;
2854       break;
2855     }
2856
2857     // We need to load the argument to a virtual register if we determined
2858     // above that we ran out of physical registers of the appropriate type.
2859     if (needsLoad) {
2860       if (ObjSize < ArgSize && !isLittleEndian)
2861         CurArgOffset += ArgSize - ObjSize;
2862       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2863       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2864       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2865                            false, false, false, 0);
2866     }
2867
2868     InVals.push_back(ArgVal);
2869   }
2870
2871   // Area that is at least reserved in the caller of this function.
2872   unsigned MinReservedArea;
2873   if (HasParameterArea)
2874     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2875   else
2876     MinReservedArea = LinkageSize;
2877
2878   // Set the size that is at least reserved in caller of this function.  Tail
2879   // call optimized functions' reserved stack space needs to be aligned so that
2880   // taking the difference between two stack areas will result in an aligned
2881   // stack.
2882   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2883   FuncInfo->setMinReservedArea(MinReservedArea);
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(PtrByteSize, Depth, true));
2892     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2893
2894     // If this function is vararg, store any remaining integer argument regs
2895     // to their spots on the stack so that they may be loaded by deferencing the
2896     // result of va_next.
2897     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2898          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2899       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2900       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2901       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2902                                    MachinePointerInfo(), false, false, 0);
2903       MemOps.push_back(Store);
2904       // Increment the address by four for the next argument to store
2905       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2906       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2907     }
2908   }
2909
2910   if (!MemOps.empty())
2911     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2912
2913   return Chain;
2914 }
2915
2916 SDValue
2917 PPCTargetLowering::LowerFormalArguments_Darwin(
2918                                       SDValue Chain,
2919                                       CallingConv::ID CallConv, bool isVarArg,
2920                                       const SmallVectorImpl<ISD::InputArg>
2921                                         &Ins,
2922                                       SDLoc dl, SelectionDAG &DAG,
2923                                       SmallVectorImpl<SDValue> &InVals) const {
2924   // TODO: add description of PPC stack frame format, or at least some docs.
2925   //
2926   MachineFunction &MF = DAG.getMachineFunction();
2927   MachineFrameInfo *MFI = MF.getFrameInfo();
2928   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2929
2930   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2931   bool isPPC64 = PtrVT == MVT::i64;
2932   // Potential tail calls could cause overwriting of argument stack slots.
2933   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2934                        (CallConv == CallingConv::Fast));
2935   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2936
2937   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2938                                                           false);
2939   unsigned ArgOffset = LinkageSize;
2940   // Area that is at least reserved in caller of this function.
2941   unsigned MinReservedArea = ArgOffset;
2942
2943   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2944     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2945     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2946   };
2947   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2948     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2949     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2950   };
2951
2952   static const MCPhysReg *FPR = GetFPR();
2953
2954   static const MCPhysReg VR[] = {
2955     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2956     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2957   };
2958
2959   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2960   const unsigned Num_FPR_Regs = 13;
2961   const unsigned Num_VR_Regs  = array_lengthof( VR);
2962
2963   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2964
2965   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2966
2967   // In 32-bit non-varargs functions, the stack space for vectors is after the
2968   // stack space for non-vectors.  We do not use this space unless we have
2969   // too many vectors to fit in registers, something that only occurs in
2970   // constructed examples:), but we have to walk the arglist to figure
2971   // that out...for the pathological case, compute VecArgOffset as the
2972   // start of the vector parameter area.  Computing VecArgOffset is the
2973   // entire point of the following loop.
2974   unsigned VecArgOffset = ArgOffset;
2975   if (!isVarArg && !isPPC64) {
2976     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2977          ++ArgNo) {
2978       EVT ObjectVT = Ins[ArgNo].VT;
2979       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2980
2981       if (Flags.isByVal()) {
2982         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2983         unsigned ObjSize = Flags.getByValSize();
2984         unsigned ArgSize =
2985                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2986         VecArgOffset += ArgSize;
2987         continue;
2988       }
2989
2990       switch(ObjectVT.getSimpleVT().SimpleTy) {
2991       default: llvm_unreachable("Unhandled argument type!");
2992       case MVT::i1:
2993       case MVT::i32:
2994       case MVT::f32:
2995         VecArgOffset += 4;
2996         break;
2997       case MVT::i64:  // PPC64
2998       case MVT::f64:
2999         // FIXME: We are guaranteed to be !isPPC64 at this point.
3000         // Does MVT::i64 apply?
3001         VecArgOffset += 8;
3002         break;
3003       case MVT::v4f32:
3004       case MVT::v4i32:
3005       case MVT::v8i16:
3006       case MVT::v16i8:
3007         // Nothing to do, we're only looking at Nonvector args here.
3008         break;
3009       }
3010     }
3011   }
3012   // We've found where the vector parameter area in memory is.  Skip the
3013   // first 12 parameters; these don't use that memory.
3014   VecArgOffset = ((VecArgOffset+15)/16)*16;
3015   VecArgOffset += 12*16;
3016
3017   // Add DAG nodes to load the arguments or copy them out of registers.  On
3018   // entry to a function on PPC, the arguments start after the linkage area,
3019   // although the first ones are often in registers.
3020
3021   SmallVector<SDValue, 8> MemOps;
3022   unsigned nAltivecParamsAtEnd = 0;
3023   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3024   unsigned CurArgIdx = 0;
3025   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3026     SDValue ArgVal;
3027     bool needsLoad = false;
3028     EVT ObjectVT = Ins[ArgNo].VT;
3029     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3030     unsigned ArgSize = ObjSize;
3031     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3032     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3033     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3034
3035     unsigned CurArgOffset = ArgOffset;
3036
3037     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3038     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3039         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3040       if (isVarArg || isPPC64) {
3041         MinReservedArea = ((MinReservedArea+15)/16)*16;
3042         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3043                                                   Flags,
3044                                                   PtrByteSize);
3045       } else  nAltivecParamsAtEnd++;
3046     } else
3047       // Calculate min reserved area.
3048       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3049                                                 Flags,
3050                                                 PtrByteSize);
3051
3052     // FIXME the codegen can be much improved in some cases.
3053     // We do not have to keep everything in memory.
3054     if (Flags.isByVal()) {
3055       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3056       ObjSize = Flags.getByValSize();
3057       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3058       // Objects of size 1 and 2 are right justified, everything else is
3059       // left justified.  This means the memory address is adjusted forwards.
3060       if (ObjSize==1 || ObjSize==2) {
3061         CurArgOffset = CurArgOffset + (4 - ObjSize);
3062       }
3063       // The value of the object is its address.
3064       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3065       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3066       InVals.push_back(FIN);
3067       if (ObjSize==1 || ObjSize==2) {
3068         if (GPR_idx != Num_GPR_Regs) {
3069           unsigned VReg;
3070           if (isPPC64)
3071             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3072           else
3073             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3074           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3075           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3076           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3077                                             MachinePointerInfo(FuncArg),
3078                                             ObjType, false, false, 0);
3079           MemOps.push_back(Store);
3080           ++GPR_idx;
3081         }
3082
3083         ArgOffset += PtrByteSize;
3084
3085         continue;
3086       }
3087       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3088         // Store whatever pieces of the object are in registers
3089         // to memory.  ArgOffset will be the address of the beginning
3090         // of the object.
3091         if (GPR_idx != Num_GPR_Regs) {
3092           unsigned VReg;
3093           if (isPPC64)
3094             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3095           else
3096             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3097           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3098           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3099           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3100           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3101                                        MachinePointerInfo(FuncArg, j),
3102                                        false, false, 0);
3103           MemOps.push_back(Store);
3104           ++GPR_idx;
3105           ArgOffset += PtrByteSize;
3106         } else {
3107           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3108           break;
3109         }
3110       }
3111       continue;
3112     }
3113
3114     switch (ObjectVT.getSimpleVT().SimpleTy) {
3115     default: llvm_unreachable("Unhandled argument type!");
3116     case MVT::i1:
3117     case MVT::i32:
3118       if (!isPPC64) {
3119         if (GPR_idx != Num_GPR_Regs) {
3120           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3121           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3122
3123           if (ObjectVT == MVT::i1)
3124             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3125
3126           ++GPR_idx;
3127         } else {
3128           needsLoad = true;
3129           ArgSize = PtrByteSize;
3130         }
3131         // All int arguments reserve stack space in the Darwin ABI.
3132         ArgOffset += PtrByteSize;
3133         break;
3134       }
3135       // FALLTHROUGH
3136     case MVT::i64:  // PPC64
3137       if (GPR_idx != Num_GPR_Regs) {
3138         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3139         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3140
3141         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3142           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3143           // value to MVT::i64 and then truncate to the correct register size.
3144           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3145
3146         ++GPR_idx;
3147       } else {
3148         needsLoad = true;
3149         ArgSize = PtrByteSize;
3150       }
3151       // All int arguments reserve stack space in the Darwin ABI.
3152       ArgOffset += 8;
3153       break;
3154
3155     case MVT::f32:
3156     case MVT::f64:
3157       // Every 4 bytes of argument space consumes one of the GPRs available for
3158       // argument passing.
3159       if (GPR_idx != Num_GPR_Regs) {
3160         ++GPR_idx;
3161         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3162           ++GPR_idx;
3163       }
3164       if (FPR_idx != Num_FPR_Regs) {
3165         unsigned VReg;
3166
3167         if (ObjectVT == MVT::f32)
3168           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3169         else
3170           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3171
3172         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3173         ++FPR_idx;
3174       } else {
3175         needsLoad = true;
3176       }
3177
3178       // All FP arguments reserve stack space in the Darwin ABI.
3179       ArgOffset += isPPC64 ? 8 : ObjSize;
3180       break;
3181     case MVT::v4f32:
3182     case MVT::v4i32:
3183     case MVT::v8i16:
3184     case MVT::v16i8:
3185       // Note that vector arguments in registers don't reserve stack space,
3186       // except in varargs functions.
3187       if (VR_idx != Num_VR_Regs) {
3188         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3189         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3190         if (isVarArg) {
3191           while ((ArgOffset % 16) != 0) {
3192             ArgOffset += PtrByteSize;
3193             if (GPR_idx != Num_GPR_Regs)
3194               GPR_idx++;
3195           }
3196           ArgOffset += 16;
3197           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3198         }
3199         ++VR_idx;
3200       } else {
3201         if (!isVarArg && !isPPC64) {
3202           // Vectors go after all the nonvectors.
3203           CurArgOffset = VecArgOffset;
3204           VecArgOffset += 16;
3205         } else {
3206           // Vectors are aligned.
3207           ArgOffset = ((ArgOffset+15)/16)*16;
3208           CurArgOffset = ArgOffset;
3209           ArgOffset += 16;
3210         }
3211         needsLoad = true;
3212       }
3213       break;
3214     }
3215
3216     // We need to load the argument to a virtual register if we determined above
3217     // that we ran out of physical registers of the appropriate type.
3218     if (needsLoad) {
3219       int FI = MFI->CreateFixedObject(ObjSize,
3220                                       CurArgOffset + (ArgSize - ObjSize),
3221                                       isImmutable);
3222       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3223       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3224                            false, false, false, 0);
3225     }
3226
3227     InVals.push_back(ArgVal);
3228   }
3229
3230   // Allow for Altivec parameters at the end, if needed.
3231   if (nAltivecParamsAtEnd) {
3232     MinReservedArea = ((MinReservedArea+15)/16)*16;
3233     MinReservedArea += 16*nAltivecParamsAtEnd;
3234   }
3235
3236   // Area that is at least reserved in the caller of this function.
3237   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3238
3239   // Set the size that is at least reserved in caller of this function.  Tail
3240   // call optimized functions' reserved stack space needs to be aligned so that
3241   // taking the difference between two stack areas will result in an aligned
3242   // stack.
3243   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3244   FuncInfo->setMinReservedArea(MinReservedArea);
3245
3246   // If the function takes variable number of arguments, make a frame index for
3247   // the start of the first vararg value... for expansion of llvm.va_start.
3248   if (isVarArg) {
3249     int Depth = ArgOffset;
3250
3251     FuncInfo->setVarArgsFrameIndex(
3252       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3253                              Depth, true));
3254     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3255
3256     // If this function is vararg, store any remaining integer argument regs
3257     // to their spots on the stack so that they may be loaded by deferencing the
3258     // result of va_next.
3259     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3260       unsigned VReg;
3261
3262       if (isPPC64)
3263         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3264       else
3265         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3266
3267       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3268       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3269                                    MachinePointerInfo(), false, false, 0);
3270       MemOps.push_back(Store);
3271       // Increment the address by four for the next argument to store
3272       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3273       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3274     }
3275   }
3276
3277   if (!MemOps.empty())
3278     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3279
3280   return Chain;
3281 }
3282
3283 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3284 /// adjusted to accommodate the arguments for the tailcall.
3285 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3286                                    unsigned ParamSize) {
3287
3288   if (!isTailCall) return 0;
3289
3290   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3291   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3292   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3293   // Remember only if the new adjustement is bigger.
3294   if (SPDiff < FI->getTailCallSPDelta())
3295     FI->setTailCallSPDelta(SPDiff);
3296
3297   return SPDiff;
3298 }
3299
3300 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3301 /// for tail call optimization. Targets which want to do tail call
3302 /// optimization should implement this function.
3303 bool
3304 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3305                                                      CallingConv::ID CalleeCC,
3306                                                      bool isVarArg,
3307                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3308                                                      SelectionDAG& DAG) const {
3309   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3310     return false;
3311
3312   // Variable argument functions are not supported.
3313   if (isVarArg)
3314     return false;
3315
3316   MachineFunction &MF = DAG.getMachineFunction();
3317   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3318   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3319     // Functions containing by val parameters are not supported.
3320     for (unsigned i = 0; i != Ins.size(); i++) {
3321        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3322        if (Flags.isByVal()) return false;
3323     }
3324
3325     // Non-PIC/GOT tail calls are supported.
3326     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3327       return true;
3328
3329     // At the moment we can only do local tail calls (in same module, hidden
3330     // or protected) if we are generating PIC.
3331     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3332       return G->getGlobal()->hasHiddenVisibility()
3333           || G->getGlobal()->hasProtectedVisibility();
3334   }
3335
3336   return false;
3337 }
3338
3339 /// isCallCompatibleAddress - Return the immediate to use if the specified
3340 /// 32-bit value is representable in the immediate field of a BxA instruction.
3341 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3342   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3343   if (!C) return nullptr;
3344
3345   int Addr = C->getZExtValue();
3346   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3347       SignExtend32<26>(Addr) != Addr)
3348     return nullptr;  // Top 6 bits have to be sext of immediate.
3349
3350   return DAG.getConstant((int)C->getZExtValue() >> 2,
3351                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3352 }
3353
3354 namespace {
3355
3356 struct TailCallArgumentInfo {
3357   SDValue Arg;
3358   SDValue FrameIdxOp;
3359   int       FrameIdx;
3360
3361   TailCallArgumentInfo() : FrameIdx(0) {}
3362 };
3363
3364 }
3365
3366 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3367 static void
3368 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3369                                            SDValue Chain,
3370                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3371                    SmallVectorImpl<SDValue> &MemOpChains,
3372                    SDLoc dl) {
3373   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3374     SDValue Arg = TailCallArgs[i].Arg;
3375     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3376     int FI = TailCallArgs[i].FrameIdx;
3377     // Store relative to framepointer.
3378     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3379                                        MachinePointerInfo::getFixedStack(FI),
3380                                        false, false, 0));
3381   }
3382 }
3383
3384 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3385 /// the appropriate stack slot for the tail call optimized function call.
3386 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3387                                                MachineFunction &MF,
3388                                                SDValue Chain,
3389                                                SDValue OldRetAddr,
3390                                                SDValue OldFP,
3391                                                int SPDiff,
3392                                                bool isPPC64,
3393                                                bool isDarwinABI,
3394                                                SDLoc dl) {
3395   if (SPDiff) {
3396     // Calculate the new stack slot for the return address.
3397     int SlotSize = isPPC64 ? 8 : 4;
3398     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3399                                                                    isDarwinABI);
3400     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3401                                                           NewRetAddrLoc, true);
3402     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3403     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3404     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3405                          MachinePointerInfo::getFixedStack(NewRetAddr),
3406                          false, false, 0);
3407
3408     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3409     // slot as the FP is never overwritten.
3410     if (isDarwinABI) {
3411       int NewFPLoc =
3412         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3413       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3414                                                           true);
3415       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3416       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3417                            MachinePointerInfo::getFixedStack(NewFPIdx),
3418                            false, false, 0);
3419     }
3420   }
3421   return Chain;
3422 }
3423
3424 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3425 /// the position of the argument.
3426 static void
3427 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3428                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3429                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3430   int Offset = ArgOffset + SPDiff;
3431   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3432   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3433   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3434   SDValue FIN = DAG.getFrameIndex(FI, VT);
3435   TailCallArgumentInfo Info;
3436   Info.Arg = Arg;
3437   Info.FrameIdxOp = FIN;
3438   Info.FrameIdx = FI;
3439   TailCallArguments.push_back(Info);
3440 }
3441
3442 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3443 /// stack slot. Returns the chain as result and the loaded frame pointers in
3444 /// LROpOut/FPOpout. Used when tail calling.
3445 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3446                                                         int SPDiff,
3447                                                         SDValue Chain,
3448                                                         SDValue &LROpOut,
3449                                                         SDValue &FPOpOut,
3450                                                         bool isDarwinABI,
3451                                                         SDLoc dl) const {
3452   if (SPDiff) {
3453     // Load the LR and FP stack slot for later adjusting.
3454     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3455     LROpOut = getReturnAddrFrameIndex(DAG);
3456     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3457                           false, false, false, 0);
3458     Chain = SDValue(LROpOut.getNode(), 1);
3459
3460     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3461     // slot as the FP is never overwritten.
3462     if (isDarwinABI) {
3463       FPOpOut = getFramePointerFrameIndex(DAG);
3464       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3465                             false, false, false, 0);
3466       Chain = SDValue(FPOpOut.getNode(), 1);
3467     }
3468   }
3469   return Chain;
3470 }
3471
3472 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3473 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3474 /// specified by the specific parameter attribute. The copy will be passed as
3475 /// a byval function parameter.
3476 /// Sometimes what we are copying is the end of a larger object, the part that
3477 /// does not fit in registers.
3478 static SDValue
3479 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3480                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3481                           SDLoc dl) {
3482   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3483   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3484                        false, false, MachinePointerInfo(),
3485                        MachinePointerInfo());
3486 }
3487
3488 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3489 /// tail calls.
3490 static void
3491 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3492                  SDValue Arg, SDValue PtrOff, int SPDiff,
3493                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3494                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3495                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3496                  SDLoc dl) {
3497   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3498   if (!isTailCall) {
3499     if (isVector) {
3500       SDValue StackPtr;
3501       if (isPPC64)
3502         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3503       else
3504         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3505       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3506                            DAG.getConstant(ArgOffset, PtrVT));
3507     }
3508     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3509                                        MachinePointerInfo(), false, false, 0));
3510   // Calculate and remember argument location.
3511   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3512                                   TailCallArguments);
3513 }
3514
3515 static
3516 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3517                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3518                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3519                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3520   MachineFunction &MF = DAG.getMachineFunction();
3521
3522   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3523   // might overwrite each other in case of tail call optimization.
3524   SmallVector<SDValue, 8> MemOpChains2;
3525   // Do not flag preceding copytoreg stuff together with the following stuff.
3526   InFlag = SDValue();
3527   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3528                                     MemOpChains2, dl);
3529   if (!MemOpChains2.empty())
3530     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3531
3532   // Store the return address to the appropriate stack slot.
3533   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3534                                         isPPC64, isDarwinABI, dl);
3535
3536   // Emit callseq_end just before tailcall node.
3537   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3538                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3539   InFlag = Chain.getValue(1);
3540 }
3541
3542 static
3543 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3544                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3545                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3546                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3547                      const PPCSubtarget &Subtarget) {
3548
3549   bool isPPC64 = Subtarget.isPPC64();
3550   bool isSVR4ABI = Subtarget.isSVR4ABI();
3551   bool isELFv2ABI = Subtarget.isELFv2ABI();
3552
3553   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3554   NodeTys.push_back(MVT::Other);   // Returns a chain
3555   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3556
3557   unsigned CallOpc = PPCISD::CALL;
3558
3559   bool needIndirectCall = true;
3560   if (!isSVR4ABI || !isPPC64)
3561     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3562       // If this is an absolute destination address, use the munged value.
3563       Callee = SDValue(Dest, 0);
3564       needIndirectCall = false;
3565     }
3566
3567   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3568     unsigned OpFlags = 0;
3569     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3570          (Subtarget.getTargetTriple().isMacOSX() &&
3571           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3572          (G->getGlobal()->isDeclaration() ||
3573           G->getGlobal()->isWeakForLinker())) ||
3574         (Subtarget.isTargetELF() && !isPPC64 &&
3575          !G->getGlobal()->hasLocalLinkage() &&
3576          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3577       // PC-relative references to external symbols should go through $stub,
3578       // unless we're building with the leopard linker or later, which
3579       // automatically synthesizes these stubs.
3580       OpFlags = PPCII::MO_PLT_OR_STUB;
3581     }
3582
3583     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3584     // every direct call is) turn it into a TargetGlobalAddress /
3585     // TargetExternalSymbol node so that legalize doesn't hack it.
3586     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3587                                         Callee.getValueType(), 0, OpFlags);
3588     needIndirectCall = false;
3589   }
3590
3591   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3592     unsigned char OpFlags = 0;
3593
3594     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3595          (Subtarget.getTargetTriple().isMacOSX() &&
3596           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3597         (Subtarget.isTargetELF() && !isPPC64 &&
3598          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3599       // PC-relative references to external symbols should go through $stub,
3600       // unless we're building with the leopard linker or later, which
3601       // automatically synthesizes these stubs.
3602       OpFlags = PPCII::MO_PLT_OR_STUB;
3603     }
3604
3605     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3606                                          OpFlags);
3607     needIndirectCall = false;
3608   }
3609
3610   if (needIndirectCall) {
3611     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3612     // to do the call, we can't use PPCISD::CALL.
3613     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3614
3615     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3616       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3617       // entry point, but to the function descriptor (the function entry point
3618       // address is part of the function descriptor though).
3619       // The function descriptor is a three doubleword structure with the
3620       // following fields: function entry point, TOC base address and
3621       // environment pointer.
3622       // Thus for a call through a function pointer, the following actions need
3623       // to be performed:
3624       //   1. Save the TOC of the caller in the TOC save area of its stack
3625       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3626       //   2. Load the address of the function entry point from the function
3627       //      descriptor.
3628       //   3. Load the TOC of the callee from the function descriptor into r2.
3629       //   4. Load the environment pointer from the function descriptor into
3630       //      r11.
3631       //   5. Branch to the function entry point address.
3632       //   6. On return of the callee, the TOC of the caller needs to be
3633       //      restored (this is done in FinishCall()).
3634       //
3635       // All those operations are flagged together to ensure that no other
3636       // operations can be scheduled in between. E.g. without flagging the
3637       // operations together, a TOC access in the caller could be scheduled
3638       // between the load of the callee TOC and the branch to the callee, which
3639       // results in the TOC access going through the TOC of the callee instead
3640       // of going through the TOC of the caller, which leads to incorrect code.
3641
3642       // Load the address of the function entry point from the function
3643       // descriptor.
3644       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3645       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3646                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3647       Chain = LoadFuncPtr.getValue(1);
3648       InFlag = LoadFuncPtr.getValue(2);
3649
3650       // Load environment pointer into r11.
3651       // Offset of the environment pointer within the function descriptor.
3652       SDValue PtrOff = DAG.getIntPtrConstant(16);
3653
3654       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3655       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3656                                        InFlag);
3657       Chain = LoadEnvPtr.getValue(1);
3658       InFlag = LoadEnvPtr.getValue(2);
3659
3660       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3661                                         InFlag);
3662       Chain = EnvVal.getValue(0);
3663       InFlag = EnvVal.getValue(1);
3664
3665       // Load TOC of the callee into r2. We are using a target-specific load
3666       // with r2 hard coded, because the result of a target-independent load
3667       // would never go directly into r2, since r2 is a reserved register (which
3668       // prevents the register allocator from allocating it), resulting in an
3669       // additional register being allocated and an unnecessary move instruction
3670       // being generated.
3671       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3672       SDValue TOCOff = DAG.getIntPtrConstant(8);
3673       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3674       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3675                                        AddTOC, InFlag);
3676       Chain = LoadTOCPtr.getValue(0);
3677       InFlag = LoadTOCPtr.getValue(1);
3678
3679       MTCTROps[0] = Chain;
3680       MTCTROps[1] = LoadFuncPtr;
3681       MTCTROps[2] = InFlag;
3682     }
3683
3684     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3685                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3686     InFlag = Chain.getValue(1);
3687
3688     NodeTys.clear();
3689     NodeTys.push_back(MVT::Other);
3690     NodeTys.push_back(MVT::Glue);
3691     Ops.push_back(Chain);
3692     CallOpc = PPCISD::BCTRL;
3693     Callee.setNode(nullptr);
3694     // Add use of X11 (holding environment pointer)
3695     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3696       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3697     // Add CTR register as callee so a bctr can be emitted later.
3698     if (isTailCall)
3699       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3700   }
3701
3702   // If this is a direct call, pass the chain and the callee.
3703   if (Callee.getNode()) {
3704     Ops.push_back(Chain);
3705     Ops.push_back(Callee);
3706   }
3707   // If this is a tail call add stack pointer delta.
3708   if (isTailCall)
3709     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3710
3711   // Add argument registers to the end of the list so that they are known live
3712   // into the call.
3713   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3714     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3715                                   RegsToPass[i].second.getValueType()));
3716
3717   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3718   if (Callee.getNode() && isELFv2ABI)
3719     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3720
3721   return CallOpc;
3722 }
3723
3724 static
3725 bool isLocalCall(const SDValue &Callee)
3726 {
3727   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3728     return !G->getGlobal()->isDeclaration() &&
3729            !G->getGlobal()->isWeakForLinker();
3730   return false;
3731 }
3732
3733 SDValue
3734 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3735                                    CallingConv::ID CallConv, bool isVarArg,
3736                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3737                                    SDLoc dl, SelectionDAG &DAG,
3738                                    SmallVectorImpl<SDValue> &InVals) const {
3739
3740   SmallVector<CCValAssign, 16> RVLocs;
3741   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3742                     *DAG.getContext());
3743   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3744
3745   // Copy all of the result registers out of their specified physreg.
3746   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3747     CCValAssign &VA = RVLocs[i];
3748     assert(VA.isRegLoc() && "Can only return in registers!");
3749
3750     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3751                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3752     Chain = Val.getValue(1);
3753     InFlag = Val.getValue(2);
3754
3755     switch (VA.getLocInfo()) {
3756     default: llvm_unreachable("Unknown loc info!");
3757     case CCValAssign::Full: break;
3758     case CCValAssign::AExt:
3759       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3760       break;
3761     case CCValAssign::ZExt:
3762       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3763                         DAG.getValueType(VA.getValVT()));
3764       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3765       break;
3766     case CCValAssign::SExt:
3767       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3768                         DAG.getValueType(VA.getValVT()));
3769       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3770       break;
3771     }
3772
3773     InVals.push_back(Val);
3774   }
3775
3776   return Chain;
3777 }
3778
3779 SDValue
3780 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3781                               bool isTailCall, bool isVarArg,
3782                               SelectionDAG &DAG,
3783                               SmallVector<std::pair<unsigned, SDValue>, 8>
3784                                 &RegsToPass,
3785                               SDValue InFlag, SDValue Chain,
3786                               SDValue &Callee,
3787                               int SPDiff, unsigned NumBytes,
3788                               const SmallVectorImpl<ISD::InputArg> &Ins,
3789                               SmallVectorImpl<SDValue> &InVals) const {
3790
3791   bool isELFv2ABI = Subtarget.isELFv2ABI();
3792   std::vector<EVT> NodeTys;
3793   SmallVector<SDValue, 8> Ops;
3794   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3795                                  isTailCall, RegsToPass, Ops, NodeTys,
3796                                  Subtarget);
3797
3798   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3799   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3800     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3801
3802   // When performing tail call optimization the callee pops its arguments off
3803   // the stack. Account for this here so these bytes can be pushed back on in
3804   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3805   int BytesCalleePops =
3806     (CallConv == CallingConv::Fast &&
3807      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3808
3809   // Add a register mask operand representing the call-preserved registers.
3810   const TargetRegisterInfo *TRI =
3811       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3812   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3813   assert(Mask && "Missing call preserved mask for calling convention");
3814   Ops.push_back(DAG.getRegisterMask(Mask));
3815
3816   if (InFlag.getNode())
3817     Ops.push_back(InFlag);
3818
3819   // Emit tail call.
3820   if (isTailCall) {
3821     assert(((Callee.getOpcode() == ISD::Register &&
3822              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3823             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3824             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3825             isa<ConstantSDNode>(Callee)) &&
3826     "Expecting an global address, external symbol, absolute value or register");
3827
3828     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3829   }
3830
3831   // Add a NOP immediately after the branch instruction when using the 64-bit
3832   // SVR4 ABI. At link time, if caller and callee are in a different module and
3833   // thus have a different TOC, the call will be replaced with a call to a stub
3834   // function which saves the current TOC, loads the TOC of the callee and
3835   // branches to the callee. The NOP will be replaced with a load instruction
3836   // which restores the TOC of the caller from the TOC save slot of the current
3837   // stack frame. If caller and callee belong to the same module (and have the
3838   // same TOC), the NOP will remain unchanged.
3839
3840   bool needsTOCRestore = false;
3841   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3842     if (CallOpc == PPCISD::BCTRL) {
3843       // This is a call through a function pointer.
3844       // Restore the caller TOC from the save area into R2.
3845       // See PrepareCall() for more information about calls through function
3846       // pointers in the 64-bit SVR4 ABI.
3847       // We are using a target-specific load with r2 hard coded, because the
3848       // result of a target-independent load would never go directly into r2,
3849       // since r2 is a reserved register (which prevents the register allocator
3850       // from allocating it), resulting in an additional register being
3851       // allocated and an unnecessary move instruction being generated.
3852       needsTOCRestore = true;
3853     } else if ((CallOpc == PPCISD::CALL) &&
3854                (!isLocalCall(Callee) ||
3855                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3856       // Otherwise insert NOP for non-local calls.
3857       CallOpc = PPCISD::CALL_NOP;
3858     }
3859   }
3860
3861   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3862   InFlag = Chain.getValue(1);
3863
3864   if (needsTOCRestore) {
3865     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3866     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3867     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3868     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3869     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3870     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3871     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3872     InFlag = Chain.getValue(1);
3873   }
3874
3875   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3876                              DAG.getIntPtrConstant(BytesCalleePops, true),
3877                              InFlag, dl);
3878   if (!Ins.empty())
3879     InFlag = Chain.getValue(1);
3880
3881   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3882                          Ins, dl, DAG, InVals);
3883 }
3884
3885 SDValue
3886 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3887                              SmallVectorImpl<SDValue> &InVals) const {
3888   SelectionDAG &DAG                     = CLI.DAG;
3889   SDLoc &dl                             = CLI.DL;
3890   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3891   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3892   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3893   SDValue Chain                         = CLI.Chain;
3894   SDValue Callee                        = CLI.Callee;
3895   bool &isTailCall                      = CLI.IsTailCall;
3896   CallingConv::ID CallConv              = CLI.CallConv;
3897   bool isVarArg                         = CLI.IsVarArg;
3898
3899   if (isTailCall)
3900     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3901                                                    Ins, DAG);
3902
3903   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3904     report_fatal_error("failed to perform tail call elimination on a call "
3905                        "site marked musttail");
3906
3907   if (Subtarget.isSVR4ABI()) {
3908     if (Subtarget.isPPC64())
3909       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3910                               isTailCall, Outs, OutVals, Ins,
3911                               dl, DAG, InVals);
3912     else
3913       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3914                               isTailCall, Outs, OutVals, Ins,
3915                               dl, DAG, InVals);
3916   }
3917
3918   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3919                           isTailCall, Outs, OutVals, Ins,
3920                           dl, DAG, InVals);
3921 }
3922
3923 SDValue
3924 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3925                                     CallingConv::ID CallConv, bool isVarArg,
3926                                     bool isTailCall,
3927                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3928                                     const SmallVectorImpl<SDValue> &OutVals,
3929                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3930                                     SDLoc dl, SelectionDAG &DAG,
3931                                     SmallVectorImpl<SDValue> &InVals) const {
3932   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3933   // of the 32-bit SVR4 ABI stack frame layout.
3934
3935   assert((CallConv == CallingConv::C ||
3936           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3937
3938   unsigned PtrByteSize = 4;
3939
3940   MachineFunction &MF = DAG.getMachineFunction();
3941
3942   // Mark this function as potentially containing a function that contains a
3943   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3944   // and restoring the callers stack pointer in this functions epilog. This is
3945   // done because by tail calling the called function might overwrite the value
3946   // in this function's (MF) stack pointer stack slot 0(SP).
3947   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3948       CallConv == CallingConv::Fast)
3949     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3950
3951   // Count how many bytes are to be pushed on the stack, including the linkage
3952   // area, parameter list area and the part of the local variable space which
3953   // contains copies of aggregates which are passed by value.
3954
3955   // Assign locations to all of the outgoing arguments.
3956   SmallVector<CCValAssign, 16> ArgLocs;
3957   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3958                  *DAG.getContext());
3959
3960   // Reserve space for the linkage area on the stack.
3961   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3962                        PtrByteSize);
3963
3964   if (isVarArg) {
3965     // Handle fixed and variable vector arguments differently.
3966     // Fixed vector arguments go into registers as long as registers are
3967     // available. Variable vector arguments always go into memory.
3968     unsigned NumArgs = Outs.size();
3969
3970     for (unsigned i = 0; i != NumArgs; ++i) {
3971       MVT ArgVT = Outs[i].VT;
3972       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3973       bool Result;
3974
3975       if (Outs[i].IsFixed) {
3976         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3977                                CCInfo);
3978       } else {
3979         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3980                                       ArgFlags, CCInfo);
3981       }
3982
3983       if (Result) {
3984 #ifndef NDEBUG
3985         errs() << "Call operand #" << i << " has unhandled type "
3986              << EVT(ArgVT).getEVTString() << "\n";
3987 #endif
3988         llvm_unreachable(nullptr);
3989       }
3990     }
3991   } else {
3992     // All arguments are treated the same.
3993     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3994   }
3995
3996   // Assign locations to all of the outgoing aggregate by value arguments.
3997   SmallVector<CCValAssign, 16> ByValArgLocs;
3998   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3999                       ByValArgLocs, *DAG.getContext());
4000
4001   // Reserve stack space for the allocations in CCInfo.
4002   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4003
4004   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4005
4006   // Size of the linkage area, parameter list area and the part of the local
4007   // space variable where copies of aggregates which are passed by value are
4008   // stored.
4009   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4010
4011   // Calculate by how many bytes the stack has to be adjusted in case of tail
4012   // call optimization.
4013   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4014
4015   // Adjust the stack pointer for the new arguments...
4016   // These operations are automatically eliminated by the prolog/epilog pass
4017   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4018                                dl);
4019   SDValue CallSeqStart = Chain;
4020
4021   // Load the return address and frame pointer so it can be moved somewhere else
4022   // later.
4023   SDValue LROp, FPOp;
4024   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4025                                        dl);
4026
4027   // Set up a copy of the stack pointer for use loading and storing any
4028   // arguments that may not fit in the registers available for argument
4029   // passing.
4030   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4031
4032   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4033   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4034   SmallVector<SDValue, 8> MemOpChains;
4035
4036   bool seenFloatArg = false;
4037   // Walk the register/memloc assignments, inserting copies/loads.
4038   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4039        i != e;
4040        ++i) {
4041     CCValAssign &VA = ArgLocs[i];
4042     SDValue Arg = OutVals[i];
4043     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4044
4045     if (Flags.isByVal()) {
4046       // Argument is an aggregate which is passed by value, thus we need to
4047       // create a copy of it in the local variable space of the current stack
4048       // frame (which is the stack frame of the caller) and pass the address of
4049       // this copy to the callee.
4050       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4051       CCValAssign &ByValVA = ByValArgLocs[j++];
4052       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4053
4054       // Memory reserved in the local variable space of the callers stack frame.
4055       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4056
4057       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4058       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4059
4060       // Create a copy of the argument in the local area of the current
4061       // stack frame.
4062       SDValue MemcpyCall =
4063         CreateCopyOfByValArgument(Arg, PtrOff,
4064                                   CallSeqStart.getNode()->getOperand(0),
4065                                   Flags, DAG, dl);
4066
4067       // This must go outside the CALLSEQ_START..END.
4068       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4069                            CallSeqStart.getNode()->getOperand(1),
4070                            SDLoc(MemcpyCall));
4071       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4072                              NewCallSeqStart.getNode());
4073       Chain = CallSeqStart = NewCallSeqStart;
4074
4075       // Pass the address of the aggregate copy on the stack either in a
4076       // physical register or in the parameter list area of the current stack
4077       // frame to the callee.
4078       Arg = PtrOff;
4079     }
4080
4081     if (VA.isRegLoc()) {
4082       if (Arg.getValueType() == MVT::i1)
4083         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4084
4085       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4086       // Put argument in a physical register.
4087       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4088     } else {
4089       // Put argument in the parameter list area of the current stack frame.
4090       assert(VA.isMemLoc());
4091       unsigned LocMemOffset = VA.getLocMemOffset();
4092
4093       if (!isTailCall) {
4094         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4095         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4096
4097         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4098                                            MachinePointerInfo(),
4099                                            false, false, 0));
4100       } else {
4101         // Calculate and remember argument location.
4102         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4103                                  TailCallArguments);
4104       }
4105     }
4106   }
4107
4108   if (!MemOpChains.empty())
4109     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4110
4111   // Build a sequence of copy-to-reg nodes chained together with token chain
4112   // and flag operands which copy the outgoing args into the appropriate regs.
4113   SDValue InFlag;
4114   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4115     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4116                              RegsToPass[i].second, InFlag);
4117     InFlag = Chain.getValue(1);
4118   }
4119
4120   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4121   // registers.
4122   if (isVarArg) {
4123     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4124     SDValue Ops[] = { Chain, InFlag };
4125
4126     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4127                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4128
4129     InFlag = Chain.getValue(1);
4130   }
4131
4132   if (isTailCall)
4133     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4134                     false, TailCallArguments);
4135
4136   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4137                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4138                     Ins, InVals);
4139 }
4140
4141 // Copy an argument into memory, being careful to do this outside the
4142 // call sequence for the call to which the argument belongs.
4143 SDValue
4144 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4145                                               SDValue CallSeqStart,
4146                                               ISD::ArgFlagsTy Flags,
4147                                               SelectionDAG &DAG,
4148                                               SDLoc dl) const {
4149   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4150                         CallSeqStart.getNode()->getOperand(0),
4151                         Flags, DAG, dl);
4152   // The MEMCPY must go outside the CALLSEQ_START..END.
4153   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4154                              CallSeqStart.getNode()->getOperand(1),
4155                              SDLoc(MemcpyCall));
4156   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4157                          NewCallSeqStart.getNode());
4158   return NewCallSeqStart;
4159 }
4160
4161 SDValue
4162 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4163                                     CallingConv::ID CallConv, bool isVarArg,
4164                                     bool isTailCall,
4165                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4166                                     const SmallVectorImpl<SDValue> &OutVals,
4167                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4168                                     SDLoc dl, SelectionDAG &DAG,
4169                                     SmallVectorImpl<SDValue> &InVals) const {
4170
4171   bool isELFv2ABI = Subtarget.isELFv2ABI();
4172   bool isLittleEndian = Subtarget.isLittleEndian();
4173   unsigned NumOps = Outs.size();
4174
4175   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4176   unsigned PtrByteSize = 8;
4177
4178   MachineFunction &MF = DAG.getMachineFunction();
4179
4180   // Mark this function as potentially containing a function that contains a
4181   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4182   // and restoring the callers stack pointer in this functions epilog. This is
4183   // done because by tail calling the called function might overwrite the value
4184   // in this function's (MF) stack pointer stack slot 0(SP).
4185   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4186       CallConv == CallingConv::Fast)
4187     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4188
4189   // Count how many bytes are to be pushed on the stack, including the linkage
4190   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4191   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4192   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4193   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4194                                                           isELFv2ABI);
4195   unsigned NumBytes = LinkageSize;
4196
4197   // Add up all the space actually used.
4198   for (unsigned i = 0; i != NumOps; ++i) {
4199     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4200     EVT ArgVT = Outs[i].VT;
4201     EVT OrigVT = Outs[i].ArgVT;
4202
4203     /* Respect alignment of argument on the stack.  */
4204     unsigned Align =
4205       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4206     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4207
4208     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4209     if (Flags.isInConsecutiveRegsLast())
4210       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4211   }
4212
4213   unsigned NumBytesActuallyUsed = NumBytes;
4214
4215   // The prolog code of the callee may store up to 8 GPR argument registers to
4216   // the stack, allowing va_start to index over them in memory if its varargs.
4217   // Because we cannot tell if this is needed on the caller side, we have to
4218   // conservatively assume that it is needed.  As such, make sure we have at
4219   // least enough stack space for the caller to store the 8 GPRs.
4220   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4221   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4222
4223   // Tail call needs the stack to be aligned.
4224   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4225       CallConv == CallingConv::Fast)
4226     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4227
4228   // Calculate by how many bytes the stack has to be adjusted in case of tail
4229   // call optimization.
4230   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4231
4232   // To protect arguments on the stack from being clobbered in a tail call,
4233   // force all the loads to happen before doing any other lowering.
4234   if (isTailCall)
4235     Chain = DAG.getStackArgumentTokenFactor(Chain);
4236
4237   // Adjust the stack pointer for the new arguments...
4238   // These operations are automatically eliminated by the prolog/epilog pass
4239   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4240                                dl);
4241   SDValue CallSeqStart = Chain;
4242
4243   // Load the return address and frame pointer so it can be move somewhere else
4244   // later.
4245   SDValue LROp, FPOp;
4246   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4247                                        dl);
4248
4249   // Set up a copy of the stack pointer for use loading and storing any
4250   // arguments that may not fit in the registers available for argument
4251   // passing.
4252   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4253
4254   // Figure out which arguments are going to go in registers, and which in
4255   // memory.  Also, if this is a vararg function, floating point operations
4256   // must be stored to our stack, and loaded into integer regs as well, if
4257   // any integer regs are available for argument passing.
4258   unsigned ArgOffset = LinkageSize;
4259   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4260
4261   static const MCPhysReg GPR[] = {
4262     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4263     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4264   };
4265   static const MCPhysReg *FPR = GetFPR();
4266
4267   static const MCPhysReg VR[] = {
4268     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4269     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4270   };
4271   static const MCPhysReg VSRH[] = {
4272     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4273     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4274   };
4275
4276   const unsigned NumGPRs = array_lengthof(GPR);
4277   const unsigned NumFPRs = 13;
4278   const unsigned NumVRs  = array_lengthof(VR);
4279
4280   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4281   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4282
4283   SmallVector<SDValue, 8> MemOpChains;
4284   for (unsigned i = 0; i != NumOps; ++i) {
4285     SDValue Arg = OutVals[i];
4286     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4287     EVT ArgVT = Outs[i].VT;
4288     EVT OrigVT = Outs[i].ArgVT;
4289
4290     /* Respect alignment of argument on the stack.  */
4291     unsigned Align =
4292       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4293     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4294
4295     /* Compute GPR index associated with argument offset.  */
4296     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4297     GPR_idx = std::min(GPR_idx, NumGPRs);
4298
4299     // PtrOff will be used to store the current argument to the stack if a
4300     // register cannot be found for it.
4301     SDValue PtrOff;
4302
4303     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4304
4305     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4306
4307     // Promote integers to 64-bit values.
4308     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4309       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4310       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4311       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4312     }
4313
4314     // FIXME memcpy is used way more than necessary.  Correctness first.
4315     // Note: "by value" is code for passing a structure by value, not
4316     // basic types.
4317     if (Flags.isByVal()) {
4318       // Note: Size includes alignment padding, so
4319       //   struct x { short a; char b; }
4320       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4321       // These are the proper values we need for right-justifying the
4322       // aggregate in a parameter register.
4323       unsigned Size = Flags.getByValSize();
4324
4325       // An empty aggregate parameter takes up no storage and no
4326       // registers.
4327       if (Size == 0)
4328         continue;
4329
4330       // All aggregates smaller than 8 bytes must be passed right-justified.
4331       if (Size==1 || Size==2 || Size==4) {
4332         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4333         if (GPR_idx != NumGPRs) {
4334           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4335                                         MachinePointerInfo(), VT,
4336                                         false, false, false, 0);
4337           MemOpChains.push_back(Load.getValue(1));
4338           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4339
4340           ArgOffset += PtrByteSize;
4341           continue;
4342         }
4343       }
4344
4345       if (GPR_idx == NumGPRs && Size < 8) {
4346         SDValue AddPtr = PtrOff;
4347         if (!isLittleEndian) {
4348           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4349                                           PtrOff.getValueType());
4350           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4351         }
4352         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4353                                                           CallSeqStart,
4354                                                           Flags, DAG, dl);
4355         ArgOffset += PtrByteSize;
4356         continue;
4357       }
4358       // Copy entire object into memory.  There are cases where gcc-generated
4359       // code assumes it is there, even if it could be put entirely into
4360       // registers.  (This is not what the doc says.)
4361
4362       // FIXME: The above statement is likely due to a misunderstanding of the
4363       // documents.  All arguments must be copied into the parameter area BY
4364       // THE CALLEE in the event that the callee takes the address of any
4365       // formal argument.  That has not yet been implemented.  However, it is
4366       // reasonable to use the stack area as a staging area for the register
4367       // load.
4368
4369       // Skip this for small aggregates, as we will use the same slot for a
4370       // right-justified copy, below.
4371       if (Size >= 8)
4372         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4373                                                           CallSeqStart,
4374                                                           Flags, DAG, dl);
4375
4376       // When a register is available, pass a small aggregate right-justified.
4377       if (Size < 8 && GPR_idx != NumGPRs) {
4378         // The easiest way to get this right-justified in a register
4379         // is to copy the structure into the rightmost portion of a
4380         // local variable slot, then load the whole slot into the
4381         // register.
4382         // FIXME: The memcpy seems to produce pretty awful code for
4383         // small aggregates, particularly for packed ones.
4384         // FIXME: It would be preferable to use the slot in the
4385         // parameter save area instead of a new local variable.
4386         SDValue AddPtr = PtrOff;
4387         if (!isLittleEndian) {
4388           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4389           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4390         }
4391         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4392                                                           CallSeqStart,
4393                                                           Flags, DAG, dl);
4394
4395         // Load the slot into the register.
4396         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4397                                    MachinePointerInfo(),
4398                                    false, false, false, 0);
4399         MemOpChains.push_back(Load.getValue(1));
4400         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4401
4402         // Done with this argument.
4403         ArgOffset += PtrByteSize;
4404         continue;
4405       }
4406
4407       // For aggregates larger than PtrByteSize, copy the pieces of the
4408       // object that fit into registers from the parameter save area.
4409       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4410         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4411         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4412         if (GPR_idx != NumGPRs) {
4413           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4414                                      MachinePointerInfo(),
4415                                      false, false, false, 0);
4416           MemOpChains.push_back(Load.getValue(1));
4417           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4418           ArgOffset += PtrByteSize;
4419         } else {
4420           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4421           break;
4422         }
4423       }
4424       continue;
4425     }
4426
4427     switch (Arg.getSimpleValueType().SimpleTy) {
4428     default: llvm_unreachable("Unexpected ValueType for argument!");
4429     case MVT::i1:
4430     case MVT::i32:
4431     case MVT::i64:
4432       // These can be scalar arguments or elements of an integer array type
4433       // passed directly.  Clang may use those instead of "byval" aggregate
4434       // types to avoid forcing arguments to memory unnecessarily.
4435       if (GPR_idx != NumGPRs) {
4436         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4437       } else {
4438         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4439                          true, isTailCall, false, MemOpChains,
4440                          TailCallArguments, dl);
4441       }
4442       ArgOffset += PtrByteSize;
4443       break;
4444     case MVT::f32:
4445     case MVT::f64: {
4446       // These can be scalar arguments or elements of a float array type
4447       // passed directly.  The latter are used to implement ELFv2 homogenous
4448       // float aggregates.
4449
4450       // Named arguments go into FPRs first, and once they overflow, the
4451       // remaining arguments go into GPRs and then the parameter save area.
4452       // Unnamed arguments for vararg functions always go to GPRs and
4453       // then the parameter save area.  For now, put all arguments to vararg
4454       // routines always in both locations (FPR *and* GPR or stack slot).
4455       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4456
4457       // First load the argument into the next available FPR.
4458       if (FPR_idx != NumFPRs)
4459         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4460
4461       // Next, load the argument into GPR or stack slot if needed.
4462       if (!NeedGPROrStack)
4463         ;
4464       else if (GPR_idx != NumGPRs) {
4465         // In the non-vararg case, this can only ever happen in the
4466         // presence of f32 array types, since otherwise we never run
4467         // out of FPRs before running out of GPRs.
4468         SDValue ArgVal;
4469
4470         // Double values are always passed in a single GPR.
4471         if (Arg.getValueType() != MVT::f32) {
4472           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4473
4474         // Non-array float values are extended and passed in a GPR.
4475         } else if (!Flags.isInConsecutiveRegs()) {
4476           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4477           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4478
4479         // If we have an array of floats, we collect every odd element
4480         // together with its predecessor into one GPR.
4481         } else if (ArgOffset % PtrByteSize != 0) {
4482           SDValue Lo, Hi;
4483           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4484           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4485           if (!isLittleEndian)
4486             std::swap(Lo, Hi);
4487           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4488
4489         // The final element, if even, goes into the first half of a GPR.
4490         } else if (Flags.isInConsecutiveRegsLast()) {
4491           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4492           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4493           if (!isLittleEndian)
4494             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4495                                  DAG.getConstant(32, MVT::i32));
4496
4497         // Non-final even elements are skipped; they will be handled
4498         // together the with subsequent argument on the next go-around.
4499         } else
4500           ArgVal = SDValue();
4501
4502         if (ArgVal.getNode())
4503           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4504       } else {
4505         // Single-precision floating-point values are mapped to the
4506         // second (rightmost) word of the stack doubleword.
4507         if (Arg.getValueType() == MVT::f32 &&
4508             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4509           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4510           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4511         }
4512
4513         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4514                          true, isTailCall, false, MemOpChains,
4515                          TailCallArguments, dl);
4516       }
4517       // When passing an array of floats, the array occupies consecutive
4518       // space in the argument area; only round up to the next doubleword
4519       // at the end of the array.  Otherwise, each float takes 8 bytes.
4520       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4521                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4522       if (Flags.isInConsecutiveRegsLast())
4523         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4524       break;
4525     }
4526     case MVT::v4f32:
4527     case MVT::v4i32:
4528     case MVT::v8i16:
4529     case MVT::v16i8:
4530     case MVT::v2f64:
4531     case MVT::v2i64:
4532       // These can be scalar arguments or elements of a vector array type
4533       // passed directly.  The latter are used to implement ELFv2 homogenous
4534       // vector aggregates.
4535
4536       // For a varargs call, named arguments go into VRs or on the stack as
4537       // usual; unnamed arguments always go to the stack or the corresponding
4538       // GPRs when within range.  For now, we always put the value in both
4539       // locations (or even all three).
4540       if (isVarArg) {
4541         // We could elide this store in the case where the object fits
4542         // entirely in R registers.  Maybe later.
4543         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4544                                      MachinePointerInfo(), false, false, 0);
4545         MemOpChains.push_back(Store);
4546         if (VR_idx != NumVRs) {
4547           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4548                                      MachinePointerInfo(),
4549                                      false, false, false, 0);
4550           MemOpChains.push_back(Load.getValue(1));
4551
4552           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4553                            Arg.getSimpleValueType() == MVT::v2i64) ?
4554                           VSRH[VR_idx] : VR[VR_idx];
4555           ++VR_idx;
4556
4557           RegsToPass.push_back(std::make_pair(VReg, Load));
4558         }
4559         ArgOffset += 16;
4560         for (unsigned i=0; i<16; i+=PtrByteSize) {
4561           if (GPR_idx == NumGPRs)
4562             break;
4563           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4564                                   DAG.getConstant(i, PtrVT));
4565           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4566                                      false, false, false, 0);
4567           MemOpChains.push_back(Load.getValue(1));
4568           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4569         }
4570         break;
4571       }
4572
4573       // Non-varargs Altivec params go into VRs or on the stack.
4574       if (VR_idx != NumVRs) {
4575         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4576                          Arg.getSimpleValueType() == MVT::v2i64) ?
4577                         VSRH[VR_idx] : VR[VR_idx];
4578         ++VR_idx;
4579
4580         RegsToPass.push_back(std::make_pair(VReg, Arg));
4581       } else {
4582         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4583                          true, isTailCall, true, MemOpChains,
4584                          TailCallArguments, dl);
4585       }
4586       ArgOffset += 16;
4587       break;
4588     }
4589   }
4590
4591   assert(NumBytesActuallyUsed == ArgOffset);
4592   (void)NumBytesActuallyUsed;
4593
4594   if (!MemOpChains.empty())
4595     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4596
4597   // Check if this is an indirect call (MTCTR/BCTRL).
4598   // See PrepareCall() for more information about calls through function
4599   // pointers in the 64-bit SVR4 ABI.
4600   if (!isTailCall &&
4601       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4602       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4603     // Load r2 into a virtual register and store it to the TOC save area.
4604     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4605     // TOC save area offset.
4606     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4607     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4608     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4609     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4610                          false, false, 0);
4611     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4612     // This does not mean the MTCTR instruction must use R12; it's easier
4613     // to model this as an extra parameter, so do that.
4614     if (isELFv2ABI)
4615       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4616   }
4617
4618   // Build a sequence of copy-to-reg nodes chained together with token chain
4619   // and flag operands which copy the outgoing args into the appropriate regs.
4620   SDValue InFlag;
4621   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4622     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4623                              RegsToPass[i].second, InFlag);
4624     InFlag = Chain.getValue(1);
4625   }
4626
4627   if (isTailCall)
4628     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4629                     FPOp, true, TailCallArguments);
4630
4631   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4632                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4633                     Ins, InVals);
4634 }
4635
4636 SDValue
4637 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4638                                     CallingConv::ID CallConv, bool isVarArg,
4639                                     bool isTailCall,
4640                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4641                                     const SmallVectorImpl<SDValue> &OutVals,
4642                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4643                                     SDLoc dl, SelectionDAG &DAG,
4644                                     SmallVectorImpl<SDValue> &InVals) const {
4645
4646   unsigned NumOps = Outs.size();
4647
4648   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4649   bool isPPC64 = PtrVT == MVT::i64;
4650   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4651
4652   MachineFunction &MF = DAG.getMachineFunction();
4653
4654   // Mark this function as potentially containing a function that contains a
4655   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4656   // and restoring the callers stack pointer in this functions epilog. This is
4657   // done because by tail calling the called function might overwrite the value
4658   // in this function's (MF) stack pointer stack slot 0(SP).
4659   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4660       CallConv == CallingConv::Fast)
4661     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4662
4663   // Count how many bytes are to be pushed on the stack, including the linkage
4664   // area, and parameter passing area.  We start with 24/48 bytes, which is
4665   // prereserved space for [SP][CR][LR][3 x unused].
4666   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4667                                                           false);
4668   unsigned NumBytes = LinkageSize;
4669
4670   // Add up all the space actually used.
4671   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4672   // they all go in registers, but we must reserve stack space for them for
4673   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4674   // assigned stack space in order, with padding so Altivec parameters are
4675   // 16-byte aligned.
4676   unsigned nAltivecParamsAtEnd = 0;
4677   for (unsigned i = 0; i != NumOps; ++i) {
4678     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4679     EVT ArgVT = Outs[i].VT;
4680     // Varargs Altivec parameters are padded to a 16 byte boundary.
4681     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4682         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4683         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4684       if (!isVarArg && !isPPC64) {
4685         // Non-varargs Altivec parameters go after all the non-Altivec
4686         // parameters; handle those later so we know how much padding we need.
4687         nAltivecParamsAtEnd++;
4688         continue;
4689       }
4690       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4691       NumBytes = ((NumBytes+15)/16)*16;
4692     }
4693     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4694   }
4695
4696   // Allow for Altivec parameters at the end, if needed.
4697   if (nAltivecParamsAtEnd) {
4698     NumBytes = ((NumBytes+15)/16)*16;
4699     NumBytes += 16*nAltivecParamsAtEnd;
4700   }
4701
4702   // The prolog code of the callee may store up to 8 GPR argument registers to
4703   // the stack, allowing va_start to index over them in memory if its varargs.
4704   // Because we cannot tell if this is needed on the caller side, we have to
4705   // conservatively assume that it is needed.  As such, make sure we have at
4706   // least enough stack space for the caller to store the 8 GPRs.
4707   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4708
4709   // Tail call needs the stack to be aligned.
4710   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4711       CallConv == CallingConv::Fast)
4712     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4713
4714   // Calculate by how many bytes the stack has to be adjusted in case of tail
4715   // call optimization.
4716   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4717
4718   // To protect arguments on the stack from being clobbered in a tail call,
4719   // force all the loads to happen before doing any other lowering.
4720   if (isTailCall)
4721     Chain = DAG.getStackArgumentTokenFactor(Chain);
4722
4723   // Adjust the stack pointer for the new arguments...
4724   // These operations are automatically eliminated by the prolog/epilog pass
4725   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4726                                dl);
4727   SDValue CallSeqStart = Chain;
4728
4729   // Load the return address and frame pointer so it can be move somewhere else
4730   // later.
4731   SDValue LROp, FPOp;
4732   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4733                                        dl);
4734
4735   // Set up a copy of the stack pointer for use loading and storing any
4736   // arguments that may not fit in the registers available for argument
4737   // passing.
4738   SDValue StackPtr;
4739   if (isPPC64)
4740     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4741   else
4742     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4743
4744   // Figure out which arguments are going to go in registers, and which in
4745   // memory.  Also, if this is a vararg function, floating point operations
4746   // must be stored to our stack, and loaded into integer regs as well, if
4747   // any integer regs are available for argument passing.
4748   unsigned ArgOffset = LinkageSize;
4749   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4750
4751   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4752     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4753     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4754   };
4755   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4756     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4757     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4758   };
4759   static const MCPhysReg *FPR = GetFPR();
4760
4761   static const MCPhysReg VR[] = {
4762     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4763     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4764   };
4765   const unsigned NumGPRs = array_lengthof(GPR_32);
4766   const unsigned NumFPRs = 13;
4767   const unsigned NumVRs  = array_lengthof(VR);
4768
4769   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4770
4771   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4772   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4773
4774   SmallVector<SDValue, 8> MemOpChains;
4775   for (unsigned i = 0; i != NumOps; ++i) {
4776     SDValue Arg = OutVals[i];
4777     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4778
4779     // PtrOff will be used to store the current argument to the stack if a
4780     // register cannot be found for it.
4781     SDValue PtrOff;
4782
4783     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4784
4785     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4786
4787     // On PPC64, promote integers to 64-bit values.
4788     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4789       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4790       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4791       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4792     }
4793
4794     // FIXME memcpy is used way more than necessary.  Correctness first.
4795     // Note: "by value" is code for passing a structure by value, not
4796     // basic types.
4797     if (Flags.isByVal()) {
4798       unsigned Size = Flags.getByValSize();
4799       // Very small objects are passed right-justified.  Everything else is
4800       // passed left-justified.
4801       if (Size==1 || Size==2) {
4802         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4803         if (GPR_idx != NumGPRs) {
4804           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4805                                         MachinePointerInfo(), VT,
4806                                         false, false, false, 0);
4807           MemOpChains.push_back(Load.getValue(1));
4808           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4809
4810           ArgOffset += PtrByteSize;
4811         } else {
4812           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4813                                           PtrOff.getValueType());
4814           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4815           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4816                                                             CallSeqStart,
4817                                                             Flags, DAG, dl);
4818           ArgOffset += PtrByteSize;
4819         }
4820         continue;
4821       }
4822       // Copy entire object into memory.  There are cases where gcc-generated
4823       // code assumes it is there, even if it could be put entirely into
4824       // registers.  (This is not what the doc says.)
4825       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4826                                                         CallSeqStart,
4827                                                         Flags, DAG, dl);
4828
4829       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4830       // copy the pieces of the object that fit into registers from the
4831       // parameter save area.
4832       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4833         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4834         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4835         if (GPR_idx != NumGPRs) {
4836           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4837                                      MachinePointerInfo(),
4838                                      false, false, false, 0);
4839           MemOpChains.push_back(Load.getValue(1));
4840           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4841           ArgOffset += PtrByteSize;
4842         } else {
4843           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4844           break;
4845         }
4846       }
4847       continue;
4848     }
4849
4850     switch (Arg.getSimpleValueType().SimpleTy) {
4851     default: llvm_unreachable("Unexpected ValueType for argument!");
4852     case MVT::i1:
4853     case MVT::i32:
4854     case MVT::i64:
4855       if (GPR_idx != NumGPRs) {
4856         if (Arg.getValueType() == MVT::i1)
4857           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4858
4859         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4860       } else {
4861         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4862                          isPPC64, isTailCall, false, MemOpChains,
4863                          TailCallArguments, dl);
4864       }
4865       ArgOffset += PtrByteSize;
4866       break;
4867     case MVT::f32:
4868     case MVT::f64:
4869       if (FPR_idx != NumFPRs) {
4870         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4871
4872         if (isVarArg) {
4873           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4874                                        MachinePointerInfo(), false, false, 0);
4875           MemOpChains.push_back(Store);
4876
4877           // Float varargs are always shadowed in available integer registers
4878           if (GPR_idx != NumGPRs) {
4879             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4880                                        MachinePointerInfo(), false, false,
4881                                        false, 0);
4882             MemOpChains.push_back(Load.getValue(1));
4883             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4884           }
4885           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4886             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4887             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4888             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4889                                        MachinePointerInfo(),
4890                                        false, false, false, 0);
4891             MemOpChains.push_back(Load.getValue(1));
4892             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4893           }
4894         } else {
4895           // If we have any FPRs remaining, we may also have GPRs remaining.
4896           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4897           // GPRs.
4898           if (GPR_idx != NumGPRs)
4899             ++GPR_idx;
4900           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4901               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4902             ++GPR_idx;
4903         }
4904       } else
4905         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4906                          isPPC64, isTailCall, false, MemOpChains,
4907                          TailCallArguments, dl);
4908       if (isPPC64)
4909         ArgOffset += 8;
4910       else
4911         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4912       break;
4913     case MVT::v4f32:
4914     case MVT::v4i32:
4915     case MVT::v8i16:
4916     case MVT::v16i8:
4917       if (isVarArg) {
4918         // These go aligned on the stack, or in the corresponding R registers
4919         // when within range.  The Darwin PPC ABI doc claims they also go in
4920         // V registers; in fact gcc does this only for arguments that are
4921         // prototyped, not for those that match the ...  We do it for all
4922         // arguments, seems to work.
4923         while (ArgOffset % 16 !=0) {
4924           ArgOffset += PtrByteSize;
4925           if (GPR_idx != NumGPRs)
4926             GPR_idx++;
4927         }
4928         // We could elide this store in the case where the object fits
4929         // entirely in R registers.  Maybe later.
4930         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4931                             DAG.getConstant(ArgOffset, PtrVT));
4932         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4933                                      MachinePointerInfo(), false, false, 0);
4934         MemOpChains.push_back(Store);
4935         if (VR_idx != NumVRs) {
4936           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4937                                      MachinePointerInfo(),
4938                                      false, false, false, 0);
4939           MemOpChains.push_back(Load.getValue(1));
4940           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4941         }
4942         ArgOffset += 16;
4943         for (unsigned i=0; i<16; i+=PtrByteSize) {
4944           if (GPR_idx == NumGPRs)
4945             break;
4946           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4947                                   DAG.getConstant(i, PtrVT));
4948           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4949                                      false, false, false, 0);
4950           MemOpChains.push_back(Load.getValue(1));
4951           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4952         }
4953         break;
4954       }
4955
4956       // Non-varargs Altivec params generally go in registers, but have
4957       // stack space allocated at the end.
4958       if (VR_idx != NumVRs) {
4959         // Doesn't have GPR space allocated.
4960         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4961       } else if (nAltivecParamsAtEnd==0) {
4962         // We are emitting Altivec params in order.
4963         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4964                          isPPC64, isTailCall, true, MemOpChains,
4965                          TailCallArguments, dl);
4966         ArgOffset += 16;
4967       }
4968       break;
4969     }
4970   }
4971   // If all Altivec parameters fit in registers, as they usually do,
4972   // they get stack space following the non-Altivec parameters.  We
4973   // don't track this here because nobody below needs it.
4974   // If there are more Altivec parameters than fit in registers emit
4975   // the stores here.
4976   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4977     unsigned j = 0;
4978     // Offset is aligned; skip 1st 12 params which go in V registers.
4979     ArgOffset = ((ArgOffset+15)/16)*16;
4980     ArgOffset += 12*16;
4981     for (unsigned i = 0; i != NumOps; ++i) {
4982       SDValue Arg = OutVals[i];
4983       EVT ArgType = Outs[i].VT;
4984       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4985           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4986         if (++j > NumVRs) {
4987           SDValue PtrOff;
4988           // We are emitting Altivec params in order.
4989           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4990                            isPPC64, isTailCall, true, MemOpChains,
4991                            TailCallArguments, dl);
4992           ArgOffset += 16;
4993         }
4994       }
4995     }
4996   }
4997
4998   if (!MemOpChains.empty())
4999     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5000
5001   // On Darwin, R12 must contain the address of an indirect callee.  This does
5002   // not mean the MTCTR instruction must use R12; it's easier to model this as
5003   // an extra parameter, so do that.
5004   if (!isTailCall &&
5005       !dyn_cast<GlobalAddressSDNode>(Callee) &&
5006       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5007       !isBLACompatibleAddress(Callee, DAG))
5008     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5009                                                    PPC::R12), Callee));
5010
5011   // Build a sequence of copy-to-reg nodes chained together with token chain
5012   // and flag operands which copy the outgoing args into the appropriate regs.
5013   SDValue InFlag;
5014   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5015     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5016                              RegsToPass[i].second, InFlag);
5017     InFlag = Chain.getValue(1);
5018   }
5019
5020   if (isTailCall)
5021     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5022                     FPOp, true, TailCallArguments);
5023
5024   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5025                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5026                     Ins, InVals);
5027 }
5028
5029 bool
5030 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5031                                   MachineFunction &MF, bool isVarArg,
5032                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5033                                   LLVMContext &Context) const {
5034   SmallVector<CCValAssign, 16> RVLocs;
5035   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5036   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5037 }
5038
5039 SDValue
5040 PPCTargetLowering::LowerReturn(SDValue Chain,
5041                                CallingConv::ID CallConv, bool isVarArg,
5042                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5043                                const SmallVectorImpl<SDValue> &OutVals,
5044                                SDLoc dl, SelectionDAG &DAG) const {
5045
5046   SmallVector<CCValAssign, 16> RVLocs;
5047   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5048                  *DAG.getContext());
5049   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5050
5051   SDValue Flag;
5052   SmallVector<SDValue, 4> RetOps(1, Chain);
5053
5054   // Copy the result values into the output registers.
5055   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5056     CCValAssign &VA = RVLocs[i];
5057     assert(VA.isRegLoc() && "Can only return in registers!");
5058
5059     SDValue Arg = OutVals[i];
5060
5061     switch (VA.getLocInfo()) {
5062     default: llvm_unreachable("Unknown loc info!");
5063     case CCValAssign::Full: break;
5064     case CCValAssign::AExt:
5065       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5066       break;
5067     case CCValAssign::ZExt:
5068       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5069       break;
5070     case CCValAssign::SExt:
5071       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5072       break;
5073     }
5074
5075     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5076     Flag = Chain.getValue(1);
5077     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5078   }
5079
5080   RetOps[0] = Chain;  // Update chain.
5081
5082   // Add the flag if we have it.
5083   if (Flag.getNode())
5084     RetOps.push_back(Flag);
5085
5086   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5087 }
5088
5089 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5090                                    const PPCSubtarget &Subtarget) const {
5091   // When we pop the dynamic allocation we need to restore the SP link.
5092   SDLoc dl(Op);
5093
5094   // Get the corect type for pointers.
5095   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5096
5097   // Construct the stack pointer operand.
5098   bool isPPC64 = Subtarget.isPPC64();
5099   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5100   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5101
5102   // Get the operands for the STACKRESTORE.
5103   SDValue Chain = Op.getOperand(0);
5104   SDValue SaveSP = Op.getOperand(1);
5105
5106   // Load the old link SP.
5107   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5108                                    MachinePointerInfo(),
5109                                    false, false, false, 0);
5110
5111   // Restore the stack pointer.
5112   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5113
5114   // Store the old link SP.
5115   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5116                       false, false, 0);
5117 }
5118
5119
5120
5121 SDValue
5122 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5123   MachineFunction &MF = DAG.getMachineFunction();
5124   bool isPPC64 = Subtarget.isPPC64();
5125   bool isDarwinABI = Subtarget.isDarwinABI();
5126   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5127
5128   // Get current frame pointer save index.  The users of this index will be
5129   // primarily DYNALLOC instructions.
5130   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5131   int RASI = FI->getReturnAddrSaveIndex();
5132
5133   // If the frame pointer save index hasn't been defined yet.
5134   if (!RASI) {
5135     // Find out what the fix offset of the frame pointer save area.
5136     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5137     // Allocate the frame index for frame pointer save area.
5138     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5139     // Save the result.
5140     FI->setReturnAddrSaveIndex(RASI);
5141   }
5142   return DAG.getFrameIndex(RASI, PtrVT);
5143 }
5144
5145 SDValue
5146 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5147   MachineFunction &MF = DAG.getMachineFunction();
5148   bool isPPC64 = Subtarget.isPPC64();
5149   bool isDarwinABI = Subtarget.isDarwinABI();
5150   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5151
5152   // Get current frame pointer save index.  The users of this index will be
5153   // primarily DYNALLOC instructions.
5154   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5155   int FPSI = FI->getFramePointerSaveIndex();
5156
5157   // If the frame pointer save index hasn't been defined yet.
5158   if (!FPSI) {
5159     // Find out what the fix offset of the frame pointer save area.
5160     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5161                                                            isDarwinABI);
5162
5163     // Allocate the frame index for frame pointer save area.
5164     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5165     // Save the result.
5166     FI->setFramePointerSaveIndex(FPSI);
5167   }
5168   return DAG.getFrameIndex(FPSI, PtrVT);
5169 }
5170
5171 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5172                                          SelectionDAG &DAG,
5173                                          const PPCSubtarget &Subtarget) const {
5174   // Get the inputs.
5175   SDValue Chain = Op.getOperand(0);
5176   SDValue Size  = Op.getOperand(1);
5177   SDLoc dl(Op);
5178
5179   // Get the corect type for pointers.
5180   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5181   // Negate the size.
5182   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5183                                   DAG.getConstant(0, PtrVT), Size);
5184   // Construct a node for the frame pointer save index.
5185   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5186   // Build a DYNALLOC node.
5187   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5188   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5189   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5190 }
5191
5192 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5193                                                SelectionDAG &DAG) const {
5194   SDLoc DL(Op);
5195   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5196                      DAG.getVTList(MVT::i32, MVT::Other),
5197                      Op.getOperand(0), Op.getOperand(1));
5198 }
5199
5200 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5201                                                 SelectionDAG &DAG) const {
5202   SDLoc DL(Op);
5203   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5204                      Op.getOperand(0), Op.getOperand(1));
5205 }
5206
5207 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5208   assert(Op.getValueType() == MVT::i1 &&
5209          "Custom lowering only for i1 loads");
5210
5211   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5212
5213   SDLoc dl(Op);
5214   LoadSDNode *LD = cast<LoadSDNode>(Op);
5215
5216   SDValue Chain = LD->getChain();
5217   SDValue BasePtr = LD->getBasePtr();
5218   MachineMemOperand *MMO = LD->getMemOperand();
5219
5220   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5221                                  BasePtr, MVT::i8, MMO);
5222   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5223
5224   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5225   return DAG.getMergeValues(Ops, dl);
5226 }
5227
5228 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5229   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5230          "Custom lowering only for i1 stores");
5231
5232   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5233
5234   SDLoc dl(Op);
5235   StoreSDNode *ST = cast<StoreSDNode>(Op);
5236
5237   SDValue Chain = ST->getChain();
5238   SDValue BasePtr = ST->getBasePtr();
5239   SDValue Value = ST->getValue();
5240   MachineMemOperand *MMO = ST->getMemOperand();
5241
5242   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5243   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5244 }
5245
5246 // FIXME: Remove this once the ANDI glue bug is fixed:
5247 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5248   assert(Op.getValueType() == MVT::i1 &&
5249          "Custom lowering only for i1 results");
5250
5251   SDLoc DL(Op);
5252   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5253                      Op.getOperand(0));
5254 }
5255
5256 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5257 /// possible.
5258 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5259   // Not FP? Not a fsel.
5260   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5261       !Op.getOperand(2).getValueType().isFloatingPoint())
5262     return Op;
5263
5264   // We might be able to do better than this under some circumstances, but in
5265   // general, fsel-based lowering of select is a finite-math-only optimization.
5266   // For more information, see section F.3 of the 2.06 ISA specification.
5267   if (!DAG.getTarget().Options.NoInfsFPMath ||
5268       !DAG.getTarget().Options.NoNaNsFPMath)
5269     return Op;
5270
5271   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5272
5273   EVT ResVT = Op.getValueType();
5274   EVT CmpVT = Op.getOperand(0).getValueType();
5275   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5276   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5277   SDLoc dl(Op);
5278
5279   // If the RHS of the comparison is a 0.0, we don't need to do the
5280   // subtraction at all.
5281   SDValue Sel1;
5282   if (isFloatingPointZero(RHS))
5283     switch (CC) {
5284     default: break;       // SETUO etc aren't handled by fsel.
5285     case ISD::SETNE:
5286       std::swap(TV, FV);
5287     case ISD::SETEQ:
5288       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5289         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5290       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5291       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5292         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5293       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5294                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5295     case ISD::SETULT:
5296     case ISD::SETLT:
5297       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5298     case ISD::SETOGE:
5299     case ISD::SETGE:
5300       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5301         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5302       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5303     case ISD::SETUGT:
5304     case ISD::SETGT:
5305       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5306     case ISD::SETOLE:
5307     case ISD::SETLE:
5308       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5309         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5310       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5311                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5312     }
5313
5314   SDValue Cmp;
5315   switch (CC) {
5316   default: break;       // SETUO etc aren't handled by fsel.
5317   case ISD::SETNE:
5318     std::swap(TV, FV);
5319   case ISD::SETEQ:
5320     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5321     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5322       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5323     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5324     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5325       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5326     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5327                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5328   case ISD::SETULT:
5329   case ISD::SETLT:
5330     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5331     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5332       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5333     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5334   case ISD::SETOGE:
5335   case ISD::SETGE:
5336     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5337     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5338       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5339     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5340   case ISD::SETUGT:
5341   case ISD::SETGT:
5342     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5343     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5344       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5345     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5346   case ISD::SETOLE:
5347   case ISD::SETLE:
5348     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5349     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5350       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5351     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5352   }
5353   return Op;
5354 }
5355
5356 // FIXME: Split this code up when LegalizeDAGTypes lands.
5357 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5358                                            SDLoc dl) const {
5359   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5360   SDValue Src = Op.getOperand(0);
5361   if (Src.getValueType() == MVT::f32)
5362     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5363
5364   SDValue Tmp;
5365   switch (Op.getSimpleValueType().SimpleTy) {
5366   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5367   case MVT::i32:
5368     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5369                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5370                                                    PPCISD::FCTIDZ),
5371                       dl, MVT::f64, Src);
5372     break;
5373   case MVT::i64:
5374     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5375            "i64 FP_TO_UINT is supported only with FPCVT");
5376     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5377                                                         PPCISD::FCTIDUZ,
5378                       dl, MVT::f64, Src);
5379     break;
5380   }
5381
5382   // Convert the FP value to an int value through memory.
5383   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5384     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5385   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5386   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5387   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5388
5389   // Emit a store to the stack slot.
5390   SDValue Chain;
5391   if (i32Stack) {
5392     MachineFunction &MF = DAG.getMachineFunction();
5393     MachineMemOperand *MMO =
5394       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5395     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5396     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5397               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5398   } else
5399     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5400                          MPI, false, false, 0);
5401
5402   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5403   // add in a bias.
5404   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5405     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5406                         DAG.getConstant(4, FIPtr.getValueType()));
5407     MPI = MachinePointerInfo();
5408   }
5409
5410   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5411                      false, false, false, 0);
5412 }
5413
5414 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5415                                            SelectionDAG &DAG) const {
5416   SDLoc dl(Op);
5417   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5418   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5419     return SDValue();
5420
5421   if (Op.getOperand(0).getValueType() == MVT::i1)
5422     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5423                        DAG.getConstantFP(1.0, Op.getValueType()),
5424                        DAG.getConstantFP(0.0, Op.getValueType()));
5425
5426   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5427          "UINT_TO_FP is supported only with FPCVT");
5428
5429   // If we have FCFIDS, then use it when converting to single-precision.
5430   // Otherwise, convert to double-precision and then round.
5431   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5432                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5433                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5434                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5435                     PPCISD::FCFIDU : PPCISD::FCFID);
5436   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5437                    MVT::f32 : MVT::f64;
5438
5439   if (Op.getOperand(0).getValueType() == MVT::i64) {
5440     SDValue SINT = Op.getOperand(0);
5441     // When converting to single-precision, we actually need to convert
5442     // to double-precision first and then round to single-precision.
5443     // To avoid double-rounding effects during that operation, we have
5444     // to prepare the input operand.  Bits that might be truncated when
5445     // converting to double-precision are replaced by a bit that won't
5446     // be lost at this stage, but is below the single-precision rounding
5447     // position.
5448     //
5449     // However, if -enable-unsafe-fp-math is in effect, accept double
5450     // rounding to avoid the extra overhead.
5451     if (Op.getValueType() == MVT::f32 &&
5452         !Subtarget.hasFPCVT() &&
5453         !DAG.getTarget().Options.UnsafeFPMath) {
5454
5455       // Twiddle input to make sure the low 11 bits are zero.  (If this
5456       // is the case, we are guaranteed the value will fit into the 53 bit
5457       // mantissa of an IEEE double-precision value without rounding.)
5458       // If any of those low 11 bits were not zero originally, make sure
5459       // bit 12 (value 2048) is set instead, so that the final rounding
5460       // to single-precision gets the correct result.
5461       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5462                                   SINT, DAG.getConstant(2047, MVT::i64));
5463       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5464                           Round, DAG.getConstant(2047, MVT::i64));
5465       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5466       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5467                           Round, DAG.getConstant(-2048, MVT::i64));
5468
5469       // However, we cannot use that value unconditionally: if the magnitude
5470       // of the input value is small, the bit-twiddling we did above might
5471       // end up visibly changing the output.  Fortunately, in that case, we
5472       // don't need to twiddle bits since the original input will convert
5473       // exactly to double-precision floating-point already.  Therefore,
5474       // construct a conditional to use the original value if the top 11
5475       // bits are all sign-bit copies, and use the rounded value computed
5476       // above otherwise.
5477       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5478                                  SINT, DAG.getConstant(53, MVT::i32));
5479       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5480                          Cond, DAG.getConstant(1, MVT::i64));
5481       Cond = DAG.getSetCC(dl, MVT::i32,
5482                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5483
5484       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5485     }
5486
5487     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5488     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5489
5490     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5491       FP = DAG.getNode(ISD::FP_ROUND, dl,
5492                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5493     return FP;
5494   }
5495
5496   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5497          "Unhandled INT_TO_FP type in custom expander!");
5498   // Since we only generate this in 64-bit mode, we can take advantage of
5499   // 64-bit registers.  In particular, sign extend the input value into the
5500   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5501   // then lfd it and fcfid it.
5502   MachineFunction &MF = DAG.getMachineFunction();
5503   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5504   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5505
5506   SDValue Ld;
5507   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5508     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5509     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5510
5511     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5512                                  MachinePointerInfo::getFixedStack(FrameIdx),
5513                                  false, false, 0);
5514
5515     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5516            "Expected an i32 store");
5517     MachineMemOperand *MMO =
5518       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5519                               MachineMemOperand::MOLoad, 4, 4);
5520     SDValue Ops[] = { Store, FIdx };
5521     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5522                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5523                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5524                                  Ops, MVT::i32, MMO);
5525   } else {
5526     assert(Subtarget.isPPC64() &&
5527            "i32->FP without LFIWAX supported only on PPC64");
5528
5529     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5530     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5531
5532     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5533                                 Op.getOperand(0));
5534
5535     // STD the extended value into the stack slot.
5536     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5537                                  MachinePointerInfo::getFixedStack(FrameIdx),
5538                                  false, false, 0);
5539
5540     // Load the value as a double.
5541     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5542                      MachinePointerInfo::getFixedStack(FrameIdx),
5543                      false, false, false, 0);
5544   }
5545
5546   // FCFID it and return it.
5547   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5548   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5549     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5550   return FP;
5551 }
5552
5553 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5554                                             SelectionDAG &DAG) const {
5555   SDLoc dl(Op);
5556   /*
5557    The rounding mode is in bits 30:31 of FPSR, and has the following
5558    settings:
5559      00 Round to nearest
5560      01 Round to 0
5561      10 Round to +inf
5562      11 Round to -inf
5563
5564   FLT_ROUNDS, on the other hand, expects the following:
5565     -1 Undefined
5566      0 Round to 0
5567      1 Round to nearest
5568      2 Round to +inf
5569      3 Round to -inf
5570
5571   To perform the conversion, we do:
5572     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5573   */
5574
5575   MachineFunction &MF = DAG.getMachineFunction();
5576   EVT VT = Op.getValueType();
5577   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5578
5579   // Save FP Control Word to register
5580   EVT NodeTys[] = {
5581     MVT::f64,    // return register
5582     MVT::Glue    // unused in this context
5583   };
5584   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5585
5586   // Save FP register to stack slot
5587   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5588   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5589   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5590                                StackSlot, MachinePointerInfo(), false, false,0);
5591
5592   // Load FP Control Word from low 32 bits of stack slot.
5593   SDValue Four = DAG.getConstant(4, PtrVT);
5594   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5595   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5596                             false, false, false, 0);
5597
5598   // Transform as necessary
5599   SDValue CWD1 =
5600     DAG.getNode(ISD::AND, dl, MVT::i32,
5601                 CWD, DAG.getConstant(3, MVT::i32));
5602   SDValue CWD2 =
5603     DAG.getNode(ISD::SRL, dl, MVT::i32,
5604                 DAG.getNode(ISD::AND, dl, MVT::i32,
5605                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5606                                         CWD, DAG.getConstant(3, MVT::i32)),
5607                             DAG.getConstant(3, MVT::i32)),
5608                 DAG.getConstant(1, MVT::i32));
5609
5610   SDValue RetVal =
5611     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5612
5613   return DAG.getNode((VT.getSizeInBits() < 16 ?
5614                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5615 }
5616
5617 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5618   EVT VT = Op.getValueType();
5619   unsigned BitWidth = VT.getSizeInBits();
5620   SDLoc dl(Op);
5621   assert(Op.getNumOperands() == 3 &&
5622          VT == Op.getOperand(1).getValueType() &&
5623          "Unexpected SHL!");
5624
5625   // Expand into a bunch of logical ops.  Note that these ops
5626   // depend on the PPC behavior for oversized shift amounts.
5627   SDValue Lo = Op.getOperand(0);
5628   SDValue Hi = Op.getOperand(1);
5629   SDValue Amt = Op.getOperand(2);
5630   EVT AmtVT = Amt.getValueType();
5631
5632   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5633                              DAG.getConstant(BitWidth, AmtVT), Amt);
5634   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5635   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5636   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5637   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5638                              DAG.getConstant(-BitWidth, AmtVT));
5639   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5640   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5641   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5642   SDValue OutOps[] = { OutLo, OutHi };
5643   return DAG.getMergeValues(OutOps, dl);
5644 }
5645
5646 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5647   EVT VT = Op.getValueType();
5648   SDLoc dl(Op);
5649   unsigned BitWidth = VT.getSizeInBits();
5650   assert(Op.getNumOperands() == 3 &&
5651          VT == Op.getOperand(1).getValueType() &&
5652          "Unexpected SRL!");
5653
5654   // Expand into a bunch of logical ops.  Note that these ops
5655   // depend on the PPC behavior for oversized shift amounts.
5656   SDValue Lo = Op.getOperand(0);
5657   SDValue Hi = Op.getOperand(1);
5658   SDValue Amt = Op.getOperand(2);
5659   EVT AmtVT = Amt.getValueType();
5660
5661   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5662                              DAG.getConstant(BitWidth, AmtVT), Amt);
5663   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5664   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5665   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5666   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5667                              DAG.getConstant(-BitWidth, AmtVT));
5668   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5669   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5670   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5671   SDValue OutOps[] = { OutLo, OutHi };
5672   return DAG.getMergeValues(OutOps, dl);
5673 }
5674
5675 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5676   SDLoc dl(Op);
5677   EVT VT = Op.getValueType();
5678   unsigned BitWidth = VT.getSizeInBits();
5679   assert(Op.getNumOperands() == 3 &&
5680          VT == Op.getOperand(1).getValueType() &&
5681          "Unexpected SRA!");
5682
5683   // Expand into a bunch of logical ops, followed by a select_cc.
5684   SDValue Lo = Op.getOperand(0);
5685   SDValue Hi = Op.getOperand(1);
5686   SDValue Amt = Op.getOperand(2);
5687   EVT AmtVT = Amt.getValueType();
5688
5689   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5690                              DAG.getConstant(BitWidth, AmtVT), Amt);
5691   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5692   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5693   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5694   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5695                              DAG.getConstant(-BitWidth, AmtVT));
5696   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5697   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5698   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5699                                   Tmp4, Tmp6, ISD::SETLE);
5700   SDValue OutOps[] = { OutLo, OutHi };
5701   return DAG.getMergeValues(OutOps, dl);
5702 }
5703
5704 //===----------------------------------------------------------------------===//
5705 // Vector related lowering.
5706 //
5707
5708 /// BuildSplatI - Build a canonical splati of Val with an element size of
5709 /// SplatSize.  Cast the result to VT.
5710 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5711                              SelectionDAG &DAG, SDLoc dl) {
5712   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5713
5714   static const EVT VTys[] = { // canonical VT to use for each size.
5715     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5716   };
5717
5718   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5719
5720   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5721   if (Val == -1)
5722     SplatSize = 1;
5723
5724   EVT CanonicalVT = VTys[SplatSize-1];
5725
5726   // Build a canonical splat for this value.
5727   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5728   SmallVector<SDValue, 8> Ops;
5729   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5730   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5731   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5732 }
5733
5734 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5735 /// specified intrinsic ID.
5736 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5737                                 SelectionDAG &DAG, SDLoc dl,
5738                                 EVT DestVT = MVT::Other) {
5739   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5740   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5741                      DAG.getConstant(IID, MVT::i32), Op);
5742 }
5743
5744 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5745 /// specified intrinsic ID.
5746 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5747                                 SelectionDAG &DAG, SDLoc dl,
5748                                 EVT DestVT = MVT::Other) {
5749   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5750   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5751                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5752 }
5753
5754 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5755 /// specified intrinsic ID.
5756 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5757                                 SDValue Op2, SelectionDAG &DAG,
5758                                 SDLoc dl, EVT DestVT = MVT::Other) {
5759   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5760   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5761                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5762 }
5763
5764
5765 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5766 /// amount.  The result has the specified value type.
5767 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5768                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5769   // Force LHS/RHS to be the right type.
5770   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5771   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5772
5773   int Ops[16];
5774   for (unsigned i = 0; i != 16; ++i)
5775     Ops[i] = i + Amt;
5776   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5777   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5778 }
5779
5780 // If this is a case we can't handle, return null and let the default
5781 // expansion code take care of it.  If we CAN select this case, and if it
5782 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5783 // this case more efficiently than a constant pool load, lower it to the
5784 // sequence of ops that should be used.
5785 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5786                                              SelectionDAG &DAG) const {
5787   SDLoc dl(Op);
5788   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5789   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5790
5791   // Check if this is a splat of a constant value.
5792   APInt APSplatBits, APSplatUndef;
5793   unsigned SplatBitSize;
5794   bool HasAnyUndefs;
5795   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5796                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5797     return SDValue();
5798
5799   unsigned SplatBits = APSplatBits.getZExtValue();
5800   unsigned SplatUndef = APSplatUndef.getZExtValue();
5801   unsigned SplatSize = SplatBitSize / 8;
5802
5803   // First, handle single instruction cases.
5804
5805   // All zeros?
5806   if (SplatBits == 0) {
5807     // Canonicalize all zero vectors to be v4i32.
5808     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5809       SDValue Z = DAG.getConstant(0, MVT::i32);
5810       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5811       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5812     }
5813     return Op;
5814   }
5815
5816   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5817   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5818                     (32-SplatBitSize));
5819   if (SextVal >= -16 && SextVal <= 15)
5820     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5821
5822
5823   // Two instruction sequences.
5824
5825   // If this value is in the range [-32,30] and is even, use:
5826   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5827   // If this value is in the range [17,31] and is odd, use:
5828   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5829   // If this value is in the range [-31,-17] and is odd, use:
5830   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5831   // Note the last two are three-instruction sequences.
5832   if (SextVal >= -32 && SextVal <= 31) {
5833     // To avoid having these optimizations undone by constant folding,
5834     // we convert to a pseudo that will be expanded later into one of
5835     // the above forms.
5836     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5837     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5838               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5839     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5840     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5841     if (VT == Op.getValueType())
5842       return RetVal;
5843     else
5844       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5845   }
5846
5847   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5848   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5849   // for fneg/fabs.
5850   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5851     // Make -1 and vspltisw -1:
5852     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5853
5854     // Make the VSLW intrinsic, computing 0x8000_0000.
5855     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5856                                    OnesV, DAG, dl);
5857
5858     // xor by OnesV to invert it.
5859     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5860     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5861   }
5862
5863   // The remaining cases assume either big endian element order or
5864   // a splat-size that equates to the element size of the vector
5865   // to be built.  An example that doesn't work for little endian is
5866   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5867   // and a vector element size of 16 bits.  The code below will
5868   // produce the vector in big endian element order, which for little
5869   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5870
5871   // For now, just avoid these optimizations in that case.
5872   // FIXME: Develop correct optimizations for LE with mismatched
5873   // splat and element sizes.
5874
5875   if (Subtarget.isLittleEndian() &&
5876       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5877     return SDValue();
5878
5879   // Check to see if this is a wide variety of vsplti*, binop self cases.
5880   static const signed char SplatCsts[] = {
5881     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5882     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5883   };
5884
5885   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5886     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5887     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5888     int i = SplatCsts[idx];
5889
5890     // Figure out what shift amount will be used by altivec if shifted by i in
5891     // this splat size.
5892     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5893
5894     // vsplti + shl self.
5895     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5896       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5897       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5898         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5899         Intrinsic::ppc_altivec_vslw
5900       };
5901       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5902       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5903     }
5904
5905     // vsplti + srl self.
5906     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5907       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5908       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5909         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5910         Intrinsic::ppc_altivec_vsrw
5911       };
5912       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5913       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5914     }
5915
5916     // vsplti + sra self.
5917     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5918       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5919       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5920         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5921         Intrinsic::ppc_altivec_vsraw
5922       };
5923       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5924       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5925     }
5926
5927     // vsplti + rol self.
5928     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5929                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5930       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5931       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5932         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5933         Intrinsic::ppc_altivec_vrlw
5934       };
5935       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5936       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5937     }
5938
5939     // t = vsplti c, result = vsldoi t, t, 1
5940     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5941       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5942       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5943     }
5944     // t = vsplti c, result = vsldoi t, t, 2
5945     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5946       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5947       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5948     }
5949     // t = vsplti c, result = vsldoi t, t, 3
5950     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5951       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5952       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5953     }
5954   }
5955
5956   return SDValue();
5957 }
5958
5959 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5960 /// the specified operations to build the shuffle.
5961 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5962                                       SDValue RHS, SelectionDAG &DAG,
5963                                       SDLoc dl) {
5964   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5965   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5966   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5967
5968   enum {
5969     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5970     OP_VMRGHW,
5971     OP_VMRGLW,
5972     OP_VSPLTISW0,
5973     OP_VSPLTISW1,
5974     OP_VSPLTISW2,
5975     OP_VSPLTISW3,
5976     OP_VSLDOI4,
5977     OP_VSLDOI8,
5978     OP_VSLDOI12
5979   };
5980
5981   if (OpNum == OP_COPY) {
5982     if (LHSID == (1*9+2)*9+3) return LHS;
5983     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5984     return RHS;
5985   }
5986
5987   SDValue OpLHS, OpRHS;
5988   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5989   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5990
5991   int ShufIdxs[16];
5992   switch (OpNum) {
5993   default: llvm_unreachable("Unknown i32 permute!");
5994   case OP_VMRGHW:
5995     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5996     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5997     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5998     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5999     break;
6000   case OP_VMRGLW:
6001     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6002     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6003     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6004     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6005     break;
6006   case OP_VSPLTISW0:
6007     for (unsigned i = 0; i != 16; ++i)
6008       ShufIdxs[i] = (i&3)+0;
6009     break;
6010   case OP_VSPLTISW1:
6011     for (unsigned i = 0; i != 16; ++i)
6012       ShufIdxs[i] = (i&3)+4;
6013     break;
6014   case OP_VSPLTISW2:
6015     for (unsigned i = 0; i != 16; ++i)
6016       ShufIdxs[i] = (i&3)+8;
6017     break;
6018   case OP_VSPLTISW3:
6019     for (unsigned i = 0; i != 16; ++i)
6020       ShufIdxs[i] = (i&3)+12;
6021     break;
6022   case OP_VSLDOI4:
6023     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6024   case OP_VSLDOI8:
6025     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6026   case OP_VSLDOI12:
6027     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6028   }
6029   EVT VT = OpLHS.getValueType();
6030   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6031   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6032   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6033   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6034 }
6035
6036 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6037 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6038 /// return the code it can be lowered into.  Worst case, it can always be
6039 /// lowered into a vperm.
6040 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6041                                                SelectionDAG &DAG) const {
6042   SDLoc dl(Op);
6043   SDValue V1 = Op.getOperand(0);
6044   SDValue V2 = Op.getOperand(1);
6045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6046   EVT VT = Op.getValueType();
6047   bool isLittleEndian = Subtarget.isLittleEndian();
6048
6049   // Cases that are handled by instructions that take permute immediates
6050   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6051   // selected by the instruction selector.
6052   if (V2.getOpcode() == ISD::UNDEF) {
6053     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6054         PPC::isSplatShuffleMask(SVOp, 2) ||
6055         PPC::isSplatShuffleMask(SVOp, 4) ||
6056         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6057         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6058         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6059         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6060         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6061         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6062         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6063         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6064         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6065       return Op;
6066     }
6067   }
6068
6069   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6070   // and produce a fixed permutation.  If any of these match, do not lower to
6071   // VPERM.
6072   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6073   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6074       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6075       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6076       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6077       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6078       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6079       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6080       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6081       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6082     return Op;
6083
6084   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6085   // perfect shuffle table to emit an optimal matching sequence.
6086   ArrayRef<int> PermMask = SVOp->getMask();
6087
6088   unsigned PFIndexes[4];
6089   bool isFourElementShuffle = true;
6090   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6091     unsigned EltNo = 8;   // Start out undef.
6092     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6093       if (PermMask[i*4+j] < 0)
6094         continue;   // Undef, ignore it.
6095
6096       unsigned ByteSource = PermMask[i*4+j];
6097       if ((ByteSource & 3) != j) {
6098         isFourElementShuffle = false;
6099         break;
6100       }
6101
6102       if (EltNo == 8) {
6103         EltNo = ByteSource/4;
6104       } else if (EltNo != ByteSource/4) {
6105         isFourElementShuffle = false;
6106         break;
6107       }
6108     }
6109     PFIndexes[i] = EltNo;
6110   }
6111
6112   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6113   // perfect shuffle vector to determine if it is cost effective to do this as
6114   // discrete instructions, or whether we should use a vperm.
6115   // For now, we skip this for little endian until such time as we have a
6116   // little-endian perfect shuffle table.
6117   if (isFourElementShuffle && !isLittleEndian) {
6118     // Compute the index in the perfect shuffle table.
6119     unsigned PFTableIndex =
6120       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6121
6122     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6123     unsigned Cost  = (PFEntry >> 30);
6124
6125     // Determining when to avoid vperm is tricky.  Many things affect the cost
6126     // of vperm, particularly how many times the perm mask needs to be computed.
6127     // For example, if the perm mask can be hoisted out of a loop or is already
6128     // used (perhaps because there are multiple permutes with the same shuffle
6129     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6130     // the loop requires an extra register.
6131     //
6132     // As a compromise, we only emit discrete instructions if the shuffle can be
6133     // generated in 3 or fewer operations.  When we have loop information
6134     // available, if this block is within a loop, we should avoid using vperm
6135     // for 3-operation perms and use a constant pool load instead.
6136     if (Cost < 3)
6137       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6138   }
6139
6140   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6141   // vector that will get spilled to the constant pool.
6142   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6143
6144   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6145   // that it is in input element units, not in bytes.  Convert now.
6146
6147   // For little endian, the order of the input vectors is reversed, and
6148   // the permutation mask is complemented with respect to 31.  This is
6149   // necessary to produce proper semantics with the big-endian-biased vperm
6150   // instruction.
6151   EVT EltVT = V1.getValueType().getVectorElementType();
6152   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6153
6154   SmallVector<SDValue, 16> ResultMask;
6155   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6156     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6157
6158     for (unsigned j = 0; j != BytesPerElement; ++j)
6159       if (isLittleEndian)
6160         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6161                                              MVT::i32));
6162       else
6163         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6164                                              MVT::i32));
6165   }
6166
6167   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6168                                   ResultMask);
6169   if (isLittleEndian)
6170     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6171                        V2, V1, VPermMask);
6172   else
6173     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6174                        V1, V2, VPermMask);
6175 }
6176
6177 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6178 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6179 /// information about the intrinsic.
6180 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6181                                   bool &isDot) {
6182   unsigned IntrinsicID =
6183     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6184   CompareOpc = -1;
6185   isDot = false;
6186   switch (IntrinsicID) {
6187   default: return false;
6188     // Comparison predicates.
6189   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6190   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6191   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6192   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6193   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6194   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6195   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6196   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6197   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6198   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6199   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6200   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6201   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6202
6203     // Normal Comparisons.
6204   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6205   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6206   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6207   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6208   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6209   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6210   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6211   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6212   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6213   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6214   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6215   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6216   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6217   }
6218   return true;
6219 }
6220
6221 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6222 /// lower, do it, otherwise return null.
6223 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6224                                                    SelectionDAG &DAG) const {
6225   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6226   // opcode number of the comparison.
6227   SDLoc dl(Op);
6228   int CompareOpc;
6229   bool isDot;
6230   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6231     return SDValue();    // Don't custom lower most intrinsics.
6232
6233   // If this is a non-dot comparison, make the VCMP node and we are done.
6234   if (!isDot) {
6235     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6236                               Op.getOperand(1), Op.getOperand(2),
6237                               DAG.getConstant(CompareOpc, MVT::i32));
6238     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6239   }
6240
6241   // Create the PPCISD altivec 'dot' comparison node.
6242   SDValue Ops[] = {
6243     Op.getOperand(2),  // LHS
6244     Op.getOperand(3),  // RHS
6245     DAG.getConstant(CompareOpc, MVT::i32)
6246   };
6247   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6248   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6249
6250   // Now that we have the comparison, emit a copy from the CR to a GPR.
6251   // This is flagged to the above dot comparison.
6252   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6253                                 DAG.getRegister(PPC::CR6, MVT::i32),
6254                                 CompNode.getValue(1));
6255
6256   // Unpack the result based on how the target uses it.
6257   unsigned BitNo;   // Bit # of CR6.
6258   bool InvertBit;   // Invert result?
6259   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6260   default:  // Can't happen, don't crash on invalid number though.
6261   case 0:   // Return the value of the EQ bit of CR6.
6262     BitNo = 0; InvertBit = false;
6263     break;
6264   case 1:   // Return the inverted value of the EQ bit of CR6.
6265     BitNo = 0; InvertBit = true;
6266     break;
6267   case 2:   // Return the value of the LT bit of CR6.
6268     BitNo = 2; InvertBit = false;
6269     break;
6270   case 3:   // Return the inverted value of the LT bit of CR6.
6271     BitNo = 2; InvertBit = true;
6272     break;
6273   }
6274
6275   // Shift the bit into the low position.
6276   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6277                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6278   // Isolate the bit.
6279   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6280                       DAG.getConstant(1, MVT::i32));
6281
6282   // If we are supposed to, toggle the bit.
6283   if (InvertBit)
6284     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6285                         DAG.getConstant(1, MVT::i32));
6286   return Flags;
6287 }
6288
6289 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6290                                                   SelectionDAG &DAG) const {
6291   SDLoc dl(Op);
6292   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6293   // instructions), but for smaller types, we need to first extend up to v2i32
6294   // before doing going farther.
6295   if (Op.getValueType() == MVT::v2i64) {
6296     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6297     if (ExtVT != MVT::v2i32) {
6298       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6299       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6300                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6301                                         ExtVT.getVectorElementType(), 4)));
6302       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6303       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6304                        DAG.getValueType(MVT::v2i32));
6305     }
6306
6307     return Op;
6308   }
6309
6310   return SDValue();
6311 }
6312
6313 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6314                                                    SelectionDAG &DAG) const {
6315   SDLoc dl(Op);
6316   // Create a stack slot that is 16-byte aligned.
6317   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6318   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6319   EVT PtrVT = getPointerTy();
6320   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6321
6322   // Store the input value into Value#0 of the stack slot.
6323   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6324                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6325                                false, false, 0);
6326   // Load it out.
6327   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6328                      false, false, false, 0);
6329 }
6330
6331 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6332   SDLoc dl(Op);
6333   if (Op.getValueType() == MVT::v4i32) {
6334     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6335
6336     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6337     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6338
6339     SDValue RHSSwap =   // = vrlw RHS, 16
6340       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6341
6342     // Shrinkify inputs to v8i16.
6343     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6344     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6345     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6346
6347     // Low parts multiplied together, generating 32-bit results (we ignore the
6348     // top parts).
6349     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6350                                         LHS, RHS, DAG, dl, MVT::v4i32);
6351
6352     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6353                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6354     // Shift the high parts up 16 bits.
6355     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6356                               Neg16, DAG, dl);
6357     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6358   } else if (Op.getValueType() == MVT::v8i16) {
6359     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6360
6361     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6362
6363     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6364                             LHS, RHS, Zero, DAG, dl);
6365   } else if (Op.getValueType() == MVT::v16i8) {
6366     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6367     bool isLittleEndian = Subtarget.isLittleEndian();
6368
6369     // Multiply the even 8-bit parts, producing 16-bit sums.
6370     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6371                                            LHS, RHS, DAG, dl, MVT::v8i16);
6372     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6373
6374     // Multiply the odd 8-bit parts, producing 16-bit sums.
6375     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6376                                           LHS, RHS, DAG, dl, MVT::v8i16);
6377     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6378
6379     // Merge the results together.  Because vmuleub and vmuloub are
6380     // instructions with a big-endian bias, we must reverse the
6381     // element numbering and reverse the meaning of "odd" and "even"
6382     // when generating little endian code.
6383     int Ops[16];
6384     for (unsigned i = 0; i != 8; ++i) {
6385       if (isLittleEndian) {
6386         Ops[i*2  ] = 2*i;
6387         Ops[i*2+1] = 2*i+16;
6388       } else {
6389         Ops[i*2  ] = 2*i+1;
6390         Ops[i*2+1] = 2*i+1+16;
6391       }
6392     }
6393     if (isLittleEndian)
6394       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6395     else
6396       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6397   } else {
6398     llvm_unreachable("Unknown mul to lower!");
6399   }
6400 }
6401
6402 /// LowerOperation - Provide custom lowering hooks for some operations.
6403 ///
6404 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6405   switch (Op.getOpcode()) {
6406   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6407   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6408   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6409   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6410   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6411   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6412   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6413   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6414   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6415   case ISD::VASTART:
6416     return LowerVASTART(Op, DAG, Subtarget);
6417
6418   case ISD::VAARG:
6419     return LowerVAARG(Op, DAG, Subtarget);
6420
6421   case ISD::VACOPY:
6422     return LowerVACOPY(Op, DAG, Subtarget);
6423
6424   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6425   case ISD::DYNAMIC_STACKALLOC:
6426     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6427
6428   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6429   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6430
6431   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6432   case ISD::STORE:              return LowerSTORE(Op, DAG);
6433   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6434   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6435   case ISD::FP_TO_UINT:
6436   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6437                                                        SDLoc(Op));
6438   case ISD::UINT_TO_FP:
6439   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6440   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6441
6442   // Lower 64-bit shifts.
6443   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6444   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6445   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6446
6447   // Vector-related lowering.
6448   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6449   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6450   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6451   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6452   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6453   case ISD::MUL:                return LowerMUL(Op, DAG);
6454
6455   // For counter-based loop handling.
6456   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6457
6458   // Frame & Return address.
6459   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6460   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6461   }
6462 }
6463
6464 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6465                                            SmallVectorImpl<SDValue>&Results,
6466                                            SelectionDAG &DAG) const {
6467   const TargetMachine &TM = getTargetMachine();
6468   SDLoc dl(N);
6469   switch (N->getOpcode()) {
6470   default:
6471     llvm_unreachable("Do not know how to custom type legalize this operation!");
6472   case ISD::INTRINSIC_W_CHAIN: {
6473     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6474         Intrinsic::ppc_is_decremented_ctr_nonzero)
6475       break;
6476
6477     assert(N->getValueType(0) == MVT::i1 &&
6478            "Unexpected result type for CTR decrement intrinsic");
6479     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6480     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6481     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6482                                  N->getOperand(1)); 
6483
6484     Results.push_back(NewInt);
6485     Results.push_back(NewInt.getValue(1));
6486     break;
6487   }
6488   case ISD::VAARG: {
6489     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6490         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6491       return;
6492
6493     EVT VT = N->getValueType(0);
6494
6495     if (VT == MVT::i64) {
6496       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6497
6498       Results.push_back(NewNode);
6499       Results.push_back(NewNode.getValue(1));
6500     }
6501     return;
6502   }
6503   case ISD::FP_ROUND_INREG: {
6504     assert(N->getValueType(0) == MVT::ppcf128);
6505     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6506     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6507                              MVT::f64, N->getOperand(0),
6508                              DAG.getIntPtrConstant(0));
6509     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6510                              MVT::f64, N->getOperand(0),
6511                              DAG.getIntPtrConstant(1));
6512
6513     // Add the two halves of the long double in round-to-zero mode.
6514     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6515
6516     // We know the low half is about to be thrown away, so just use something
6517     // convenient.
6518     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6519                                 FPreg, FPreg));
6520     return;
6521   }
6522   case ISD::FP_TO_SINT:
6523     // LowerFP_TO_INT() can only handle f32 and f64.
6524     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6525       return;
6526     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6527     return;
6528   }
6529 }
6530
6531
6532 //===----------------------------------------------------------------------===//
6533 //  Other Lowering Code
6534 //===----------------------------------------------------------------------===//
6535
6536 MachineBasicBlock *
6537 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6538                                     bool is64bit, unsigned BinOpcode) const {
6539   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6540   const TargetInstrInfo *TII =
6541       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6542
6543   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6544   MachineFunction *F = BB->getParent();
6545   MachineFunction::iterator It = BB;
6546   ++It;
6547
6548   unsigned dest = MI->getOperand(0).getReg();
6549   unsigned ptrA = MI->getOperand(1).getReg();
6550   unsigned ptrB = MI->getOperand(2).getReg();
6551   unsigned incr = MI->getOperand(3).getReg();
6552   DebugLoc dl = MI->getDebugLoc();
6553
6554   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6555   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6556   F->insert(It, loopMBB);
6557   F->insert(It, exitMBB);
6558   exitMBB->splice(exitMBB->begin(), BB,
6559                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6560   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6561
6562   MachineRegisterInfo &RegInfo = F->getRegInfo();
6563   unsigned TmpReg = (!BinOpcode) ? incr :
6564     RegInfo.createVirtualRegister(
6565        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6566                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6567
6568   //  thisMBB:
6569   //   ...
6570   //   fallthrough --> loopMBB
6571   BB->addSuccessor(loopMBB);
6572
6573   //  loopMBB:
6574   //   l[wd]arx dest, ptr
6575   //   add r0, dest, incr
6576   //   st[wd]cx. r0, ptr
6577   //   bne- loopMBB
6578   //   fallthrough --> exitMBB
6579   BB = loopMBB;
6580   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6581     .addReg(ptrA).addReg(ptrB);
6582   if (BinOpcode)
6583     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6584   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6585     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6586   BuildMI(BB, dl, TII->get(PPC::BCC))
6587     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6588   BB->addSuccessor(loopMBB);
6589   BB->addSuccessor(exitMBB);
6590
6591   //  exitMBB:
6592   //   ...
6593   BB = exitMBB;
6594   return BB;
6595 }
6596
6597 MachineBasicBlock *
6598 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6599                                             MachineBasicBlock *BB,
6600                                             bool is8bit,    // operation
6601                                             unsigned BinOpcode) const {
6602   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6603   const TargetInstrInfo *TII =
6604       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6605   // In 64 bit mode we have to use 64 bits for addresses, even though the
6606   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6607   // registers without caring whether they're 32 or 64, but here we're
6608   // doing actual arithmetic on the addresses.
6609   bool is64bit = Subtarget.isPPC64();
6610   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6611
6612   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6613   MachineFunction *F = BB->getParent();
6614   MachineFunction::iterator It = BB;
6615   ++It;
6616
6617   unsigned dest = MI->getOperand(0).getReg();
6618   unsigned ptrA = MI->getOperand(1).getReg();
6619   unsigned ptrB = MI->getOperand(2).getReg();
6620   unsigned incr = MI->getOperand(3).getReg();
6621   DebugLoc dl = MI->getDebugLoc();
6622
6623   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6624   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6625   F->insert(It, loopMBB);
6626   F->insert(It, exitMBB);
6627   exitMBB->splice(exitMBB->begin(), BB,
6628                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6629   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6630
6631   MachineRegisterInfo &RegInfo = F->getRegInfo();
6632   const TargetRegisterClass *RC =
6633     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6634               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6635   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6636   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6637   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6638   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6639   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6640   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6641   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6642   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6643   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6644   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6645   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6646   unsigned Ptr1Reg;
6647   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6648
6649   //  thisMBB:
6650   //   ...
6651   //   fallthrough --> loopMBB
6652   BB->addSuccessor(loopMBB);
6653
6654   // The 4-byte load must be aligned, while a char or short may be
6655   // anywhere in the word.  Hence all this nasty bookkeeping code.
6656   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6657   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6658   //   xori shift, shift1, 24 [16]
6659   //   rlwinm ptr, ptr1, 0, 0, 29
6660   //   slw incr2, incr, shift
6661   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6662   //   slw mask, mask2, shift
6663   //  loopMBB:
6664   //   lwarx tmpDest, ptr
6665   //   add tmp, tmpDest, incr2
6666   //   andc tmp2, tmpDest, mask
6667   //   and tmp3, tmp, mask
6668   //   or tmp4, tmp3, tmp2
6669   //   stwcx. tmp4, ptr
6670   //   bne- loopMBB
6671   //   fallthrough --> exitMBB
6672   //   srw dest, tmpDest, shift
6673   if (ptrA != ZeroReg) {
6674     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6675     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6676       .addReg(ptrA).addReg(ptrB);
6677   } else {
6678     Ptr1Reg = ptrB;
6679   }
6680   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6681       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6682   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6683       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6684   if (is64bit)
6685     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6686       .addReg(Ptr1Reg).addImm(0).addImm(61);
6687   else
6688     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6689       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6690   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6691       .addReg(incr).addReg(ShiftReg);
6692   if (is8bit)
6693     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6694   else {
6695     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6696     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6697   }
6698   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6699       .addReg(Mask2Reg).addReg(ShiftReg);
6700
6701   BB = loopMBB;
6702   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6703     .addReg(ZeroReg).addReg(PtrReg);
6704   if (BinOpcode)
6705     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6706       .addReg(Incr2Reg).addReg(TmpDestReg);
6707   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6708     .addReg(TmpDestReg).addReg(MaskReg);
6709   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6710     .addReg(TmpReg).addReg(MaskReg);
6711   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6712     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6713   BuildMI(BB, dl, TII->get(PPC::STWCX))
6714     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6715   BuildMI(BB, dl, TII->get(PPC::BCC))
6716     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6717   BB->addSuccessor(loopMBB);
6718   BB->addSuccessor(exitMBB);
6719
6720   //  exitMBB:
6721   //   ...
6722   BB = exitMBB;
6723   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6724     .addReg(ShiftReg);
6725   return BB;
6726 }
6727
6728 llvm::MachineBasicBlock*
6729 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6730                                     MachineBasicBlock *MBB) const {
6731   DebugLoc DL = MI->getDebugLoc();
6732   const TargetInstrInfo *TII =
6733       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6734
6735   MachineFunction *MF = MBB->getParent();
6736   MachineRegisterInfo &MRI = MF->getRegInfo();
6737
6738   const BasicBlock *BB = MBB->getBasicBlock();
6739   MachineFunction::iterator I = MBB;
6740   ++I;
6741
6742   // Memory Reference
6743   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6744   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6745
6746   unsigned DstReg = MI->getOperand(0).getReg();
6747   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6748   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6749   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6750   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6751
6752   MVT PVT = getPointerTy();
6753   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6754          "Invalid Pointer Size!");
6755   // For v = setjmp(buf), we generate
6756   //
6757   // thisMBB:
6758   //  SjLjSetup mainMBB
6759   //  bl mainMBB
6760   //  v_restore = 1
6761   //  b sinkMBB
6762   //
6763   // mainMBB:
6764   //  buf[LabelOffset] = LR
6765   //  v_main = 0
6766   //
6767   // sinkMBB:
6768   //  v = phi(main, restore)
6769   //
6770
6771   MachineBasicBlock *thisMBB = MBB;
6772   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6773   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6774   MF->insert(I, mainMBB);
6775   MF->insert(I, sinkMBB);
6776
6777   MachineInstrBuilder MIB;
6778
6779   // Transfer the remainder of BB and its successor edges to sinkMBB.
6780   sinkMBB->splice(sinkMBB->begin(), MBB,
6781                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6782   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6783
6784   // Note that the structure of the jmp_buf used here is not compatible
6785   // with that used by libc, and is not designed to be. Specifically, it
6786   // stores only those 'reserved' registers that LLVM does not otherwise
6787   // understand how to spill. Also, by convention, by the time this
6788   // intrinsic is called, Clang has already stored the frame address in the
6789   // first slot of the buffer and stack address in the third. Following the
6790   // X86 target code, we'll store the jump address in the second slot. We also
6791   // need to save the TOC pointer (R2) to handle jumps between shared
6792   // libraries, and that will be stored in the fourth slot. The thread
6793   // identifier (R13) is not affected.
6794
6795   // thisMBB:
6796   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6797   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6798   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6799
6800   // Prepare IP either in reg.
6801   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6802   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6803   unsigned BufReg = MI->getOperand(1).getReg();
6804
6805   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6806     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6807             .addReg(PPC::X2)
6808             .addImm(TOCOffset)
6809             .addReg(BufReg);
6810     MIB.setMemRefs(MMOBegin, MMOEnd);
6811   }
6812
6813   // Naked functions never have a base pointer, and so we use r1. For all
6814   // other functions, this decision must be delayed until during PEI.
6815   unsigned BaseReg;
6816   if (MF->getFunction()->getAttributes().hasAttribute(
6817           AttributeSet::FunctionIndex, Attribute::Naked))
6818     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6819   else
6820     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6821
6822   MIB = BuildMI(*thisMBB, MI, DL,
6823                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6824           .addReg(BaseReg)
6825           .addImm(BPOffset)
6826           .addReg(BufReg);
6827   MIB.setMemRefs(MMOBegin, MMOEnd);
6828
6829   // Setup
6830   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6831   const PPCRegisterInfo *TRI =
6832       getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6833   MIB.addRegMask(TRI->getNoPreservedMask());
6834
6835   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6836
6837   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6838           .addMBB(mainMBB);
6839   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6840
6841   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6842   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6843
6844   // mainMBB:
6845   //  mainDstReg = 0
6846   MIB = BuildMI(mainMBB, DL,
6847     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6848
6849   // Store IP
6850   if (Subtarget.isPPC64()) {
6851     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6852             .addReg(LabelReg)
6853             .addImm(LabelOffset)
6854             .addReg(BufReg);
6855   } else {
6856     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6857             .addReg(LabelReg)
6858             .addImm(LabelOffset)
6859             .addReg(BufReg);
6860   }
6861
6862   MIB.setMemRefs(MMOBegin, MMOEnd);
6863
6864   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6865   mainMBB->addSuccessor(sinkMBB);
6866
6867   // sinkMBB:
6868   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6869           TII->get(PPC::PHI), DstReg)
6870     .addReg(mainDstReg).addMBB(mainMBB)
6871     .addReg(restoreDstReg).addMBB(thisMBB);
6872
6873   MI->eraseFromParent();
6874   return sinkMBB;
6875 }
6876
6877 MachineBasicBlock *
6878 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6879                                      MachineBasicBlock *MBB) const {
6880   DebugLoc DL = MI->getDebugLoc();
6881   const TargetInstrInfo *TII =
6882       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6883
6884   MachineFunction *MF = MBB->getParent();
6885   MachineRegisterInfo &MRI = MF->getRegInfo();
6886
6887   // Memory Reference
6888   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6889   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6890
6891   MVT PVT = getPointerTy();
6892   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6893          "Invalid Pointer Size!");
6894
6895   const TargetRegisterClass *RC =
6896     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6897   unsigned Tmp = MRI.createVirtualRegister(RC);
6898   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6899   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6900   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6901   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6902                   (Subtarget.isSVR4ABI() &&
6903                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6904                      PPC::R29 : PPC::R30);
6905
6906   MachineInstrBuilder MIB;
6907
6908   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6909   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6910   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6911   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6912
6913   unsigned BufReg = MI->getOperand(0).getReg();
6914
6915   // Reload FP (the jumped-to function may not have had a
6916   // frame pointer, and if so, then its r31 will be restored
6917   // as necessary).
6918   if (PVT == MVT::i64) {
6919     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6920             .addImm(0)
6921             .addReg(BufReg);
6922   } else {
6923     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6924             .addImm(0)
6925             .addReg(BufReg);
6926   }
6927   MIB.setMemRefs(MMOBegin, MMOEnd);
6928
6929   // Reload IP
6930   if (PVT == MVT::i64) {
6931     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6932             .addImm(LabelOffset)
6933             .addReg(BufReg);
6934   } else {
6935     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6936             .addImm(LabelOffset)
6937             .addReg(BufReg);
6938   }
6939   MIB.setMemRefs(MMOBegin, MMOEnd);
6940
6941   // Reload SP
6942   if (PVT == MVT::i64) {
6943     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6944             .addImm(SPOffset)
6945             .addReg(BufReg);
6946   } else {
6947     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6948             .addImm(SPOffset)
6949             .addReg(BufReg);
6950   }
6951   MIB.setMemRefs(MMOBegin, MMOEnd);
6952
6953   // Reload BP
6954   if (PVT == MVT::i64) {
6955     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6956             .addImm(BPOffset)
6957             .addReg(BufReg);
6958   } else {
6959     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6960             .addImm(BPOffset)
6961             .addReg(BufReg);
6962   }
6963   MIB.setMemRefs(MMOBegin, MMOEnd);
6964
6965   // Reload TOC
6966   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6967     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6968             .addImm(TOCOffset)
6969             .addReg(BufReg);
6970
6971     MIB.setMemRefs(MMOBegin, MMOEnd);
6972   }
6973
6974   // Jump
6975   BuildMI(*MBB, MI, DL,
6976           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6977   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6978
6979   MI->eraseFromParent();
6980   return MBB;
6981 }
6982
6983 MachineBasicBlock *
6984 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6985                                                MachineBasicBlock *BB) const {
6986   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6987       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6988     return emitEHSjLjSetJmp(MI, BB);
6989   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6990              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6991     return emitEHSjLjLongJmp(MI, BB);
6992   }
6993
6994   const TargetInstrInfo *TII =
6995       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6996
6997   // To "insert" these instructions we actually have to insert their
6998   // control-flow patterns.
6999   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7000   MachineFunction::iterator It = BB;
7001   ++It;
7002
7003   MachineFunction *F = BB->getParent();
7004
7005   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7006                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
7007                                  MI->getOpcode() == PPC::SELECT_I4 ||
7008                                  MI->getOpcode() == PPC::SELECT_I8)) {
7009     SmallVector<MachineOperand, 2> Cond;
7010     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7011         MI->getOpcode() == PPC::SELECT_CC_I8)
7012       Cond.push_back(MI->getOperand(4));
7013     else
7014       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7015     Cond.push_back(MI->getOperand(1));
7016
7017     DebugLoc dl = MI->getDebugLoc();
7018     const TargetInstrInfo *TII =
7019         getTargetMachine().getSubtargetImpl()->getInstrInfo();
7020     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7021                       Cond, MI->getOperand(2).getReg(),
7022                       MI->getOperand(3).getReg());
7023   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7024              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7025              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7026              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7027              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7028              MI->getOpcode() == PPC::SELECT_I4 ||
7029              MI->getOpcode() == PPC::SELECT_I8 ||
7030              MI->getOpcode() == PPC::SELECT_F4 ||
7031              MI->getOpcode() == PPC::SELECT_F8 ||
7032              MI->getOpcode() == PPC::SELECT_VRRC) {
7033     // The incoming instruction knows the destination vreg to set, the
7034     // condition code register to branch on, the true/false values to
7035     // select between, and a branch opcode to use.
7036
7037     //  thisMBB:
7038     //  ...
7039     //   TrueVal = ...
7040     //   cmpTY ccX, r1, r2
7041     //   bCC copy1MBB
7042     //   fallthrough --> copy0MBB
7043     MachineBasicBlock *thisMBB = BB;
7044     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7045     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7046     DebugLoc dl = MI->getDebugLoc();
7047     F->insert(It, copy0MBB);
7048     F->insert(It, sinkMBB);
7049
7050     // Transfer the remainder of BB and its successor edges to sinkMBB.
7051     sinkMBB->splice(sinkMBB->begin(), BB,
7052                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7053     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7054
7055     // Next, add the true and fallthrough blocks as its successors.
7056     BB->addSuccessor(copy0MBB);
7057     BB->addSuccessor(sinkMBB);
7058
7059     if (MI->getOpcode() == PPC::SELECT_I4 ||
7060         MI->getOpcode() == PPC::SELECT_I8 ||
7061         MI->getOpcode() == PPC::SELECT_F4 ||
7062         MI->getOpcode() == PPC::SELECT_F8 ||
7063         MI->getOpcode() == PPC::SELECT_VRRC) {
7064       BuildMI(BB, dl, TII->get(PPC::BC))
7065         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7066     } else {
7067       unsigned SelectPred = MI->getOperand(4).getImm();
7068       BuildMI(BB, dl, TII->get(PPC::BCC))
7069         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7070     }
7071
7072     //  copy0MBB:
7073     //   %FalseValue = ...
7074     //   # fallthrough to sinkMBB
7075     BB = copy0MBB;
7076
7077     // Update machine-CFG edges
7078     BB->addSuccessor(sinkMBB);
7079
7080     //  sinkMBB:
7081     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7082     //  ...
7083     BB = sinkMBB;
7084     BuildMI(*BB, BB->begin(), dl,
7085             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7086       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7087       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7088   }
7089   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7090     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7091   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7092     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7093   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7094     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7095   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7096     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7097
7098   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7099     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7100   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7101     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7102   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7103     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7104   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7105     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7106
7107   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7108     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7109   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7110     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7111   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7112     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7113   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7114     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7115
7116   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7117     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7118   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7119     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7120   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7121     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7122   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7123     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7124
7125   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7126     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7127   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7128     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7129   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7130     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7131   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7132     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7133
7134   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7135     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7136   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7137     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7138   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7139     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7140   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7141     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7142
7143   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7144     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7145   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7146     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7147   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7148     BB = EmitAtomicBinary(MI, BB, false, 0);
7149   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7150     BB = EmitAtomicBinary(MI, BB, true, 0);
7151
7152   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7153            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7154     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7155
7156     unsigned dest   = MI->getOperand(0).getReg();
7157     unsigned ptrA   = MI->getOperand(1).getReg();
7158     unsigned ptrB   = MI->getOperand(2).getReg();
7159     unsigned oldval = MI->getOperand(3).getReg();
7160     unsigned newval = MI->getOperand(4).getReg();
7161     DebugLoc dl     = MI->getDebugLoc();
7162
7163     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7164     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7165     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7166     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7167     F->insert(It, loop1MBB);
7168     F->insert(It, loop2MBB);
7169     F->insert(It, midMBB);
7170     F->insert(It, exitMBB);
7171     exitMBB->splice(exitMBB->begin(), BB,
7172                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7173     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7174
7175     //  thisMBB:
7176     //   ...
7177     //   fallthrough --> loopMBB
7178     BB->addSuccessor(loop1MBB);
7179
7180     // loop1MBB:
7181     //   l[wd]arx dest, ptr
7182     //   cmp[wd] dest, oldval
7183     //   bne- midMBB
7184     // loop2MBB:
7185     //   st[wd]cx. newval, ptr
7186     //   bne- loopMBB
7187     //   b exitBB
7188     // midMBB:
7189     //   st[wd]cx. dest, ptr
7190     // exitBB:
7191     BB = loop1MBB;
7192     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7193       .addReg(ptrA).addReg(ptrB);
7194     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7195       .addReg(oldval).addReg(dest);
7196     BuildMI(BB, dl, TII->get(PPC::BCC))
7197       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7198     BB->addSuccessor(loop2MBB);
7199     BB->addSuccessor(midMBB);
7200
7201     BB = loop2MBB;
7202     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7203       .addReg(newval).addReg(ptrA).addReg(ptrB);
7204     BuildMI(BB, dl, TII->get(PPC::BCC))
7205       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7206     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7207     BB->addSuccessor(loop1MBB);
7208     BB->addSuccessor(exitMBB);
7209
7210     BB = midMBB;
7211     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7212       .addReg(dest).addReg(ptrA).addReg(ptrB);
7213     BB->addSuccessor(exitMBB);
7214
7215     //  exitMBB:
7216     //   ...
7217     BB = exitMBB;
7218   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7219              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7220     // We must use 64-bit registers for addresses when targeting 64-bit,
7221     // since we're actually doing arithmetic on them.  Other registers
7222     // can be 32-bit.
7223     bool is64bit = Subtarget.isPPC64();
7224     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7225
7226     unsigned dest   = MI->getOperand(0).getReg();
7227     unsigned ptrA   = MI->getOperand(1).getReg();
7228     unsigned ptrB   = MI->getOperand(2).getReg();
7229     unsigned oldval = MI->getOperand(3).getReg();
7230     unsigned newval = MI->getOperand(4).getReg();
7231     DebugLoc dl     = MI->getDebugLoc();
7232
7233     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7234     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7235     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7236     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7237     F->insert(It, loop1MBB);
7238     F->insert(It, loop2MBB);
7239     F->insert(It, midMBB);
7240     F->insert(It, exitMBB);
7241     exitMBB->splice(exitMBB->begin(), BB,
7242                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7243     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7244
7245     MachineRegisterInfo &RegInfo = F->getRegInfo();
7246     const TargetRegisterClass *RC =
7247       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7248                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7249     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7250     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7251     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7252     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7253     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7254     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7255     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7256     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7257     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7258     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7259     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7260     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7261     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7262     unsigned Ptr1Reg;
7263     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7264     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7265     //  thisMBB:
7266     //   ...
7267     //   fallthrough --> loopMBB
7268     BB->addSuccessor(loop1MBB);
7269
7270     // The 4-byte load must be aligned, while a char or short may be
7271     // anywhere in the word.  Hence all this nasty bookkeeping code.
7272     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7273     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7274     //   xori shift, shift1, 24 [16]
7275     //   rlwinm ptr, ptr1, 0, 0, 29
7276     //   slw newval2, newval, shift
7277     //   slw oldval2, oldval,shift
7278     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7279     //   slw mask, mask2, shift
7280     //   and newval3, newval2, mask
7281     //   and oldval3, oldval2, mask
7282     // loop1MBB:
7283     //   lwarx tmpDest, ptr
7284     //   and tmp, tmpDest, mask
7285     //   cmpw tmp, oldval3
7286     //   bne- midMBB
7287     // loop2MBB:
7288     //   andc tmp2, tmpDest, mask
7289     //   or tmp4, tmp2, newval3
7290     //   stwcx. tmp4, ptr
7291     //   bne- loop1MBB
7292     //   b exitBB
7293     // midMBB:
7294     //   stwcx. tmpDest, ptr
7295     // exitBB:
7296     //   srw dest, tmpDest, shift
7297     if (ptrA != ZeroReg) {
7298       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7299       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7300         .addReg(ptrA).addReg(ptrB);
7301     } else {
7302       Ptr1Reg = ptrB;
7303     }
7304     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7305         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7306     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7307         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7308     if (is64bit)
7309       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7310         .addReg(Ptr1Reg).addImm(0).addImm(61);
7311     else
7312       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7313         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7314     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7315         .addReg(newval).addReg(ShiftReg);
7316     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7317         .addReg(oldval).addReg(ShiftReg);
7318     if (is8bit)
7319       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7320     else {
7321       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7322       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7323         .addReg(Mask3Reg).addImm(65535);
7324     }
7325     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7326         .addReg(Mask2Reg).addReg(ShiftReg);
7327     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7328         .addReg(NewVal2Reg).addReg(MaskReg);
7329     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7330         .addReg(OldVal2Reg).addReg(MaskReg);
7331
7332     BB = loop1MBB;
7333     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7334         .addReg(ZeroReg).addReg(PtrReg);
7335     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7336         .addReg(TmpDestReg).addReg(MaskReg);
7337     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7338         .addReg(TmpReg).addReg(OldVal3Reg);
7339     BuildMI(BB, dl, TII->get(PPC::BCC))
7340         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7341     BB->addSuccessor(loop2MBB);
7342     BB->addSuccessor(midMBB);
7343
7344     BB = loop2MBB;
7345     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7346         .addReg(TmpDestReg).addReg(MaskReg);
7347     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7348         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7349     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7350         .addReg(ZeroReg).addReg(PtrReg);
7351     BuildMI(BB, dl, TII->get(PPC::BCC))
7352       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7353     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7354     BB->addSuccessor(loop1MBB);
7355     BB->addSuccessor(exitMBB);
7356
7357     BB = midMBB;
7358     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7359       .addReg(ZeroReg).addReg(PtrReg);
7360     BB->addSuccessor(exitMBB);
7361
7362     //  exitMBB:
7363     //   ...
7364     BB = exitMBB;
7365     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7366       .addReg(ShiftReg);
7367   } else if (MI->getOpcode() == PPC::FADDrtz) {
7368     // This pseudo performs an FADD with rounding mode temporarily forced
7369     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7370     // is not modeled at the SelectionDAG level.
7371     unsigned Dest = MI->getOperand(0).getReg();
7372     unsigned Src1 = MI->getOperand(1).getReg();
7373     unsigned Src2 = MI->getOperand(2).getReg();
7374     DebugLoc dl   = MI->getDebugLoc();
7375
7376     MachineRegisterInfo &RegInfo = F->getRegInfo();
7377     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7378
7379     // Save FPSCR value.
7380     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7381
7382     // Set rounding mode to round-to-zero.
7383     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7384     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7385
7386     // Perform addition.
7387     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7388
7389     // Restore FPSCR value.
7390     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7391   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7392              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7393              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7394              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7395     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7396                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7397                       PPC::ANDIo8 : PPC::ANDIo;
7398     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7399                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7400
7401     MachineRegisterInfo &RegInfo = F->getRegInfo();
7402     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7403                                                   &PPC::GPRCRegClass :
7404                                                   &PPC::G8RCRegClass);
7405
7406     DebugLoc dl   = MI->getDebugLoc();
7407     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7408       .addReg(MI->getOperand(1).getReg()).addImm(1);
7409     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7410             MI->getOperand(0).getReg())
7411       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7412   } else {
7413     llvm_unreachable("Unexpected instr type to insert");
7414   }
7415
7416   MI->eraseFromParent();   // The pseudo instruction is gone now.
7417   return BB;
7418 }
7419
7420 //===----------------------------------------------------------------------===//
7421 // Target Optimization Hooks
7422 //===----------------------------------------------------------------------===//
7423
7424 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7425                                                DAGCombinerInfo &DCI) const {
7426   if (DCI.isAfterLegalizeVectorOps())
7427     return SDValue();
7428
7429   EVT VT = Op.getValueType();
7430
7431   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7432       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7433       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7434       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7435
7436     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7437     // For the reciprocal, we need to find the zero of the function:
7438     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7439     //     =>
7440     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7441     //     does not require additional intermediate precision]
7442
7443     // Convergence is quadratic, so we essentially double the number of digits
7444     // correct after every iteration. The minimum architected relative
7445     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7446     // 23 digits and double has 52 digits.
7447     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7448     if (VT.getScalarType() == MVT::f64)
7449       ++Iterations;
7450
7451     SelectionDAG &DAG = DCI.DAG;
7452     SDLoc dl(Op);
7453
7454     SDValue FPOne =
7455       DAG.getConstantFP(1.0, VT.getScalarType());
7456     if (VT.isVector()) {
7457       assert(VT.getVectorNumElements() == 4 &&
7458              "Unknown vector type");
7459       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7460                           FPOne, FPOne, FPOne, FPOne);
7461     }
7462
7463     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7464     DCI.AddToWorklist(Est.getNode());
7465
7466     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7467     for (int i = 0; i < Iterations; ++i) {
7468       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7469       DCI.AddToWorklist(NewEst.getNode());
7470
7471       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7472       DCI.AddToWorklist(NewEst.getNode());
7473
7474       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7475       DCI.AddToWorklist(NewEst.getNode());
7476
7477       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7478       DCI.AddToWorklist(Est.getNode());
7479     }
7480
7481     return Est;
7482   }
7483
7484   return SDValue();
7485 }
7486
7487 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7488                                              DAGCombinerInfo &DCI) const {
7489   if (DCI.isAfterLegalizeVectorOps())
7490     return SDValue();
7491
7492   EVT VT = Op.getValueType();
7493
7494   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7495       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7496       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7497       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7498
7499     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7500     // For the reciprocal sqrt, we need to find the zero of the function:
7501     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7502     //     =>
7503     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7504     // As a result, we precompute A/2 prior to the iteration loop.
7505
7506     // Convergence is quadratic, so we essentially double the number of digits
7507     // correct after every iteration. The minimum architected relative
7508     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7509     // 23 digits and double has 52 digits.
7510     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7511     if (VT.getScalarType() == MVT::f64)
7512       ++Iterations;
7513
7514     SelectionDAG &DAG = DCI.DAG;
7515     SDLoc dl(Op);
7516
7517     SDValue FPThreeHalves =
7518       DAG.getConstantFP(1.5, VT.getScalarType());
7519     if (VT.isVector()) {
7520       assert(VT.getVectorNumElements() == 4 &&
7521              "Unknown vector type");
7522       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7523                                   FPThreeHalves, FPThreeHalves,
7524                                   FPThreeHalves, FPThreeHalves);
7525     }
7526
7527     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7528     DCI.AddToWorklist(Est.getNode());
7529
7530     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7531     // this entire sequence requires only one FP constant.
7532     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7533     DCI.AddToWorklist(HalfArg.getNode());
7534
7535     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7536     DCI.AddToWorklist(HalfArg.getNode());
7537
7538     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7539     for (int i = 0; i < Iterations; ++i) {
7540       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7541       DCI.AddToWorklist(NewEst.getNode());
7542
7543       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7544       DCI.AddToWorklist(NewEst.getNode());
7545
7546       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7547       DCI.AddToWorklist(NewEst.getNode());
7548
7549       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7550       DCI.AddToWorklist(Est.getNode());
7551     }
7552
7553     return Est;
7554   }
7555
7556   return SDValue();
7557 }
7558
7559 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7560                             unsigned Bytes, int Dist,
7561                             SelectionDAG &DAG) {
7562   if (VT.getSizeInBits() / 8 != Bytes)
7563     return false;
7564
7565   SDValue BaseLoc = Base->getBasePtr();
7566   if (Loc.getOpcode() == ISD::FrameIndex) {
7567     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7568       return false;
7569     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7570     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7571     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7572     int FS  = MFI->getObjectSize(FI);
7573     int BFS = MFI->getObjectSize(BFI);
7574     if (FS != BFS || FS != (int)Bytes) return false;
7575     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7576   }
7577
7578   // Handle X+C
7579   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7580       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7581     return true;
7582
7583   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7584   const GlobalValue *GV1 = nullptr;
7585   const GlobalValue *GV2 = nullptr;
7586   int64_t Offset1 = 0;
7587   int64_t Offset2 = 0;
7588   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7589   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7590   if (isGA1 && isGA2 && GV1 == GV2)
7591     return Offset1 == (Offset2 + Dist*Bytes);
7592   return false;
7593 }
7594
7595 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7596 // not enforce equality of the chain operands.
7597 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7598                             unsigned Bytes, int Dist,
7599                             SelectionDAG &DAG) {
7600   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7601     EVT VT = LS->getMemoryVT();
7602     SDValue Loc = LS->getBasePtr();
7603     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7604   }
7605
7606   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7607     EVT VT;
7608     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7609     default: return false;
7610     case Intrinsic::ppc_altivec_lvx:
7611     case Intrinsic::ppc_altivec_lvxl:
7612       VT = MVT::v4i32;
7613       break;
7614     case Intrinsic::ppc_altivec_lvebx:
7615       VT = MVT::i8;
7616       break;
7617     case Intrinsic::ppc_altivec_lvehx:
7618       VT = MVT::i16;
7619       break;
7620     case Intrinsic::ppc_altivec_lvewx:
7621       VT = MVT::i32;
7622       break;
7623     }
7624
7625     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7626   }
7627
7628   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7629     EVT VT;
7630     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7631     default: return false;
7632     case Intrinsic::ppc_altivec_stvx:
7633     case Intrinsic::ppc_altivec_stvxl:
7634       VT = MVT::v4i32;
7635       break;
7636     case Intrinsic::ppc_altivec_stvebx:
7637       VT = MVT::i8;
7638       break;
7639     case Intrinsic::ppc_altivec_stvehx:
7640       VT = MVT::i16;
7641       break;
7642     case Intrinsic::ppc_altivec_stvewx:
7643       VT = MVT::i32;
7644       break;
7645     }
7646
7647     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7648   }
7649
7650   return false;
7651 }
7652
7653 // Return true is there is a nearyby consecutive load to the one provided
7654 // (regardless of alignment). We search up and down the chain, looking though
7655 // token factors and other loads (but nothing else). As a result, a true result
7656 // indicates that it is safe to create a new consecutive load adjacent to the
7657 // load provided.
7658 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7659   SDValue Chain = LD->getChain();
7660   EVT VT = LD->getMemoryVT();
7661
7662   SmallSet<SDNode *, 16> LoadRoots;
7663   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7664   SmallSet<SDNode *, 16> Visited;
7665
7666   // First, search up the chain, branching to follow all token-factor operands.
7667   // If we find a consecutive load, then we're done, otherwise, record all
7668   // nodes just above the top-level loads and token factors.
7669   while (!Queue.empty()) {
7670     SDNode *ChainNext = Queue.pop_back_val();
7671     if (!Visited.insert(ChainNext))
7672       continue;
7673
7674     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7675       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7676         return true;
7677
7678       if (!Visited.count(ChainLD->getChain().getNode()))
7679         Queue.push_back(ChainLD->getChain().getNode());
7680     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7681       for (const SDUse &O : ChainNext->ops())
7682         if (!Visited.count(O.getNode()))
7683           Queue.push_back(O.getNode());
7684     } else
7685       LoadRoots.insert(ChainNext);
7686   }
7687
7688   // Second, search down the chain, starting from the top-level nodes recorded
7689   // in the first phase. These top-level nodes are the nodes just above all
7690   // loads and token factors. Starting with their uses, recursively look though
7691   // all loads (just the chain uses) and token factors to find a consecutive
7692   // load.
7693   Visited.clear();
7694   Queue.clear();
7695
7696   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7697        IE = LoadRoots.end(); I != IE; ++I) {
7698     Queue.push_back(*I);
7699        
7700     while (!Queue.empty()) {
7701       SDNode *LoadRoot = Queue.pop_back_val();
7702       if (!Visited.insert(LoadRoot))
7703         continue;
7704
7705       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7706         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7707           return true;
7708
7709       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7710            UE = LoadRoot->use_end(); UI != UE; ++UI)
7711         if (((isa<MemSDNode>(*UI) &&
7712             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7713             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7714           Queue.push_back(*UI);
7715     }
7716   }
7717
7718   return false;
7719 }
7720
7721 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7722                                                   DAGCombinerInfo &DCI) const {
7723   SelectionDAG &DAG = DCI.DAG;
7724   SDLoc dl(N);
7725
7726   assert(Subtarget.useCRBits() &&
7727          "Expecting to be tracking CR bits");
7728   // If we're tracking CR bits, we need to be careful that we don't have:
7729   //   trunc(binary-ops(zext(x), zext(y)))
7730   // or
7731   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7732   // such that we're unnecessarily moving things into GPRs when it would be
7733   // better to keep them in CR bits.
7734
7735   // Note that trunc here can be an actual i1 trunc, or can be the effective
7736   // truncation that comes from a setcc or select_cc.
7737   if (N->getOpcode() == ISD::TRUNCATE &&
7738       N->getValueType(0) != MVT::i1)
7739     return SDValue();
7740
7741   if (N->getOperand(0).getValueType() != MVT::i32 &&
7742       N->getOperand(0).getValueType() != MVT::i64)
7743     return SDValue();
7744
7745   if (N->getOpcode() == ISD::SETCC ||
7746       N->getOpcode() == ISD::SELECT_CC) {
7747     // If we're looking at a comparison, then we need to make sure that the
7748     // high bits (all except for the first) don't matter the result.
7749     ISD::CondCode CC =
7750       cast<CondCodeSDNode>(N->getOperand(
7751         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7752     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7753
7754     if (ISD::isSignedIntSetCC(CC)) {
7755       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7756           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7757         return SDValue();
7758     } else if (ISD::isUnsignedIntSetCC(CC)) {
7759       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7760                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7761           !DAG.MaskedValueIsZero(N->getOperand(1),
7762                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7763         return SDValue();
7764     } else {
7765       // This is neither a signed nor an unsigned comparison, just make sure
7766       // that the high bits are equal.
7767       APInt Op1Zero, Op1One;
7768       APInt Op2Zero, Op2One;
7769       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7770       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7771
7772       // We don't really care about what is known about the first bit (if
7773       // anything), so clear it in all masks prior to comparing them.
7774       Op1Zero.clearBit(0); Op1One.clearBit(0);
7775       Op2Zero.clearBit(0); Op2One.clearBit(0);
7776
7777       if (Op1Zero != Op2Zero || Op1One != Op2One)
7778         return SDValue();
7779     }
7780   }
7781
7782   // We now know that the higher-order bits are irrelevant, we just need to
7783   // make sure that all of the intermediate operations are bit operations, and
7784   // all inputs are extensions.
7785   if (N->getOperand(0).getOpcode() != ISD::AND &&
7786       N->getOperand(0).getOpcode() != ISD::OR  &&
7787       N->getOperand(0).getOpcode() != ISD::XOR &&
7788       N->getOperand(0).getOpcode() != ISD::SELECT &&
7789       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7790       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7791       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7792       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7793       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7794     return SDValue();
7795
7796   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7797       N->getOperand(1).getOpcode() != ISD::AND &&
7798       N->getOperand(1).getOpcode() != ISD::OR  &&
7799       N->getOperand(1).getOpcode() != ISD::XOR &&
7800       N->getOperand(1).getOpcode() != ISD::SELECT &&
7801       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7802       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7803       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7804       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7805       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7806     return SDValue();
7807
7808   SmallVector<SDValue, 4> Inputs;
7809   SmallVector<SDValue, 8> BinOps, PromOps;
7810   SmallPtrSet<SDNode *, 16> Visited;
7811
7812   for (unsigned i = 0; i < 2; ++i) {
7813     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7814           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7815           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7816           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7817         isa<ConstantSDNode>(N->getOperand(i)))
7818       Inputs.push_back(N->getOperand(i));
7819     else
7820       BinOps.push_back(N->getOperand(i));
7821
7822     if (N->getOpcode() == ISD::TRUNCATE)
7823       break;
7824   }
7825
7826   // Visit all inputs, collect all binary operations (and, or, xor and
7827   // select) that are all fed by extensions. 
7828   while (!BinOps.empty()) {
7829     SDValue BinOp = BinOps.back();
7830     BinOps.pop_back();
7831
7832     if (!Visited.insert(BinOp.getNode()))
7833       continue;
7834
7835     PromOps.push_back(BinOp);
7836
7837     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7838       // The condition of the select is not promoted.
7839       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7840         continue;
7841       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7842         continue;
7843
7844       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7845             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7846             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7847            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7848           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7849         Inputs.push_back(BinOp.getOperand(i)); 
7850       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7851                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7852                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7853                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7854                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7855                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7856                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7857                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7858                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7859         BinOps.push_back(BinOp.getOperand(i));
7860       } else {
7861         // We have an input that is not an extension or another binary
7862         // operation; we'll abort this transformation.
7863         return SDValue();
7864       }
7865     }
7866   }
7867
7868   // Make sure that this is a self-contained cluster of operations (which
7869   // is not quite the same thing as saying that everything has only one
7870   // use).
7871   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7872     if (isa<ConstantSDNode>(Inputs[i]))
7873       continue;
7874
7875     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7876                               UE = Inputs[i].getNode()->use_end();
7877          UI != UE; ++UI) {
7878       SDNode *User = *UI;
7879       if (User != N && !Visited.count(User))
7880         return SDValue();
7881
7882       // Make sure that we're not going to promote the non-output-value
7883       // operand(s) or SELECT or SELECT_CC.
7884       // FIXME: Although we could sometimes handle this, and it does occur in
7885       // practice that one of the condition inputs to the select is also one of
7886       // the outputs, we currently can't deal with this.
7887       if (User->getOpcode() == ISD::SELECT) {
7888         if (User->getOperand(0) == Inputs[i])
7889           return SDValue();
7890       } else if (User->getOpcode() == ISD::SELECT_CC) {
7891         if (User->getOperand(0) == Inputs[i] ||
7892             User->getOperand(1) == Inputs[i])
7893           return SDValue();
7894       }
7895     }
7896   }
7897
7898   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7899     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7900                               UE = PromOps[i].getNode()->use_end();
7901          UI != UE; ++UI) {
7902       SDNode *User = *UI;
7903       if (User != N && !Visited.count(User))
7904         return SDValue();
7905
7906       // Make sure that we're not going to promote the non-output-value
7907       // operand(s) or SELECT or SELECT_CC.
7908       // FIXME: Although we could sometimes handle this, and it does occur in
7909       // practice that one of the condition inputs to the select is also one of
7910       // the outputs, we currently can't deal with this.
7911       if (User->getOpcode() == ISD::SELECT) {
7912         if (User->getOperand(0) == PromOps[i])
7913           return SDValue();
7914       } else if (User->getOpcode() == ISD::SELECT_CC) {
7915         if (User->getOperand(0) == PromOps[i] ||
7916             User->getOperand(1) == PromOps[i])
7917           return SDValue();
7918       }
7919     }
7920   }
7921
7922   // Replace all inputs with the extension operand.
7923   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7924     // Constants may have users outside the cluster of to-be-promoted nodes,
7925     // and so we need to replace those as we do the promotions.
7926     if (isa<ConstantSDNode>(Inputs[i]))
7927       continue;
7928     else
7929       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7930   }
7931
7932   // Replace all operations (these are all the same, but have a different
7933   // (i1) return type). DAG.getNode will validate that the types of
7934   // a binary operator match, so go through the list in reverse so that
7935   // we've likely promoted both operands first. Any intermediate truncations or
7936   // extensions disappear.
7937   while (!PromOps.empty()) {
7938     SDValue PromOp = PromOps.back();
7939     PromOps.pop_back();
7940
7941     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7942         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7943         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7944         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7945       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7946           PromOp.getOperand(0).getValueType() != MVT::i1) {
7947         // The operand is not yet ready (see comment below).
7948         PromOps.insert(PromOps.begin(), PromOp);
7949         continue;
7950       }
7951
7952       SDValue RepValue = PromOp.getOperand(0);
7953       if (isa<ConstantSDNode>(RepValue))
7954         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7955
7956       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7957       continue;
7958     }
7959
7960     unsigned C;
7961     switch (PromOp.getOpcode()) {
7962     default:             C = 0; break;
7963     case ISD::SELECT:    C = 1; break;
7964     case ISD::SELECT_CC: C = 2; break;
7965     }
7966
7967     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7968          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7969         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7970          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7971       // The to-be-promoted operands of this node have not yet been
7972       // promoted (this should be rare because we're going through the
7973       // list backward, but if one of the operands has several users in
7974       // this cluster of to-be-promoted nodes, it is possible).
7975       PromOps.insert(PromOps.begin(), PromOp);
7976       continue;
7977     }
7978
7979     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7980                                 PromOp.getNode()->op_end());
7981
7982     // If there are any constant inputs, make sure they're replaced now.
7983     for (unsigned i = 0; i < 2; ++i)
7984       if (isa<ConstantSDNode>(Ops[C+i]))
7985         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7986
7987     DAG.ReplaceAllUsesOfValueWith(PromOp,
7988       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7989   }
7990
7991   // Now we're left with the initial truncation itself.
7992   if (N->getOpcode() == ISD::TRUNCATE)
7993     return N->getOperand(0);
7994
7995   // Otherwise, this is a comparison. The operands to be compared have just
7996   // changed type (to i1), but everything else is the same.
7997   return SDValue(N, 0);
7998 }
7999
8000 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8001                                                   DAGCombinerInfo &DCI) const {
8002   SelectionDAG &DAG = DCI.DAG;
8003   SDLoc dl(N);
8004
8005   // If we're tracking CR bits, we need to be careful that we don't have:
8006   //   zext(binary-ops(trunc(x), trunc(y)))
8007   // or
8008   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8009   // such that we're unnecessarily moving things into CR bits that can more
8010   // efficiently stay in GPRs. Note that if we're not certain that the high
8011   // bits are set as required by the final extension, we still may need to do
8012   // some masking to get the proper behavior.
8013
8014   // This same functionality is important on PPC64 when dealing with
8015   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8016   // the return values of functions. Because it is so similar, it is handled
8017   // here as well.
8018
8019   if (N->getValueType(0) != MVT::i32 &&
8020       N->getValueType(0) != MVT::i64)
8021     return SDValue();
8022
8023   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8024         Subtarget.useCRBits()) ||
8025        (N->getOperand(0).getValueType() == MVT::i32 &&
8026         Subtarget.isPPC64())))
8027     return SDValue();
8028
8029   if (N->getOperand(0).getOpcode() != ISD::AND &&
8030       N->getOperand(0).getOpcode() != ISD::OR  &&
8031       N->getOperand(0).getOpcode() != ISD::XOR &&
8032       N->getOperand(0).getOpcode() != ISD::SELECT &&
8033       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8034     return SDValue();
8035
8036   SmallVector<SDValue, 4> Inputs;
8037   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8038   SmallPtrSet<SDNode *, 16> Visited;
8039
8040   // Visit all inputs, collect all binary operations (and, or, xor and
8041   // select) that are all fed by truncations. 
8042   while (!BinOps.empty()) {
8043     SDValue BinOp = BinOps.back();
8044     BinOps.pop_back();
8045
8046     if (!Visited.insert(BinOp.getNode()))
8047       continue;
8048
8049     PromOps.push_back(BinOp);
8050
8051     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8052       // The condition of the select is not promoted.
8053       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8054         continue;
8055       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8056         continue;
8057
8058       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8059           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8060         Inputs.push_back(BinOp.getOperand(i)); 
8061       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8062                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8063                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8064                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8065                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8066         BinOps.push_back(BinOp.getOperand(i));
8067       } else {
8068         // We have an input that is not a truncation or another binary
8069         // operation; we'll abort this transformation.
8070         return SDValue();
8071       }
8072     }
8073   }
8074
8075   // Make sure that this is a self-contained cluster of operations (which
8076   // is not quite the same thing as saying that everything has only one
8077   // use).
8078   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8079     if (isa<ConstantSDNode>(Inputs[i]))
8080       continue;
8081
8082     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8083                               UE = Inputs[i].getNode()->use_end();
8084          UI != UE; ++UI) {
8085       SDNode *User = *UI;
8086       if (User != N && !Visited.count(User))
8087         return SDValue();
8088
8089       // Make sure that we're not going to promote the non-output-value
8090       // operand(s) or SELECT or SELECT_CC.
8091       // FIXME: Although we could sometimes handle this, and it does occur in
8092       // practice that one of the condition inputs to the select is also one of
8093       // the outputs, we currently can't deal with this.
8094       if (User->getOpcode() == ISD::SELECT) {
8095         if (User->getOperand(0) == Inputs[i])
8096           return SDValue();
8097       } else if (User->getOpcode() == ISD::SELECT_CC) {
8098         if (User->getOperand(0) == Inputs[i] ||
8099             User->getOperand(1) == Inputs[i])
8100           return SDValue();
8101       }
8102     }
8103   }
8104
8105   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8106     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8107                               UE = PromOps[i].getNode()->use_end();
8108          UI != UE; ++UI) {
8109       SDNode *User = *UI;
8110       if (User != N && !Visited.count(User))
8111         return SDValue();
8112
8113       // Make sure that we're not going to promote the non-output-value
8114       // operand(s) or SELECT or SELECT_CC.
8115       // FIXME: Although we could sometimes handle this, and it does occur in
8116       // practice that one of the condition inputs to the select is also one of
8117       // the outputs, we currently can't deal with this.
8118       if (User->getOpcode() == ISD::SELECT) {
8119         if (User->getOperand(0) == PromOps[i])
8120           return SDValue();
8121       } else if (User->getOpcode() == ISD::SELECT_CC) {
8122         if (User->getOperand(0) == PromOps[i] ||
8123             User->getOperand(1) == PromOps[i])
8124           return SDValue();
8125       }
8126     }
8127   }
8128
8129   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8130   bool ReallyNeedsExt = false;
8131   if (N->getOpcode() != ISD::ANY_EXTEND) {
8132     // If all of the inputs are not already sign/zero extended, then
8133     // we'll still need to do that at the end.
8134     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8135       if (isa<ConstantSDNode>(Inputs[i]))
8136         continue;
8137
8138       unsigned OpBits =
8139         Inputs[i].getOperand(0).getValueSizeInBits();
8140       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8141
8142       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8143            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8144                                   APInt::getHighBitsSet(OpBits,
8145                                                         OpBits-PromBits))) ||
8146           (N->getOpcode() == ISD::SIGN_EXTEND &&
8147            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8148              (OpBits-(PromBits-1)))) {
8149         ReallyNeedsExt = true;
8150         break;
8151       }
8152     }
8153   }
8154
8155   // Replace all inputs, either with the truncation operand, or a
8156   // truncation or extension to the final output type.
8157   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8158     // Constant inputs need to be replaced with the to-be-promoted nodes that
8159     // use them because they might have users outside of the cluster of
8160     // promoted nodes.
8161     if (isa<ConstantSDNode>(Inputs[i]))
8162       continue;
8163
8164     SDValue InSrc = Inputs[i].getOperand(0);
8165     if (Inputs[i].getValueType() == N->getValueType(0))
8166       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8167     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8168       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8169         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8170     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8171       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8172         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8173     else
8174       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8175         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8176   }
8177
8178   // Replace all operations (these are all the same, but have a different
8179   // (promoted) return type). DAG.getNode will validate that the types of
8180   // a binary operator match, so go through the list in reverse so that
8181   // we've likely promoted both operands first.
8182   while (!PromOps.empty()) {
8183     SDValue PromOp = PromOps.back();
8184     PromOps.pop_back();
8185
8186     unsigned C;
8187     switch (PromOp.getOpcode()) {
8188     default:             C = 0; break;
8189     case ISD::SELECT:    C = 1; break;
8190     case ISD::SELECT_CC: C = 2; break;
8191     }
8192
8193     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8194          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8195         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8196          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8197       // The to-be-promoted operands of this node have not yet been
8198       // promoted (this should be rare because we're going through the
8199       // list backward, but if one of the operands has several users in
8200       // this cluster of to-be-promoted nodes, it is possible).
8201       PromOps.insert(PromOps.begin(), PromOp);
8202       continue;
8203     }
8204
8205     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8206                                 PromOp.getNode()->op_end());
8207
8208     // If this node has constant inputs, then they'll need to be promoted here.
8209     for (unsigned i = 0; i < 2; ++i) {
8210       if (!isa<ConstantSDNode>(Ops[C+i]))
8211         continue;
8212       if (Ops[C+i].getValueType() == N->getValueType(0))
8213         continue;
8214
8215       if (N->getOpcode() == ISD::SIGN_EXTEND)
8216         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8217       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8218         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8219       else
8220         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8221     }
8222
8223     DAG.ReplaceAllUsesOfValueWith(PromOp,
8224       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8225   }
8226
8227   // Now we're left with the initial extension itself.
8228   if (!ReallyNeedsExt)
8229     return N->getOperand(0);
8230
8231   // To zero extend, just mask off everything except for the first bit (in the
8232   // i1 case).
8233   if (N->getOpcode() == ISD::ZERO_EXTEND)
8234     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8235                        DAG.getConstant(APInt::getLowBitsSet(
8236                                          N->getValueSizeInBits(0), PromBits),
8237                                        N->getValueType(0)));
8238
8239   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8240          "Invalid extension type");
8241   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8242   SDValue ShiftCst =
8243     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8244   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8245                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8246                                  N->getOperand(0), ShiftCst), ShiftCst);
8247 }
8248
8249 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8250                                              DAGCombinerInfo &DCI) const {
8251   const TargetMachine &TM = getTargetMachine();
8252   SelectionDAG &DAG = DCI.DAG;
8253   SDLoc dl(N);
8254   switch (N->getOpcode()) {
8255   default: break;
8256   case PPCISD::SHL:
8257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8258       if (C->isNullValue())   // 0 << V -> 0.
8259         return N->getOperand(0);
8260     }
8261     break;
8262   case PPCISD::SRL:
8263     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8264       if (C->isNullValue())   // 0 >>u V -> 0.
8265         return N->getOperand(0);
8266     }
8267     break;
8268   case PPCISD::SRA:
8269     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8270       if (C->isNullValue() ||   //  0 >>s V -> 0.
8271           C->isAllOnesValue())    // -1 >>s V -> -1.
8272         return N->getOperand(0);
8273     }
8274     break;
8275   case ISD::SIGN_EXTEND:
8276   case ISD::ZERO_EXTEND:
8277   case ISD::ANY_EXTEND: 
8278     return DAGCombineExtBoolTrunc(N, DCI);
8279   case ISD::TRUNCATE:
8280   case ISD::SETCC:
8281   case ISD::SELECT_CC:
8282     return DAGCombineTruncBoolExt(N, DCI);
8283   case ISD::FDIV: {
8284     assert(TM.Options.UnsafeFPMath &&
8285            "Reciprocal estimates require UnsafeFPMath");
8286
8287     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8288       SDValue RV =
8289         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8290       if (RV.getNode()) {
8291         DCI.AddToWorklist(RV.getNode());
8292         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8293                            N->getOperand(0), RV);
8294       }
8295     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8296                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8297       SDValue RV =
8298         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8299                                  DCI);
8300       if (RV.getNode()) {
8301         DCI.AddToWorklist(RV.getNode());
8302         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8303                          N->getValueType(0), RV);
8304         DCI.AddToWorklist(RV.getNode());
8305         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8306                            N->getOperand(0), RV);
8307       }
8308     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8309                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8310       SDValue RV =
8311         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8312                                  DCI);
8313       if (RV.getNode()) {
8314         DCI.AddToWorklist(RV.getNode());
8315         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8316                          N->getValueType(0), RV,
8317                          N->getOperand(1).getOperand(1));
8318         DCI.AddToWorklist(RV.getNode());
8319         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8320                            N->getOperand(0), RV);
8321       }
8322     }
8323
8324     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8325     if (RV.getNode()) {
8326       DCI.AddToWorklist(RV.getNode());
8327       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8328                          N->getOperand(0), RV);
8329     }
8330
8331     }
8332     break;
8333   case ISD::FSQRT: {
8334     assert(TM.Options.UnsafeFPMath &&
8335            "Reciprocal estimates require UnsafeFPMath");
8336
8337     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8338     // reciprocal sqrt.
8339     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8340     if (RV.getNode()) {
8341       DCI.AddToWorklist(RV.getNode());
8342       RV = DAGCombineFastRecip(RV, DCI);
8343       if (RV.getNode()) {
8344         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8345         // this case and force the answer to 0.
8346
8347         EVT VT = RV.getValueType();
8348
8349         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8350         if (VT.isVector()) {
8351           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8352           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8353         }
8354
8355         SDValue ZeroCmp =
8356           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8357                        N->getOperand(0), Zero, ISD::SETEQ);
8358         DCI.AddToWorklist(ZeroCmp.getNode());
8359         DCI.AddToWorklist(RV.getNode());
8360
8361         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8362                          ZeroCmp, Zero, RV);
8363         return RV;
8364       }
8365     }
8366
8367     }
8368     break;
8369   case ISD::SINT_TO_FP:
8370     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8371       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8372         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8373         // We allow the src/dst to be either f32/f64, but the intermediate
8374         // type must be i64.
8375         if (N->getOperand(0).getValueType() == MVT::i64 &&
8376             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8377           SDValue Val = N->getOperand(0).getOperand(0);
8378           if (Val.getValueType() == MVT::f32) {
8379             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8380             DCI.AddToWorklist(Val.getNode());
8381           }
8382
8383           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8384           DCI.AddToWorklist(Val.getNode());
8385           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8386           DCI.AddToWorklist(Val.getNode());
8387           if (N->getValueType(0) == MVT::f32) {
8388             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8389                               DAG.getIntPtrConstant(0));
8390             DCI.AddToWorklist(Val.getNode());
8391           }
8392           return Val;
8393         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8394           // If the intermediate type is i32, we can avoid the load/store here
8395           // too.
8396         }
8397       }
8398     }
8399     break;
8400   case ISD::STORE:
8401     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8402     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8403         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8404         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8405         N->getOperand(1).getValueType() == MVT::i32 &&
8406         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8407       SDValue Val = N->getOperand(1).getOperand(0);
8408       if (Val.getValueType() == MVT::f32) {
8409         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8410         DCI.AddToWorklist(Val.getNode());
8411       }
8412       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8413       DCI.AddToWorklist(Val.getNode());
8414
8415       SDValue Ops[] = {
8416         N->getOperand(0), Val, N->getOperand(2),
8417         DAG.getValueType(N->getOperand(1).getValueType())
8418       };
8419
8420       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8421               DAG.getVTList(MVT::Other), Ops,
8422               cast<StoreSDNode>(N)->getMemoryVT(),
8423               cast<StoreSDNode>(N)->getMemOperand());
8424       DCI.AddToWorklist(Val.getNode());
8425       return Val;
8426     }
8427
8428     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8429     if (cast<StoreSDNode>(N)->isUnindexed() &&
8430         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8431         N->getOperand(1).getNode()->hasOneUse() &&
8432         (N->getOperand(1).getValueType() == MVT::i32 ||
8433          N->getOperand(1).getValueType() == MVT::i16 ||
8434          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8435           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8436           N->getOperand(1).getValueType() == MVT::i64))) {
8437       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8438       // Do an any-extend to 32-bits if this is a half-word input.
8439       if (BSwapOp.getValueType() == MVT::i16)
8440         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8441
8442       SDValue Ops[] = {
8443         N->getOperand(0), BSwapOp, N->getOperand(2),
8444         DAG.getValueType(N->getOperand(1).getValueType())
8445       };
8446       return
8447         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8448                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8449                                 cast<StoreSDNode>(N)->getMemOperand());
8450     }
8451     break;
8452   case ISD::LOAD: {
8453     LoadSDNode *LD = cast<LoadSDNode>(N);
8454     EVT VT = LD->getValueType(0);
8455     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8456     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8457     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8458         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8459         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8460          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8461         LD->getAlignment() < ABIAlignment) {
8462       // This is a type-legal unaligned Altivec load.
8463       SDValue Chain = LD->getChain();
8464       SDValue Ptr = LD->getBasePtr();
8465       bool isLittleEndian = Subtarget.isLittleEndian();
8466
8467       // This implements the loading of unaligned vectors as described in
8468       // the venerable Apple Velocity Engine overview. Specifically:
8469       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8470       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8471       //
8472       // The general idea is to expand a sequence of one or more unaligned
8473       // loads into an alignment-based permutation-control instruction (lvsl
8474       // or lvsr), a series of regular vector loads (which always truncate
8475       // their input address to an aligned address), and a series of
8476       // permutations.  The results of these permutations are the requested
8477       // loaded values.  The trick is that the last "extra" load is not taken
8478       // from the address you might suspect (sizeof(vector) bytes after the
8479       // last requested load), but rather sizeof(vector) - 1 bytes after the
8480       // last requested vector. The point of this is to avoid a page fault if
8481       // the base address happened to be aligned. This works because if the
8482       // base address is aligned, then adding less than a full vector length
8483       // will cause the last vector in the sequence to be (re)loaded.
8484       // Otherwise, the next vector will be fetched as you might suspect was
8485       // necessary.
8486
8487       // We might be able to reuse the permutation generation from
8488       // a different base address offset from this one by an aligned amount.
8489       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8490       // optimization later.
8491       Intrinsic::ID Intr = (isLittleEndian ?
8492                             Intrinsic::ppc_altivec_lvsr :
8493                             Intrinsic::ppc_altivec_lvsl);
8494       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8495
8496       // Create the new MMO for the new base load. It is like the original MMO,
8497       // but represents an area in memory almost twice the vector size centered
8498       // on the original address. If the address is unaligned, we might start
8499       // reading up to (sizeof(vector)-1) bytes below the address of the
8500       // original unaligned load.
8501       MachineFunction &MF = DAG.getMachineFunction();
8502       MachineMemOperand *BaseMMO =
8503         MF.getMachineMemOperand(LD->getMemOperand(),
8504                                 -LD->getMemoryVT().getStoreSize()+1,
8505                                 2*LD->getMemoryVT().getStoreSize()-1);
8506
8507       // Create the new base load.
8508       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8509                                                getPointerTy());
8510       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8511       SDValue BaseLoad =
8512         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8513                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8514                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8515
8516       // Note that the value of IncOffset (which is provided to the next
8517       // load's pointer info offset value, and thus used to calculate the
8518       // alignment), and the value of IncValue (which is actually used to
8519       // increment the pointer value) are different! This is because we
8520       // require the next load to appear to be aligned, even though it
8521       // is actually offset from the base pointer by a lesser amount.
8522       int IncOffset = VT.getSizeInBits() / 8;
8523       int IncValue = IncOffset;
8524
8525       // Walk (both up and down) the chain looking for another load at the real
8526       // (aligned) offset (the alignment of the other load does not matter in
8527       // this case). If found, then do not use the offset reduction trick, as
8528       // that will prevent the loads from being later combined (as they would
8529       // otherwise be duplicates).
8530       if (!findConsecutiveLoad(LD, DAG))
8531         --IncValue;
8532
8533       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8534       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8535
8536       MachineMemOperand *ExtraMMO =
8537         MF.getMachineMemOperand(LD->getMemOperand(),
8538                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8539       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8540       SDValue ExtraLoad =
8541         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8542                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8543                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8544
8545       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8546         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8547
8548       // Because vperm has a big-endian bias, we must reverse the order
8549       // of the input vectors and complement the permute control vector
8550       // when generating little endian code.  We have already handled the
8551       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8552       // and ExtraLoad here.
8553       SDValue Perm;
8554       if (isLittleEndian)
8555         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8556                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8557       else
8558         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8559                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8560
8561       if (VT != MVT::v4i32)
8562         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8563
8564       // The output of the permutation is our loaded result, the TokenFactor is
8565       // our new chain.
8566       DCI.CombineTo(N, Perm, TF);
8567       return SDValue(N, 0);
8568     }
8569     }
8570     break;
8571   case ISD::INTRINSIC_WO_CHAIN: {
8572     bool isLittleEndian = Subtarget.isLittleEndian();
8573     Intrinsic::ID Intr = (isLittleEndian ?
8574                           Intrinsic::ppc_altivec_lvsr :
8575                           Intrinsic::ppc_altivec_lvsl);
8576     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8577         N->getOperand(1)->getOpcode() == ISD::ADD) {
8578       SDValue Add = N->getOperand(1);
8579
8580       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8581             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8582               Add.getValueType().getScalarType().getSizeInBits()))) {
8583         SDNode *BasePtr = Add->getOperand(0).getNode();
8584         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8585              UE = BasePtr->use_end(); UI != UE; ++UI) {
8586           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8587               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8588                 Intr) {
8589             // We've found another LVSL/LVSR, and this address is an aligned
8590             // multiple of that one. The results will be the same, so use the
8591             // one we've just found instead.
8592
8593             return SDValue(*UI, 0);
8594           }
8595         }
8596       }
8597     }
8598     }
8599
8600     break;
8601   case ISD::BSWAP:
8602     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8603     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8604         N->getOperand(0).hasOneUse() &&
8605         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8606          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8607           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8608           N->getValueType(0) == MVT::i64))) {
8609       SDValue Load = N->getOperand(0);
8610       LoadSDNode *LD = cast<LoadSDNode>(Load);
8611       // Create the byte-swapping load.
8612       SDValue Ops[] = {
8613         LD->getChain(),    // Chain
8614         LD->getBasePtr(),  // Ptr
8615         DAG.getValueType(N->getValueType(0)) // VT
8616       };
8617       SDValue BSLoad =
8618         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8619                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8620                                               MVT::i64 : MVT::i32, MVT::Other),
8621                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8622
8623       // If this is an i16 load, insert the truncate.
8624       SDValue ResVal = BSLoad;
8625       if (N->getValueType(0) == MVT::i16)
8626         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8627
8628       // First, combine the bswap away.  This makes the value produced by the
8629       // load dead.
8630       DCI.CombineTo(N, ResVal);
8631
8632       // Next, combine the load away, we give it a bogus result value but a real
8633       // chain result.  The result value is dead because the bswap is dead.
8634       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8635
8636       // Return N so it doesn't get rechecked!
8637       return SDValue(N, 0);
8638     }
8639
8640     break;
8641   case PPCISD::VCMP: {
8642     // If a VCMPo node already exists with exactly the same operands as this
8643     // node, use its result instead of this node (VCMPo computes both a CR6 and
8644     // a normal output).
8645     //
8646     if (!N->getOperand(0).hasOneUse() &&
8647         !N->getOperand(1).hasOneUse() &&
8648         !N->getOperand(2).hasOneUse()) {
8649
8650       // Scan all of the users of the LHS, looking for VCMPo's that match.
8651       SDNode *VCMPoNode = nullptr;
8652
8653       SDNode *LHSN = N->getOperand(0).getNode();
8654       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8655            UI != E; ++UI)
8656         if (UI->getOpcode() == PPCISD::VCMPo &&
8657             UI->getOperand(1) == N->getOperand(1) &&
8658             UI->getOperand(2) == N->getOperand(2) &&
8659             UI->getOperand(0) == N->getOperand(0)) {
8660           VCMPoNode = *UI;
8661           break;
8662         }
8663
8664       // If there is no VCMPo node, or if the flag value has a single use, don't
8665       // transform this.
8666       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8667         break;
8668
8669       // Look at the (necessarily single) use of the flag value.  If it has a
8670       // chain, this transformation is more complex.  Note that multiple things
8671       // could use the value result, which we should ignore.
8672       SDNode *FlagUser = nullptr;
8673       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8674            FlagUser == nullptr; ++UI) {
8675         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8676         SDNode *User = *UI;
8677         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8678           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8679             FlagUser = User;
8680             break;
8681           }
8682         }
8683       }
8684
8685       // If the user is a MFOCRF instruction, we know this is safe.
8686       // Otherwise we give up for right now.
8687       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8688         return SDValue(VCMPoNode, 0);
8689     }
8690     break;
8691   }
8692   case ISD::BRCOND: {
8693     SDValue Cond = N->getOperand(1);
8694     SDValue Target = N->getOperand(2);
8695  
8696     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8697         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8698           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8699
8700       // We now need to make the intrinsic dead (it cannot be instruction
8701       // selected).
8702       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8703       assert(Cond.getNode()->hasOneUse() &&
8704              "Counter decrement has more than one use");
8705
8706       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8707                          N->getOperand(0), Target);
8708     }
8709   }
8710   break;
8711   case ISD::BR_CC: {
8712     // If this is a branch on an altivec predicate comparison, lower this so
8713     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8714     // lowering is done pre-legalize, because the legalizer lowers the predicate
8715     // compare down to code that is difficult to reassemble.
8716     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8717     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8718
8719     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8720     // value. If so, pass-through the AND to get to the intrinsic.
8721     if (LHS.getOpcode() == ISD::AND &&
8722         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8723         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8724           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8725         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8726         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8727           isZero())
8728       LHS = LHS.getOperand(0);
8729
8730     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8731         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8732           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8733         isa<ConstantSDNode>(RHS)) {
8734       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8735              "Counter decrement comparison is not EQ or NE");
8736
8737       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8738       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8739                     (CC == ISD::SETNE && !Val);
8740
8741       // We now need to make the intrinsic dead (it cannot be instruction
8742       // selected).
8743       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8744       assert(LHS.getNode()->hasOneUse() &&
8745              "Counter decrement has more than one use");
8746
8747       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8748                          N->getOperand(0), N->getOperand(4));
8749     }
8750
8751     int CompareOpc;
8752     bool isDot;
8753
8754     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8755         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8756         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8757       assert(isDot && "Can't compare against a vector result!");
8758
8759       // If this is a comparison against something other than 0/1, then we know
8760       // that the condition is never/always true.
8761       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8762       if (Val != 0 && Val != 1) {
8763         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8764           return N->getOperand(0);
8765         // Always !=, turn it into an unconditional branch.
8766         return DAG.getNode(ISD::BR, dl, MVT::Other,
8767                            N->getOperand(0), N->getOperand(4));
8768       }
8769
8770       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8771
8772       // Create the PPCISD altivec 'dot' comparison node.
8773       SDValue Ops[] = {
8774         LHS.getOperand(2),  // LHS of compare
8775         LHS.getOperand(3),  // RHS of compare
8776         DAG.getConstant(CompareOpc, MVT::i32)
8777       };
8778       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8779       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8780
8781       // Unpack the result based on how the target uses it.
8782       PPC::Predicate CompOpc;
8783       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8784       default:  // Can't happen, don't crash on invalid number though.
8785       case 0:   // Branch on the value of the EQ bit of CR6.
8786         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8787         break;
8788       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8789         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8790         break;
8791       case 2:   // Branch on the value of the LT bit of CR6.
8792         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8793         break;
8794       case 3:   // Branch on the inverted value of the LT bit of CR6.
8795         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8796         break;
8797       }
8798
8799       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8800                          DAG.getConstant(CompOpc, MVT::i32),
8801                          DAG.getRegister(PPC::CR6, MVT::i32),
8802                          N->getOperand(4), CompNode.getValue(1));
8803     }
8804     break;
8805   }
8806   }
8807
8808   return SDValue();
8809 }
8810
8811 //===----------------------------------------------------------------------===//
8812 // Inline Assembly Support
8813 //===----------------------------------------------------------------------===//
8814
8815 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8816                                                       APInt &KnownZero,
8817                                                       APInt &KnownOne,
8818                                                       const SelectionDAG &DAG,
8819                                                       unsigned Depth) const {
8820   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8821   switch (Op.getOpcode()) {
8822   default: break;
8823   case PPCISD::LBRX: {
8824     // lhbrx is known to have the top bits cleared out.
8825     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8826       KnownZero = 0xFFFF0000;
8827     break;
8828   }
8829   case ISD::INTRINSIC_WO_CHAIN: {
8830     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8831     default: break;
8832     case Intrinsic::ppc_altivec_vcmpbfp_p:
8833     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8834     case Intrinsic::ppc_altivec_vcmpequb_p:
8835     case Intrinsic::ppc_altivec_vcmpequh_p:
8836     case Intrinsic::ppc_altivec_vcmpequw_p:
8837     case Intrinsic::ppc_altivec_vcmpgefp_p:
8838     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8839     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8840     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8841     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8842     case Intrinsic::ppc_altivec_vcmpgtub_p:
8843     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8844     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8845       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8846       break;
8847     }
8848   }
8849   }
8850 }
8851
8852
8853 /// getConstraintType - Given a constraint, return the type of
8854 /// constraint it is for this target.
8855 PPCTargetLowering::ConstraintType
8856 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8857   if (Constraint.size() == 1) {
8858     switch (Constraint[0]) {
8859     default: break;
8860     case 'b':
8861     case 'r':
8862     case 'f':
8863     case 'v':
8864     case 'y':
8865       return C_RegisterClass;
8866     case 'Z':
8867       // FIXME: While Z does indicate a memory constraint, it specifically
8868       // indicates an r+r address (used in conjunction with the 'y' modifier
8869       // in the replacement string). Currently, we're forcing the base
8870       // register to be r0 in the asm printer (which is interpreted as zero)
8871       // and forming the complete address in the second register. This is
8872       // suboptimal.
8873       return C_Memory;
8874     }
8875   } else if (Constraint == "wc") { // individual CR bits.
8876     return C_RegisterClass;
8877   } else if (Constraint == "wa" || Constraint == "wd" ||
8878              Constraint == "wf" || Constraint == "ws") {
8879     return C_RegisterClass; // VSX registers.
8880   }
8881   return TargetLowering::getConstraintType(Constraint);
8882 }
8883
8884 /// Examine constraint type and operand type and determine a weight value.
8885 /// This object must already have been set up with the operand type
8886 /// and the current alternative constraint selected.
8887 TargetLowering::ConstraintWeight
8888 PPCTargetLowering::getSingleConstraintMatchWeight(
8889     AsmOperandInfo &info, const char *constraint) const {
8890   ConstraintWeight weight = CW_Invalid;
8891   Value *CallOperandVal = info.CallOperandVal;
8892     // If we don't have a value, we can't do a match,
8893     // but allow it at the lowest weight.
8894   if (!CallOperandVal)
8895     return CW_Default;
8896   Type *type = CallOperandVal->getType();
8897
8898   // Look at the constraint type.
8899   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8900     return CW_Register; // an individual CR bit.
8901   else if ((StringRef(constraint) == "wa" ||
8902             StringRef(constraint) == "wd" ||
8903             StringRef(constraint) == "wf") &&
8904            type->isVectorTy())
8905     return CW_Register;
8906   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8907     return CW_Register;
8908
8909   switch (*constraint) {
8910   default:
8911     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8912     break;
8913   case 'b':
8914     if (type->isIntegerTy())
8915       weight = CW_Register;
8916     break;
8917   case 'f':
8918     if (type->isFloatTy())
8919       weight = CW_Register;
8920     break;
8921   case 'd':
8922     if (type->isDoubleTy())
8923       weight = CW_Register;
8924     break;
8925   case 'v':
8926     if (type->isVectorTy())
8927       weight = CW_Register;
8928     break;
8929   case 'y':
8930     weight = CW_Register;
8931     break;
8932   case 'Z':
8933     weight = CW_Memory;
8934     break;
8935   }
8936   return weight;
8937 }
8938
8939 std::pair<unsigned, const TargetRegisterClass*>
8940 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8941                                                 MVT VT) const {
8942   if (Constraint.size() == 1) {
8943     // GCC RS6000 Constraint Letters
8944     switch (Constraint[0]) {
8945     case 'b':   // R1-R31
8946       if (VT == MVT::i64 && Subtarget.isPPC64())
8947         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8948       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8949     case 'r':   // R0-R31
8950       if (VT == MVT::i64 && Subtarget.isPPC64())
8951         return std::make_pair(0U, &PPC::G8RCRegClass);
8952       return std::make_pair(0U, &PPC::GPRCRegClass);
8953     case 'f':
8954       if (VT == MVT::f32 || VT == MVT::i32)
8955         return std::make_pair(0U, &PPC::F4RCRegClass);
8956       if (VT == MVT::f64 || VT == MVT::i64)
8957         return std::make_pair(0U, &PPC::F8RCRegClass);
8958       break;
8959     case 'v':
8960       return std::make_pair(0U, &PPC::VRRCRegClass);
8961     case 'y':   // crrc
8962       return std::make_pair(0U, &PPC::CRRCRegClass);
8963     }
8964   } else if (Constraint == "wc") { // an individual CR bit.
8965     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8966   } else if (Constraint == "wa" || Constraint == "wd" ||
8967              Constraint == "wf") {
8968     return std::make_pair(0U, &PPC::VSRCRegClass);
8969   } else if (Constraint == "ws") {
8970     return std::make_pair(0U, &PPC::VSFRCRegClass);
8971   }
8972
8973   std::pair<unsigned, const TargetRegisterClass*> R =
8974     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8975
8976   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8977   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8978   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8979   // register.
8980   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8981   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8982   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8983       PPC::GPRCRegClass.contains(R.first)) {
8984     const TargetRegisterInfo *TRI =
8985         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8986     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8987                             PPC::sub_32, &PPC::G8RCRegClass),
8988                           &PPC::G8RCRegClass);
8989   }
8990
8991   return R;
8992 }
8993
8994
8995 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8996 /// vector.  If it is invalid, don't add anything to Ops.
8997 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8998                                                      std::string &Constraint,
8999                                                      std::vector<SDValue>&Ops,
9000                                                      SelectionDAG &DAG) const {
9001   SDValue Result;
9002
9003   // Only support length 1 constraints.
9004   if (Constraint.length() > 1) return;
9005
9006   char Letter = Constraint[0];
9007   switch (Letter) {
9008   default: break;
9009   case 'I':
9010   case 'J':
9011   case 'K':
9012   case 'L':
9013   case 'M':
9014   case 'N':
9015   case 'O':
9016   case 'P': {
9017     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9018     if (!CST) return; // Must be an immediate to match.
9019     unsigned Value = CST->getZExtValue();
9020     switch (Letter) {
9021     default: llvm_unreachable("Unknown constraint letter!");
9022     case 'I':  // "I" is a signed 16-bit constant.
9023       if ((short)Value == (int)Value)
9024         Result = DAG.getTargetConstant(Value, Op.getValueType());
9025       break;
9026     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9027     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9028       if ((short)Value == 0)
9029         Result = DAG.getTargetConstant(Value, Op.getValueType());
9030       break;
9031     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9032       if ((Value >> 16) == 0)
9033         Result = DAG.getTargetConstant(Value, Op.getValueType());
9034       break;
9035     case 'M':  // "M" is a constant that is greater than 31.
9036       if (Value > 31)
9037         Result = DAG.getTargetConstant(Value, Op.getValueType());
9038       break;
9039     case 'N':  // "N" is a positive constant that is an exact power of two.
9040       if ((int)Value > 0 && isPowerOf2_32(Value))
9041         Result = DAG.getTargetConstant(Value, Op.getValueType());
9042       break;
9043     case 'O':  // "O" is the constant zero.
9044       if (Value == 0)
9045         Result = DAG.getTargetConstant(Value, Op.getValueType());
9046       break;
9047     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9048       if ((short)-Value == (int)-Value)
9049         Result = DAG.getTargetConstant(Value, Op.getValueType());
9050       break;
9051     }
9052     break;
9053   }
9054   }
9055
9056   if (Result.getNode()) {
9057     Ops.push_back(Result);
9058     return;
9059   }
9060
9061   // Handle standard constraint letters.
9062   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9063 }
9064
9065 // isLegalAddressingMode - Return true if the addressing mode represented
9066 // by AM is legal for this target, for a load/store of the specified type.
9067 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9068                                               Type *Ty) const {
9069   // FIXME: PPC does not allow r+i addressing modes for vectors!
9070
9071   // PPC allows a sign-extended 16-bit immediate field.
9072   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9073     return false;
9074
9075   // No global is ever allowed as a base.
9076   if (AM.BaseGV)
9077     return false;
9078
9079   // PPC only support r+r,
9080   switch (AM.Scale) {
9081   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9082     break;
9083   case 1:
9084     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9085       return false;
9086     // Otherwise we have r+r or r+i.
9087     break;
9088   case 2:
9089     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9090       return false;
9091     // Allow 2*r as r+r.
9092     break;
9093   default:
9094     // No other scales are supported.
9095     return false;
9096   }
9097
9098   return true;
9099 }
9100
9101 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9102                                            SelectionDAG &DAG) const {
9103   MachineFunction &MF = DAG.getMachineFunction();
9104   MachineFrameInfo *MFI = MF.getFrameInfo();
9105   MFI->setReturnAddressIsTaken(true);
9106
9107   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9108     return SDValue();
9109
9110   SDLoc dl(Op);
9111   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9112
9113   // Make sure the function does not optimize away the store of the RA to
9114   // the stack.
9115   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9116   FuncInfo->setLRStoreRequired();
9117   bool isPPC64 = Subtarget.isPPC64();
9118   bool isDarwinABI = Subtarget.isDarwinABI();
9119
9120   if (Depth > 0) {
9121     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9122     SDValue Offset =
9123
9124       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9125                       isPPC64? MVT::i64 : MVT::i32);
9126     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9127                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9128                                    FrameAddr, Offset),
9129                        MachinePointerInfo(), false, false, false, 0);
9130   }
9131
9132   // Just load the return address off the stack.
9133   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9134   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9135                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9136 }
9137
9138 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9139                                           SelectionDAG &DAG) const {
9140   SDLoc dl(Op);
9141   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9142
9143   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9144   bool isPPC64 = PtrVT == MVT::i64;
9145
9146   MachineFunction &MF = DAG.getMachineFunction();
9147   MachineFrameInfo *MFI = MF.getFrameInfo();
9148   MFI->setFrameAddressIsTaken(true);
9149
9150   // Naked functions never have a frame pointer, and so we use r1. For all
9151   // other functions, this decision must be delayed until during PEI.
9152   unsigned FrameReg;
9153   if (MF.getFunction()->getAttributes().hasAttribute(
9154         AttributeSet::FunctionIndex, Attribute::Naked))
9155     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9156   else
9157     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9158
9159   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9160                                          PtrVT);
9161   while (Depth--)
9162     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9163                             FrameAddr, MachinePointerInfo(), false, false,
9164                             false, 0);
9165   return FrameAddr;
9166 }
9167
9168 // FIXME? Maybe this could be a TableGen attribute on some registers and
9169 // this table could be generated automatically from RegInfo.
9170 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9171                                               EVT VT) const {
9172   bool isPPC64 = Subtarget.isPPC64();
9173   bool isDarwinABI = Subtarget.isDarwinABI();
9174
9175   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9176       (!isPPC64 && VT != MVT::i32))
9177     report_fatal_error("Invalid register global variable type");
9178
9179   bool is64Bit = isPPC64 && VT == MVT::i64;
9180   unsigned Reg = StringSwitch<unsigned>(RegName)
9181                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9182                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9183                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9184                                   (is64Bit ? PPC::X13 : PPC::R13))
9185                    .Default(0);
9186
9187   if (Reg)
9188     return Reg;
9189   report_fatal_error("Invalid register name global variable");
9190 }
9191
9192 bool
9193 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9194   // The PowerPC target isn't yet aware of offsets.
9195   return false;
9196 }
9197
9198 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9199                                            const CallInst &I,
9200                                            unsigned Intrinsic) const {
9201
9202   switch (Intrinsic) {
9203   case Intrinsic::ppc_altivec_lvx:
9204   case Intrinsic::ppc_altivec_lvxl:
9205   case Intrinsic::ppc_altivec_lvebx:
9206   case Intrinsic::ppc_altivec_lvehx:
9207   case Intrinsic::ppc_altivec_lvewx: {
9208     EVT VT;
9209     switch (Intrinsic) {
9210     case Intrinsic::ppc_altivec_lvebx:
9211       VT = MVT::i8;
9212       break;
9213     case Intrinsic::ppc_altivec_lvehx:
9214       VT = MVT::i16;
9215       break;
9216     case Intrinsic::ppc_altivec_lvewx:
9217       VT = MVT::i32;
9218       break;
9219     default:
9220       VT = MVT::v4i32;
9221       break;
9222     }
9223
9224     Info.opc = ISD::INTRINSIC_W_CHAIN;
9225     Info.memVT = VT;
9226     Info.ptrVal = I.getArgOperand(0);
9227     Info.offset = -VT.getStoreSize()+1;
9228     Info.size = 2*VT.getStoreSize()-1;
9229     Info.align = 1;
9230     Info.vol = false;
9231     Info.readMem = true;
9232     Info.writeMem = false;
9233     return true;
9234   }
9235   case Intrinsic::ppc_altivec_stvx:
9236   case Intrinsic::ppc_altivec_stvxl:
9237   case Intrinsic::ppc_altivec_stvebx:
9238   case Intrinsic::ppc_altivec_stvehx:
9239   case Intrinsic::ppc_altivec_stvewx: {
9240     EVT VT;
9241     switch (Intrinsic) {
9242     case Intrinsic::ppc_altivec_stvebx:
9243       VT = MVT::i8;
9244       break;
9245     case Intrinsic::ppc_altivec_stvehx:
9246       VT = MVT::i16;
9247       break;
9248     case Intrinsic::ppc_altivec_stvewx:
9249       VT = MVT::i32;
9250       break;
9251     default:
9252       VT = MVT::v4i32;
9253       break;
9254     }
9255
9256     Info.opc = ISD::INTRINSIC_VOID;
9257     Info.memVT = VT;
9258     Info.ptrVal = I.getArgOperand(1);
9259     Info.offset = -VT.getStoreSize()+1;
9260     Info.size = 2*VT.getStoreSize()-1;
9261     Info.align = 1;
9262     Info.vol = false;
9263     Info.readMem = false;
9264     Info.writeMem = true;
9265     return true;
9266   }
9267   default:
9268     break;
9269   }
9270
9271   return false;
9272 }
9273
9274 /// getOptimalMemOpType - Returns the target specific optimal type for load
9275 /// and store operations as a result of memset, memcpy, and memmove
9276 /// lowering. If DstAlign is zero that means it's safe to destination
9277 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9278 /// means there isn't a need to check it against alignment requirement,
9279 /// probably because the source does not need to be loaded. If 'IsMemset' is
9280 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9281 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9282 /// source is constant so it does not need to be loaded.
9283 /// It returns EVT::Other if the type should be determined using generic
9284 /// target-independent logic.
9285 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9286                                            unsigned DstAlign, unsigned SrcAlign,
9287                                            bool IsMemset, bool ZeroMemset,
9288                                            bool MemcpyStrSrc,
9289                                            MachineFunction &MF) const {
9290   if (Subtarget.isPPC64()) {
9291     return MVT::i64;
9292   } else {
9293     return MVT::i32;
9294   }
9295 }
9296
9297 /// \brief Returns true if it is beneficial to convert a load of a constant
9298 /// to just the constant itself.
9299 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9300                                                           Type *Ty) const {
9301   assert(Ty->isIntegerTy());
9302
9303   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9304   if (BitSize == 0 || BitSize > 64)
9305     return false;
9306   return true;
9307 }
9308
9309 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9310   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9311     return false;
9312   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9313   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9314   return NumBits1 == 64 && NumBits2 == 32;
9315 }
9316
9317 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9318   if (!VT1.isInteger() || !VT2.isInteger())
9319     return false;
9320   unsigned NumBits1 = VT1.getSizeInBits();
9321   unsigned NumBits2 = VT2.getSizeInBits();
9322   return NumBits1 == 64 && NumBits2 == 32;
9323 }
9324
9325 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9326   return isInt<16>(Imm) || isUInt<16>(Imm);
9327 }
9328
9329 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9330   return isInt<16>(Imm) || isUInt<16>(Imm);
9331 }
9332
9333 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9334                                                        unsigned,
9335                                                        unsigned,
9336                                                        bool *Fast) const {
9337   if (DisablePPCUnaligned)
9338     return false;
9339
9340   // PowerPC supports unaligned memory access for simple non-vector types.
9341   // Although accessing unaligned addresses is not as efficient as accessing
9342   // aligned addresses, it is generally more efficient than manual expansion,
9343   // and generally only traps for software emulation when crossing page
9344   // boundaries.
9345
9346   if (!VT.isSimple())
9347     return false;
9348
9349   if (VT.getSimpleVT().isVector()) {
9350     if (Subtarget.hasVSX()) {
9351       if (VT != MVT::v2f64 && VT != MVT::v2i64)
9352         return false;
9353     } else {
9354       return false;
9355     }
9356   }
9357
9358   if (VT == MVT::ppcf128)
9359     return false;
9360
9361   if (Fast)
9362     *Fast = true;
9363
9364   return true;
9365 }
9366
9367 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9368   VT = VT.getScalarType();
9369
9370   if (!VT.isSimple())
9371     return false;
9372
9373   switch (VT.getSimpleVT().SimpleTy) {
9374   case MVT::f32:
9375   case MVT::f64:
9376     return true;
9377   default:
9378     break;
9379   }
9380
9381   return false;
9382 }
9383
9384 bool
9385 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9386                      EVT VT , unsigned DefinedValues) const {
9387   if (VT == MVT::v2i64)
9388     return false;
9389
9390   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9391 }
9392
9393 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9394   if (DisableILPPref || Subtarget.enableMachineScheduler())
9395     return TargetLowering::getSchedulingPreference(N);
9396
9397   return Sched::ILP;
9398 }
9399
9400 // Create a fast isel object.
9401 FastISel *
9402 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9403                                   const TargetLibraryInfo *LibInfo) const {
9404   return PPC::createFastISel(FuncInfo, LibInfo);
9405 }