[PowerPC] Fix and improve vector comparisons
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAG.h"
29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetOptions.h"
40 using namespace llvm;
41
42 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
43 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
44
45 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
46 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
47
48 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
49 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
50
51 // FIXME: Remove this once the bug has been fixed!
52 extern cl::opt<bool> ANDIGlueBug;
53
54 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
55   // If it isn't a Mach-O file then it's going to be a linux ELF
56   // object file.
57   if (TT.isOSDarwin())
58     return new TargetLoweringObjectFileMachO();
59
60   return new PPC64LinuxTargetObjectFile();
61 }
62
63 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
64     : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))),
65       Subtarget(*TM.getSubtargetImpl()) {
66   setPow2DivIsCheap();
67
68   // Use _setjmp/_longjmp instead of setjmp/longjmp.
69   setUseUnderscoreSetJmp(true);
70   setUseUnderscoreLongJmp(true);
71
72   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
73   // arguments are at least 4/8 bytes aligned.
74   bool isPPC64 = Subtarget.isPPC64();
75   setMinStackArgumentAlignment(isPPC64 ? 8:4);
76
77   // Set up the register classes.
78   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
79   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
80   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
81
82   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
83   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
84   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
85
86   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
87
88   // PowerPC has pre-inc load and store's.
89   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
90   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
91   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
92   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
93   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
94   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
95   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
96   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
97   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
98   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
99
100   if (Subtarget.useCRBits()) {
101     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
102
103     if (isPPC64 || Subtarget.hasFPCVT()) {
104       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
105       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
106                          isPPC64 ? MVT::i64 : MVT::i32);
107       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
108       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
109                          isPPC64 ? MVT::i64 : MVT::i32);
110     } else {
111       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
112       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
113     }
114
115     // PowerPC does not support direct load / store of condition registers
116     setOperationAction(ISD::LOAD, MVT::i1, Custom);
117     setOperationAction(ISD::STORE, MVT::i1, Custom);
118
119     // FIXME: Remove this once the ANDI glue bug is fixed:
120     if (ANDIGlueBug)
121       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
122
123     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
125     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
126     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
127     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
128     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
129
130     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
131   }
132
133   // This is used in the ppcf128->int sequence.  Note it has different semantics
134   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
135   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
136
137   // We do not currently implement these libm ops for PowerPC.
138   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
139   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
140   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
141   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
142   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
143   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
144
145   // PowerPC has no SREM/UREM instructions
146   setOperationAction(ISD::SREM, MVT::i32, Expand);
147   setOperationAction(ISD::UREM, MVT::i32, Expand);
148   setOperationAction(ISD::SREM, MVT::i64, Expand);
149   setOperationAction(ISD::UREM, MVT::i64, Expand);
150
151   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
152   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
153   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
154   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
155   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
156   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
157   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
158   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
159   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
160
161   // We don't support sin/cos/sqrt/fmod/pow
162   setOperationAction(ISD::FSIN , MVT::f64, Expand);
163   setOperationAction(ISD::FCOS , MVT::f64, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
165   setOperationAction(ISD::FREM , MVT::f64, Expand);
166   setOperationAction(ISD::FPOW , MVT::f64, Expand);
167   setOperationAction(ISD::FMA  , MVT::f64, Legal);
168   setOperationAction(ISD::FSIN , MVT::f32, Expand);
169   setOperationAction(ISD::FCOS , MVT::f32, Expand);
170   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
171   setOperationAction(ISD::FREM , MVT::f32, Expand);
172   setOperationAction(ISD::FPOW , MVT::f32, Expand);
173   setOperationAction(ISD::FMA  , MVT::f32, Legal);
174
175   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
176
177   // If we're enabling GP optimizations, use hardware square root
178   if (!Subtarget.hasFSQRT() &&
179       !(TM.Options.UnsafeFPMath &&
180         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
181     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
182
183   if (!Subtarget.hasFSQRT() &&
184       !(TM.Options.UnsafeFPMath &&
185         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
186     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
187
188   if (Subtarget.hasFCPSGN()) {
189     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
190     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
191   } else {
192     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
193     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
194   }
195
196   if (Subtarget.hasFPRND()) {
197     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
198     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
199     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
200     setOperationAction(ISD::FROUND, MVT::f64, Legal);
201
202     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
203     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
204     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
205     setOperationAction(ISD::FROUND, MVT::f32, Legal);
206   }
207
208   // PowerPC does not have BSWAP, CTPOP or CTTZ
209   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
210   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
211   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
212   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
213   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
214   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
215   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
217
218   if (Subtarget.hasPOPCNTD()) {
219     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
220     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
221   } else {
222     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
223     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
224   }
225
226   // PowerPC does not have ROTR
227   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
228   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
229
230   if (!Subtarget.useCRBits()) {
231     // PowerPC does not have Select
232     setOperationAction(ISD::SELECT, MVT::i32, Expand);
233     setOperationAction(ISD::SELECT, MVT::i64, Expand);
234     setOperationAction(ISD::SELECT, MVT::f32, Expand);
235     setOperationAction(ISD::SELECT, MVT::f64, Expand);
236   }
237
238   // PowerPC wants to turn select_cc of FP into fsel when possible.
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241
242   // PowerPC wants to optimize integer setcc a bit
243   if (!Subtarget.useCRBits())
244     setOperationAction(ISD::SETCC, MVT::i32, Custom);
245
246   // PowerPC does not have BRCOND which requires SetCC
247   if (!Subtarget.useCRBits())
248     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
249
250   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
251
252   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
253   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254
255   // PowerPC does not have [U|S]INT_TO_FP
256   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
257   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
258
259   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
260   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
261   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
262   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
263
264   // We cannot sextinreg(i1).  Expand to shifts.
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
266
267   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
268   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
269   // support continuation, user-level threading, and etc.. As a result, no
270   // other SjLj exception interfaces are implemented and please don't build
271   // your own exception handling based on them.
272   // LLVM/Clang supports zero-cost DWARF exception handling.
273   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
274   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
275
276   // We want to legalize GlobalAddress and ConstantPool nodes into the
277   // appropriate instructions to materialize the address.
278   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
279   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
280   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
281   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
282   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
283   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
285   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
286   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
287   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
288
289   // TRAP is legal.
290   setOperationAction(ISD::TRAP, MVT::Other, Legal);
291
292   // TRAMPOLINE is custom lowered.
293   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
294   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
295
296   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
297   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
298
299   if (Subtarget.isSVR4ABI()) {
300     if (isPPC64) {
301       // VAARG always uses double-word chunks, so promote anything smaller.
302       setOperationAction(ISD::VAARG, MVT::i1, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::i8, Promote);
305       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
306       setOperationAction(ISD::VAARG, MVT::i16, Promote);
307       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
308       setOperationAction(ISD::VAARG, MVT::i32, Promote);
309       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
310       setOperationAction(ISD::VAARG, MVT::Other, Expand);
311     } else {
312       // VAARG is custom lowered with the 32-bit SVR4 ABI.
313       setOperationAction(ISD::VAARG, MVT::Other, Custom);
314       setOperationAction(ISD::VAARG, MVT::i64, Custom);
315     }
316   } else
317     setOperationAction(ISD::VAARG, MVT::Other, Expand);
318
319   if (Subtarget.isSVR4ABI() && !isPPC64)
320     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
321     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
322   else
323     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
324
325   // Use the default implementation.
326   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
327   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
328   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
329   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
330   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
331
332   // We want to custom lower some of our intrinsics.
333   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
334
335   // To handle counter-based loop conditions.
336   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
337
338   // Comparisons that require checking two conditions.
339   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
345   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
346   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
347   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
348   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
349   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
350   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
351
352   if (Subtarget.has64BitSupport()) {
353     // They also have instructions for converting between i64 and fp.
354     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
355     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
356     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
357     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358     // This is just the low 32 bits of a (signed) fp->i64 conversion.
359     // We cannot do this with Promote because i64 is not a legal type.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361
362     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
363       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
364   } else {
365     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
366     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
367   }
368
369   // With the instructions enabled under FPCVT, we can do everything.
370   if (Subtarget.hasFPCVT()) {
371     if (Subtarget.has64BitSupport()) {
372       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
373       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
374       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
375       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
376     }
377
378     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
379     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
380     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
381     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
382   }
383
384   if (Subtarget.use64BitRegs()) {
385     // 64-bit PowerPC implementations can support i64 types directly
386     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
387     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
388     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
389     // 64-bit PowerPC wants to expand i128 shifts itself.
390     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
391     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
392     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
393   } else {
394     // 32-bit PowerPC wants to expand i64 shifts itself.
395     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
396     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
397     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
398   }
399
400   if (Subtarget.hasAltivec()) {
401     // First set operation action for all vector types to expand. Then we
402     // will selectively turn on ones that can be effectively codegen'd.
403     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
404          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
405       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
406
407       // add/sub are legal for all supported vector VT's.
408       setOperationAction(ISD::ADD , VT, Legal);
409       setOperationAction(ISD::SUB , VT, Legal);
410
411       // We promote all shuffles to v16i8.
412       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
413       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
414
415       // We promote all non-typed operations to v4i32.
416       setOperationAction(ISD::AND   , VT, Promote);
417       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
418       setOperationAction(ISD::OR    , VT, Promote);
419       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
420       setOperationAction(ISD::XOR   , VT, Promote);
421       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
422       setOperationAction(ISD::LOAD  , VT, Promote);
423       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
424       setOperationAction(ISD::SELECT, VT, Promote);
425       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
426       setOperationAction(ISD::STORE, VT, Promote);
427       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
428
429       // No other operations are legal.
430       setOperationAction(ISD::MUL , VT, Expand);
431       setOperationAction(ISD::SDIV, VT, Expand);
432       setOperationAction(ISD::SREM, VT, Expand);
433       setOperationAction(ISD::UDIV, VT, Expand);
434       setOperationAction(ISD::UREM, VT, Expand);
435       setOperationAction(ISD::FDIV, VT, Expand);
436       setOperationAction(ISD::FREM, VT, Expand);
437       setOperationAction(ISD::FNEG, VT, Expand);
438       setOperationAction(ISD::FSQRT, VT, Expand);
439       setOperationAction(ISD::FLOG, VT, Expand);
440       setOperationAction(ISD::FLOG10, VT, Expand);
441       setOperationAction(ISD::FLOG2, VT, Expand);
442       setOperationAction(ISD::FEXP, VT, Expand);
443       setOperationAction(ISD::FEXP2, VT, Expand);
444       setOperationAction(ISD::FSIN, VT, Expand);
445       setOperationAction(ISD::FCOS, VT, Expand);
446       setOperationAction(ISD::FABS, VT, Expand);
447       setOperationAction(ISD::FPOWI, VT, Expand);
448       setOperationAction(ISD::FFLOOR, VT, Expand);
449       setOperationAction(ISD::FCEIL,  VT, Expand);
450       setOperationAction(ISD::FTRUNC, VT, Expand);
451       setOperationAction(ISD::FRINT,  VT, Expand);
452       setOperationAction(ISD::FNEARBYINT, VT, Expand);
453       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
454       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
455       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
456       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
457       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
458       setOperationAction(ISD::UDIVREM, VT, Expand);
459       setOperationAction(ISD::SDIVREM, VT, Expand);
460       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
461       setOperationAction(ISD::FPOW, VT, Expand);
462       setOperationAction(ISD::BSWAP, VT, Expand);
463       setOperationAction(ISD::CTPOP, VT, Expand);
464       setOperationAction(ISD::CTLZ, VT, Expand);
465       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
466       setOperationAction(ISD::CTTZ, VT, Expand);
467       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
468       setOperationAction(ISD::VSELECT, VT, Expand);
469       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
470
471       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
472            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
473         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
474         setTruncStoreAction(VT, InnerVT, Expand);
475       }
476       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
477       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
478       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
479     }
480
481     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
482     // with merges, splats, etc.
483     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
484
485     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
486     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
487     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
488     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
489     setOperationAction(ISD::SELECT, MVT::v4i32,
490                        Subtarget.useCRBits() ? Legal : Expand);
491     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
492     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
493     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
494     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
495     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
496     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
497     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
498     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
499     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
500
501     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
502     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
503     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
504     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
505
506     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
507     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
508
509     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
510       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
511       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
512     }
513
514     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
515     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
516     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
517
518     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
519     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
520
521     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
522     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
523     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
524     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
525
526     // Altivec does not contain unordered floating-point compare instructions
527     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
528     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
529     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
530     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
531
532     if (Subtarget.hasVSX()) {
533       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
534       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
535
536       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
537       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
538       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
539       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
540       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
541
542       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
543
544       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
545       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
546
547       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
548       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
549
550       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
551       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
552       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
553       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
554       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
555
556       // Share the Altivec comparison restrictions.
557       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
558       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
559       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
560       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
561
562       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
563       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
564
565       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
566
567       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
568
569       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
570       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
571
572       // VSX v2i64 only supports non-arithmetic operations.
573       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
574       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
575
576       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
577       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
578       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
579
580       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
581
582       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
583       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
584       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
585       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
586
587       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
588
589       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
590       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
591       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
592       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
593
594       // Vector operation legalization checks the result type of
595       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
596       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
597       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
598       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
599       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
600
601       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
602     }
603   }
604
605   if (Subtarget.has64BitSupport()) {
606     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
607     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
608   }
609
610   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i32, Expand);
611   setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
612   setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
613   setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
614
615   setBooleanContents(ZeroOrOneBooleanContent);
616   // Altivec instructions set fields to all zeros or all ones.
617   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
618
619   if (!isPPC64) {
620     // These libcalls are not available in 32-bit.
621     setLibcallName(RTLIB::SHL_I128, nullptr);
622     setLibcallName(RTLIB::SRL_I128, nullptr);
623     setLibcallName(RTLIB::SRA_I128, nullptr);
624   }
625
626   if (isPPC64) {
627     setStackPointerRegisterToSaveRestore(PPC::X1);
628     setExceptionPointerRegister(PPC::X3);
629     setExceptionSelectorRegister(PPC::X4);
630   } else {
631     setStackPointerRegisterToSaveRestore(PPC::R1);
632     setExceptionPointerRegister(PPC::R3);
633     setExceptionSelectorRegister(PPC::R4);
634   }
635
636   // We have target-specific dag combine patterns for the following nodes:
637   setTargetDAGCombine(ISD::SINT_TO_FP);
638   setTargetDAGCombine(ISD::LOAD);
639   setTargetDAGCombine(ISD::STORE);
640   setTargetDAGCombine(ISD::BR_CC);
641   if (Subtarget.useCRBits())
642     setTargetDAGCombine(ISD::BRCOND);
643   setTargetDAGCombine(ISD::BSWAP);
644   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
645
646   setTargetDAGCombine(ISD::SIGN_EXTEND);
647   setTargetDAGCombine(ISD::ZERO_EXTEND);
648   setTargetDAGCombine(ISD::ANY_EXTEND);
649
650   if (Subtarget.useCRBits()) {
651     setTargetDAGCombine(ISD::TRUNCATE);
652     setTargetDAGCombine(ISD::SETCC);
653     setTargetDAGCombine(ISD::SELECT_CC);
654   }
655
656   // Use reciprocal estimates.
657   if (TM.Options.UnsafeFPMath) {
658     setTargetDAGCombine(ISD::FDIV);
659     setTargetDAGCombine(ISD::FSQRT);
660   }
661
662   // Darwin long double math library functions have $LDBL128 appended.
663   if (Subtarget.isDarwin()) {
664     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
665     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
666     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
667     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
668     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
669     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
670     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
671     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
672     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
673     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
674   }
675
676   // With 32 condition bits, we don't need to sink (and duplicate) compares
677   // aggressively in CodeGenPrep.
678   if (Subtarget.useCRBits())
679     setHasMultipleConditionRegisters();
680
681   setMinFunctionAlignment(2);
682   if (Subtarget.isDarwin())
683     setPrefFunctionAlignment(4);
684
685   if (isPPC64 && Subtarget.isJITCodeModel())
686     // Temporary workaround for the inability of PPC64 JIT to handle jump
687     // tables.
688     setSupportJumpTables(false);
689
690   setInsertFencesForAtomic(true);
691
692   if (Subtarget.enableMachineScheduler())
693     setSchedulingPreference(Sched::Source);
694   else
695     setSchedulingPreference(Sched::Hybrid);
696
697   computeRegisterProperties();
698
699   // The Freescale cores does better with aggressive inlining of memcpy and
700   // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
701   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
702       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
703     MaxStoresPerMemset = 32;
704     MaxStoresPerMemsetOptSize = 16;
705     MaxStoresPerMemcpy = 32;
706     MaxStoresPerMemcpyOptSize = 8;
707     MaxStoresPerMemmove = 32;
708     MaxStoresPerMemmoveOptSize = 8;
709
710     setPrefFunctionAlignment(4);
711   }
712 }
713
714 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
715 /// the desired ByVal argument alignment.
716 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
717                              unsigned MaxMaxAlign) {
718   if (MaxAlign == MaxMaxAlign)
719     return;
720   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
721     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
722       MaxAlign = 32;
723     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
724       MaxAlign = 16;
725   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
726     unsigned EltAlign = 0;
727     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
728     if (EltAlign > MaxAlign)
729       MaxAlign = EltAlign;
730   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
731     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
732       unsigned EltAlign = 0;
733       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
734       if (EltAlign > MaxAlign)
735         MaxAlign = EltAlign;
736       if (MaxAlign == MaxMaxAlign)
737         break;
738     }
739   }
740 }
741
742 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
743 /// function arguments in the caller parameter area.
744 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
745   // Darwin passes everything on 4 byte boundary.
746   if (Subtarget.isDarwin())
747     return 4;
748
749   // 16byte and wider vectors are passed on 16byte boundary.
750   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
751   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
752   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
753     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
754   return Align;
755 }
756
757 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
758   switch (Opcode) {
759   default: return nullptr;
760   case PPCISD::FSEL:            return "PPCISD::FSEL";
761   case PPCISD::FCFID:           return "PPCISD::FCFID";
762   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
763   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
764   case PPCISD::FRE:             return "PPCISD::FRE";
765   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
766   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
767   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
768   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
769   case PPCISD::VPERM:           return "PPCISD::VPERM";
770   case PPCISD::Hi:              return "PPCISD::Hi";
771   case PPCISD::Lo:              return "PPCISD::Lo";
772   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
773   case PPCISD::LOAD:            return "PPCISD::LOAD";
774   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
775   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
776   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
777   case PPCISD::SRL:             return "PPCISD::SRL";
778   case PPCISD::SRA:             return "PPCISD::SRA";
779   case PPCISD::SHL:             return "PPCISD::SHL";
780   case PPCISD::CALL:            return "PPCISD::CALL";
781   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
782   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
783   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
784   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
785   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
786   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
787   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
788   case PPCISD::VCMP:            return "PPCISD::VCMP";
789   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
790   case PPCISD::LBRX:            return "PPCISD::LBRX";
791   case PPCISD::STBRX:           return "PPCISD::STBRX";
792   case PPCISD::LARX:            return "PPCISD::LARX";
793   case PPCISD::STCX:            return "PPCISD::STCX";
794   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
795   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
796   case PPCISD::BDZ:             return "PPCISD::BDZ";
797   case PPCISD::MFFS:            return "PPCISD::MFFS";
798   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
799   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
800   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
801   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
802   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
803   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
804   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
805   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
806   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
807   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
808   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
809   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
810   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
811   case PPCISD::GET_TLS_ADDR:    return "PPCISD::GET_TLS_ADDR";
812   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
813   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
814   case PPCISD::GET_TLSLD_ADDR:  return "PPCISD::GET_TLSLD_ADDR";
815   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
816   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
817   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
818   case PPCISD::SC:              return "PPCISD::SC";
819   }
820 }
821
822 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
823   if (!VT.isVector())
824     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
825   return VT.changeVectorElementTypeToInteger();
826 }
827
828 //===----------------------------------------------------------------------===//
829 // Node matching predicates, for use by the tblgen matching code.
830 //===----------------------------------------------------------------------===//
831
832 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
833 static bool isFloatingPointZero(SDValue Op) {
834   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
835     return CFP->getValueAPF().isZero();
836   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
837     // Maybe this has already been legalized into the constant pool?
838     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
839       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
840         return CFP->getValueAPF().isZero();
841   }
842   return false;
843 }
844
845 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
846 /// true if Op is undef or if it matches the specified value.
847 static bool isConstantOrUndef(int Op, int Val) {
848   return Op < 0 || Op == Val;
849 }
850
851 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
852 /// VPKUHUM instruction.
853 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
854                                SelectionDAG &DAG) {
855   unsigned j = DAG.getTarget().getDataLayout()->isLittleEndian() ? 0 : 1;
856   if (!isUnary) {
857     for (unsigned i = 0; i != 16; ++i)
858       if (!isConstantOrUndef(N->getMaskElt(i),  i*2+j))
859         return false;
860   } else {
861     for (unsigned i = 0; i != 8; ++i)
862       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
863           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
864         return false;
865   }
866   return true;
867 }
868
869 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
870 /// VPKUWUM instruction.
871 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary,
872                                SelectionDAG &DAG) {
873   unsigned j, k;
874   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
875     j = 0;
876     k = 1;
877   } else {
878     j = 2;
879     k = 3;
880   }
881   if (!isUnary) {
882     for (unsigned i = 0; i != 16; i += 2)
883       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
884           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k))
885         return false;
886   } else {
887     for (unsigned i = 0; i != 8; i += 2)
888       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j) ||
889           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+k) ||
890           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j) ||
891           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+k))
892         return false;
893   }
894   return true;
895 }
896
897 /// isVMerge - Common function, used to match vmrg* shuffles.
898 ///
899 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
900                      unsigned LHSStart, unsigned RHSStart) {
901   if (N->getValueType(0) != MVT::v16i8)
902     return false;
903   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
904          "Unsupported merge size!");
905
906   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
907     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
908       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
909                              LHSStart+j+i*UnitSize) ||
910           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
911                              RHSStart+j+i*UnitSize))
912         return false;
913     }
914   return true;
915 }
916
917 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
918 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
919 /// The ShuffleKind distinguishes between big-endian merges with two 
920 /// different inputs (0), either-endian merges with two identical inputs (1),
921 /// and little-endian merges with two different inputs (2).  For the latter,
922 /// the input operands are swapped (see PPCInstrAltivec.td).
923 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
924                              unsigned ShuffleKind, SelectionDAG &DAG) {
925   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
926     if (ShuffleKind == 1) // unary
927       return isVMerge(N, UnitSize, 0, 0);
928     else if (ShuffleKind == 2) // swapped
929       return isVMerge(N, UnitSize, 0, 16);
930     else
931       return false;
932   } else {
933     if (ShuffleKind == 1) // unary
934       return isVMerge(N, UnitSize, 8, 8);
935     else if (ShuffleKind == 0) // normal
936       return isVMerge(N, UnitSize, 8, 24);
937     else
938       return false;
939   }
940 }
941
942 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
943 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
944 /// The ShuffleKind distinguishes between big-endian merges with two 
945 /// different inputs (0), either-endian merges with two identical inputs (1),
946 /// and little-endian merges with two different inputs (2).  For the latter,
947 /// the input operands are swapped (see PPCInstrAltivec.td).
948 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
949                              unsigned ShuffleKind, SelectionDAG &DAG) {
950   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
951     if (ShuffleKind == 1) // unary
952       return isVMerge(N, UnitSize, 8, 8);
953     else if (ShuffleKind == 2) // swapped
954       return isVMerge(N, UnitSize, 8, 24);
955     else
956       return false;
957   } else {
958     if (ShuffleKind == 1) // unary
959       return isVMerge(N, UnitSize, 0, 0);
960     else if (ShuffleKind == 0) // normal
961       return isVMerge(N, UnitSize, 0, 16);
962     else
963       return false;
964   }
965 }
966
967
968 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
969 /// amount, otherwise return -1.
970 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary, SelectionDAG &DAG) {
971   if (N->getValueType(0) != MVT::v16i8)
972     return -1;
973
974   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
975
976   // Find the first non-undef value in the shuffle mask.
977   unsigned i;
978   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
979     /*search*/;
980
981   if (i == 16) return -1;  // all undef.
982
983   // Otherwise, check to see if the rest of the elements are consecutively
984   // numbered from this value.
985   unsigned ShiftAmt = SVOp->getMaskElt(i);
986   if (ShiftAmt < i) return -1;
987
988   if (DAG.getTarget().getDataLayout()->isLittleEndian()) {
989
990     ShiftAmt += i;
991
992     if (!isUnary) {
993       // Check the rest of the elements to see if they are consecutive.
994       for (++i; i != 16; ++i)
995         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt - i))
996           return -1;
997     } else {
998       // Check the rest of the elements to see if they are consecutive.
999       for (++i; i != 16; ++i)
1000         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt - i) & 15))
1001           return -1;
1002     }
1003
1004   } else {  // Big Endian
1005
1006     ShiftAmt -= i;
1007
1008     if (!isUnary) {
1009       // Check the rest of the elements to see if they are consecutive.
1010       for (++i; i != 16; ++i)
1011         if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1012           return -1;
1013     } else {
1014       // Check the rest of the elements to see if they are consecutive.
1015       for (++i; i != 16; ++i)
1016         if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1017           return -1;
1018     }
1019   }
1020   return ShiftAmt;
1021 }
1022
1023 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1024 /// specifies a splat of a single element that is suitable for input to
1025 /// VSPLTB/VSPLTH/VSPLTW.
1026 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1027   assert(N->getValueType(0) == MVT::v16i8 &&
1028          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1029
1030   // This is a splat operation if each element of the permute is the same, and
1031   // if the value doesn't reference the second vector.
1032   unsigned ElementBase = N->getMaskElt(0);
1033
1034   // FIXME: Handle UNDEF elements too!
1035   if (ElementBase >= 16)
1036     return false;
1037
1038   // Check that the indices are consecutive, in the case of a multi-byte element
1039   // splatted with a v16i8 mask.
1040   for (unsigned i = 1; i != EltSize; ++i)
1041     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1042       return false;
1043
1044   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1045     if (N->getMaskElt(i) < 0) continue;
1046     for (unsigned j = 0; j != EltSize; ++j)
1047       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1048         return false;
1049   }
1050   return true;
1051 }
1052
1053 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1054 /// are -0.0.
1055 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1056   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1057
1058   APInt APVal, APUndef;
1059   unsigned BitSize;
1060   bool HasAnyUndefs;
1061
1062   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1063     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1064       return CFP->getValueAPF().isNegZero();
1065
1066   return false;
1067 }
1068
1069 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1070 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1071 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1072                                 SelectionDAG &DAG) {
1073   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1074   assert(isSplatShuffleMask(SVOp, EltSize));
1075   if (DAG.getTarget().getDataLayout()->isLittleEndian())
1076     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1077   else
1078     return SVOp->getMaskElt(0) / EltSize;
1079 }
1080
1081 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1082 /// by using a vspltis[bhw] instruction of the specified element size, return
1083 /// the constant being splatted.  The ByteSize field indicates the number of
1084 /// bytes of each element [124] -> [bhw].
1085 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1086   SDValue OpVal(nullptr, 0);
1087
1088   // If ByteSize of the splat is bigger than the element size of the
1089   // build_vector, then we have a case where we are checking for a splat where
1090   // multiple elements of the buildvector are folded together into a single
1091   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1092   unsigned EltSize = 16/N->getNumOperands();
1093   if (EltSize < ByteSize) {
1094     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1095     SDValue UniquedVals[4];
1096     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1097
1098     // See if all of the elements in the buildvector agree across.
1099     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1100       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1101       // If the element isn't a constant, bail fully out.
1102       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1103
1104
1105       if (!UniquedVals[i&(Multiple-1)].getNode())
1106         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1107       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1108         return SDValue();  // no match.
1109     }
1110
1111     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1112     // either constant or undef values that are identical for each chunk.  See
1113     // if these chunks can form into a larger vspltis*.
1114
1115     // Check to see if all of the leading entries are either 0 or -1.  If
1116     // neither, then this won't fit into the immediate field.
1117     bool LeadingZero = true;
1118     bool LeadingOnes = true;
1119     for (unsigned i = 0; i != Multiple-1; ++i) {
1120       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1121
1122       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1123       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1124     }
1125     // Finally, check the least significant entry.
1126     if (LeadingZero) {
1127       if (!UniquedVals[Multiple-1].getNode())
1128         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1129       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1130       if (Val < 16)
1131         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1132     }
1133     if (LeadingOnes) {
1134       if (!UniquedVals[Multiple-1].getNode())
1135         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1136       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1137       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1138         return DAG.getTargetConstant(Val, MVT::i32);
1139     }
1140
1141     return SDValue();
1142   }
1143
1144   // Check to see if this buildvec has a single non-undef value in its elements.
1145   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1146     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1147     if (!OpVal.getNode())
1148       OpVal = N->getOperand(i);
1149     else if (OpVal != N->getOperand(i))
1150       return SDValue();
1151   }
1152
1153   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1154
1155   unsigned ValSizeInBytes = EltSize;
1156   uint64_t Value = 0;
1157   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1158     Value = CN->getZExtValue();
1159   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1160     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1161     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1162   }
1163
1164   // If the splat value is larger than the element value, then we can never do
1165   // this splat.  The only case that we could fit the replicated bits into our
1166   // immediate field for would be zero, and we prefer to use vxor for it.
1167   if (ValSizeInBytes < ByteSize) return SDValue();
1168
1169   // If the element value is larger than the splat value, cut it in half and
1170   // check to see if the two halves are equal.  Continue doing this until we
1171   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1172   while (ValSizeInBytes > ByteSize) {
1173     ValSizeInBytes >>= 1;
1174
1175     // If the top half equals the bottom half, we're still ok.
1176     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1177          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1178       return SDValue();
1179   }
1180
1181   // Properly sign extend the value.
1182   int MaskVal = SignExtend32(Value, ByteSize * 8);
1183
1184   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1185   if (MaskVal == 0) return SDValue();
1186
1187   // Finally, if this value fits in a 5 bit sext field, return it
1188   if (SignExtend32<5>(MaskVal) == MaskVal)
1189     return DAG.getTargetConstant(MaskVal, MVT::i32);
1190   return SDValue();
1191 }
1192
1193 //===----------------------------------------------------------------------===//
1194 //  Addressing Mode Selection
1195 //===----------------------------------------------------------------------===//
1196
1197 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1198 /// or 64-bit immediate, and if the value can be accurately represented as a
1199 /// sign extension from a 16-bit value.  If so, this returns true and the
1200 /// immediate.
1201 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1202   if (!isa<ConstantSDNode>(N))
1203     return false;
1204
1205   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1206   if (N->getValueType(0) == MVT::i32)
1207     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1208   else
1209     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1210 }
1211 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1212   return isIntS16Immediate(Op.getNode(), Imm);
1213 }
1214
1215
1216 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1217 /// can be represented as an indexed [r+r] operation.  Returns false if it
1218 /// can be more efficiently represented with [r+imm].
1219 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1220                                             SDValue &Index,
1221                                             SelectionDAG &DAG) const {
1222   short imm = 0;
1223   if (N.getOpcode() == ISD::ADD) {
1224     if (isIntS16Immediate(N.getOperand(1), imm))
1225       return false;    // r+i
1226     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1227       return false;    // r+i
1228
1229     Base = N.getOperand(0);
1230     Index = N.getOperand(1);
1231     return true;
1232   } else if (N.getOpcode() == ISD::OR) {
1233     if (isIntS16Immediate(N.getOperand(1), imm))
1234       return false;    // r+i can fold it if we can.
1235
1236     // If this is an or of disjoint bitfields, we can codegen this as an add
1237     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1238     // disjoint.
1239     APInt LHSKnownZero, LHSKnownOne;
1240     APInt RHSKnownZero, RHSKnownOne;
1241     DAG.computeKnownBits(N.getOperand(0),
1242                          LHSKnownZero, LHSKnownOne);
1243
1244     if (LHSKnownZero.getBoolValue()) {
1245       DAG.computeKnownBits(N.getOperand(1),
1246                            RHSKnownZero, RHSKnownOne);
1247       // If all of the bits are known zero on the LHS or RHS, the add won't
1248       // carry.
1249       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1250         Base = N.getOperand(0);
1251         Index = N.getOperand(1);
1252         return true;
1253       }
1254     }
1255   }
1256
1257   return false;
1258 }
1259
1260 // If we happen to be doing an i64 load or store into a stack slot that has
1261 // less than a 4-byte alignment, then the frame-index elimination may need to
1262 // use an indexed load or store instruction (because the offset may not be a
1263 // multiple of 4). The extra register needed to hold the offset comes from the
1264 // register scavenger, and it is possible that the scavenger will need to use
1265 // an emergency spill slot. As a result, we need to make sure that a spill slot
1266 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1267 // stack slot.
1268 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1269   // FIXME: This does not handle the LWA case.
1270   if (VT != MVT::i64)
1271     return;
1272
1273   // NOTE: We'll exclude negative FIs here, which come from argument
1274   // lowering, because there are no known test cases triggering this problem
1275   // using packed structures (or similar). We can remove this exclusion if
1276   // we find such a test case. The reason why this is so test-case driven is
1277   // because this entire 'fixup' is only to prevent crashes (from the
1278   // register scavenger) on not-really-valid inputs. For example, if we have:
1279   //   %a = alloca i1
1280   //   %b = bitcast i1* %a to i64*
1281   //   store i64* a, i64 b
1282   // then the store should really be marked as 'align 1', but is not. If it
1283   // were marked as 'align 1' then the indexed form would have been
1284   // instruction-selected initially, and the problem this 'fixup' is preventing
1285   // won't happen regardless.
1286   if (FrameIdx < 0)
1287     return;
1288
1289   MachineFunction &MF = DAG.getMachineFunction();
1290   MachineFrameInfo *MFI = MF.getFrameInfo();
1291
1292   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1293   if (Align >= 4)
1294     return;
1295
1296   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1297   FuncInfo->setHasNonRISpills();
1298 }
1299
1300 /// Returns true if the address N can be represented by a base register plus
1301 /// a signed 16-bit displacement [r+imm], and if it is not better
1302 /// represented as reg+reg.  If Aligned is true, only accept displacements
1303 /// suitable for STD and friends, i.e. multiples of 4.
1304 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1305                                             SDValue &Base,
1306                                             SelectionDAG &DAG,
1307                                             bool Aligned) const {
1308   // FIXME dl should come from parent load or store, not from address
1309   SDLoc dl(N);
1310   // If this can be more profitably realized as r+r, fail.
1311   if (SelectAddressRegReg(N, Disp, Base, DAG))
1312     return false;
1313
1314   if (N.getOpcode() == ISD::ADD) {
1315     short imm = 0;
1316     if (isIntS16Immediate(N.getOperand(1), imm) &&
1317         (!Aligned || (imm & 3) == 0)) {
1318       Disp = DAG.getTargetConstant(imm, N.getValueType());
1319       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1320         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1321         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1322       } else {
1323         Base = N.getOperand(0);
1324       }
1325       return true; // [r+i]
1326     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1327       // Match LOAD (ADD (X, Lo(G))).
1328       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1329              && "Cannot handle constant offsets yet!");
1330       Disp = N.getOperand(1).getOperand(0);  // The global address.
1331       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1332              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1333              Disp.getOpcode() == ISD::TargetConstantPool ||
1334              Disp.getOpcode() == ISD::TargetJumpTable);
1335       Base = N.getOperand(0);
1336       return true;  // [&g+r]
1337     }
1338   } else if (N.getOpcode() == ISD::OR) {
1339     short imm = 0;
1340     if (isIntS16Immediate(N.getOperand(1), imm) &&
1341         (!Aligned || (imm & 3) == 0)) {
1342       // If this is an or of disjoint bitfields, we can codegen this as an add
1343       // (for better address arithmetic) if the LHS and RHS of the OR are
1344       // provably disjoint.
1345       APInt LHSKnownZero, LHSKnownOne;
1346       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1347
1348       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1349         // If all of the bits are known zero on the LHS or RHS, the add won't
1350         // carry.
1351         if (FrameIndexSDNode *FI =
1352               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1353           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1354           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1355         } else {
1356           Base = N.getOperand(0);
1357         }
1358         Disp = DAG.getTargetConstant(imm, N.getValueType());
1359         return true;
1360       }
1361     }
1362   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1363     // Loading from a constant address.
1364
1365     // If this address fits entirely in a 16-bit sext immediate field, codegen
1366     // this as "d, 0"
1367     short Imm;
1368     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1369       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1370       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1371                              CN->getValueType(0));
1372       return true;
1373     }
1374
1375     // Handle 32-bit sext immediates with LIS + addr mode.
1376     if ((CN->getValueType(0) == MVT::i32 ||
1377          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1378         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1379       int Addr = (int)CN->getZExtValue();
1380
1381       // Otherwise, break this down into an LIS + disp.
1382       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1383
1384       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1385       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1386       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1387       return true;
1388     }
1389   }
1390
1391   Disp = DAG.getTargetConstant(0, getPointerTy());
1392   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1393     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1394     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1395   } else
1396     Base = N;
1397   return true;      // [r+0]
1398 }
1399
1400 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1401 /// represented as an indexed [r+r] operation.
1402 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1403                                                 SDValue &Index,
1404                                                 SelectionDAG &DAG) const {
1405   // Check to see if we can easily represent this as an [r+r] address.  This
1406   // will fail if it thinks that the address is more profitably represented as
1407   // reg+imm, e.g. where imm = 0.
1408   if (SelectAddressRegReg(N, Base, Index, DAG))
1409     return true;
1410
1411   // If the operand is an addition, always emit this as [r+r], since this is
1412   // better (for code size, and execution, as the memop does the add for free)
1413   // than emitting an explicit add.
1414   if (N.getOpcode() == ISD::ADD) {
1415     Base = N.getOperand(0);
1416     Index = N.getOperand(1);
1417     return true;
1418   }
1419
1420   // Otherwise, do it the hard way, using R0 as the base register.
1421   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1422                          N.getValueType());
1423   Index = N;
1424   return true;
1425 }
1426
1427 /// getPreIndexedAddressParts - returns true by value, base pointer and
1428 /// offset pointer and addressing mode by reference if the node's address
1429 /// can be legally represented as pre-indexed load / store address.
1430 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1431                                                   SDValue &Offset,
1432                                                   ISD::MemIndexedMode &AM,
1433                                                   SelectionDAG &DAG) const {
1434   if (DisablePPCPreinc) return false;
1435
1436   bool isLoad = true;
1437   SDValue Ptr;
1438   EVT VT;
1439   unsigned Alignment;
1440   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1441     Ptr = LD->getBasePtr();
1442     VT = LD->getMemoryVT();
1443     Alignment = LD->getAlignment();
1444   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1445     Ptr = ST->getBasePtr();
1446     VT  = ST->getMemoryVT();
1447     Alignment = ST->getAlignment();
1448     isLoad = false;
1449   } else
1450     return false;
1451
1452   // PowerPC doesn't have preinc load/store instructions for vectors.
1453   if (VT.isVector())
1454     return false;
1455
1456   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1457
1458     // Common code will reject creating a pre-inc form if the base pointer
1459     // is a frame index, or if N is a store and the base pointer is either
1460     // the same as or a predecessor of the value being stored.  Check for
1461     // those situations here, and try with swapped Base/Offset instead.
1462     bool Swap = false;
1463
1464     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1465       Swap = true;
1466     else if (!isLoad) {
1467       SDValue Val = cast<StoreSDNode>(N)->getValue();
1468       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1469         Swap = true;
1470     }
1471
1472     if (Swap)
1473       std::swap(Base, Offset);
1474
1475     AM = ISD::PRE_INC;
1476     return true;
1477   }
1478
1479   // LDU/STU can only handle immediates that are a multiple of 4.
1480   if (VT != MVT::i64) {
1481     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1482       return false;
1483   } else {
1484     // LDU/STU need an address with at least 4-byte alignment.
1485     if (Alignment < 4)
1486       return false;
1487
1488     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1489       return false;
1490   }
1491
1492   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1493     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1494     // sext i32 to i64 when addr mode is r+i.
1495     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1496         LD->getExtensionType() == ISD::SEXTLOAD &&
1497         isa<ConstantSDNode>(Offset))
1498       return false;
1499   }
1500
1501   AM = ISD::PRE_INC;
1502   return true;
1503 }
1504
1505 //===----------------------------------------------------------------------===//
1506 //  LowerOperation implementation
1507 //===----------------------------------------------------------------------===//
1508
1509 /// GetLabelAccessInfo - Return true if we should reference labels using a
1510 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1511 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1512                                unsigned &LoOpFlags,
1513                                const GlobalValue *GV = nullptr) {
1514   HiOpFlags = PPCII::MO_HA;
1515   LoOpFlags = PPCII::MO_LO;
1516
1517   // Don't use the pic base if not in PIC relocation model.
1518   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1519
1520   if (isPIC) {
1521     HiOpFlags |= PPCII::MO_PIC_FLAG;
1522     LoOpFlags |= PPCII::MO_PIC_FLAG;
1523   }
1524
1525   // If this is a reference to a global value that requires a non-lazy-ptr, make
1526   // sure that instruction lowering adds it.
1527   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1528     HiOpFlags |= PPCII::MO_NLP_FLAG;
1529     LoOpFlags |= PPCII::MO_NLP_FLAG;
1530
1531     if (GV->hasHiddenVisibility()) {
1532       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1533       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1534     }
1535   }
1536
1537   return isPIC;
1538 }
1539
1540 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1541                              SelectionDAG &DAG) {
1542   EVT PtrVT = HiPart.getValueType();
1543   SDValue Zero = DAG.getConstant(0, PtrVT);
1544   SDLoc DL(HiPart);
1545
1546   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1547   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1548
1549   // With PIC, the first instruction is actually "GR+hi(&G)".
1550   if (isPIC)
1551     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1552                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1553
1554   // Generate non-pic code that has direct accesses to the constant pool.
1555   // The address of the global is just (hi(&g)+lo(&g)).
1556   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1557 }
1558
1559 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1560                                              SelectionDAG &DAG) const {
1561   EVT PtrVT = Op.getValueType();
1562   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1563   const Constant *C = CP->getConstVal();
1564
1565   // 64-bit SVR4 ABI code is always position-independent.
1566   // The actual address of the GlobalValue is stored in the TOC.
1567   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1568     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1569     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1570                        DAG.getRegister(PPC::X2, MVT::i64));
1571   }
1572
1573   unsigned MOHiFlag, MOLoFlag;
1574   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1575
1576   if (isPIC && Subtarget.isSVR4ABI()) {
1577     SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1578                                            PPCII::MO_PIC_FLAG);
1579     SDLoc DL(CP);
1580     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1581                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1582   }
1583
1584   SDValue CPIHi =
1585     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1586   SDValue CPILo =
1587     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1588   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1589 }
1590
1591 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1592   EVT PtrVT = Op.getValueType();
1593   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1594
1595   // 64-bit SVR4 ABI code is always position-independent.
1596   // The actual address of the GlobalValue is stored in the TOC.
1597   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1598     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1599     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1600                        DAG.getRegister(PPC::X2, MVT::i64));
1601   }
1602
1603   unsigned MOHiFlag, MOLoFlag;
1604   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1605
1606   if (isPIC && Subtarget.isSVR4ABI()) {
1607     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1608                                         PPCII::MO_PIC_FLAG);
1609     SDLoc DL(GA);
1610     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1611                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1612   }
1613
1614   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1615   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1616   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1617 }
1618
1619 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1620                                              SelectionDAG &DAG) const {
1621   EVT PtrVT = Op.getValueType();
1622
1623   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1624
1625   unsigned MOHiFlag, MOLoFlag;
1626   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1627   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1628   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1629   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1630 }
1631
1632 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1633                                               SelectionDAG &DAG) const {
1634
1635   // FIXME: TLS addresses currently use medium model code sequences,
1636   // which is the most useful form.  Eventually support for small and
1637   // large models could be added if users need it, at the cost of
1638   // additional complexity.
1639   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1640   SDLoc dl(GA);
1641   const GlobalValue *GV = GA->getGlobal();
1642   EVT PtrVT = getPointerTy();
1643   bool is64bit = Subtarget.isPPC64();
1644
1645   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1646
1647   if (Model == TLSModel::LocalExec) {
1648     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1649                                                PPCII::MO_TPREL_HA);
1650     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1651                                                PPCII::MO_TPREL_LO);
1652     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1653                                      is64bit ? MVT::i64 : MVT::i32);
1654     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1655     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1656   }
1657
1658   if (Model == TLSModel::InitialExec) {
1659     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1660     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1661                                                 PPCII::MO_TLS);
1662     SDValue GOTPtr;
1663     if (is64bit) {
1664       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1665       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1666                            PtrVT, GOTReg, TGA);
1667     } else
1668       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1669     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1670                                    PtrVT, TGA, GOTPtr);
1671     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1672   }
1673
1674   if (Model == TLSModel::GeneralDynamic) {
1675     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1676     SDValue GOTPtr;
1677     if (is64bit) {
1678       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1679       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1680                                    GOTReg, TGA);
1681     } else {
1682       GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1683     }
1684     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1685                                    GOTPtr, TGA);
1686
1687     // We need a chain node, and don't have one handy.  The underlying
1688     // call has no side effects, so using the function entry node
1689     // suffices.
1690     SDValue Chain = DAG.getEntryNode();
1691     Chain = DAG.getCopyToReg(Chain, dl,
1692                              is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1693     SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1694                                       is64bit ? MVT::i64 : MVT::i32);
1695     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1696                                   PtrVT, ParmReg, TGA);
1697     // The return value from GET_TLS_ADDR really is in X3 already, but
1698     // some hacks are needed here to tie everything together.  The extra
1699     // copies dissolve during subsequent transforms.
1700     Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1701     return DAG.getCopyFromReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, PtrVT);
1702   }
1703
1704   if (Model == TLSModel::LocalDynamic) {
1705     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1706     SDValue GOTPtr;
1707     if (is64bit) {
1708       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1709       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1710                            GOTReg, TGA);
1711     } else {
1712       GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1713     }
1714     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1715                                    GOTPtr, TGA);
1716
1717     // We need a chain node, and don't have one handy.  The underlying
1718     // call has no side effects, so using the function entry node
1719     // suffices.
1720     SDValue Chain = DAG.getEntryNode();
1721     Chain = DAG.getCopyToReg(Chain, dl,
1722                              is64bit ? PPC::X3 : PPC::R3, GOTEntry);
1723     SDValue ParmReg = DAG.getRegister(is64bit ? PPC::X3 : PPC::R3,
1724                                       is64bit ? MVT::i64 : MVT::i32);
1725     SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1726                                   PtrVT, ParmReg, TGA);
1727     // The return value from GET_TLSLD_ADDR really is in X3 already, but
1728     // some hacks are needed here to tie everything together.  The extra
1729     // copies dissolve during subsequent transforms.
1730     Chain = DAG.getCopyToReg(Chain, dl, is64bit ? PPC::X3 : PPC::R3, TLSAddr);
1731     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1732                                       Chain, ParmReg, TGA);
1733     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1734   }
1735
1736   llvm_unreachable("Unknown TLS model!");
1737 }
1738
1739 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1740                                               SelectionDAG &DAG) const {
1741   EVT PtrVT = Op.getValueType();
1742   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1743   SDLoc DL(GSDN);
1744   const GlobalValue *GV = GSDN->getGlobal();
1745
1746   // 64-bit SVR4 ABI code is always position-independent.
1747   // The actual address of the GlobalValue is stored in the TOC.
1748   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1749     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1750     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1751                        DAG.getRegister(PPC::X2, MVT::i64));
1752   }
1753
1754   unsigned MOHiFlag, MOLoFlag;
1755   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1756
1757   if (isPIC && Subtarget.isSVR4ABI()) {
1758     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1759                                             GSDN->getOffset(),
1760                                             PPCII::MO_PIC_FLAG);
1761     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1762                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1763   }
1764
1765   SDValue GAHi =
1766     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1767   SDValue GALo =
1768     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1769
1770   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1771
1772   // If the global reference is actually to a non-lazy-pointer, we have to do an
1773   // extra load to get the address of the global.
1774   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1775     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1776                       false, false, false, 0);
1777   return Ptr;
1778 }
1779
1780 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1781   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1782   SDLoc dl(Op);
1783
1784   if (Op.getValueType() == MVT::v2i64) {
1785     // When the operands themselves are v2i64 values, we need to do something
1786     // special because VSX has no underlying comparison operations for these.
1787     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1788       // Equality can be handled by casting to the legal type for Altivec
1789       // comparisons, everything else needs to be expanded.
1790       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1791         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1792                  DAG.getSetCC(dl, MVT::v4i32,
1793                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1794                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1795                    CC));
1796       }
1797
1798       return SDValue();
1799     }
1800
1801     // We handle most of these in the usual way.
1802     return Op;
1803   }
1804
1805   // If we're comparing for equality to zero, expose the fact that this is
1806   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1807   // fold the new nodes.
1808   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1809     if (C->isNullValue() && CC == ISD::SETEQ) {
1810       EVT VT = Op.getOperand(0).getValueType();
1811       SDValue Zext = Op.getOperand(0);
1812       if (VT.bitsLT(MVT::i32)) {
1813         VT = MVT::i32;
1814         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1815       }
1816       unsigned Log2b = Log2_32(VT.getSizeInBits());
1817       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1818       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1819                                 DAG.getConstant(Log2b, MVT::i32));
1820       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1821     }
1822     // Leave comparisons against 0 and -1 alone for now, since they're usually
1823     // optimized.  FIXME: revisit this when we can custom lower all setcc
1824     // optimizations.
1825     if (C->isAllOnesValue() || C->isNullValue())
1826       return SDValue();
1827   }
1828
1829   // If we have an integer seteq/setne, turn it into a compare against zero
1830   // by xor'ing the rhs with the lhs, which is faster than setting a
1831   // condition register, reading it back out, and masking the correct bit.  The
1832   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1833   // the result to other bit-twiddling opportunities.
1834   EVT LHSVT = Op.getOperand(0).getValueType();
1835   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1836     EVT VT = Op.getValueType();
1837     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1838                                 Op.getOperand(1));
1839     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1840   }
1841   return SDValue();
1842 }
1843
1844 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1845                                       const PPCSubtarget &Subtarget) const {
1846   SDNode *Node = Op.getNode();
1847   EVT VT = Node->getValueType(0);
1848   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1849   SDValue InChain = Node->getOperand(0);
1850   SDValue VAListPtr = Node->getOperand(1);
1851   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1852   SDLoc dl(Node);
1853
1854   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1855
1856   // gpr_index
1857   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1858                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1859                                     false, false, false, 0);
1860   InChain = GprIndex.getValue(1);
1861
1862   if (VT == MVT::i64) {
1863     // Check if GprIndex is even
1864     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1865                                  DAG.getConstant(1, MVT::i32));
1866     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1867                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1868     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1869                                           DAG.getConstant(1, MVT::i32));
1870     // Align GprIndex to be even if it isn't
1871     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1872                            GprIndex);
1873   }
1874
1875   // fpr index is 1 byte after gpr
1876   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1877                                DAG.getConstant(1, MVT::i32));
1878
1879   // fpr
1880   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1881                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1882                                     false, false, false, 0);
1883   InChain = FprIndex.getValue(1);
1884
1885   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1886                                        DAG.getConstant(8, MVT::i32));
1887
1888   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1889                                         DAG.getConstant(4, MVT::i32));
1890
1891   // areas
1892   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1893                                      MachinePointerInfo(), false, false,
1894                                      false, 0);
1895   InChain = OverflowArea.getValue(1);
1896
1897   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1898                                     MachinePointerInfo(), false, false,
1899                                     false, 0);
1900   InChain = RegSaveArea.getValue(1);
1901
1902   // select overflow_area if index > 8
1903   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1904                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1905
1906   // adjustment constant gpr_index * 4/8
1907   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1908                                     VT.isInteger() ? GprIndex : FprIndex,
1909                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1910                                                     MVT::i32));
1911
1912   // OurReg = RegSaveArea + RegConstant
1913   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1914                                RegConstant);
1915
1916   // Floating types are 32 bytes into RegSaveArea
1917   if (VT.isFloatingPoint())
1918     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1919                          DAG.getConstant(32, MVT::i32));
1920
1921   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1922   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1923                                    VT.isInteger() ? GprIndex : FprIndex,
1924                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1925                                                    MVT::i32));
1926
1927   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1928                               VT.isInteger() ? VAListPtr : FprPtr,
1929                               MachinePointerInfo(SV),
1930                               MVT::i8, false, false, 0);
1931
1932   // determine if we should load from reg_save_area or overflow_area
1933   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1934
1935   // increase overflow_area by 4/8 if gpr/fpr > 8
1936   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1937                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1938                                           MVT::i32));
1939
1940   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1941                              OverflowAreaPlusN);
1942
1943   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1944                               OverflowAreaPtr,
1945                               MachinePointerInfo(),
1946                               MVT::i32, false, false, 0);
1947
1948   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1949                      false, false, false, 0);
1950 }
1951
1952 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1953                                        const PPCSubtarget &Subtarget) const {
1954   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1955
1956   // We have to copy the entire va_list struct:
1957   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
1958   return DAG.getMemcpy(Op.getOperand(0), Op,
1959                        Op.getOperand(1), Op.getOperand(2),
1960                        DAG.getConstant(12, MVT::i32), 8, false, true,
1961                        MachinePointerInfo(), MachinePointerInfo());
1962 }
1963
1964 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1965                                                   SelectionDAG &DAG) const {
1966   return Op.getOperand(0);
1967 }
1968
1969 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1970                                                 SelectionDAG &DAG) const {
1971   SDValue Chain = Op.getOperand(0);
1972   SDValue Trmp = Op.getOperand(1); // trampoline
1973   SDValue FPtr = Op.getOperand(2); // nested function
1974   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1975   SDLoc dl(Op);
1976
1977   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1978   bool isPPC64 = (PtrVT == MVT::i64);
1979   Type *IntPtrTy =
1980     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1981                                                              *DAG.getContext());
1982
1983   TargetLowering::ArgListTy Args;
1984   TargetLowering::ArgListEntry Entry;
1985
1986   Entry.Ty = IntPtrTy;
1987   Entry.Node = Trmp; Args.push_back(Entry);
1988
1989   // TrampSize == (isPPC64 ? 48 : 40);
1990   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1991                                isPPC64 ? MVT::i64 : MVT::i32);
1992   Args.push_back(Entry);
1993
1994   Entry.Node = FPtr; Args.push_back(Entry);
1995   Entry.Node = Nest; Args.push_back(Entry);
1996
1997   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1998   TargetLowering::CallLoweringInfo CLI(DAG);
1999   CLI.setDebugLoc(dl).setChain(Chain)
2000     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2001                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2002                std::move(Args), 0);
2003
2004   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2005   return CallResult.second;
2006 }
2007
2008 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2009                                         const PPCSubtarget &Subtarget) const {
2010   MachineFunction &MF = DAG.getMachineFunction();
2011   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2012
2013   SDLoc dl(Op);
2014
2015   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2016     // vastart just stores the address of the VarArgsFrameIndex slot into the
2017     // memory location argument.
2018     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2019     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2020     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2021     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2022                         MachinePointerInfo(SV),
2023                         false, false, 0);
2024   }
2025
2026   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2027   // We suppose the given va_list is already allocated.
2028   //
2029   // typedef struct {
2030   //  char gpr;     /* index into the array of 8 GPRs
2031   //                 * stored in the register save area
2032   //                 * gpr=0 corresponds to r3,
2033   //                 * gpr=1 to r4, etc.
2034   //                 */
2035   //  char fpr;     /* index into the array of 8 FPRs
2036   //                 * stored in the register save area
2037   //                 * fpr=0 corresponds to f1,
2038   //                 * fpr=1 to f2, etc.
2039   //                 */
2040   //  char *overflow_arg_area;
2041   //                /* location on stack that holds
2042   //                 * the next overflow argument
2043   //                 */
2044   //  char *reg_save_area;
2045   //               /* where r3:r10 and f1:f8 (if saved)
2046   //                * are stored
2047   //                */
2048   // } va_list[1];
2049
2050
2051   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2052   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2053
2054
2055   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2056
2057   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2058                                             PtrVT);
2059   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2060                                  PtrVT);
2061
2062   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2063   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2064
2065   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2066   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2067
2068   uint64_t FPROffset = 1;
2069   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2070
2071   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2072
2073   // Store first byte : number of int regs
2074   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2075                                          Op.getOperand(1),
2076                                          MachinePointerInfo(SV),
2077                                          MVT::i8, false, false, 0);
2078   uint64_t nextOffset = FPROffset;
2079   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2080                                   ConstFPROffset);
2081
2082   // Store second byte : number of float regs
2083   SDValue secondStore =
2084     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2085                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2086                       false, false, 0);
2087   nextOffset += StackOffset;
2088   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2089
2090   // Store second word : arguments given on stack
2091   SDValue thirdStore =
2092     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2093                  MachinePointerInfo(SV, nextOffset),
2094                  false, false, 0);
2095   nextOffset += FrameOffset;
2096   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2097
2098   // Store third word : arguments given in registers
2099   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2100                       MachinePointerInfo(SV, nextOffset),
2101                       false, false, 0);
2102
2103 }
2104
2105 #include "PPCGenCallingConv.inc"
2106
2107 // Function whose sole purpose is to kill compiler warnings 
2108 // stemming from unused functions included from PPCGenCallingConv.inc.
2109 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2110   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2111 }
2112
2113 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2114                                       CCValAssign::LocInfo &LocInfo,
2115                                       ISD::ArgFlagsTy &ArgFlags,
2116                                       CCState &State) {
2117   return true;
2118 }
2119
2120 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2121                                              MVT &LocVT,
2122                                              CCValAssign::LocInfo &LocInfo,
2123                                              ISD::ArgFlagsTy &ArgFlags,
2124                                              CCState &State) {
2125   static const MCPhysReg ArgRegs[] = {
2126     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2127     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2128   };
2129   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2130
2131   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2132
2133   // Skip one register if the first unallocated register has an even register
2134   // number and there are still argument registers available which have not been
2135   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2136   // need to skip a register if RegNum is odd.
2137   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2138     State.AllocateReg(ArgRegs[RegNum]);
2139   }
2140
2141   // Always return false here, as this function only makes sure that the first
2142   // unallocated register has an odd register number and does not actually
2143   // allocate a register for the current argument.
2144   return false;
2145 }
2146
2147 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2148                                                MVT &LocVT,
2149                                                CCValAssign::LocInfo &LocInfo,
2150                                                ISD::ArgFlagsTy &ArgFlags,
2151                                                CCState &State) {
2152   static const MCPhysReg ArgRegs[] = {
2153     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2154     PPC::F8
2155   };
2156
2157   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2158
2159   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2160
2161   // If there is only one Floating-point register left we need to put both f64
2162   // values of a split ppc_fp128 value on the stack.
2163   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2164     State.AllocateReg(ArgRegs[RegNum]);
2165   }
2166
2167   // Always return false here, as this function only makes sure that the two f64
2168   // values a ppc_fp128 value is split into are both passed in registers or both
2169   // passed on the stack and does not actually allocate a register for the
2170   // current argument.
2171   return false;
2172 }
2173
2174 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2175 /// on Darwin.
2176 static const MCPhysReg *GetFPR() {
2177   static const MCPhysReg FPR[] = {
2178     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2179     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2180   };
2181
2182   return FPR;
2183 }
2184
2185 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2186 /// the stack.
2187 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2188                                        unsigned PtrByteSize) {
2189   unsigned ArgSize = ArgVT.getStoreSize();
2190   if (Flags.isByVal())
2191     ArgSize = Flags.getByValSize();
2192
2193   // Round up to multiples of the pointer size, except for array members,
2194   // which are always packed.
2195   if (!Flags.isInConsecutiveRegs())
2196     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2197
2198   return ArgSize;
2199 }
2200
2201 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2202 /// on the stack.
2203 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2204                                             ISD::ArgFlagsTy Flags,
2205                                             unsigned PtrByteSize) {
2206   unsigned Align = PtrByteSize;
2207
2208   // Altivec parameters are padded to a 16 byte boundary.
2209   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2210       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2211       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2212     Align = 16;
2213
2214   // ByVal parameters are aligned as requested.
2215   if (Flags.isByVal()) {
2216     unsigned BVAlign = Flags.getByValAlign();
2217     if (BVAlign > PtrByteSize) {
2218       if (BVAlign % PtrByteSize != 0)
2219           llvm_unreachable(
2220             "ByVal alignment is not a multiple of the pointer size");
2221
2222       Align = BVAlign;
2223     }
2224   }
2225
2226   // Array members are always packed to their original alignment.
2227   if (Flags.isInConsecutiveRegs()) {
2228     // If the array member was split into multiple registers, the first
2229     // needs to be aligned to the size of the full type.  (Except for
2230     // ppcf128, which is only aligned as its f64 components.)
2231     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2232       Align = OrigVT.getStoreSize();
2233     else
2234       Align = ArgVT.getStoreSize();
2235   }
2236
2237   return Align;
2238 }
2239
2240 /// CalculateStackSlotUsed - Return whether this argument will use its
2241 /// stack slot (instead of being passed in registers).  ArgOffset,
2242 /// AvailableFPRs, and AvailableVRs must hold the current argument
2243 /// position, and will be updated to account for this argument.
2244 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2245                                    ISD::ArgFlagsTy Flags,
2246                                    unsigned PtrByteSize,
2247                                    unsigned LinkageSize,
2248                                    unsigned ParamAreaSize,
2249                                    unsigned &ArgOffset,
2250                                    unsigned &AvailableFPRs,
2251                                    unsigned &AvailableVRs) {
2252   bool UseMemory = false;
2253
2254   // Respect alignment of argument on the stack.
2255   unsigned Align =
2256     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2257   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2258   // If there's no space left in the argument save area, we must
2259   // use memory (this check also catches zero-sized arguments).
2260   if (ArgOffset >= LinkageSize + ParamAreaSize)
2261     UseMemory = true;
2262
2263   // Allocate argument on the stack.
2264   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2265   if (Flags.isInConsecutiveRegsLast())
2266     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2267   // If we overran the argument save area, we must use memory
2268   // (this check catches arguments passed partially in memory)
2269   if (ArgOffset > LinkageSize + ParamAreaSize)
2270     UseMemory = true;
2271
2272   // However, if the argument is actually passed in an FPR or a VR,
2273   // we don't use memory after all.
2274   if (!Flags.isByVal()) {
2275     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2276       if (AvailableFPRs > 0) {
2277         --AvailableFPRs;
2278         return false;
2279       }
2280     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2281         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2282         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2283       if (AvailableVRs > 0) {
2284         --AvailableVRs;
2285         return false;
2286       }
2287   }
2288
2289   return UseMemory;
2290 }
2291
2292 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2293 /// ensure minimum alignment required for target.
2294 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2295                                      unsigned NumBytes) {
2296   unsigned TargetAlign = Target.getFrameLowering()->getStackAlignment();
2297   unsigned AlignMask = TargetAlign - 1;
2298   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2299   return NumBytes;
2300 }
2301
2302 SDValue
2303 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2304                                         CallingConv::ID CallConv, bool isVarArg,
2305                                         const SmallVectorImpl<ISD::InputArg>
2306                                           &Ins,
2307                                         SDLoc dl, SelectionDAG &DAG,
2308                                         SmallVectorImpl<SDValue> &InVals)
2309                                           const {
2310   if (Subtarget.isSVR4ABI()) {
2311     if (Subtarget.isPPC64())
2312       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2313                                          dl, DAG, InVals);
2314     else
2315       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2316                                          dl, DAG, InVals);
2317   } else {
2318     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2319                                        dl, DAG, InVals);
2320   }
2321 }
2322
2323 SDValue
2324 PPCTargetLowering::LowerFormalArguments_32SVR4(
2325                                       SDValue Chain,
2326                                       CallingConv::ID CallConv, bool isVarArg,
2327                                       const SmallVectorImpl<ISD::InputArg>
2328                                         &Ins,
2329                                       SDLoc dl, SelectionDAG &DAG,
2330                                       SmallVectorImpl<SDValue> &InVals) const {
2331
2332   // 32-bit SVR4 ABI Stack Frame Layout:
2333   //              +-----------------------------------+
2334   //        +-->  |            Back chain             |
2335   //        |     +-----------------------------------+
2336   //        |     | Floating-point register save area |
2337   //        |     +-----------------------------------+
2338   //        |     |    General register save area     |
2339   //        |     +-----------------------------------+
2340   //        |     |          CR save word             |
2341   //        |     +-----------------------------------+
2342   //        |     |         VRSAVE save word          |
2343   //        |     +-----------------------------------+
2344   //        |     |         Alignment padding         |
2345   //        |     +-----------------------------------+
2346   //        |     |     Vector register save area     |
2347   //        |     +-----------------------------------+
2348   //        |     |       Local variable space        |
2349   //        |     +-----------------------------------+
2350   //        |     |        Parameter list area        |
2351   //        |     +-----------------------------------+
2352   //        |     |           LR save word            |
2353   //        |     +-----------------------------------+
2354   // SP-->  +---  |            Back chain             |
2355   //              +-----------------------------------+
2356   //
2357   // Specifications:
2358   //   System V Application Binary Interface PowerPC Processor Supplement
2359   //   AltiVec Technology Programming Interface Manual
2360
2361   MachineFunction &MF = DAG.getMachineFunction();
2362   MachineFrameInfo *MFI = MF.getFrameInfo();
2363   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2364
2365   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2366   // Potential tail calls could cause overwriting of argument stack slots.
2367   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2368                        (CallConv == CallingConv::Fast));
2369   unsigned PtrByteSize = 4;
2370
2371   // Assign locations to all of the incoming arguments.
2372   SmallVector<CCValAssign, 16> ArgLocs;
2373   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2374                  getTargetMachine(), ArgLocs, *DAG.getContext());
2375
2376   // Reserve space for the linkage area on the stack.
2377   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2378   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2379
2380   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2381
2382   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2383     CCValAssign &VA = ArgLocs[i];
2384
2385     // Arguments stored in registers.
2386     if (VA.isRegLoc()) {
2387       const TargetRegisterClass *RC;
2388       EVT ValVT = VA.getValVT();
2389
2390       switch (ValVT.getSimpleVT().SimpleTy) {
2391         default:
2392           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2393         case MVT::i1:
2394         case MVT::i32:
2395           RC = &PPC::GPRCRegClass;
2396           break;
2397         case MVT::f32:
2398           RC = &PPC::F4RCRegClass;
2399           break;
2400         case MVT::f64:
2401           if (Subtarget.hasVSX())
2402             RC = &PPC::VSFRCRegClass;
2403           else
2404             RC = &PPC::F8RCRegClass;
2405           break;
2406         case MVT::v16i8:
2407         case MVT::v8i16:
2408         case MVT::v4i32:
2409         case MVT::v4f32:
2410           RC = &PPC::VRRCRegClass;
2411           break;
2412         case MVT::v2f64:
2413         case MVT::v2i64:
2414           RC = &PPC::VSHRCRegClass;
2415           break;
2416       }
2417
2418       // Transform the arguments stored in physical registers into virtual ones.
2419       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2420       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2421                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2422
2423       if (ValVT == MVT::i1)
2424         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2425
2426       InVals.push_back(ArgValue);
2427     } else {
2428       // Argument stored in memory.
2429       assert(VA.isMemLoc());
2430
2431       unsigned ArgSize = VA.getLocVT().getStoreSize();
2432       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2433                                       isImmutable);
2434
2435       // Create load nodes to retrieve arguments from the stack.
2436       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2437       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2438                                    MachinePointerInfo(),
2439                                    false, false, false, 0));
2440     }
2441   }
2442
2443   // Assign locations to all of the incoming aggregate by value arguments.
2444   // Aggregates passed by value are stored in the local variable space of the
2445   // caller's stack frame, right above the parameter list area.
2446   SmallVector<CCValAssign, 16> ByValArgLocs;
2447   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2448                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
2449
2450   // Reserve stack space for the allocations in CCInfo.
2451   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2452
2453   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2454
2455   // Area that is at least reserved in the caller of this function.
2456   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2457   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2458
2459   // Set the size that is at least reserved in caller of this function.  Tail
2460   // call optimized function's reserved stack space needs to be aligned so that
2461   // taking the difference between two stack areas will result in an aligned
2462   // stack.
2463   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2464   FuncInfo->setMinReservedArea(MinReservedArea);
2465
2466   SmallVector<SDValue, 8> MemOps;
2467
2468   // If the function takes variable number of arguments, make a frame index for
2469   // the start of the first vararg value... for expansion of llvm.va_start.
2470   if (isVarArg) {
2471     static const MCPhysReg GPArgRegs[] = {
2472       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2473       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2474     };
2475     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2476
2477     static const MCPhysReg FPArgRegs[] = {
2478       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2479       PPC::F8
2480     };
2481     const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2482
2483     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2484                                                           NumGPArgRegs));
2485     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2486                                                           NumFPArgRegs));
2487
2488     // Make room for NumGPArgRegs and NumFPArgRegs.
2489     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2490                 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2491
2492     FuncInfo->setVarArgsStackOffset(
2493       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2494                              CCInfo.getNextStackOffset(), true));
2495
2496     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2497     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2498
2499     // The fixed integer arguments of a variadic function are stored to the
2500     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2501     // the result of va_next.
2502     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2503       // Get an existing live-in vreg, or add a new one.
2504       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2505       if (!VReg)
2506         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2507
2508       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2509       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2510                                    MachinePointerInfo(), false, false, 0);
2511       MemOps.push_back(Store);
2512       // Increment the address by four for the next argument to store
2513       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2514       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2515     }
2516
2517     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2518     // is set.
2519     // The double arguments are stored to the VarArgsFrameIndex
2520     // on the stack.
2521     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2522       // Get an existing live-in vreg, or add a new one.
2523       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2524       if (!VReg)
2525         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2526
2527       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2528       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2529                                    MachinePointerInfo(), false, false, 0);
2530       MemOps.push_back(Store);
2531       // Increment the address by eight for the next argument to store
2532       SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2533                                          PtrVT);
2534       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2535     }
2536   }
2537
2538   if (!MemOps.empty())
2539     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2540
2541   return Chain;
2542 }
2543
2544 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2545 // value to MVT::i64 and then truncate to the correct register size.
2546 SDValue
2547 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2548                                      SelectionDAG &DAG, SDValue ArgVal,
2549                                      SDLoc dl) const {
2550   if (Flags.isSExt())
2551     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2552                          DAG.getValueType(ObjectVT));
2553   else if (Flags.isZExt())
2554     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2555                          DAG.getValueType(ObjectVT));
2556
2557   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2558 }
2559
2560 SDValue
2561 PPCTargetLowering::LowerFormalArguments_64SVR4(
2562                                       SDValue Chain,
2563                                       CallingConv::ID CallConv, bool isVarArg,
2564                                       const SmallVectorImpl<ISD::InputArg>
2565                                         &Ins,
2566                                       SDLoc dl, SelectionDAG &DAG,
2567                                       SmallVectorImpl<SDValue> &InVals) const {
2568   // TODO: add description of PPC stack frame format, or at least some docs.
2569   //
2570   bool isELFv2ABI = Subtarget.isELFv2ABI();
2571   bool isLittleEndian = Subtarget.isLittleEndian();
2572   MachineFunction &MF = DAG.getMachineFunction();
2573   MachineFrameInfo *MFI = MF.getFrameInfo();
2574   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2575
2576   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2577   // Potential tail calls could cause overwriting of argument stack slots.
2578   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2579                        (CallConv == CallingConv::Fast));
2580   unsigned PtrByteSize = 8;
2581
2582   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2583                                                           isELFv2ABI);
2584
2585   static const MCPhysReg GPR[] = {
2586     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2587     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2588   };
2589
2590   static const MCPhysReg *FPR = GetFPR();
2591
2592   static const MCPhysReg VR[] = {
2593     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2594     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2595   };
2596   static const MCPhysReg VSRH[] = {
2597     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2598     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2599   };
2600
2601   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2602   const unsigned Num_FPR_Regs = 13;
2603   const unsigned Num_VR_Regs  = array_lengthof(VR);
2604
2605   // Do a first pass over the arguments to determine whether the ABI
2606   // guarantees that our caller has allocated the parameter save area
2607   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2608   // in the ELFv2 ABI, it is true if this is a vararg function or if
2609   // any parameter is located in a stack slot.
2610
2611   bool HasParameterArea = !isELFv2ABI || isVarArg;
2612   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2613   unsigned NumBytes = LinkageSize;
2614   unsigned AvailableFPRs = Num_FPR_Regs;
2615   unsigned AvailableVRs = Num_VR_Regs;
2616   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2617     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2618                                PtrByteSize, LinkageSize, ParamAreaSize,
2619                                NumBytes, AvailableFPRs, AvailableVRs))
2620       HasParameterArea = true;
2621
2622   // Add DAG nodes to load the arguments or copy them out of registers.  On
2623   // entry to a function on PPC, the arguments start after the linkage area,
2624   // although the first ones are often in registers.
2625
2626   unsigned ArgOffset = LinkageSize;
2627   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2628   SmallVector<SDValue, 8> MemOps;
2629   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2630   unsigned CurArgIdx = 0;
2631   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2632     SDValue ArgVal;
2633     bool needsLoad = false;
2634     EVT ObjectVT = Ins[ArgNo].VT;
2635     EVT OrigVT = Ins[ArgNo].ArgVT;
2636     unsigned ObjSize = ObjectVT.getStoreSize();
2637     unsigned ArgSize = ObjSize;
2638     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2639     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2640     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2641
2642     /* Respect alignment of argument on the stack.  */
2643     unsigned Align =
2644       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2645     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2646     unsigned CurArgOffset = ArgOffset;
2647
2648     /* Compute GPR index associated with argument offset.  */
2649     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2650     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2651
2652     // FIXME the codegen can be much improved in some cases.
2653     // We do not have to keep everything in memory.
2654     if (Flags.isByVal()) {
2655       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2656       ObjSize = Flags.getByValSize();
2657       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2658       // Empty aggregate parameters do not take up registers.  Examples:
2659       //   struct { } a;
2660       //   union  { } b;
2661       //   int c[0];
2662       // etc.  However, we have to provide a place-holder in InVals, so
2663       // pretend we have an 8-byte item at the current address for that
2664       // purpose.
2665       if (!ObjSize) {
2666         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2667         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2668         InVals.push_back(FIN);
2669         continue;
2670       }
2671
2672       // Create a stack object covering all stack doublewords occupied
2673       // by the argument.  If the argument is (fully or partially) on
2674       // the stack, or if the argument is fully in registers but the
2675       // caller has allocated the parameter save anyway, we can refer
2676       // directly to the caller's stack frame.  Otherwise, create a
2677       // local copy in our own frame.
2678       int FI;
2679       if (HasParameterArea ||
2680           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2681         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false);
2682       else
2683         FI = MFI->CreateStackObject(ArgSize, Align, false);
2684       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2685
2686       // Handle aggregates smaller than 8 bytes.
2687       if (ObjSize < PtrByteSize) {
2688         // The value of the object is its address, which differs from the
2689         // address of the enclosing doubleword on big-endian systems.
2690         SDValue Arg = FIN;
2691         if (!isLittleEndian) {
2692           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2693           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2694         }
2695         InVals.push_back(Arg);
2696
2697         if (GPR_idx != Num_GPR_Regs) {
2698           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2699           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2700           SDValue Store;
2701
2702           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2703             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2704                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2705             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2706                                       MachinePointerInfo(FuncArg),
2707                                       ObjType, false, false, 0);
2708           } else {
2709             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2710             // store the whole register as-is to the parameter save area
2711             // slot.
2712             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2713                                  MachinePointerInfo(FuncArg),
2714                                  false, false, 0);
2715           }
2716
2717           MemOps.push_back(Store);
2718         }
2719         // Whether we copied from a register or not, advance the offset
2720         // into the parameter save area by a full doubleword.
2721         ArgOffset += PtrByteSize;
2722         continue;
2723       }
2724
2725       // The value of the object is its address, which is the address of
2726       // its first stack doubleword.
2727       InVals.push_back(FIN);
2728
2729       // Store whatever pieces of the object are in registers to memory.
2730       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2731         if (GPR_idx == Num_GPR_Regs)
2732           break;
2733
2734         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2735         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2736         SDValue Addr = FIN;
2737         if (j) {
2738           SDValue Off = DAG.getConstant(j, PtrVT);
2739           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2740         }
2741         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2742                                      MachinePointerInfo(FuncArg, j),
2743                                      false, false, 0);
2744         MemOps.push_back(Store);
2745         ++GPR_idx;
2746       }
2747       ArgOffset += ArgSize;
2748       continue;
2749     }
2750
2751     switch (ObjectVT.getSimpleVT().SimpleTy) {
2752     default: llvm_unreachable("Unhandled argument type!");
2753     case MVT::i1:
2754     case MVT::i32:
2755     case MVT::i64:
2756       // These can be scalar arguments or elements of an integer array type
2757       // passed directly.  Clang may use those instead of "byval" aggregate
2758       // types to avoid forcing arguments to memory unnecessarily.
2759       if (GPR_idx != Num_GPR_Regs) {
2760         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2761         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2762
2763         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2764           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2765           // value to MVT::i64 and then truncate to the correct register size.
2766           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2767       } else {
2768         needsLoad = true;
2769         ArgSize = PtrByteSize;
2770       }
2771       ArgOffset += 8;
2772       break;
2773
2774     case MVT::f32:
2775     case MVT::f64:
2776       // These can be scalar arguments or elements of a float array type
2777       // passed directly.  The latter are used to implement ELFv2 homogenous
2778       // float aggregates.
2779       if (FPR_idx != Num_FPR_Regs) {
2780         unsigned VReg;
2781
2782         if (ObjectVT == MVT::f32)
2783           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2784         else
2785           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2786                                             &PPC::VSFRCRegClass :
2787                                             &PPC::F8RCRegClass);
2788
2789         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2790         ++FPR_idx;
2791       } else if (GPR_idx != Num_GPR_Regs) {
2792         // This can only ever happen in the presence of f32 array types,
2793         // since otherwise we never run out of FPRs before running out
2794         // of GPRs.
2795         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2796         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2797
2798         if (ObjectVT == MVT::f32) {
2799           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2800             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2801                                  DAG.getConstant(32, MVT::i32));
2802           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2803         }
2804
2805         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2806       } else {
2807         needsLoad = true;
2808       }
2809
2810       // When passing an array of floats, the array occupies consecutive
2811       // space in the argument area; only round up to the next doubleword
2812       // at the end of the array.  Otherwise, each float takes 8 bytes.
2813       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2814       ArgOffset += ArgSize;
2815       if (Flags.isInConsecutiveRegsLast())
2816         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2817       break;
2818     case MVT::v4f32:
2819     case MVT::v4i32:
2820     case MVT::v8i16:
2821     case MVT::v16i8:
2822     case MVT::v2f64:
2823     case MVT::v2i64:
2824       // These can be scalar arguments or elements of a vector array type
2825       // passed directly.  The latter are used to implement ELFv2 homogenous
2826       // vector aggregates.
2827       if (VR_idx != Num_VR_Regs) {
2828         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2829                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2830                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2831         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2832         ++VR_idx;
2833       } else {
2834         needsLoad = true;
2835       }
2836       ArgOffset += 16;
2837       break;
2838     }
2839
2840     // We need to load the argument to a virtual register if we determined
2841     // above that we ran out of physical registers of the appropriate type.
2842     if (needsLoad) {
2843       if (ObjSize < ArgSize && !isLittleEndian)
2844         CurArgOffset += ArgSize - ObjSize;
2845       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2846       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2847       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2848                            false, false, false, 0);
2849     }
2850
2851     InVals.push_back(ArgVal);
2852   }
2853
2854   // Area that is at least reserved in the caller of this function.
2855   unsigned MinReservedArea;
2856   if (HasParameterArea)
2857     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2858   else
2859     MinReservedArea = LinkageSize;
2860
2861   // Set the size that is at least reserved in caller of this function.  Tail
2862   // call optimized functions' reserved stack space needs to be aligned so that
2863   // taking the difference between two stack areas will result in an aligned
2864   // stack.
2865   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2866   FuncInfo->setMinReservedArea(MinReservedArea);
2867
2868   // If the function takes variable number of arguments, make a frame index for
2869   // the start of the first vararg value... for expansion of llvm.va_start.
2870   if (isVarArg) {
2871     int Depth = ArgOffset;
2872
2873     FuncInfo->setVarArgsFrameIndex(
2874       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2875     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2876
2877     // If this function is vararg, store any remaining integer argument regs
2878     // to their spots on the stack so that they may be loaded by deferencing the
2879     // result of va_next.
2880     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2881          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2882       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2883       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2884       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2885                                    MachinePointerInfo(), false, false, 0);
2886       MemOps.push_back(Store);
2887       // Increment the address by four for the next argument to store
2888       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2889       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2890     }
2891   }
2892
2893   if (!MemOps.empty())
2894     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2895
2896   return Chain;
2897 }
2898
2899 SDValue
2900 PPCTargetLowering::LowerFormalArguments_Darwin(
2901                                       SDValue Chain,
2902                                       CallingConv::ID CallConv, bool isVarArg,
2903                                       const SmallVectorImpl<ISD::InputArg>
2904                                         &Ins,
2905                                       SDLoc dl, SelectionDAG &DAG,
2906                                       SmallVectorImpl<SDValue> &InVals) const {
2907   // TODO: add description of PPC stack frame format, or at least some docs.
2908   //
2909   MachineFunction &MF = DAG.getMachineFunction();
2910   MachineFrameInfo *MFI = MF.getFrameInfo();
2911   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2912
2913   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2914   bool isPPC64 = PtrVT == MVT::i64;
2915   // Potential tail calls could cause overwriting of argument stack slots.
2916   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2917                        (CallConv == CallingConv::Fast));
2918   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2919
2920   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2921                                                           false);
2922   unsigned ArgOffset = LinkageSize;
2923   // Area that is at least reserved in caller of this function.
2924   unsigned MinReservedArea = ArgOffset;
2925
2926   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2927     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2928     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2929   };
2930   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2931     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2932     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2933   };
2934
2935   static const MCPhysReg *FPR = GetFPR();
2936
2937   static const MCPhysReg VR[] = {
2938     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2939     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2940   };
2941
2942   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2943   const unsigned Num_FPR_Regs = 13;
2944   const unsigned Num_VR_Regs  = array_lengthof( VR);
2945
2946   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2947
2948   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2949
2950   // In 32-bit non-varargs functions, the stack space for vectors is after the
2951   // stack space for non-vectors.  We do not use this space unless we have
2952   // too many vectors to fit in registers, something that only occurs in
2953   // constructed examples:), but we have to walk the arglist to figure
2954   // that out...for the pathological case, compute VecArgOffset as the
2955   // start of the vector parameter area.  Computing VecArgOffset is the
2956   // entire point of the following loop.
2957   unsigned VecArgOffset = ArgOffset;
2958   if (!isVarArg && !isPPC64) {
2959     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2960          ++ArgNo) {
2961       EVT ObjectVT = Ins[ArgNo].VT;
2962       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2963
2964       if (Flags.isByVal()) {
2965         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2966         unsigned ObjSize = Flags.getByValSize();
2967         unsigned ArgSize =
2968                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2969         VecArgOffset += ArgSize;
2970         continue;
2971       }
2972
2973       switch(ObjectVT.getSimpleVT().SimpleTy) {
2974       default: llvm_unreachable("Unhandled argument type!");
2975       case MVT::i1:
2976       case MVT::i32:
2977       case MVT::f32:
2978         VecArgOffset += 4;
2979         break;
2980       case MVT::i64:  // PPC64
2981       case MVT::f64:
2982         // FIXME: We are guaranteed to be !isPPC64 at this point.
2983         // Does MVT::i64 apply?
2984         VecArgOffset += 8;
2985         break;
2986       case MVT::v4f32:
2987       case MVT::v4i32:
2988       case MVT::v8i16:
2989       case MVT::v16i8:
2990         // Nothing to do, we're only looking at Nonvector args here.
2991         break;
2992       }
2993     }
2994   }
2995   // We've found where the vector parameter area in memory is.  Skip the
2996   // first 12 parameters; these don't use that memory.
2997   VecArgOffset = ((VecArgOffset+15)/16)*16;
2998   VecArgOffset += 12*16;
2999
3000   // Add DAG nodes to load the arguments or copy them out of registers.  On
3001   // entry to a function on PPC, the arguments start after the linkage area,
3002   // although the first ones are often in registers.
3003
3004   SmallVector<SDValue, 8> MemOps;
3005   unsigned nAltivecParamsAtEnd = 0;
3006   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3007   unsigned CurArgIdx = 0;
3008   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3009     SDValue ArgVal;
3010     bool needsLoad = false;
3011     EVT ObjectVT = Ins[ArgNo].VT;
3012     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3013     unsigned ArgSize = ObjSize;
3014     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3015     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3016     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3017
3018     unsigned CurArgOffset = ArgOffset;
3019
3020     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3021     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3022         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3023       if (isVarArg || isPPC64) {
3024         MinReservedArea = ((MinReservedArea+15)/16)*16;
3025         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3026                                                   Flags,
3027                                                   PtrByteSize);
3028       } else  nAltivecParamsAtEnd++;
3029     } else
3030       // Calculate min reserved area.
3031       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3032                                                 Flags,
3033                                                 PtrByteSize);
3034
3035     // FIXME the codegen can be much improved in some cases.
3036     // We do not have to keep everything in memory.
3037     if (Flags.isByVal()) {
3038       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3039       ObjSize = Flags.getByValSize();
3040       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3041       // Objects of size 1 and 2 are right justified, everything else is
3042       // left justified.  This means the memory address is adjusted forwards.
3043       if (ObjSize==1 || ObjSize==2) {
3044         CurArgOffset = CurArgOffset + (4 - ObjSize);
3045       }
3046       // The value of the object is its address.
3047       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
3048       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3049       InVals.push_back(FIN);
3050       if (ObjSize==1 || ObjSize==2) {
3051         if (GPR_idx != Num_GPR_Regs) {
3052           unsigned VReg;
3053           if (isPPC64)
3054             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3055           else
3056             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3057           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3058           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3059           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3060                                             MachinePointerInfo(FuncArg),
3061                                             ObjType, false, false, 0);
3062           MemOps.push_back(Store);
3063           ++GPR_idx;
3064         }
3065
3066         ArgOffset += PtrByteSize;
3067
3068         continue;
3069       }
3070       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3071         // Store whatever pieces of the object are in registers
3072         // to memory.  ArgOffset will be the address of the beginning
3073         // of the object.
3074         if (GPR_idx != Num_GPR_Regs) {
3075           unsigned VReg;
3076           if (isPPC64)
3077             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3078           else
3079             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3080           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3081           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3082           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3083           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3084                                        MachinePointerInfo(FuncArg, j),
3085                                        false, false, 0);
3086           MemOps.push_back(Store);
3087           ++GPR_idx;
3088           ArgOffset += PtrByteSize;
3089         } else {
3090           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3091           break;
3092         }
3093       }
3094       continue;
3095     }
3096
3097     switch (ObjectVT.getSimpleVT().SimpleTy) {
3098     default: llvm_unreachable("Unhandled argument type!");
3099     case MVT::i1:
3100     case MVT::i32:
3101       if (!isPPC64) {
3102         if (GPR_idx != Num_GPR_Regs) {
3103           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3104           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3105
3106           if (ObjectVT == MVT::i1)
3107             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3108
3109           ++GPR_idx;
3110         } else {
3111           needsLoad = true;
3112           ArgSize = PtrByteSize;
3113         }
3114         // All int arguments reserve stack space in the Darwin ABI.
3115         ArgOffset += PtrByteSize;
3116         break;
3117       }
3118       // FALLTHROUGH
3119     case MVT::i64:  // PPC64
3120       if (GPR_idx != Num_GPR_Regs) {
3121         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3122         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3123
3124         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3125           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3126           // value to MVT::i64 and then truncate to the correct register size.
3127           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3128
3129         ++GPR_idx;
3130       } else {
3131         needsLoad = true;
3132         ArgSize = PtrByteSize;
3133       }
3134       // All int arguments reserve stack space in the Darwin ABI.
3135       ArgOffset += 8;
3136       break;
3137
3138     case MVT::f32:
3139     case MVT::f64:
3140       // Every 4 bytes of argument space consumes one of the GPRs available for
3141       // argument passing.
3142       if (GPR_idx != Num_GPR_Regs) {
3143         ++GPR_idx;
3144         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3145           ++GPR_idx;
3146       }
3147       if (FPR_idx != Num_FPR_Regs) {
3148         unsigned VReg;
3149
3150         if (ObjectVT == MVT::f32)
3151           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3152         else
3153           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3154
3155         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3156         ++FPR_idx;
3157       } else {
3158         needsLoad = true;
3159       }
3160
3161       // All FP arguments reserve stack space in the Darwin ABI.
3162       ArgOffset += isPPC64 ? 8 : ObjSize;
3163       break;
3164     case MVT::v4f32:
3165     case MVT::v4i32:
3166     case MVT::v8i16:
3167     case MVT::v16i8:
3168       // Note that vector arguments in registers don't reserve stack space,
3169       // except in varargs functions.
3170       if (VR_idx != Num_VR_Regs) {
3171         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3172         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3173         if (isVarArg) {
3174           while ((ArgOffset % 16) != 0) {
3175             ArgOffset += PtrByteSize;
3176             if (GPR_idx != Num_GPR_Regs)
3177               GPR_idx++;
3178           }
3179           ArgOffset += 16;
3180           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3181         }
3182         ++VR_idx;
3183       } else {
3184         if (!isVarArg && !isPPC64) {
3185           // Vectors go after all the nonvectors.
3186           CurArgOffset = VecArgOffset;
3187           VecArgOffset += 16;
3188         } else {
3189           // Vectors are aligned.
3190           ArgOffset = ((ArgOffset+15)/16)*16;
3191           CurArgOffset = ArgOffset;
3192           ArgOffset += 16;
3193         }
3194         needsLoad = true;
3195       }
3196       break;
3197     }
3198
3199     // We need to load the argument to a virtual register if we determined above
3200     // that we ran out of physical registers of the appropriate type.
3201     if (needsLoad) {
3202       int FI = MFI->CreateFixedObject(ObjSize,
3203                                       CurArgOffset + (ArgSize - ObjSize),
3204                                       isImmutable);
3205       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3206       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3207                            false, false, false, 0);
3208     }
3209
3210     InVals.push_back(ArgVal);
3211   }
3212
3213   // Allow for Altivec parameters at the end, if needed.
3214   if (nAltivecParamsAtEnd) {
3215     MinReservedArea = ((MinReservedArea+15)/16)*16;
3216     MinReservedArea += 16*nAltivecParamsAtEnd;
3217   }
3218
3219   // Area that is at least reserved in the caller of this function.
3220   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3221
3222   // Set the size that is at least reserved in caller of this function.  Tail
3223   // call optimized functions' reserved stack space needs to be aligned so that
3224   // taking the difference between two stack areas will result in an aligned
3225   // stack.
3226   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3227   FuncInfo->setMinReservedArea(MinReservedArea);
3228
3229   // If the function takes variable number of arguments, make a frame index for
3230   // the start of the first vararg value... for expansion of llvm.va_start.
3231   if (isVarArg) {
3232     int Depth = ArgOffset;
3233
3234     FuncInfo->setVarArgsFrameIndex(
3235       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3236                              Depth, true));
3237     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3238
3239     // If this function is vararg, store any remaining integer argument regs
3240     // to their spots on the stack so that they may be loaded by deferencing the
3241     // result of va_next.
3242     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3243       unsigned VReg;
3244
3245       if (isPPC64)
3246         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3247       else
3248         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3249
3250       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3251       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3252                                    MachinePointerInfo(), false, false, 0);
3253       MemOps.push_back(Store);
3254       // Increment the address by four for the next argument to store
3255       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3256       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3257     }
3258   }
3259
3260   if (!MemOps.empty())
3261     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3262
3263   return Chain;
3264 }
3265
3266 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3267 /// adjusted to accommodate the arguments for the tailcall.
3268 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3269                                    unsigned ParamSize) {
3270
3271   if (!isTailCall) return 0;
3272
3273   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3274   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3275   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3276   // Remember only if the new adjustement is bigger.
3277   if (SPDiff < FI->getTailCallSPDelta())
3278     FI->setTailCallSPDelta(SPDiff);
3279
3280   return SPDiff;
3281 }
3282
3283 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3284 /// for tail call optimization. Targets which want to do tail call
3285 /// optimization should implement this function.
3286 bool
3287 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3288                                                      CallingConv::ID CalleeCC,
3289                                                      bool isVarArg,
3290                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3291                                                      SelectionDAG& DAG) const {
3292   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3293     return false;
3294
3295   // Variable argument functions are not supported.
3296   if (isVarArg)
3297     return false;
3298
3299   MachineFunction &MF = DAG.getMachineFunction();
3300   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3301   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3302     // Functions containing by val parameters are not supported.
3303     for (unsigned i = 0; i != Ins.size(); i++) {
3304        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3305        if (Flags.isByVal()) return false;
3306     }
3307
3308     // Non-PIC/GOT tail calls are supported.
3309     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3310       return true;
3311
3312     // At the moment we can only do local tail calls (in same module, hidden
3313     // or protected) if we are generating PIC.
3314     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3315       return G->getGlobal()->hasHiddenVisibility()
3316           || G->getGlobal()->hasProtectedVisibility();
3317   }
3318
3319   return false;
3320 }
3321
3322 /// isCallCompatibleAddress - Return the immediate to use if the specified
3323 /// 32-bit value is representable in the immediate field of a BxA instruction.
3324 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3325   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3326   if (!C) return nullptr;
3327
3328   int Addr = C->getZExtValue();
3329   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3330       SignExtend32<26>(Addr) != Addr)
3331     return nullptr;  // Top 6 bits have to be sext of immediate.
3332
3333   return DAG.getConstant((int)C->getZExtValue() >> 2,
3334                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3335 }
3336
3337 namespace {
3338
3339 struct TailCallArgumentInfo {
3340   SDValue Arg;
3341   SDValue FrameIdxOp;
3342   int       FrameIdx;
3343
3344   TailCallArgumentInfo() : FrameIdx(0) {}
3345 };
3346
3347 }
3348
3349 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3350 static void
3351 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3352                                            SDValue Chain,
3353                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3354                    SmallVectorImpl<SDValue> &MemOpChains,
3355                    SDLoc dl) {
3356   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3357     SDValue Arg = TailCallArgs[i].Arg;
3358     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3359     int FI = TailCallArgs[i].FrameIdx;
3360     // Store relative to framepointer.
3361     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3362                                        MachinePointerInfo::getFixedStack(FI),
3363                                        false, false, 0));
3364   }
3365 }
3366
3367 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3368 /// the appropriate stack slot for the tail call optimized function call.
3369 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3370                                                MachineFunction &MF,
3371                                                SDValue Chain,
3372                                                SDValue OldRetAddr,
3373                                                SDValue OldFP,
3374                                                int SPDiff,
3375                                                bool isPPC64,
3376                                                bool isDarwinABI,
3377                                                SDLoc dl) {
3378   if (SPDiff) {
3379     // Calculate the new stack slot for the return address.
3380     int SlotSize = isPPC64 ? 8 : 4;
3381     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3382                                                                    isDarwinABI);
3383     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3384                                                           NewRetAddrLoc, true);
3385     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3386     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3387     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3388                          MachinePointerInfo::getFixedStack(NewRetAddr),
3389                          false, false, 0);
3390
3391     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3392     // slot as the FP is never overwritten.
3393     if (isDarwinABI) {
3394       int NewFPLoc =
3395         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3396       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3397                                                           true);
3398       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3399       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3400                            MachinePointerInfo::getFixedStack(NewFPIdx),
3401                            false, false, 0);
3402     }
3403   }
3404   return Chain;
3405 }
3406
3407 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3408 /// the position of the argument.
3409 static void
3410 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3411                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3412                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3413   int Offset = ArgOffset + SPDiff;
3414   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3415   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3416   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3417   SDValue FIN = DAG.getFrameIndex(FI, VT);
3418   TailCallArgumentInfo Info;
3419   Info.Arg = Arg;
3420   Info.FrameIdxOp = FIN;
3421   Info.FrameIdx = FI;
3422   TailCallArguments.push_back(Info);
3423 }
3424
3425 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3426 /// stack slot. Returns the chain as result and the loaded frame pointers in
3427 /// LROpOut/FPOpout. Used when tail calling.
3428 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3429                                                         int SPDiff,
3430                                                         SDValue Chain,
3431                                                         SDValue &LROpOut,
3432                                                         SDValue &FPOpOut,
3433                                                         bool isDarwinABI,
3434                                                         SDLoc dl) const {
3435   if (SPDiff) {
3436     // Load the LR and FP stack slot for later adjusting.
3437     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3438     LROpOut = getReturnAddrFrameIndex(DAG);
3439     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3440                           false, false, false, 0);
3441     Chain = SDValue(LROpOut.getNode(), 1);
3442
3443     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3444     // slot as the FP is never overwritten.
3445     if (isDarwinABI) {
3446       FPOpOut = getFramePointerFrameIndex(DAG);
3447       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3448                             false, false, false, 0);
3449       Chain = SDValue(FPOpOut.getNode(), 1);
3450     }
3451   }
3452   return Chain;
3453 }
3454
3455 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3456 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3457 /// specified by the specific parameter attribute. The copy will be passed as
3458 /// a byval function parameter.
3459 /// Sometimes what we are copying is the end of a larger object, the part that
3460 /// does not fit in registers.
3461 static SDValue
3462 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3463                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3464                           SDLoc dl) {
3465   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3466   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3467                        false, false, MachinePointerInfo(),
3468                        MachinePointerInfo());
3469 }
3470
3471 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3472 /// tail calls.
3473 static void
3474 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3475                  SDValue Arg, SDValue PtrOff, int SPDiff,
3476                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3477                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3478                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3479                  SDLoc dl) {
3480   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3481   if (!isTailCall) {
3482     if (isVector) {
3483       SDValue StackPtr;
3484       if (isPPC64)
3485         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3486       else
3487         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3488       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3489                            DAG.getConstant(ArgOffset, PtrVT));
3490     }
3491     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3492                                        MachinePointerInfo(), false, false, 0));
3493   // Calculate and remember argument location.
3494   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3495                                   TailCallArguments);
3496 }
3497
3498 static
3499 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3500                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3501                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3502                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3503   MachineFunction &MF = DAG.getMachineFunction();
3504
3505   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3506   // might overwrite each other in case of tail call optimization.
3507   SmallVector<SDValue, 8> MemOpChains2;
3508   // Do not flag preceding copytoreg stuff together with the following stuff.
3509   InFlag = SDValue();
3510   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3511                                     MemOpChains2, dl);
3512   if (!MemOpChains2.empty())
3513     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3514
3515   // Store the return address to the appropriate stack slot.
3516   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3517                                         isPPC64, isDarwinABI, dl);
3518
3519   // Emit callseq_end just before tailcall node.
3520   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3521                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3522   InFlag = Chain.getValue(1);
3523 }
3524
3525 static
3526 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3527                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3528                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3529                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3530                      const PPCSubtarget &Subtarget) {
3531
3532   bool isPPC64 = Subtarget.isPPC64();
3533   bool isSVR4ABI = Subtarget.isSVR4ABI();
3534   bool isELFv2ABI = Subtarget.isELFv2ABI();
3535
3536   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3537   NodeTys.push_back(MVT::Other);   // Returns a chain
3538   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3539
3540   unsigned CallOpc = PPCISD::CALL;
3541
3542   bool needIndirectCall = true;
3543   if (!isSVR4ABI || !isPPC64)
3544     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3545       // If this is an absolute destination address, use the munged value.
3546       Callee = SDValue(Dest, 0);
3547       needIndirectCall = false;
3548     }
3549
3550   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3551     // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3552     // Use indirect calls for ALL functions calls in JIT mode, since the
3553     // far-call stubs may be outside relocation limits for a BL instruction.
3554     if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3555       unsigned OpFlags = 0;
3556       if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3557           (Subtarget.getTargetTriple().isMacOSX() &&
3558            Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3559           (G->getGlobal()->isDeclaration() ||
3560            G->getGlobal()->isWeakForLinker())) ||
3561           (Subtarget.isTargetELF() && !isPPC64 &&
3562            !G->getGlobal()->hasLocalLinkage() &&
3563            DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3564         // PC-relative references to external symbols should go through $stub,
3565         // unless we're building with the leopard linker or later, which
3566         // automatically synthesizes these stubs.
3567         OpFlags = PPCII::MO_PLT_OR_STUB;
3568       }
3569
3570       // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3571       // every direct call is) turn it into a TargetGlobalAddress /
3572       // TargetExternalSymbol node so that legalize doesn't hack it.
3573       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3574                                           Callee.getValueType(),
3575                                           0, OpFlags);
3576       needIndirectCall = false;
3577     }
3578   }
3579
3580   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3581     unsigned char OpFlags = 0;
3582
3583     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3584          (Subtarget.getTargetTriple().isMacOSX() &&
3585           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3586         (Subtarget.isTargetELF() && !isPPC64 &&
3587          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3588       // PC-relative references to external symbols should go through $stub,
3589       // unless we're building with the leopard linker or later, which
3590       // automatically synthesizes these stubs.
3591       OpFlags = PPCII::MO_PLT_OR_STUB;
3592     }
3593
3594     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3595                                          OpFlags);
3596     needIndirectCall = false;
3597   }
3598
3599   if (needIndirectCall) {
3600     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3601     // to do the call, we can't use PPCISD::CALL.
3602     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3603
3604     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3605       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3606       // entry point, but to the function descriptor (the function entry point
3607       // address is part of the function descriptor though).
3608       // The function descriptor is a three doubleword structure with the
3609       // following fields: function entry point, TOC base address and
3610       // environment pointer.
3611       // Thus for a call through a function pointer, the following actions need
3612       // to be performed:
3613       //   1. Save the TOC of the caller in the TOC save area of its stack
3614       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3615       //   2. Load the address of the function entry point from the function
3616       //      descriptor.
3617       //   3. Load the TOC of the callee from the function descriptor into r2.
3618       //   4. Load the environment pointer from the function descriptor into
3619       //      r11.
3620       //   5. Branch to the function entry point address.
3621       //   6. On return of the callee, the TOC of the caller needs to be
3622       //      restored (this is done in FinishCall()).
3623       //
3624       // All those operations are flagged together to ensure that no other
3625       // operations can be scheduled in between. E.g. without flagging the
3626       // operations together, a TOC access in the caller could be scheduled
3627       // between the load of the callee TOC and the branch to the callee, which
3628       // results in the TOC access going through the TOC of the callee instead
3629       // of going through the TOC of the caller, which leads to incorrect code.
3630
3631       // Load the address of the function entry point from the function
3632       // descriptor.
3633       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3634       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3635                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3636       Chain = LoadFuncPtr.getValue(1);
3637       InFlag = LoadFuncPtr.getValue(2);
3638
3639       // Load environment pointer into r11.
3640       // Offset of the environment pointer within the function descriptor.
3641       SDValue PtrOff = DAG.getIntPtrConstant(16);
3642
3643       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3644       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3645                                        InFlag);
3646       Chain = LoadEnvPtr.getValue(1);
3647       InFlag = LoadEnvPtr.getValue(2);
3648
3649       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3650                                         InFlag);
3651       Chain = EnvVal.getValue(0);
3652       InFlag = EnvVal.getValue(1);
3653
3654       // Load TOC of the callee into r2. We are using a target-specific load
3655       // with r2 hard coded, because the result of a target-independent load
3656       // would never go directly into r2, since r2 is a reserved register (which
3657       // prevents the register allocator from allocating it), resulting in an
3658       // additional register being allocated and an unnecessary move instruction
3659       // being generated.
3660       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3661       SDValue TOCOff = DAG.getIntPtrConstant(8);
3662       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3663       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3664                                        AddTOC, InFlag);
3665       Chain = LoadTOCPtr.getValue(0);
3666       InFlag = LoadTOCPtr.getValue(1);
3667
3668       MTCTROps[0] = Chain;
3669       MTCTROps[1] = LoadFuncPtr;
3670       MTCTROps[2] = InFlag;
3671     }
3672
3673     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3674                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3675     InFlag = Chain.getValue(1);
3676
3677     NodeTys.clear();
3678     NodeTys.push_back(MVT::Other);
3679     NodeTys.push_back(MVT::Glue);
3680     Ops.push_back(Chain);
3681     CallOpc = PPCISD::BCTRL;
3682     Callee.setNode(nullptr);
3683     // Add use of X11 (holding environment pointer)
3684     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3685       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3686     // Add CTR register as callee so a bctr can be emitted later.
3687     if (isTailCall)
3688       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3689   }
3690
3691   // If this is a direct call, pass the chain and the callee.
3692   if (Callee.getNode()) {
3693     Ops.push_back(Chain);
3694     Ops.push_back(Callee);
3695   }
3696   // If this is a tail call add stack pointer delta.
3697   if (isTailCall)
3698     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3699
3700   // Add argument registers to the end of the list so that they are known live
3701   // into the call.
3702   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3703     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3704                                   RegsToPass[i].second.getValueType()));
3705
3706   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3707   if (Callee.getNode() && isELFv2ABI)
3708     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3709
3710   return CallOpc;
3711 }
3712
3713 static
3714 bool isLocalCall(const SDValue &Callee)
3715 {
3716   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3717     return !G->getGlobal()->isDeclaration() &&
3718            !G->getGlobal()->isWeakForLinker();
3719   return false;
3720 }
3721
3722 SDValue
3723 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3724                                    CallingConv::ID CallConv, bool isVarArg,
3725                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3726                                    SDLoc dl, SelectionDAG &DAG,
3727                                    SmallVectorImpl<SDValue> &InVals) const {
3728
3729   SmallVector<CCValAssign, 16> RVLocs;
3730   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3731                     getTargetMachine(), RVLocs, *DAG.getContext());
3732   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3733
3734   // Copy all of the result registers out of their specified physreg.
3735   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3736     CCValAssign &VA = RVLocs[i];
3737     assert(VA.isRegLoc() && "Can only return in registers!");
3738
3739     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3740                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3741     Chain = Val.getValue(1);
3742     InFlag = Val.getValue(2);
3743
3744     switch (VA.getLocInfo()) {
3745     default: llvm_unreachable("Unknown loc info!");
3746     case CCValAssign::Full: break;
3747     case CCValAssign::AExt:
3748       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3749       break;
3750     case CCValAssign::ZExt:
3751       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3752                         DAG.getValueType(VA.getValVT()));
3753       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3754       break;
3755     case CCValAssign::SExt:
3756       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3757                         DAG.getValueType(VA.getValVT()));
3758       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3759       break;
3760     }
3761
3762     InVals.push_back(Val);
3763   }
3764
3765   return Chain;
3766 }
3767
3768 SDValue
3769 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3770                               bool isTailCall, bool isVarArg,
3771                               SelectionDAG &DAG,
3772                               SmallVector<std::pair<unsigned, SDValue>, 8>
3773                                 &RegsToPass,
3774                               SDValue InFlag, SDValue Chain,
3775                               SDValue &Callee,
3776                               int SPDiff, unsigned NumBytes,
3777                               const SmallVectorImpl<ISD::InputArg> &Ins,
3778                               SmallVectorImpl<SDValue> &InVals) const {
3779
3780   bool isELFv2ABI = Subtarget.isELFv2ABI();
3781   std::vector<EVT> NodeTys;
3782   SmallVector<SDValue, 8> Ops;
3783   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3784                                  isTailCall, RegsToPass, Ops, NodeTys,
3785                                  Subtarget);
3786
3787   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3788   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3789     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3790
3791   // When performing tail call optimization the callee pops its arguments off
3792   // the stack. Account for this here so these bytes can be pushed back on in
3793   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3794   int BytesCalleePops =
3795     (CallConv == CallingConv::Fast &&
3796      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3797
3798   // Add a register mask operand representing the call-preserved registers.
3799   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3800   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3801   assert(Mask && "Missing call preserved mask for calling convention");
3802   Ops.push_back(DAG.getRegisterMask(Mask));
3803
3804   if (InFlag.getNode())
3805     Ops.push_back(InFlag);
3806
3807   // Emit tail call.
3808   if (isTailCall) {
3809     assert(((Callee.getOpcode() == ISD::Register &&
3810              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3811             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3812             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3813             isa<ConstantSDNode>(Callee)) &&
3814     "Expecting an global address, external symbol, absolute value or register");
3815
3816     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3817   }
3818
3819   // Add a NOP immediately after the branch instruction when using the 64-bit
3820   // SVR4 ABI. At link time, if caller and callee are in a different module and
3821   // thus have a different TOC, the call will be replaced with a call to a stub
3822   // function which saves the current TOC, loads the TOC of the callee and
3823   // branches to the callee. The NOP will be replaced with a load instruction
3824   // which restores the TOC of the caller from the TOC save slot of the current
3825   // stack frame. If caller and callee belong to the same module (and have the
3826   // same TOC), the NOP will remain unchanged.
3827
3828   bool needsTOCRestore = false;
3829   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3830     if (CallOpc == PPCISD::BCTRL) {
3831       // This is a call through a function pointer.
3832       // Restore the caller TOC from the save area into R2.
3833       // See PrepareCall() for more information about calls through function
3834       // pointers in the 64-bit SVR4 ABI.
3835       // We are using a target-specific load with r2 hard coded, because the
3836       // result of a target-independent load would never go directly into r2,
3837       // since r2 is a reserved register (which prevents the register allocator
3838       // from allocating it), resulting in an additional register being
3839       // allocated and an unnecessary move instruction being generated.
3840       needsTOCRestore = true;
3841     } else if ((CallOpc == PPCISD::CALL) &&
3842                (!isLocalCall(Callee) ||
3843                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3844       // Otherwise insert NOP for non-local calls.
3845       CallOpc = PPCISD::CALL_NOP;
3846     }
3847   }
3848
3849   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3850   InFlag = Chain.getValue(1);
3851
3852   if (needsTOCRestore) {
3853     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3854     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3855     SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3856     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3857     SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3858     SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3859     Chain = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain, AddTOC, InFlag);
3860     InFlag = Chain.getValue(1);
3861   }
3862
3863   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3864                              DAG.getIntPtrConstant(BytesCalleePops, true),
3865                              InFlag, dl);
3866   if (!Ins.empty())
3867     InFlag = Chain.getValue(1);
3868
3869   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3870                          Ins, dl, DAG, InVals);
3871 }
3872
3873 SDValue
3874 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3875                              SmallVectorImpl<SDValue> &InVals) const {
3876   SelectionDAG &DAG                     = CLI.DAG;
3877   SDLoc &dl                             = CLI.DL;
3878   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3879   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3880   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3881   SDValue Chain                         = CLI.Chain;
3882   SDValue Callee                        = CLI.Callee;
3883   bool &isTailCall                      = CLI.IsTailCall;
3884   CallingConv::ID CallConv              = CLI.CallConv;
3885   bool isVarArg                         = CLI.IsVarArg;
3886
3887   if (isTailCall)
3888     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3889                                                    Ins, DAG);
3890
3891   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3892     report_fatal_error("failed to perform tail call elimination on a call "
3893                        "site marked musttail");
3894
3895   if (Subtarget.isSVR4ABI()) {
3896     if (Subtarget.isPPC64())
3897       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3898                               isTailCall, Outs, OutVals, Ins,
3899                               dl, DAG, InVals);
3900     else
3901       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3902                               isTailCall, Outs, OutVals, Ins,
3903                               dl, DAG, InVals);
3904   }
3905
3906   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3907                           isTailCall, Outs, OutVals, Ins,
3908                           dl, DAG, InVals);
3909 }
3910
3911 SDValue
3912 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3913                                     CallingConv::ID CallConv, bool isVarArg,
3914                                     bool isTailCall,
3915                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3916                                     const SmallVectorImpl<SDValue> &OutVals,
3917                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3918                                     SDLoc dl, SelectionDAG &DAG,
3919                                     SmallVectorImpl<SDValue> &InVals) const {
3920   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3921   // of the 32-bit SVR4 ABI stack frame layout.
3922
3923   assert((CallConv == CallingConv::C ||
3924           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3925
3926   unsigned PtrByteSize = 4;
3927
3928   MachineFunction &MF = DAG.getMachineFunction();
3929
3930   // Mark this function as potentially containing a function that contains a
3931   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3932   // and restoring the callers stack pointer in this functions epilog. This is
3933   // done because by tail calling the called function might overwrite the value
3934   // in this function's (MF) stack pointer stack slot 0(SP).
3935   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3936       CallConv == CallingConv::Fast)
3937     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3938
3939   // Count how many bytes are to be pushed on the stack, including the linkage
3940   // area, parameter list area and the part of the local variable space which
3941   // contains copies of aggregates which are passed by value.
3942
3943   // Assign locations to all of the outgoing arguments.
3944   SmallVector<CCValAssign, 16> ArgLocs;
3945   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3946                  getTargetMachine(), ArgLocs, *DAG.getContext());
3947
3948   // Reserve space for the linkage area on the stack.
3949   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
3950                        PtrByteSize);
3951
3952   if (isVarArg) {
3953     // Handle fixed and variable vector arguments differently.
3954     // Fixed vector arguments go into registers as long as registers are
3955     // available. Variable vector arguments always go into memory.
3956     unsigned NumArgs = Outs.size();
3957
3958     for (unsigned i = 0; i != NumArgs; ++i) {
3959       MVT ArgVT = Outs[i].VT;
3960       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3961       bool Result;
3962
3963       if (Outs[i].IsFixed) {
3964         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3965                                CCInfo);
3966       } else {
3967         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3968                                       ArgFlags, CCInfo);
3969       }
3970
3971       if (Result) {
3972 #ifndef NDEBUG
3973         errs() << "Call operand #" << i << " has unhandled type "
3974              << EVT(ArgVT).getEVTString() << "\n";
3975 #endif
3976         llvm_unreachable(nullptr);
3977       }
3978     }
3979   } else {
3980     // All arguments are treated the same.
3981     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3982   }
3983
3984   // Assign locations to all of the outgoing aggregate by value arguments.
3985   SmallVector<CCValAssign, 16> ByValArgLocs;
3986   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3987                       getTargetMachine(), ByValArgLocs, *DAG.getContext());
3988
3989   // Reserve stack space for the allocations in CCInfo.
3990   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3991
3992   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3993
3994   // Size of the linkage area, parameter list area and the part of the local
3995   // space variable where copies of aggregates which are passed by value are
3996   // stored.
3997   unsigned NumBytes = CCByValInfo.getNextStackOffset();
3998
3999   // Calculate by how many bytes the stack has to be adjusted in case of tail
4000   // call optimization.
4001   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4002
4003   // Adjust the stack pointer for the new arguments...
4004   // These operations are automatically eliminated by the prolog/epilog pass
4005   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4006                                dl);
4007   SDValue CallSeqStart = Chain;
4008
4009   // Load the return address and frame pointer so it can be moved somewhere else
4010   // later.
4011   SDValue LROp, FPOp;
4012   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4013                                        dl);
4014
4015   // Set up a copy of the stack pointer for use loading and storing any
4016   // arguments that may not fit in the registers available for argument
4017   // passing.
4018   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4019
4020   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4021   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4022   SmallVector<SDValue, 8> MemOpChains;
4023
4024   bool seenFloatArg = false;
4025   // Walk the register/memloc assignments, inserting copies/loads.
4026   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4027        i != e;
4028        ++i) {
4029     CCValAssign &VA = ArgLocs[i];
4030     SDValue Arg = OutVals[i];
4031     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4032
4033     if (Flags.isByVal()) {
4034       // Argument is an aggregate which is passed by value, thus we need to
4035       // create a copy of it in the local variable space of the current stack
4036       // frame (which is the stack frame of the caller) and pass the address of
4037       // this copy to the callee.
4038       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4039       CCValAssign &ByValVA = ByValArgLocs[j++];
4040       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4041
4042       // Memory reserved in the local variable space of the callers stack frame.
4043       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4044
4045       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4046       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4047
4048       // Create a copy of the argument in the local area of the current
4049       // stack frame.
4050       SDValue MemcpyCall =
4051         CreateCopyOfByValArgument(Arg, PtrOff,
4052                                   CallSeqStart.getNode()->getOperand(0),
4053                                   Flags, DAG, dl);
4054
4055       // This must go outside the CALLSEQ_START..END.
4056       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4057                            CallSeqStart.getNode()->getOperand(1),
4058                            SDLoc(MemcpyCall));
4059       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4060                              NewCallSeqStart.getNode());
4061       Chain = CallSeqStart = NewCallSeqStart;
4062
4063       // Pass the address of the aggregate copy on the stack either in a
4064       // physical register or in the parameter list area of the current stack
4065       // frame to the callee.
4066       Arg = PtrOff;
4067     }
4068
4069     if (VA.isRegLoc()) {
4070       if (Arg.getValueType() == MVT::i1)
4071         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4072
4073       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4074       // Put argument in a physical register.
4075       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4076     } else {
4077       // Put argument in the parameter list area of the current stack frame.
4078       assert(VA.isMemLoc());
4079       unsigned LocMemOffset = VA.getLocMemOffset();
4080
4081       if (!isTailCall) {
4082         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4083         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4084
4085         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4086                                            MachinePointerInfo(),
4087                                            false, false, 0));
4088       } else {
4089         // Calculate and remember argument location.
4090         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4091                                  TailCallArguments);
4092       }
4093     }
4094   }
4095
4096   if (!MemOpChains.empty())
4097     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4098
4099   // Build a sequence of copy-to-reg nodes chained together with token chain
4100   // and flag operands which copy the outgoing args into the appropriate regs.
4101   SDValue InFlag;
4102   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4103     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4104                              RegsToPass[i].second, InFlag);
4105     InFlag = Chain.getValue(1);
4106   }
4107
4108   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4109   // registers.
4110   if (isVarArg) {
4111     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4112     SDValue Ops[] = { Chain, InFlag };
4113
4114     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4115                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4116
4117     InFlag = Chain.getValue(1);
4118   }
4119
4120   if (isTailCall)
4121     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4122                     false, TailCallArguments);
4123
4124   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4125                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4126                     Ins, InVals);
4127 }
4128
4129 // Copy an argument into memory, being careful to do this outside the
4130 // call sequence for the call to which the argument belongs.
4131 SDValue
4132 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4133                                               SDValue CallSeqStart,
4134                                               ISD::ArgFlagsTy Flags,
4135                                               SelectionDAG &DAG,
4136                                               SDLoc dl) const {
4137   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4138                         CallSeqStart.getNode()->getOperand(0),
4139                         Flags, DAG, dl);
4140   // The MEMCPY must go outside the CALLSEQ_START..END.
4141   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4142                              CallSeqStart.getNode()->getOperand(1),
4143                              SDLoc(MemcpyCall));
4144   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4145                          NewCallSeqStart.getNode());
4146   return NewCallSeqStart;
4147 }
4148
4149 SDValue
4150 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4151                                     CallingConv::ID CallConv, bool isVarArg,
4152                                     bool isTailCall,
4153                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4154                                     const SmallVectorImpl<SDValue> &OutVals,
4155                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4156                                     SDLoc dl, SelectionDAG &DAG,
4157                                     SmallVectorImpl<SDValue> &InVals) const {
4158
4159   bool isELFv2ABI = Subtarget.isELFv2ABI();
4160   bool isLittleEndian = Subtarget.isLittleEndian();
4161   unsigned NumOps = Outs.size();
4162
4163   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4164   unsigned PtrByteSize = 8;
4165
4166   MachineFunction &MF = DAG.getMachineFunction();
4167
4168   // Mark this function as potentially containing a function that contains a
4169   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4170   // and restoring the callers stack pointer in this functions epilog. This is
4171   // done because by tail calling the called function might overwrite the value
4172   // in this function's (MF) stack pointer stack slot 0(SP).
4173   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4174       CallConv == CallingConv::Fast)
4175     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4176
4177   // Count how many bytes are to be pushed on the stack, including the linkage
4178   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4179   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4180   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4181   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4182                                                           isELFv2ABI);
4183   unsigned NumBytes = LinkageSize;
4184
4185   // Add up all the space actually used.
4186   for (unsigned i = 0; i != NumOps; ++i) {
4187     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4188     EVT ArgVT = Outs[i].VT;
4189     EVT OrigVT = Outs[i].ArgVT;
4190
4191     /* Respect alignment of argument on the stack.  */
4192     unsigned Align =
4193       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4194     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4195
4196     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4197     if (Flags.isInConsecutiveRegsLast())
4198       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4199   }
4200
4201   unsigned NumBytesActuallyUsed = NumBytes;
4202
4203   // The prolog code of the callee may store up to 8 GPR argument registers to
4204   // the stack, allowing va_start to index over them in memory if its varargs.
4205   // Because we cannot tell if this is needed on the caller side, we have to
4206   // conservatively assume that it is needed.  As such, make sure we have at
4207   // least enough stack space for the caller to store the 8 GPRs.
4208   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4209   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4210
4211   // Tail call needs the stack to be aligned.
4212   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4213       CallConv == CallingConv::Fast)
4214     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4215
4216   // Calculate by how many bytes the stack has to be adjusted in case of tail
4217   // call optimization.
4218   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4219
4220   // To protect arguments on the stack from being clobbered in a tail call,
4221   // force all the loads to happen before doing any other lowering.
4222   if (isTailCall)
4223     Chain = DAG.getStackArgumentTokenFactor(Chain);
4224
4225   // Adjust the stack pointer for the new arguments...
4226   // These operations are automatically eliminated by the prolog/epilog pass
4227   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4228                                dl);
4229   SDValue CallSeqStart = Chain;
4230
4231   // Load the return address and frame pointer so it can be move somewhere else
4232   // later.
4233   SDValue LROp, FPOp;
4234   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4235                                        dl);
4236
4237   // Set up a copy of the stack pointer for use loading and storing any
4238   // arguments that may not fit in the registers available for argument
4239   // passing.
4240   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4241
4242   // Figure out which arguments are going to go in registers, and which in
4243   // memory.  Also, if this is a vararg function, floating point operations
4244   // must be stored to our stack, and loaded into integer regs as well, if
4245   // any integer regs are available for argument passing.
4246   unsigned ArgOffset = LinkageSize;
4247   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4248
4249   static const MCPhysReg GPR[] = {
4250     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4251     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4252   };
4253   static const MCPhysReg *FPR = GetFPR();
4254
4255   static const MCPhysReg VR[] = {
4256     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4257     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4258   };
4259   static const MCPhysReg VSRH[] = {
4260     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4261     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4262   };
4263
4264   const unsigned NumGPRs = array_lengthof(GPR);
4265   const unsigned NumFPRs = 13;
4266   const unsigned NumVRs  = array_lengthof(VR);
4267
4268   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4269   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4270
4271   SmallVector<SDValue, 8> MemOpChains;
4272   for (unsigned i = 0; i != NumOps; ++i) {
4273     SDValue Arg = OutVals[i];
4274     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4275     EVT ArgVT = Outs[i].VT;
4276     EVT OrigVT = Outs[i].ArgVT;
4277
4278     /* Respect alignment of argument on the stack.  */
4279     unsigned Align =
4280       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4281     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4282
4283     /* Compute GPR index associated with argument offset.  */
4284     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4285     GPR_idx = std::min(GPR_idx, NumGPRs);
4286
4287     // PtrOff will be used to store the current argument to the stack if a
4288     // register cannot be found for it.
4289     SDValue PtrOff;
4290
4291     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4292
4293     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4294
4295     // Promote integers to 64-bit values.
4296     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4297       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4298       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4299       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4300     }
4301
4302     // FIXME memcpy is used way more than necessary.  Correctness first.
4303     // Note: "by value" is code for passing a structure by value, not
4304     // basic types.
4305     if (Flags.isByVal()) {
4306       // Note: Size includes alignment padding, so
4307       //   struct x { short a; char b; }
4308       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4309       // These are the proper values we need for right-justifying the
4310       // aggregate in a parameter register.
4311       unsigned Size = Flags.getByValSize();
4312
4313       // An empty aggregate parameter takes up no storage and no
4314       // registers.
4315       if (Size == 0)
4316         continue;
4317
4318       // All aggregates smaller than 8 bytes must be passed right-justified.
4319       if (Size==1 || Size==2 || Size==4) {
4320         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4321         if (GPR_idx != NumGPRs) {
4322           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4323                                         MachinePointerInfo(), VT,
4324                                         false, false, false, 0);
4325           MemOpChains.push_back(Load.getValue(1));
4326           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4327
4328           ArgOffset += PtrByteSize;
4329           continue;
4330         }
4331       }
4332
4333       if (GPR_idx == NumGPRs && Size < 8) {
4334         SDValue AddPtr = PtrOff;
4335         if (!isLittleEndian) {
4336           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4337                                           PtrOff.getValueType());
4338           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4339         }
4340         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4341                                                           CallSeqStart,
4342                                                           Flags, DAG, dl);
4343         ArgOffset += PtrByteSize;
4344         continue;
4345       }
4346       // Copy entire object into memory.  There are cases where gcc-generated
4347       // code assumes it is there, even if it could be put entirely into
4348       // registers.  (This is not what the doc says.)
4349
4350       // FIXME: The above statement is likely due to a misunderstanding of the
4351       // documents.  All arguments must be copied into the parameter area BY
4352       // THE CALLEE in the event that the callee takes the address of any
4353       // formal argument.  That has not yet been implemented.  However, it is
4354       // reasonable to use the stack area as a staging area for the register
4355       // load.
4356
4357       // Skip this for small aggregates, as we will use the same slot for a
4358       // right-justified copy, below.
4359       if (Size >= 8)
4360         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4361                                                           CallSeqStart,
4362                                                           Flags, DAG, dl);
4363
4364       // When a register is available, pass a small aggregate right-justified.
4365       if (Size < 8 && GPR_idx != NumGPRs) {
4366         // The easiest way to get this right-justified in a register
4367         // is to copy the structure into the rightmost portion of a
4368         // local variable slot, then load the whole slot into the
4369         // register.
4370         // FIXME: The memcpy seems to produce pretty awful code for
4371         // small aggregates, particularly for packed ones.
4372         // FIXME: It would be preferable to use the slot in the
4373         // parameter save area instead of a new local variable.
4374         SDValue AddPtr = PtrOff;
4375         if (!isLittleEndian) {
4376           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4377           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4378         }
4379         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4380                                                           CallSeqStart,
4381                                                           Flags, DAG, dl);
4382
4383         // Load the slot into the register.
4384         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4385                                    MachinePointerInfo(),
4386                                    false, false, false, 0);
4387         MemOpChains.push_back(Load.getValue(1));
4388         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4389
4390         // Done with this argument.
4391         ArgOffset += PtrByteSize;
4392         continue;
4393       }
4394
4395       // For aggregates larger than PtrByteSize, copy the pieces of the
4396       // object that fit into registers from the parameter save area.
4397       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4398         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4399         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4400         if (GPR_idx != NumGPRs) {
4401           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4402                                      MachinePointerInfo(),
4403                                      false, false, false, 0);
4404           MemOpChains.push_back(Load.getValue(1));
4405           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4406           ArgOffset += PtrByteSize;
4407         } else {
4408           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4409           break;
4410         }
4411       }
4412       continue;
4413     }
4414
4415     switch (Arg.getSimpleValueType().SimpleTy) {
4416     default: llvm_unreachable("Unexpected ValueType for argument!");
4417     case MVT::i1:
4418     case MVT::i32:
4419     case MVT::i64:
4420       // These can be scalar arguments or elements of an integer array type
4421       // passed directly.  Clang may use those instead of "byval" aggregate
4422       // types to avoid forcing arguments to memory unnecessarily.
4423       if (GPR_idx != NumGPRs) {
4424         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4425       } else {
4426         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4427                          true, isTailCall, false, MemOpChains,
4428                          TailCallArguments, dl);
4429       }
4430       ArgOffset += PtrByteSize;
4431       break;
4432     case MVT::f32:
4433     case MVT::f64: {
4434       // These can be scalar arguments or elements of a float array type
4435       // passed directly.  The latter are used to implement ELFv2 homogenous
4436       // float aggregates.
4437
4438       // Named arguments go into FPRs first, and once they overflow, the
4439       // remaining arguments go into GPRs and then the parameter save area.
4440       // Unnamed arguments for vararg functions always go to GPRs and
4441       // then the parameter save area.  For now, put all arguments to vararg
4442       // routines always in both locations (FPR *and* GPR or stack slot).
4443       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4444
4445       // First load the argument into the next available FPR.
4446       if (FPR_idx != NumFPRs)
4447         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4448
4449       // Next, load the argument into GPR or stack slot if needed.
4450       if (!NeedGPROrStack)
4451         ;
4452       else if (GPR_idx != NumGPRs) {
4453         // In the non-vararg case, this can only ever happen in the
4454         // presence of f32 array types, since otherwise we never run
4455         // out of FPRs before running out of GPRs.
4456         SDValue ArgVal;
4457
4458         // Double values are always passed in a single GPR.
4459         if (Arg.getValueType() != MVT::f32) {
4460           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4461
4462         // Non-array float values are extended and passed in a GPR.
4463         } else if (!Flags.isInConsecutiveRegs()) {
4464           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4465           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4466
4467         // If we have an array of floats, we collect every odd element
4468         // together with its predecessor into one GPR.
4469         } else if (ArgOffset % PtrByteSize != 0) {
4470           SDValue Lo, Hi;
4471           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4472           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4473           if (!isLittleEndian)
4474             std::swap(Lo, Hi);
4475           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4476
4477         // The final element, if even, goes into the first half of a GPR.
4478         } else if (Flags.isInConsecutiveRegsLast()) {
4479           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4480           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4481           if (!isLittleEndian)
4482             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4483                                  DAG.getConstant(32, MVT::i32));
4484
4485         // Non-final even elements are skipped; they will be handled
4486         // together the with subsequent argument on the next go-around.
4487         } else
4488           ArgVal = SDValue();
4489
4490         if (ArgVal.getNode())
4491           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4492       } else {
4493         // Single-precision floating-point values are mapped to the
4494         // second (rightmost) word of the stack doubleword.
4495         if (Arg.getValueType() == MVT::f32 &&
4496             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4497           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4498           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4499         }
4500
4501         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4502                          true, isTailCall, false, MemOpChains,
4503                          TailCallArguments, dl);
4504       }
4505       // When passing an array of floats, the array occupies consecutive
4506       // space in the argument area; only round up to the next doubleword
4507       // at the end of the array.  Otherwise, each float takes 8 bytes.
4508       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4509                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4510       if (Flags.isInConsecutiveRegsLast())
4511         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4512       break;
4513     }
4514     case MVT::v4f32:
4515     case MVT::v4i32:
4516     case MVT::v8i16:
4517     case MVT::v16i8:
4518     case MVT::v2f64:
4519     case MVT::v2i64:
4520       // These can be scalar arguments or elements of a vector array type
4521       // passed directly.  The latter are used to implement ELFv2 homogenous
4522       // vector aggregates.
4523
4524       // For a varargs call, named arguments go into VRs or on the stack as
4525       // usual; unnamed arguments always go to the stack or the corresponding
4526       // GPRs when within range.  For now, we always put the value in both
4527       // locations (or even all three).
4528       if (isVarArg) {
4529         // We could elide this store in the case where the object fits
4530         // entirely in R registers.  Maybe later.
4531         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4532                                      MachinePointerInfo(), false, false, 0);
4533         MemOpChains.push_back(Store);
4534         if (VR_idx != NumVRs) {
4535           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4536                                      MachinePointerInfo(),
4537                                      false, false, false, 0);
4538           MemOpChains.push_back(Load.getValue(1));
4539
4540           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4541                            Arg.getSimpleValueType() == MVT::v2i64) ?
4542                           VSRH[VR_idx] : VR[VR_idx];
4543           ++VR_idx;
4544
4545           RegsToPass.push_back(std::make_pair(VReg, Load));
4546         }
4547         ArgOffset += 16;
4548         for (unsigned i=0; i<16; i+=PtrByteSize) {
4549           if (GPR_idx == NumGPRs)
4550             break;
4551           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4552                                   DAG.getConstant(i, PtrVT));
4553           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4554                                      false, false, false, 0);
4555           MemOpChains.push_back(Load.getValue(1));
4556           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4557         }
4558         break;
4559       }
4560
4561       // Non-varargs Altivec params go into VRs or on the stack.
4562       if (VR_idx != NumVRs) {
4563         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4564                          Arg.getSimpleValueType() == MVT::v2i64) ?
4565                         VSRH[VR_idx] : VR[VR_idx];
4566         ++VR_idx;
4567
4568         RegsToPass.push_back(std::make_pair(VReg, Arg));
4569       } else {
4570         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4571                          true, isTailCall, true, MemOpChains,
4572                          TailCallArguments, dl);
4573       }
4574       ArgOffset += 16;
4575       break;
4576     }
4577   }
4578
4579   assert(NumBytesActuallyUsed == ArgOffset);
4580   (void)NumBytesActuallyUsed;
4581
4582   if (!MemOpChains.empty())
4583     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4584
4585   // Check if this is an indirect call (MTCTR/BCTRL).
4586   // See PrepareCall() for more information about calls through function
4587   // pointers in the 64-bit SVR4 ABI.
4588   if (!isTailCall &&
4589       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4590       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4591     // Load r2 into a virtual register and store it to the TOC save area.
4592     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4593     // TOC save area offset.
4594     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4595     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4596     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4597     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4598                          false, false, 0);
4599     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4600     // This does not mean the MTCTR instruction must use R12; it's easier
4601     // to model this as an extra parameter, so do that.
4602     if (isELFv2ABI)
4603       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4604   }
4605
4606   // Build a sequence of copy-to-reg nodes chained together with token chain
4607   // and flag operands which copy the outgoing args into the appropriate regs.
4608   SDValue InFlag;
4609   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4610     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4611                              RegsToPass[i].second, InFlag);
4612     InFlag = Chain.getValue(1);
4613   }
4614
4615   if (isTailCall)
4616     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4617                     FPOp, true, TailCallArguments);
4618
4619   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4620                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4621                     Ins, InVals);
4622 }
4623
4624 SDValue
4625 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4626                                     CallingConv::ID CallConv, bool isVarArg,
4627                                     bool isTailCall,
4628                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4629                                     const SmallVectorImpl<SDValue> &OutVals,
4630                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4631                                     SDLoc dl, SelectionDAG &DAG,
4632                                     SmallVectorImpl<SDValue> &InVals) const {
4633
4634   unsigned NumOps = Outs.size();
4635
4636   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4637   bool isPPC64 = PtrVT == MVT::i64;
4638   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4639
4640   MachineFunction &MF = DAG.getMachineFunction();
4641
4642   // Mark this function as potentially containing a function that contains a
4643   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4644   // and restoring the callers stack pointer in this functions epilog. This is
4645   // done because by tail calling the called function might overwrite the value
4646   // in this function's (MF) stack pointer stack slot 0(SP).
4647   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4648       CallConv == CallingConv::Fast)
4649     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4650
4651   // Count how many bytes are to be pushed on the stack, including the linkage
4652   // area, and parameter passing area.  We start with 24/48 bytes, which is
4653   // prereserved space for [SP][CR][LR][3 x unused].
4654   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4655                                                           false);
4656   unsigned NumBytes = LinkageSize;
4657
4658   // Add up all the space actually used.
4659   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4660   // they all go in registers, but we must reserve stack space for them for
4661   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4662   // assigned stack space in order, with padding so Altivec parameters are
4663   // 16-byte aligned.
4664   unsigned nAltivecParamsAtEnd = 0;
4665   for (unsigned i = 0; i != NumOps; ++i) {
4666     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4667     EVT ArgVT = Outs[i].VT;
4668     // Varargs Altivec parameters are padded to a 16 byte boundary.
4669     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4670         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4671         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4672       if (!isVarArg && !isPPC64) {
4673         // Non-varargs Altivec parameters go after all the non-Altivec
4674         // parameters; handle those later so we know how much padding we need.
4675         nAltivecParamsAtEnd++;
4676         continue;
4677       }
4678       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4679       NumBytes = ((NumBytes+15)/16)*16;
4680     }
4681     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4682   }
4683
4684   // Allow for Altivec parameters at the end, if needed.
4685   if (nAltivecParamsAtEnd) {
4686     NumBytes = ((NumBytes+15)/16)*16;
4687     NumBytes += 16*nAltivecParamsAtEnd;
4688   }
4689
4690   // The prolog code of the callee may store up to 8 GPR argument registers to
4691   // the stack, allowing va_start to index over them in memory if its varargs.
4692   // Because we cannot tell if this is needed on the caller side, we have to
4693   // conservatively assume that it is needed.  As such, make sure we have at
4694   // least enough stack space for the caller to store the 8 GPRs.
4695   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4696
4697   // Tail call needs the stack to be aligned.
4698   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4699       CallConv == CallingConv::Fast)
4700     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4701
4702   // Calculate by how many bytes the stack has to be adjusted in case of tail
4703   // call optimization.
4704   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4705
4706   // To protect arguments on the stack from being clobbered in a tail call,
4707   // force all the loads to happen before doing any other lowering.
4708   if (isTailCall)
4709     Chain = DAG.getStackArgumentTokenFactor(Chain);
4710
4711   // Adjust the stack pointer for the new arguments...
4712   // These operations are automatically eliminated by the prolog/epilog pass
4713   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4714                                dl);
4715   SDValue CallSeqStart = Chain;
4716
4717   // Load the return address and frame pointer so it can be move somewhere else
4718   // later.
4719   SDValue LROp, FPOp;
4720   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4721                                        dl);
4722
4723   // Set up a copy of the stack pointer for use loading and storing any
4724   // arguments that may not fit in the registers available for argument
4725   // passing.
4726   SDValue StackPtr;
4727   if (isPPC64)
4728     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4729   else
4730     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4731
4732   // Figure out which arguments are going to go in registers, and which in
4733   // memory.  Also, if this is a vararg function, floating point operations
4734   // must be stored to our stack, and loaded into integer regs as well, if
4735   // any integer regs are available for argument passing.
4736   unsigned ArgOffset = LinkageSize;
4737   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4738
4739   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4740     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4741     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4742   };
4743   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4744     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4745     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4746   };
4747   static const MCPhysReg *FPR = GetFPR();
4748
4749   static const MCPhysReg VR[] = {
4750     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4751     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4752   };
4753   const unsigned NumGPRs = array_lengthof(GPR_32);
4754   const unsigned NumFPRs = 13;
4755   const unsigned NumVRs  = array_lengthof(VR);
4756
4757   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4758
4759   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4760   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4761
4762   SmallVector<SDValue, 8> MemOpChains;
4763   for (unsigned i = 0; i != NumOps; ++i) {
4764     SDValue Arg = OutVals[i];
4765     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4766
4767     // PtrOff will be used to store the current argument to the stack if a
4768     // register cannot be found for it.
4769     SDValue PtrOff;
4770
4771     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4772
4773     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4774
4775     // On PPC64, promote integers to 64-bit values.
4776     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4777       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4778       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4779       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4780     }
4781
4782     // FIXME memcpy is used way more than necessary.  Correctness first.
4783     // Note: "by value" is code for passing a structure by value, not
4784     // basic types.
4785     if (Flags.isByVal()) {
4786       unsigned Size = Flags.getByValSize();
4787       // Very small objects are passed right-justified.  Everything else is
4788       // passed left-justified.
4789       if (Size==1 || Size==2) {
4790         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4791         if (GPR_idx != NumGPRs) {
4792           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4793                                         MachinePointerInfo(), VT,
4794                                         false, false, false, 0);
4795           MemOpChains.push_back(Load.getValue(1));
4796           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4797
4798           ArgOffset += PtrByteSize;
4799         } else {
4800           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4801                                           PtrOff.getValueType());
4802           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4803           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4804                                                             CallSeqStart,
4805                                                             Flags, DAG, dl);
4806           ArgOffset += PtrByteSize;
4807         }
4808         continue;
4809       }
4810       // Copy entire object into memory.  There are cases where gcc-generated
4811       // code assumes it is there, even if it could be put entirely into
4812       // registers.  (This is not what the doc says.)
4813       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4814                                                         CallSeqStart,
4815                                                         Flags, DAG, dl);
4816
4817       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4818       // copy the pieces of the object that fit into registers from the
4819       // parameter save area.
4820       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4821         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4822         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4823         if (GPR_idx != NumGPRs) {
4824           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4825                                      MachinePointerInfo(),
4826                                      false, false, false, 0);
4827           MemOpChains.push_back(Load.getValue(1));
4828           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4829           ArgOffset += PtrByteSize;
4830         } else {
4831           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4832           break;
4833         }
4834       }
4835       continue;
4836     }
4837
4838     switch (Arg.getSimpleValueType().SimpleTy) {
4839     default: llvm_unreachable("Unexpected ValueType for argument!");
4840     case MVT::i1:
4841     case MVT::i32:
4842     case MVT::i64:
4843       if (GPR_idx != NumGPRs) {
4844         if (Arg.getValueType() == MVT::i1)
4845           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4846
4847         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4848       } else {
4849         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4850                          isPPC64, isTailCall, false, MemOpChains,
4851                          TailCallArguments, dl);
4852       }
4853       ArgOffset += PtrByteSize;
4854       break;
4855     case MVT::f32:
4856     case MVT::f64:
4857       if (FPR_idx != NumFPRs) {
4858         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4859
4860         if (isVarArg) {
4861           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4862                                        MachinePointerInfo(), false, false, 0);
4863           MemOpChains.push_back(Store);
4864
4865           // Float varargs are always shadowed in available integer registers
4866           if (GPR_idx != NumGPRs) {
4867             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4868                                        MachinePointerInfo(), false, false,
4869                                        false, 0);
4870             MemOpChains.push_back(Load.getValue(1));
4871             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4872           }
4873           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4874             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4875             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4876             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4877                                        MachinePointerInfo(),
4878                                        false, false, false, 0);
4879             MemOpChains.push_back(Load.getValue(1));
4880             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4881           }
4882         } else {
4883           // If we have any FPRs remaining, we may also have GPRs remaining.
4884           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4885           // GPRs.
4886           if (GPR_idx != NumGPRs)
4887             ++GPR_idx;
4888           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4889               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4890             ++GPR_idx;
4891         }
4892       } else
4893         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4894                          isPPC64, isTailCall, false, MemOpChains,
4895                          TailCallArguments, dl);
4896       if (isPPC64)
4897         ArgOffset += 8;
4898       else
4899         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4900       break;
4901     case MVT::v4f32:
4902     case MVT::v4i32:
4903     case MVT::v8i16:
4904     case MVT::v16i8:
4905       if (isVarArg) {
4906         // These go aligned on the stack, or in the corresponding R registers
4907         // when within range.  The Darwin PPC ABI doc claims they also go in
4908         // V registers; in fact gcc does this only for arguments that are
4909         // prototyped, not for those that match the ...  We do it for all
4910         // arguments, seems to work.
4911         while (ArgOffset % 16 !=0) {
4912           ArgOffset += PtrByteSize;
4913           if (GPR_idx != NumGPRs)
4914             GPR_idx++;
4915         }
4916         // We could elide this store in the case where the object fits
4917         // entirely in R registers.  Maybe later.
4918         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4919                             DAG.getConstant(ArgOffset, PtrVT));
4920         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4921                                      MachinePointerInfo(), false, false, 0);
4922         MemOpChains.push_back(Store);
4923         if (VR_idx != NumVRs) {
4924           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4925                                      MachinePointerInfo(),
4926                                      false, false, false, 0);
4927           MemOpChains.push_back(Load.getValue(1));
4928           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4929         }
4930         ArgOffset += 16;
4931         for (unsigned i=0; i<16; i+=PtrByteSize) {
4932           if (GPR_idx == NumGPRs)
4933             break;
4934           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4935                                   DAG.getConstant(i, PtrVT));
4936           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4937                                      false, false, false, 0);
4938           MemOpChains.push_back(Load.getValue(1));
4939           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4940         }
4941         break;
4942       }
4943
4944       // Non-varargs Altivec params generally go in registers, but have
4945       // stack space allocated at the end.
4946       if (VR_idx != NumVRs) {
4947         // Doesn't have GPR space allocated.
4948         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4949       } else if (nAltivecParamsAtEnd==0) {
4950         // We are emitting Altivec params in order.
4951         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4952                          isPPC64, isTailCall, true, MemOpChains,
4953                          TailCallArguments, dl);
4954         ArgOffset += 16;
4955       }
4956       break;
4957     }
4958   }
4959   // If all Altivec parameters fit in registers, as they usually do,
4960   // they get stack space following the non-Altivec parameters.  We
4961   // don't track this here because nobody below needs it.
4962   // If there are more Altivec parameters than fit in registers emit
4963   // the stores here.
4964   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4965     unsigned j = 0;
4966     // Offset is aligned; skip 1st 12 params which go in V registers.
4967     ArgOffset = ((ArgOffset+15)/16)*16;
4968     ArgOffset += 12*16;
4969     for (unsigned i = 0; i != NumOps; ++i) {
4970       SDValue Arg = OutVals[i];
4971       EVT ArgType = Outs[i].VT;
4972       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4973           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4974         if (++j > NumVRs) {
4975           SDValue PtrOff;
4976           // We are emitting Altivec params in order.
4977           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4978                            isPPC64, isTailCall, true, MemOpChains,
4979                            TailCallArguments, dl);
4980           ArgOffset += 16;
4981         }
4982       }
4983     }
4984   }
4985
4986   if (!MemOpChains.empty())
4987     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4988
4989   // On Darwin, R12 must contain the address of an indirect callee.  This does
4990   // not mean the MTCTR instruction must use R12; it's easier to model this as
4991   // an extra parameter, so do that.
4992   if (!isTailCall &&
4993       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4994       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4995       !isBLACompatibleAddress(Callee, DAG))
4996     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4997                                                    PPC::R12), Callee));
4998
4999   // Build a sequence of copy-to-reg nodes chained together with token chain
5000   // and flag operands which copy the outgoing args into the appropriate regs.
5001   SDValue InFlag;
5002   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5003     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5004                              RegsToPass[i].second, InFlag);
5005     InFlag = Chain.getValue(1);
5006   }
5007
5008   if (isTailCall)
5009     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5010                     FPOp, true, TailCallArguments);
5011
5012   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5013                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5014                     Ins, InVals);
5015 }
5016
5017 bool
5018 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5019                                   MachineFunction &MF, bool isVarArg,
5020                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5021                                   LLVMContext &Context) const {
5022   SmallVector<CCValAssign, 16> RVLocs;
5023   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
5024                  RVLocs, Context);
5025   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5026 }
5027
5028 SDValue
5029 PPCTargetLowering::LowerReturn(SDValue Chain,
5030                                CallingConv::ID CallConv, bool isVarArg,
5031                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5032                                const SmallVectorImpl<SDValue> &OutVals,
5033                                SDLoc dl, SelectionDAG &DAG) const {
5034
5035   SmallVector<CCValAssign, 16> RVLocs;
5036   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
5037                  getTargetMachine(), RVLocs, *DAG.getContext());
5038   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5039
5040   SDValue Flag;
5041   SmallVector<SDValue, 4> RetOps(1, Chain);
5042
5043   // Copy the result values into the output registers.
5044   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5045     CCValAssign &VA = RVLocs[i];
5046     assert(VA.isRegLoc() && "Can only return in registers!");
5047
5048     SDValue Arg = OutVals[i];
5049
5050     switch (VA.getLocInfo()) {
5051     default: llvm_unreachable("Unknown loc info!");
5052     case CCValAssign::Full: break;
5053     case CCValAssign::AExt:
5054       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5055       break;
5056     case CCValAssign::ZExt:
5057       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5058       break;
5059     case CCValAssign::SExt:
5060       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5061       break;
5062     }
5063
5064     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5065     Flag = Chain.getValue(1);
5066     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5067   }
5068
5069   RetOps[0] = Chain;  // Update chain.
5070
5071   // Add the flag if we have it.
5072   if (Flag.getNode())
5073     RetOps.push_back(Flag);
5074
5075   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5076 }
5077
5078 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5079                                    const PPCSubtarget &Subtarget) const {
5080   // When we pop the dynamic allocation we need to restore the SP link.
5081   SDLoc dl(Op);
5082
5083   // Get the corect type for pointers.
5084   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5085
5086   // Construct the stack pointer operand.
5087   bool isPPC64 = Subtarget.isPPC64();
5088   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5089   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5090
5091   // Get the operands for the STACKRESTORE.
5092   SDValue Chain = Op.getOperand(0);
5093   SDValue SaveSP = Op.getOperand(1);
5094
5095   // Load the old link SP.
5096   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5097                                    MachinePointerInfo(),
5098                                    false, false, false, 0);
5099
5100   // Restore the stack pointer.
5101   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5102
5103   // Store the old link SP.
5104   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5105                       false, false, 0);
5106 }
5107
5108
5109
5110 SDValue
5111 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5112   MachineFunction &MF = DAG.getMachineFunction();
5113   bool isPPC64 = Subtarget.isPPC64();
5114   bool isDarwinABI = Subtarget.isDarwinABI();
5115   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5116
5117   // Get current frame pointer save index.  The users of this index will be
5118   // primarily DYNALLOC instructions.
5119   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5120   int RASI = FI->getReturnAddrSaveIndex();
5121
5122   // If the frame pointer save index hasn't been defined yet.
5123   if (!RASI) {
5124     // Find out what the fix offset of the frame pointer save area.
5125     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5126     // Allocate the frame index for frame pointer save area.
5127     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
5128     // Save the result.
5129     FI->setReturnAddrSaveIndex(RASI);
5130   }
5131   return DAG.getFrameIndex(RASI, PtrVT);
5132 }
5133
5134 SDValue
5135 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5136   MachineFunction &MF = DAG.getMachineFunction();
5137   bool isPPC64 = Subtarget.isPPC64();
5138   bool isDarwinABI = Subtarget.isDarwinABI();
5139   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5140
5141   // Get current frame pointer save index.  The users of this index will be
5142   // primarily DYNALLOC instructions.
5143   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5144   int FPSI = FI->getFramePointerSaveIndex();
5145
5146   // If the frame pointer save index hasn't been defined yet.
5147   if (!FPSI) {
5148     // Find out what the fix offset of the frame pointer save area.
5149     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5150                                                            isDarwinABI);
5151
5152     // Allocate the frame index for frame pointer save area.
5153     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5154     // Save the result.
5155     FI->setFramePointerSaveIndex(FPSI);
5156   }
5157   return DAG.getFrameIndex(FPSI, PtrVT);
5158 }
5159
5160 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5161                                          SelectionDAG &DAG,
5162                                          const PPCSubtarget &Subtarget) const {
5163   // Get the inputs.
5164   SDValue Chain = Op.getOperand(0);
5165   SDValue Size  = Op.getOperand(1);
5166   SDLoc dl(Op);
5167
5168   // Get the corect type for pointers.
5169   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5170   // Negate the size.
5171   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5172                                   DAG.getConstant(0, PtrVT), Size);
5173   // Construct a node for the frame pointer save index.
5174   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5175   // Build a DYNALLOC node.
5176   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5177   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5178   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5179 }
5180
5181 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5182                                                SelectionDAG &DAG) const {
5183   SDLoc DL(Op);
5184   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5185                      DAG.getVTList(MVT::i32, MVT::Other),
5186                      Op.getOperand(0), Op.getOperand(1));
5187 }
5188
5189 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5190                                                 SelectionDAG &DAG) const {
5191   SDLoc DL(Op);
5192   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5193                      Op.getOperand(0), Op.getOperand(1));
5194 }
5195
5196 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5197   assert(Op.getValueType() == MVT::i1 &&
5198          "Custom lowering only for i1 loads");
5199
5200   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5201
5202   SDLoc dl(Op);
5203   LoadSDNode *LD = cast<LoadSDNode>(Op);
5204
5205   SDValue Chain = LD->getChain();
5206   SDValue BasePtr = LD->getBasePtr();
5207   MachineMemOperand *MMO = LD->getMemOperand();
5208
5209   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5210                                  BasePtr, MVT::i8, MMO);
5211   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5212
5213   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5214   return DAG.getMergeValues(Ops, dl);
5215 }
5216
5217 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5218   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5219          "Custom lowering only for i1 stores");
5220
5221   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5222
5223   SDLoc dl(Op);
5224   StoreSDNode *ST = cast<StoreSDNode>(Op);
5225
5226   SDValue Chain = ST->getChain();
5227   SDValue BasePtr = ST->getBasePtr();
5228   SDValue Value = ST->getValue();
5229   MachineMemOperand *MMO = ST->getMemOperand();
5230
5231   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5232   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5233 }
5234
5235 // FIXME: Remove this once the ANDI glue bug is fixed:
5236 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5237   assert(Op.getValueType() == MVT::i1 &&
5238          "Custom lowering only for i1 results");
5239
5240   SDLoc DL(Op);
5241   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5242                      Op.getOperand(0));
5243 }
5244
5245 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5246 /// possible.
5247 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5248   // Not FP? Not a fsel.
5249   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5250       !Op.getOperand(2).getValueType().isFloatingPoint())
5251     return Op;
5252
5253   // We might be able to do better than this under some circumstances, but in
5254   // general, fsel-based lowering of select is a finite-math-only optimization.
5255   // For more information, see section F.3 of the 2.06 ISA specification.
5256   if (!DAG.getTarget().Options.NoInfsFPMath ||
5257       !DAG.getTarget().Options.NoNaNsFPMath)
5258     return Op;
5259
5260   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5261
5262   EVT ResVT = Op.getValueType();
5263   EVT CmpVT = Op.getOperand(0).getValueType();
5264   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5265   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5266   SDLoc dl(Op);
5267
5268   // If the RHS of the comparison is a 0.0, we don't need to do the
5269   // subtraction at all.
5270   SDValue Sel1;
5271   if (isFloatingPointZero(RHS))
5272     switch (CC) {
5273     default: break;       // SETUO etc aren't handled by fsel.
5274     case ISD::SETNE:
5275       std::swap(TV, FV);
5276     case ISD::SETEQ:
5277       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5278         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5279       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5280       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5281         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5282       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5283                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5284     case ISD::SETULT:
5285     case ISD::SETLT:
5286       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5287     case ISD::SETOGE:
5288     case ISD::SETGE:
5289       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5290         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5291       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5292     case ISD::SETUGT:
5293     case ISD::SETGT:
5294       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5295     case ISD::SETOLE:
5296     case ISD::SETLE:
5297       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5298         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5299       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5300                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5301     }
5302
5303   SDValue Cmp;
5304   switch (CC) {
5305   default: break;       // SETUO etc aren't handled by fsel.
5306   case ISD::SETNE:
5307     std::swap(TV, FV);
5308   case ISD::SETEQ:
5309     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5310     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5311       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5312     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5313     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5314       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5315     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5316                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5317   case ISD::SETULT:
5318   case ISD::SETLT:
5319     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5320     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5321       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5322     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5323   case ISD::SETOGE:
5324   case ISD::SETGE:
5325     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5326     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5327       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5328     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5329   case ISD::SETUGT:
5330   case ISD::SETGT:
5331     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5332     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5333       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5334     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5335   case ISD::SETOLE:
5336   case ISD::SETLE:
5337     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5338     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5339       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5340     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5341   }
5342   return Op;
5343 }
5344
5345 // FIXME: Split this code up when LegalizeDAGTypes lands.
5346 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5347                                            SDLoc dl) const {
5348   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5349   SDValue Src = Op.getOperand(0);
5350   if (Src.getValueType() == MVT::f32)
5351     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5352
5353   SDValue Tmp;
5354   switch (Op.getSimpleValueType().SimpleTy) {
5355   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5356   case MVT::i32:
5357     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5358                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5359                                                    PPCISD::FCTIDZ),
5360                       dl, MVT::f64, Src);
5361     break;
5362   case MVT::i64:
5363     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5364            "i64 FP_TO_UINT is supported only with FPCVT");
5365     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5366                                                         PPCISD::FCTIDUZ,
5367                       dl, MVT::f64, Src);
5368     break;
5369   }
5370
5371   // Convert the FP value to an int value through memory.
5372   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5373     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5374   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5375   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5376   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5377
5378   // Emit a store to the stack slot.
5379   SDValue Chain;
5380   if (i32Stack) {
5381     MachineFunction &MF = DAG.getMachineFunction();
5382     MachineMemOperand *MMO =
5383       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5384     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5385     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5386               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5387   } else
5388     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5389                          MPI, false, false, 0);
5390
5391   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5392   // add in a bias.
5393   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5394     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5395                         DAG.getConstant(4, FIPtr.getValueType()));
5396     MPI = MachinePointerInfo();
5397   }
5398
5399   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5400                      false, false, false, 0);
5401 }
5402
5403 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5404                                            SelectionDAG &DAG) const {
5405   SDLoc dl(Op);
5406   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5407   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5408     return SDValue();
5409
5410   if (Op.getOperand(0).getValueType() == MVT::i1)
5411     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5412                        DAG.getConstantFP(1.0, Op.getValueType()),
5413                        DAG.getConstantFP(0.0, Op.getValueType()));
5414
5415   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5416          "UINT_TO_FP is supported only with FPCVT");
5417
5418   // If we have FCFIDS, then use it when converting to single-precision.
5419   // Otherwise, convert to double-precision and then round.
5420   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5421                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5422                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5423                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5424                     PPCISD::FCFIDU : PPCISD::FCFID);
5425   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5426                    MVT::f32 : MVT::f64;
5427
5428   if (Op.getOperand(0).getValueType() == MVT::i64) {
5429     SDValue SINT = Op.getOperand(0);
5430     // When converting to single-precision, we actually need to convert
5431     // to double-precision first and then round to single-precision.
5432     // To avoid double-rounding effects during that operation, we have
5433     // to prepare the input operand.  Bits that might be truncated when
5434     // converting to double-precision are replaced by a bit that won't
5435     // be lost at this stage, but is below the single-precision rounding
5436     // position.
5437     //
5438     // However, if -enable-unsafe-fp-math is in effect, accept double
5439     // rounding to avoid the extra overhead.
5440     if (Op.getValueType() == MVT::f32 &&
5441         !Subtarget.hasFPCVT() &&
5442         !DAG.getTarget().Options.UnsafeFPMath) {
5443
5444       // Twiddle input to make sure the low 11 bits are zero.  (If this
5445       // is the case, we are guaranteed the value will fit into the 53 bit
5446       // mantissa of an IEEE double-precision value without rounding.)
5447       // If any of those low 11 bits were not zero originally, make sure
5448       // bit 12 (value 2048) is set instead, so that the final rounding
5449       // to single-precision gets the correct result.
5450       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5451                                   SINT, DAG.getConstant(2047, MVT::i64));
5452       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5453                           Round, DAG.getConstant(2047, MVT::i64));
5454       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5455       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5456                           Round, DAG.getConstant(-2048, MVT::i64));
5457
5458       // However, we cannot use that value unconditionally: if the magnitude
5459       // of the input value is small, the bit-twiddling we did above might
5460       // end up visibly changing the output.  Fortunately, in that case, we
5461       // don't need to twiddle bits since the original input will convert
5462       // exactly to double-precision floating-point already.  Therefore,
5463       // construct a conditional to use the original value if the top 11
5464       // bits are all sign-bit copies, and use the rounded value computed
5465       // above otherwise.
5466       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5467                                  SINT, DAG.getConstant(53, MVT::i32));
5468       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5469                          Cond, DAG.getConstant(1, MVT::i64));
5470       Cond = DAG.getSetCC(dl, MVT::i32,
5471                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5472
5473       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5474     }
5475
5476     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5477     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5478
5479     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5480       FP = DAG.getNode(ISD::FP_ROUND, dl,
5481                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5482     return FP;
5483   }
5484
5485   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5486          "Unhandled INT_TO_FP type in custom expander!");
5487   // Since we only generate this in 64-bit mode, we can take advantage of
5488   // 64-bit registers.  In particular, sign extend the input value into the
5489   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5490   // then lfd it and fcfid it.
5491   MachineFunction &MF = DAG.getMachineFunction();
5492   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5493   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5494
5495   SDValue Ld;
5496   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5497     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5498     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5499
5500     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5501                                  MachinePointerInfo::getFixedStack(FrameIdx),
5502                                  false, false, 0);
5503
5504     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5505            "Expected an i32 store");
5506     MachineMemOperand *MMO =
5507       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5508                               MachineMemOperand::MOLoad, 4, 4);
5509     SDValue Ops[] = { Store, FIdx };
5510     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5511                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5512                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5513                                  Ops, MVT::i32, MMO);
5514   } else {
5515     assert(Subtarget.isPPC64() &&
5516            "i32->FP without LFIWAX supported only on PPC64");
5517
5518     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5519     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5520
5521     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5522                                 Op.getOperand(0));
5523
5524     // STD the extended value into the stack slot.
5525     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5526                                  MachinePointerInfo::getFixedStack(FrameIdx),
5527                                  false, false, 0);
5528
5529     // Load the value as a double.
5530     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5531                      MachinePointerInfo::getFixedStack(FrameIdx),
5532                      false, false, false, 0);
5533   }
5534
5535   // FCFID it and return it.
5536   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5537   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5538     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5539   return FP;
5540 }
5541
5542 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5543                                             SelectionDAG &DAG) const {
5544   SDLoc dl(Op);
5545   /*
5546    The rounding mode is in bits 30:31 of FPSR, and has the following
5547    settings:
5548      00 Round to nearest
5549      01 Round to 0
5550      10 Round to +inf
5551      11 Round to -inf
5552
5553   FLT_ROUNDS, on the other hand, expects the following:
5554     -1 Undefined
5555      0 Round to 0
5556      1 Round to nearest
5557      2 Round to +inf
5558      3 Round to -inf
5559
5560   To perform the conversion, we do:
5561     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5562   */
5563
5564   MachineFunction &MF = DAG.getMachineFunction();
5565   EVT VT = Op.getValueType();
5566   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5567
5568   // Save FP Control Word to register
5569   EVT NodeTys[] = {
5570     MVT::f64,    // return register
5571     MVT::Glue    // unused in this context
5572   };
5573   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5574
5575   // Save FP register to stack slot
5576   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5577   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5578   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5579                                StackSlot, MachinePointerInfo(), false, false,0);
5580
5581   // Load FP Control Word from low 32 bits of stack slot.
5582   SDValue Four = DAG.getConstant(4, PtrVT);
5583   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5584   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5585                             false, false, false, 0);
5586
5587   // Transform as necessary
5588   SDValue CWD1 =
5589     DAG.getNode(ISD::AND, dl, MVT::i32,
5590                 CWD, DAG.getConstant(3, MVT::i32));
5591   SDValue CWD2 =
5592     DAG.getNode(ISD::SRL, dl, MVT::i32,
5593                 DAG.getNode(ISD::AND, dl, MVT::i32,
5594                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5595                                         CWD, DAG.getConstant(3, MVT::i32)),
5596                             DAG.getConstant(3, MVT::i32)),
5597                 DAG.getConstant(1, MVT::i32));
5598
5599   SDValue RetVal =
5600     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5601
5602   return DAG.getNode((VT.getSizeInBits() < 16 ?
5603                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5604 }
5605
5606 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5607   EVT VT = Op.getValueType();
5608   unsigned BitWidth = VT.getSizeInBits();
5609   SDLoc dl(Op);
5610   assert(Op.getNumOperands() == 3 &&
5611          VT == Op.getOperand(1).getValueType() &&
5612          "Unexpected SHL!");
5613
5614   // Expand into a bunch of logical ops.  Note that these ops
5615   // depend on the PPC behavior for oversized shift amounts.
5616   SDValue Lo = Op.getOperand(0);
5617   SDValue Hi = Op.getOperand(1);
5618   SDValue Amt = Op.getOperand(2);
5619   EVT AmtVT = Amt.getValueType();
5620
5621   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5622                              DAG.getConstant(BitWidth, AmtVT), Amt);
5623   SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5624   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5625   SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5626   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5627                              DAG.getConstant(-BitWidth, AmtVT));
5628   SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5629   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5630   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5631   SDValue OutOps[] = { OutLo, OutHi };
5632   return DAG.getMergeValues(OutOps, dl);
5633 }
5634
5635 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5636   EVT VT = Op.getValueType();
5637   SDLoc dl(Op);
5638   unsigned BitWidth = VT.getSizeInBits();
5639   assert(Op.getNumOperands() == 3 &&
5640          VT == Op.getOperand(1).getValueType() &&
5641          "Unexpected SRL!");
5642
5643   // Expand into a bunch of logical ops.  Note that these ops
5644   // depend on the PPC behavior for oversized shift amounts.
5645   SDValue Lo = Op.getOperand(0);
5646   SDValue Hi = Op.getOperand(1);
5647   SDValue Amt = Op.getOperand(2);
5648   EVT AmtVT = Amt.getValueType();
5649
5650   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5651                              DAG.getConstant(BitWidth, AmtVT), Amt);
5652   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5653   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5654   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5655   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5656                              DAG.getConstant(-BitWidth, AmtVT));
5657   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5658   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5659   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5660   SDValue OutOps[] = { OutLo, OutHi };
5661   return DAG.getMergeValues(OutOps, dl);
5662 }
5663
5664 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5665   SDLoc dl(Op);
5666   EVT VT = Op.getValueType();
5667   unsigned BitWidth = VT.getSizeInBits();
5668   assert(Op.getNumOperands() == 3 &&
5669          VT == Op.getOperand(1).getValueType() &&
5670          "Unexpected SRA!");
5671
5672   // Expand into a bunch of logical ops, followed by a select_cc.
5673   SDValue Lo = Op.getOperand(0);
5674   SDValue Hi = Op.getOperand(1);
5675   SDValue Amt = Op.getOperand(2);
5676   EVT AmtVT = Amt.getValueType();
5677
5678   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5679                              DAG.getConstant(BitWidth, AmtVT), Amt);
5680   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5681   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5682   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5683   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5684                              DAG.getConstant(-BitWidth, AmtVT));
5685   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5686   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5687   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5688                                   Tmp4, Tmp6, ISD::SETLE);
5689   SDValue OutOps[] = { OutLo, OutHi };
5690   return DAG.getMergeValues(OutOps, dl);
5691 }
5692
5693 //===----------------------------------------------------------------------===//
5694 // Vector related lowering.
5695 //
5696
5697 /// BuildSplatI - Build a canonical splati of Val with an element size of
5698 /// SplatSize.  Cast the result to VT.
5699 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5700                              SelectionDAG &DAG, SDLoc dl) {
5701   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5702
5703   static const EVT VTys[] = { // canonical VT to use for each size.
5704     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5705   };
5706
5707   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5708
5709   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5710   if (Val == -1)
5711     SplatSize = 1;
5712
5713   EVT CanonicalVT = VTys[SplatSize-1];
5714
5715   // Build a canonical splat for this value.
5716   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5717   SmallVector<SDValue, 8> Ops;
5718   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5719   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5720   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5721 }
5722
5723 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5724 /// specified intrinsic ID.
5725 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5726                                 SelectionDAG &DAG, SDLoc dl,
5727                                 EVT DestVT = MVT::Other) {
5728   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5729   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5730                      DAG.getConstant(IID, MVT::i32), Op);
5731 }
5732
5733 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5734 /// specified intrinsic ID.
5735 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5736                                 SelectionDAG &DAG, SDLoc dl,
5737                                 EVT DestVT = MVT::Other) {
5738   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5739   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5740                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5741 }
5742
5743 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5744 /// specified intrinsic ID.
5745 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5746                                 SDValue Op2, SelectionDAG &DAG,
5747                                 SDLoc dl, EVT DestVT = MVT::Other) {
5748   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5749   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5750                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5751 }
5752
5753
5754 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5755 /// amount.  The result has the specified value type.
5756 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5757                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5758   // Force LHS/RHS to be the right type.
5759   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5760   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5761
5762   int Ops[16];
5763   for (unsigned i = 0; i != 16; ++i)
5764     Ops[i] = i + Amt;
5765   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5766   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5767 }
5768
5769 // If this is a case we can't handle, return null and let the default
5770 // expansion code take care of it.  If we CAN select this case, and if it
5771 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5772 // this case more efficiently than a constant pool load, lower it to the
5773 // sequence of ops that should be used.
5774 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5775                                              SelectionDAG &DAG) const {
5776   SDLoc dl(Op);
5777   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5778   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5779
5780   // Check if this is a splat of a constant value.
5781   APInt APSplatBits, APSplatUndef;
5782   unsigned SplatBitSize;
5783   bool HasAnyUndefs;
5784   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5785                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5786     return SDValue();
5787
5788   unsigned SplatBits = APSplatBits.getZExtValue();
5789   unsigned SplatUndef = APSplatUndef.getZExtValue();
5790   unsigned SplatSize = SplatBitSize / 8;
5791
5792   // First, handle single instruction cases.
5793
5794   // All zeros?
5795   if (SplatBits == 0) {
5796     // Canonicalize all zero vectors to be v4i32.
5797     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5798       SDValue Z = DAG.getConstant(0, MVT::i32);
5799       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5800       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5801     }
5802     return Op;
5803   }
5804
5805   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5806   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5807                     (32-SplatBitSize));
5808   if (SextVal >= -16 && SextVal <= 15)
5809     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5810
5811
5812   // Two instruction sequences.
5813
5814   // If this value is in the range [-32,30] and is even, use:
5815   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5816   // If this value is in the range [17,31] and is odd, use:
5817   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5818   // If this value is in the range [-31,-17] and is odd, use:
5819   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5820   // Note the last two are three-instruction sequences.
5821   if (SextVal >= -32 && SextVal <= 31) {
5822     // To avoid having these optimizations undone by constant folding,
5823     // we convert to a pseudo that will be expanded later into one of
5824     // the above forms.
5825     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5826     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5827               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5828     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5829     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5830     if (VT == Op.getValueType())
5831       return RetVal;
5832     else
5833       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5834   }
5835
5836   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5837   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5838   // for fneg/fabs.
5839   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5840     // Make -1 and vspltisw -1:
5841     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5842
5843     // Make the VSLW intrinsic, computing 0x8000_0000.
5844     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5845                                    OnesV, DAG, dl);
5846
5847     // xor by OnesV to invert it.
5848     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5849     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5850   }
5851
5852   // The remaining cases assume either big endian element order or
5853   // a splat-size that equates to the element size of the vector
5854   // to be built.  An example that doesn't work for little endian is
5855   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5856   // and a vector element size of 16 bits.  The code below will
5857   // produce the vector in big endian element order, which for little
5858   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5859
5860   // For now, just avoid these optimizations in that case.
5861   // FIXME: Develop correct optimizations for LE with mismatched
5862   // splat and element sizes.
5863
5864   if (Subtarget.isLittleEndian() &&
5865       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5866     return SDValue();
5867
5868   // Check to see if this is a wide variety of vsplti*, binop self cases.
5869   static const signed char SplatCsts[] = {
5870     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5871     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5872   };
5873
5874   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5875     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5876     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5877     int i = SplatCsts[idx];
5878
5879     // Figure out what shift amount will be used by altivec if shifted by i in
5880     // this splat size.
5881     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5882
5883     // vsplti + shl self.
5884     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5885       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5886       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5887         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5888         Intrinsic::ppc_altivec_vslw
5889       };
5890       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5891       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5892     }
5893
5894     // vsplti + srl 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_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5899         Intrinsic::ppc_altivec_vsrw
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 + sra 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_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5910         Intrinsic::ppc_altivec_vsraw
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 + rol self.
5917     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5918                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5919       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5920       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5921         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5922         Intrinsic::ppc_altivec_vrlw
5923       };
5924       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5925       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5926     }
5927
5928     // t = vsplti c, result = vsldoi t, t, 1
5929     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5930       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5931       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5932     }
5933     // t = vsplti c, result = vsldoi t, t, 2
5934     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5935       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5936       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5937     }
5938     // t = vsplti c, result = vsldoi t, t, 3
5939     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5940       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5941       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5942     }
5943   }
5944
5945   return SDValue();
5946 }
5947
5948 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5949 /// the specified operations to build the shuffle.
5950 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5951                                       SDValue RHS, SelectionDAG &DAG,
5952                                       SDLoc dl) {
5953   unsigned OpNum = (PFEntry >> 26) & 0x0F;
5954   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5955   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
5956
5957   enum {
5958     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5959     OP_VMRGHW,
5960     OP_VMRGLW,
5961     OP_VSPLTISW0,
5962     OP_VSPLTISW1,
5963     OP_VSPLTISW2,
5964     OP_VSPLTISW3,
5965     OP_VSLDOI4,
5966     OP_VSLDOI8,
5967     OP_VSLDOI12
5968   };
5969
5970   if (OpNum == OP_COPY) {
5971     if (LHSID == (1*9+2)*9+3) return LHS;
5972     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5973     return RHS;
5974   }
5975
5976   SDValue OpLHS, OpRHS;
5977   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5978   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5979
5980   int ShufIdxs[16];
5981   switch (OpNum) {
5982   default: llvm_unreachable("Unknown i32 permute!");
5983   case OP_VMRGHW:
5984     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
5985     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5986     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
5987     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5988     break;
5989   case OP_VMRGLW:
5990     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5991     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5992     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5993     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5994     break;
5995   case OP_VSPLTISW0:
5996     for (unsigned i = 0; i != 16; ++i)
5997       ShufIdxs[i] = (i&3)+0;
5998     break;
5999   case OP_VSPLTISW1:
6000     for (unsigned i = 0; i != 16; ++i)
6001       ShufIdxs[i] = (i&3)+4;
6002     break;
6003   case OP_VSPLTISW2:
6004     for (unsigned i = 0; i != 16; ++i)
6005       ShufIdxs[i] = (i&3)+8;
6006     break;
6007   case OP_VSPLTISW3:
6008     for (unsigned i = 0; i != 16; ++i)
6009       ShufIdxs[i] = (i&3)+12;
6010     break;
6011   case OP_VSLDOI4:
6012     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6013   case OP_VSLDOI8:
6014     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6015   case OP_VSLDOI12:
6016     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6017   }
6018   EVT VT = OpLHS.getValueType();
6019   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6020   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6021   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6022   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6023 }
6024
6025 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6026 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6027 /// return the code it can be lowered into.  Worst case, it can always be
6028 /// lowered into a vperm.
6029 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6030                                                SelectionDAG &DAG) const {
6031   SDLoc dl(Op);
6032   SDValue V1 = Op.getOperand(0);
6033   SDValue V2 = Op.getOperand(1);
6034   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6035   EVT VT = Op.getValueType();
6036   bool isLittleEndian = Subtarget.isLittleEndian();
6037
6038   // Cases that are handled by instructions that take permute immediates
6039   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6040   // selected by the instruction selector.
6041   if (V2.getOpcode() == ISD::UNDEF) {
6042     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6043         PPC::isSplatShuffleMask(SVOp, 2) ||
6044         PPC::isSplatShuffleMask(SVOp, 4) ||
6045         PPC::isVPKUWUMShuffleMask(SVOp, true, DAG) ||
6046         PPC::isVPKUHUMShuffleMask(SVOp, true, DAG) ||
6047         PPC::isVSLDOIShuffleMask(SVOp, true, DAG) != -1 ||
6048         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6049         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6050         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6051         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6052         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6053         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6054       return Op;
6055     }
6056   }
6057
6058   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6059   // and produce a fixed permutation.  If any of these match, do not lower to
6060   // VPERM.
6061   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6062   if (PPC::isVPKUWUMShuffleMask(SVOp, false, DAG) ||
6063       PPC::isVPKUHUMShuffleMask(SVOp, false, DAG) ||
6064       PPC::isVSLDOIShuffleMask(SVOp, false, DAG) != -1 ||
6065       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6066       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6067       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6068       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6069       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6070       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6071     return Op;
6072
6073   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6074   // perfect shuffle table to emit an optimal matching sequence.
6075   ArrayRef<int> PermMask = SVOp->getMask();
6076
6077   unsigned PFIndexes[4];
6078   bool isFourElementShuffle = true;
6079   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6080     unsigned EltNo = 8;   // Start out undef.
6081     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6082       if (PermMask[i*4+j] < 0)
6083         continue;   // Undef, ignore it.
6084
6085       unsigned ByteSource = PermMask[i*4+j];
6086       if ((ByteSource & 3) != j) {
6087         isFourElementShuffle = false;
6088         break;
6089       }
6090
6091       if (EltNo == 8) {
6092         EltNo = ByteSource/4;
6093       } else if (EltNo != ByteSource/4) {
6094         isFourElementShuffle = false;
6095         break;
6096       }
6097     }
6098     PFIndexes[i] = EltNo;
6099   }
6100
6101   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6102   // perfect shuffle vector to determine if it is cost effective to do this as
6103   // discrete instructions, or whether we should use a vperm.
6104   // For now, we skip this for little endian until such time as we have a
6105   // little-endian perfect shuffle table.
6106   if (isFourElementShuffle && !isLittleEndian) {
6107     // Compute the index in the perfect shuffle table.
6108     unsigned PFTableIndex =
6109       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6110
6111     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6112     unsigned Cost  = (PFEntry >> 30);
6113
6114     // Determining when to avoid vperm is tricky.  Many things affect the cost
6115     // of vperm, particularly how many times the perm mask needs to be computed.
6116     // For example, if the perm mask can be hoisted out of a loop or is already
6117     // used (perhaps because there are multiple permutes with the same shuffle
6118     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6119     // the loop requires an extra register.
6120     //
6121     // As a compromise, we only emit discrete instructions if the shuffle can be
6122     // generated in 3 or fewer operations.  When we have loop information
6123     // available, if this block is within a loop, we should avoid using vperm
6124     // for 3-operation perms and use a constant pool load instead.
6125     if (Cost < 3)
6126       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6127   }
6128
6129   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6130   // vector that will get spilled to the constant pool.
6131   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6132
6133   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6134   // that it is in input element units, not in bytes.  Convert now.
6135
6136   // For little endian, the order of the input vectors is reversed, and
6137   // the permutation mask is complemented with respect to 31.  This is
6138   // necessary to produce proper semantics with the big-endian-biased vperm
6139   // instruction.
6140   EVT EltVT = V1.getValueType().getVectorElementType();
6141   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6142
6143   SmallVector<SDValue, 16> ResultMask;
6144   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6145     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6146
6147     for (unsigned j = 0; j != BytesPerElement; ++j)
6148       if (isLittleEndian)
6149         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6150                                              MVT::i32));
6151       else
6152         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6153                                              MVT::i32));
6154   }
6155
6156   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6157                                   ResultMask);
6158   if (isLittleEndian)
6159     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6160                        V2, V1, VPermMask);
6161   else
6162     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6163                        V1, V2, VPermMask);
6164 }
6165
6166 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6167 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6168 /// information about the intrinsic.
6169 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6170                                   bool &isDot) {
6171   unsigned IntrinsicID =
6172     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6173   CompareOpc = -1;
6174   isDot = false;
6175   switch (IntrinsicID) {
6176   default: return false;
6177     // Comparison predicates.
6178   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6179   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6180   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6181   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6182   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6183   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6184   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6185   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6186   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6187   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6188   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6189   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6190   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6191
6192     // Normal Comparisons.
6193   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6194   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6195   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6196   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6197   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6198   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6199   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6200   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6201   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6202   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6203   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6204   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6205   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6206   }
6207   return true;
6208 }
6209
6210 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6211 /// lower, do it, otherwise return null.
6212 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6213                                                    SelectionDAG &DAG) const {
6214   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6215   // opcode number of the comparison.
6216   SDLoc dl(Op);
6217   int CompareOpc;
6218   bool isDot;
6219   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6220     return SDValue();    // Don't custom lower most intrinsics.
6221
6222   // If this is a non-dot comparison, make the VCMP node and we are done.
6223   if (!isDot) {
6224     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6225                               Op.getOperand(1), Op.getOperand(2),
6226                               DAG.getConstant(CompareOpc, MVT::i32));
6227     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6228   }
6229
6230   // Create the PPCISD altivec 'dot' comparison node.
6231   SDValue Ops[] = {
6232     Op.getOperand(2),  // LHS
6233     Op.getOperand(3),  // RHS
6234     DAG.getConstant(CompareOpc, MVT::i32)
6235   };
6236   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6237   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6238
6239   // Now that we have the comparison, emit a copy from the CR to a GPR.
6240   // This is flagged to the above dot comparison.
6241   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6242                                 DAG.getRegister(PPC::CR6, MVT::i32),
6243                                 CompNode.getValue(1));
6244
6245   // Unpack the result based on how the target uses it.
6246   unsigned BitNo;   // Bit # of CR6.
6247   bool InvertBit;   // Invert result?
6248   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6249   default:  // Can't happen, don't crash on invalid number though.
6250   case 0:   // Return the value of the EQ bit of CR6.
6251     BitNo = 0; InvertBit = false;
6252     break;
6253   case 1:   // Return the inverted value of the EQ bit of CR6.
6254     BitNo = 0; InvertBit = true;
6255     break;
6256   case 2:   // Return the value of the LT bit of CR6.
6257     BitNo = 2; InvertBit = false;
6258     break;
6259   case 3:   // Return the inverted value of the LT bit of CR6.
6260     BitNo = 2; InvertBit = true;
6261     break;
6262   }
6263
6264   // Shift the bit into the low position.
6265   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6266                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6267   // Isolate the bit.
6268   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6269                       DAG.getConstant(1, MVT::i32));
6270
6271   // If we are supposed to, toggle the bit.
6272   if (InvertBit)
6273     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6274                         DAG.getConstant(1, MVT::i32));
6275   return Flags;
6276 }
6277
6278 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6279                                                   SelectionDAG &DAG) const {
6280   SDLoc dl(Op);
6281   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6282   // instructions), but for smaller types, we need to first extend up to v2i32
6283   // before doing going farther.
6284   if (Op.getValueType() == MVT::v2i64) {
6285     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6286     if (ExtVT != MVT::v2i32) {
6287       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6288       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6289                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6290                                         ExtVT.getVectorElementType(), 4)));
6291       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6292       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6293                        DAG.getValueType(MVT::v2i32));
6294     }
6295
6296     return Op;
6297   }
6298
6299   return SDValue();
6300 }
6301
6302 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6303                                                    SelectionDAG &DAG) const {
6304   SDLoc dl(Op);
6305   // Create a stack slot that is 16-byte aligned.
6306   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6307   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6308   EVT PtrVT = getPointerTy();
6309   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6310
6311   // Store the input value into Value#0 of the stack slot.
6312   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6313                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6314                                false, false, 0);
6315   // Load it out.
6316   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6317                      false, false, false, 0);
6318 }
6319
6320 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6321   SDLoc dl(Op);
6322   if (Op.getValueType() == MVT::v4i32) {
6323     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6324
6325     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6326     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6327
6328     SDValue RHSSwap =   // = vrlw RHS, 16
6329       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6330
6331     // Shrinkify inputs to v8i16.
6332     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6333     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6334     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6335
6336     // Low parts multiplied together, generating 32-bit results (we ignore the
6337     // top parts).
6338     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6339                                         LHS, RHS, DAG, dl, MVT::v4i32);
6340
6341     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6342                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6343     // Shift the high parts up 16 bits.
6344     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6345                               Neg16, DAG, dl);
6346     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6347   } else if (Op.getValueType() == MVT::v8i16) {
6348     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6349
6350     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6351
6352     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6353                             LHS, RHS, Zero, DAG, dl);
6354   } else if (Op.getValueType() == MVT::v16i8) {
6355     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6356     bool isLittleEndian = Subtarget.isLittleEndian();
6357
6358     // Multiply the even 8-bit parts, producing 16-bit sums.
6359     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6360                                            LHS, RHS, DAG, dl, MVT::v8i16);
6361     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6362
6363     // Multiply the odd 8-bit parts, producing 16-bit sums.
6364     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6365                                           LHS, RHS, DAG, dl, MVT::v8i16);
6366     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6367
6368     // Merge the results together.  Because vmuleub and vmuloub are
6369     // instructions with a big-endian bias, we must reverse the
6370     // element numbering and reverse the meaning of "odd" and "even"
6371     // when generating little endian code.
6372     int Ops[16];
6373     for (unsigned i = 0; i != 8; ++i) {
6374       if (isLittleEndian) {
6375         Ops[i*2  ] = 2*i;
6376         Ops[i*2+1] = 2*i+16;
6377       } else {
6378         Ops[i*2  ] = 2*i+1;
6379         Ops[i*2+1] = 2*i+1+16;
6380       }
6381     }
6382     if (isLittleEndian)
6383       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6384     else
6385       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6386   } else {
6387     llvm_unreachable("Unknown mul to lower!");
6388   }
6389 }
6390
6391 /// LowerOperation - Provide custom lowering hooks for some operations.
6392 ///
6393 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6394   switch (Op.getOpcode()) {
6395   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6396   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6397   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6398   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6399   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6400   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6401   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6402   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6403   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6404   case ISD::VASTART:
6405     return LowerVASTART(Op, DAG, Subtarget);
6406
6407   case ISD::VAARG:
6408     return LowerVAARG(Op, DAG, Subtarget);
6409
6410   case ISD::VACOPY:
6411     return LowerVACOPY(Op, DAG, Subtarget);
6412
6413   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6414   case ISD::DYNAMIC_STACKALLOC:
6415     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6416
6417   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6418   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6419
6420   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6421   case ISD::STORE:              return LowerSTORE(Op, DAG);
6422   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6423   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6424   case ISD::FP_TO_UINT:
6425   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6426                                                        SDLoc(Op));
6427   case ISD::UINT_TO_FP:
6428   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6429   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6430
6431   // Lower 64-bit shifts.
6432   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6433   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6434   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6435
6436   // Vector-related lowering.
6437   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6438   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6439   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6440   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6441   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6442   case ISD::MUL:                return LowerMUL(Op, DAG);
6443
6444   // For counter-based loop handling.
6445   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6446
6447   // Frame & Return address.
6448   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6449   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6450   }
6451 }
6452
6453 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6454                                            SmallVectorImpl<SDValue>&Results,
6455                                            SelectionDAG &DAG) const {
6456   const TargetMachine &TM = getTargetMachine();
6457   SDLoc dl(N);
6458   switch (N->getOpcode()) {
6459   default:
6460     llvm_unreachable("Do not know how to custom type legalize this operation!");
6461   case ISD::INTRINSIC_W_CHAIN: {
6462     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6463         Intrinsic::ppc_is_decremented_ctr_nonzero)
6464       break;
6465
6466     assert(N->getValueType(0) == MVT::i1 &&
6467            "Unexpected result type for CTR decrement intrinsic");
6468     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6469     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6470     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6471                                  N->getOperand(1)); 
6472
6473     Results.push_back(NewInt);
6474     Results.push_back(NewInt.getValue(1));
6475     break;
6476   }
6477   case ISD::VAARG: {
6478     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6479         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6480       return;
6481
6482     EVT VT = N->getValueType(0);
6483
6484     if (VT == MVT::i64) {
6485       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6486
6487       Results.push_back(NewNode);
6488       Results.push_back(NewNode.getValue(1));
6489     }
6490     return;
6491   }
6492   case ISD::FP_ROUND_INREG: {
6493     assert(N->getValueType(0) == MVT::ppcf128);
6494     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6495     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6496                              MVT::f64, N->getOperand(0),
6497                              DAG.getIntPtrConstant(0));
6498     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6499                              MVT::f64, N->getOperand(0),
6500                              DAG.getIntPtrConstant(1));
6501
6502     // Add the two halves of the long double in round-to-zero mode.
6503     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6504
6505     // We know the low half is about to be thrown away, so just use something
6506     // convenient.
6507     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6508                                 FPreg, FPreg));
6509     return;
6510   }
6511   case ISD::FP_TO_SINT:
6512     // LowerFP_TO_INT() can only handle f32 and f64.
6513     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6514       return;
6515     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6516     return;
6517   }
6518 }
6519
6520
6521 //===----------------------------------------------------------------------===//
6522 //  Other Lowering Code
6523 //===----------------------------------------------------------------------===//
6524
6525 MachineBasicBlock *
6526 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6527                                     bool is64bit, unsigned BinOpcode) const {
6528   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6529   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6530
6531   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6532   MachineFunction *F = BB->getParent();
6533   MachineFunction::iterator It = BB;
6534   ++It;
6535
6536   unsigned dest = MI->getOperand(0).getReg();
6537   unsigned ptrA = MI->getOperand(1).getReg();
6538   unsigned ptrB = MI->getOperand(2).getReg();
6539   unsigned incr = MI->getOperand(3).getReg();
6540   DebugLoc dl = MI->getDebugLoc();
6541
6542   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6543   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6544   F->insert(It, loopMBB);
6545   F->insert(It, exitMBB);
6546   exitMBB->splice(exitMBB->begin(), BB,
6547                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6548   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6549
6550   MachineRegisterInfo &RegInfo = F->getRegInfo();
6551   unsigned TmpReg = (!BinOpcode) ? incr :
6552     RegInfo.createVirtualRegister(
6553        is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6554                  (const TargetRegisterClass *) &PPC::GPRCRegClass);
6555
6556   //  thisMBB:
6557   //   ...
6558   //   fallthrough --> loopMBB
6559   BB->addSuccessor(loopMBB);
6560
6561   //  loopMBB:
6562   //   l[wd]arx dest, ptr
6563   //   add r0, dest, incr
6564   //   st[wd]cx. r0, ptr
6565   //   bne- loopMBB
6566   //   fallthrough --> exitMBB
6567   BB = loopMBB;
6568   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6569     .addReg(ptrA).addReg(ptrB);
6570   if (BinOpcode)
6571     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6572   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6573     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6574   BuildMI(BB, dl, TII->get(PPC::BCC))
6575     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6576   BB->addSuccessor(loopMBB);
6577   BB->addSuccessor(exitMBB);
6578
6579   //  exitMBB:
6580   //   ...
6581   BB = exitMBB;
6582   return BB;
6583 }
6584
6585 MachineBasicBlock *
6586 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6587                                             MachineBasicBlock *BB,
6588                                             bool is8bit,    // operation
6589                                             unsigned BinOpcode) const {
6590   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6591   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6592   // In 64 bit mode we have to use 64 bits for addresses, even though the
6593   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6594   // registers without caring whether they're 32 or 64, but here we're
6595   // doing actual arithmetic on the addresses.
6596   bool is64bit = Subtarget.isPPC64();
6597   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6598
6599   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6600   MachineFunction *F = BB->getParent();
6601   MachineFunction::iterator It = BB;
6602   ++It;
6603
6604   unsigned dest = MI->getOperand(0).getReg();
6605   unsigned ptrA = MI->getOperand(1).getReg();
6606   unsigned ptrB = MI->getOperand(2).getReg();
6607   unsigned incr = MI->getOperand(3).getReg();
6608   DebugLoc dl = MI->getDebugLoc();
6609
6610   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6611   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6612   F->insert(It, loopMBB);
6613   F->insert(It, exitMBB);
6614   exitMBB->splice(exitMBB->begin(), BB,
6615                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6616   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6617
6618   MachineRegisterInfo &RegInfo = F->getRegInfo();
6619   const TargetRegisterClass *RC =
6620     is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6621               (const TargetRegisterClass *) &PPC::GPRCRegClass;
6622   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6623   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6624   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6625   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6626   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6627   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6628   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6629   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6630   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6631   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6632   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6633   unsigned Ptr1Reg;
6634   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6635
6636   //  thisMBB:
6637   //   ...
6638   //   fallthrough --> loopMBB
6639   BB->addSuccessor(loopMBB);
6640
6641   // The 4-byte load must be aligned, while a char or short may be
6642   // anywhere in the word.  Hence all this nasty bookkeeping code.
6643   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6644   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6645   //   xori shift, shift1, 24 [16]
6646   //   rlwinm ptr, ptr1, 0, 0, 29
6647   //   slw incr2, incr, shift
6648   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6649   //   slw mask, mask2, shift
6650   //  loopMBB:
6651   //   lwarx tmpDest, ptr
6652   //   add tmp, tmpDest, incr2
6653   //   andc tmp2, tmpDest, mask
6654   //   and tmp3, tmp, mask
6655   //   or tmp4, tmp3, tmp2
6656   //   stwcx. tmp4, ptr
6657   //   bne- loopMBB
6658   //   fallthrough --> exitMBB
6659   //   srw dest, tmpDest, shift
6660   if (ptrA != ZeroReg) {
6661     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6662     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6663       .addReg(ptrA).addReg(ptrB);
6664   } else {
6665     Ptr1Reg = ptrB;
6666   }
6667   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6668       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6669   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6670       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6671   if (is64bit)
6672     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6673       .addReg(Ptr1Reg).addImm(0).addImm(61);
6674   else
6675     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6676       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6677   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6678       .addReg(incr).addReg(ShiftReg);
6679   if (is8bit)
6680     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6681   else {
6682     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6683     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6684   }
6685   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6686       .addReg(Mask2Reg).addReg(ShiftReg);
6687
6688   BB = loopMBB;
6689   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6690     .addReg(ZeroReg).addReg(PtrReg);
6691   if (BinOpcode)
6692     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6693       .addReg(Incr2Reg).addReg(TmpDestReg);
6694   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6695     .addReg(TmpDestReg).addReg(MaskReg);
6696   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6697     .addReg(TmpReg).addReg(MaskReg);
6698   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6699     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6700   BuildMI(BB, dl, TII->get(PPC::STWCX))
6701     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6702   BuildMI(BB, dl, TII->get(PPC::BCC))
6703     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6704   BB->addSuccessor(loopMBB);
6705   BB->addSuccessor(exitMBB);
6706
6707   //  exitMBB:
6708   //   ...
6709   BB = exitMBB;
6710   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6711     .addReg(ShiftReg);
6712   return BB;
6713 }
6714
6715 llvm::MachineBasicBlock*
6716 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6717                                     MachineBasicBlock *MBB) const {
6718   DebugLoc DL = MI->getDebugLoc();
6719   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6720
6721   MachineFunction *MF = MBB->getParent();
6722   MachineRegisterInfo &MRI = MF->getRegInfo();
6723
6724   const BasicBlock *BB = MBB->getBasicBlock();
6725   MachineFunction::iterator I = MBB;
6726   ++I;
6727
6728   // Memory Reference
6729   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6730   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6731
6732   unsigned DstReg = MI->getOperand(0).getReg();
6733   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6734   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6735   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6736   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6737
6738   MVT PVT = getPointerTy();
6739   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6740          "Invalid Pointer Size!");
6741   // For v = setjmp(buf), we generate
6742   //
6743   // thisMBB:
6744   //  SjLjSetup mainMBB
6745   //  bl mainMBB
6746   //  v_restore = 1
6747   //  b sinkMBB
6748   //
6749   // mainMBB:
6750   //  buf[LabelOffset] = LR
6751   //  v_main = 0
6752   //
6753   // sinkMBB:
6754   //  v = phi(main, restore)
6755   //
6756
6757   MachineBasicBlock *thisMBB = MBB;
6758   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6759   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6760   MF->insert(I, mainMBB);
6761   MF->insert(I, sinkMBB);
6762
6763   MachineInstrBuilder MIB;
6764
6765   // Transfer the remainder of BB and its successor edges to sinkMBB.
6766   sinkMBB->splice(sinkMBB->begin(), MBB,
6767                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6768   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6769
6770   // Note that the structure of the jmp_buf used here is not compatible
6771   // with that used by libc, and is not designed to be. Specifically, it
6772   // stores only those 'reserved' registers that LLVM does not otherwise
6773   // understand how to spill. Also, by convention, by the time this
6774   // intrinsic is called, Clang has already stored the frame address in the
6775   // first slot of the buffer and stack address in the third. Following the
6776   // X86 target code, we'll store the jump address in the second slot. We also
6777   // need to save the TOC pointer (R2) to handle jumps between shared
6778   // libraries, and that will be stored in the fourth slot. The thread
6779   // identifier (R13) is not affected.
6780
6781   // thisMBB:
6782   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6783   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6784   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6785
6786   // Prepare IP either in reg.
6787   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6788   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6789   unsigned BufReg = MI->getOperand(1).getReg();
6790
6791   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6792     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6793             .addReg(PPC::X2)
6794             .addImm(TOCOffset)
6795             .addReg(BufReg);
6796     MIB.setMemRefs(MMOBegin, MMOEnd);
6797   }
6798
6799   // Naked functions never have a base pointer, and so we use r1. For all
6800   // other functions, this decision must be delayed until during PEI.
6801   unsigned BaseReg;
6802   if (MF->getFunction()->getAttributes().hasAttribute(
6803           AttributeSet::FunctionIndex, Attribute::Naked))
6804     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6805   else
6806     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6807
6808   MIB = BuildMI(*thisMBB, MI, DL,
6809                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6810           .addReg(BaseReg)
6811           .addImm(BPOffset)
6812           .addReg(BufReg);
6813   MIB.setMemRefs(MMOBegin, MMOEnd);
6814
6815   // Setup
6816   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6817   const PPCRegisterInfo *TRI =
6818     static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6819   MIB.addRegMask(TRI->getNoPreservedMask());
6820
6821   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6822
6823   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6824           .addMBB(mainMBB);
6825   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6826
6827   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6828   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6829
6830   // mainMBB:
6831   //  mainDstReg = 0
6832   MIB = BuildMI(mainMBB, DL,
6833     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6834
6835   // Store IP
6836   if (Subtarget.isPPC64()) {
6837     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6838             .addReg(LabelReg)
6839             .addImm(LabelOffset)
6840             .addReg(BufReg);
6841   } else {
6842     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6843             .addReg(LabelReg)
6844             .addImm(LabelOffset)
6845             .addReg(BufReg);
6846   }
6847
6848   MIB.setMemRefs(MMOBegin, MMOEnd);
6849
6850   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6851   mainMBB->addSuccessor(sinkMBB);
6852
6853   // sinkMBB:
6854   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6855           TII->get(PPC::PHI), DstReg)
6856     .addReg(mainDstReg).addMBB(mainMBB)
6857     .addReg(restoreDstReg).addMBB(thisMBB);
6858
6859   MI->eraseFromParent();
6860   return sinkMBB;
6861 }
6862
6863 MachineBasicBlock *
6864 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6865                                      MachineBasicBlock *MBB) const {
6866   DebugLoc DL = MI->getDebugLoc();
6867   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6868
6869   MachineFunction *MF = MBB->getParent();
6870   MachineRegisterInfo &MRI = MF->getRegInfo();
6871
6872   // Memory Reference
6873   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6874   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6875
6876   MVT PVT = getPointerTy();
6877   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6878          "Invalid Pointer Size!");
6879
6880   const TargetRegisterClass *RC =
6881     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6882   unsigned Tmp = MRI.createVirtualRegister(RC);
6883   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6884   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6885   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6886   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6887                   (Subtarget.isSVR4ABI() &&
6888                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6889                      PPC::R29 : PPC::R30);
6890
6891   MachineInstrBuilder MIB;
6892
6893   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6894   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6895   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6896   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6897
6898   unsigned BufReg = MI->getOperand(0).getReg();
6899
6900   // Reload FP (the jumped-to function may not have had a
6901   // frame pointer, and if so, then its r31 will be restored
6902   // as necessary).
6903   if (PVT == MVT::i64) {
6904     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6905             .addImm(0)
6906             .addReg(BufReg);
6907   } else {
6908     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6909             .addImm(0)
6910             .addReg(BufReg);
6911   }
6912   MIB.setMemRefs(MMOBegin, MMOEnd);
6913
6914   // Reload IP
6915   if (PVT == MVT::i64) {
6916     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6917             .addImm(LabelOffset)
6918             .addReg(BufReg);
6919   } else {
6920     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6921             .addImm(LabelOffset)
6922             .addReg(BufReg);
6923   }
6924   MIB.setMemRefs(MMOBegin, MMOEnd);
6925
6926   // Reload SP
6927   if (PVT == MVT::i64) {
6928     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6929             .addImm(SPOffset)
6930             .addReg(BufReg);
6931   } else {
6932     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6933             .addImm(SPOffset)
6934             .addReg(BufReg);
6935   }
6936   MIB.setMemRefs(MMOBegin, MMOEnd);
6937
6938   // Reload BP
6939   if (PVT == MVT::i64) {
6940     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
6941             .addImm(BPOffset)
6942             .addReg(BufReg);
6943   } else {
6944     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
6945             .addImm(BPOffset)
6946             .addReg(BufReg);
6947   }
6948   MIB.setMemRefs(MMOBegin, MMOEnd);
6949
6950   // Reload TOC
6951   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
6952     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6953             .addImm(TOCOffset)
6954             .addReg(BufReg);
6955
6956     MIB.setMemRefs(MMOBegin, MMOEnd);
6957   }
6958
6959   // Jump
6960   BuildMI(*MBB, MI, DL,
6961           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6962   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6963
6964   MI->eraseFromParent();
6965   return MBB;
6966 }
6967
6968 MachineBasicBlock *
6969 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6970                                                MachineBasicBlock *BB) const {
6971   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6972       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6973     return emitEHSjLjSetJmp(MI, BB);
6974   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6975              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6976     return emitEHSjLjLongJmp(MI, BB);
6977   }
6978
6979   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6980
6981   // To "insert" these instructions we actually have to insert their
6982   // control-flow patterns.
6983   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6984   MachineFunction::iterator It = BB;
6985   ++It;
6986
6987   MachineFunction *F = BB->getParent();
6988
6989   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6990                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
6991                                  MI->getOpcode() == PPC::SELECT_I4 ||
6992                                  MI->getOpcode() == PPC::SELECT_I8)) {
6993     SmallVector<MachineOperand, 2> Cond;
6994     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6995         MI->getOpcode() == PPC::SELECT_CC_I8)
6996       Cond.push_back(MI->getOperand(4));
6997     else
6998       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
6999     Cond.push_back(MI->getOperand(1));
7000
7001     DebugLoc dl = MI->getDebugLoc();
7002     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7003     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7004                       Cond, MI->getOperand(2).getReg(),
7005                       MI->getOperand(3).getReg());
7006   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7007              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7008              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7009              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7010              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7011              MI->getOpcode() == PPC::SELECT_I4 ||
7012              MI->getOpcode() == PPC::SELECT_I8 ||
7013              MI->getOpcode() == PPC::SELECT_F4 ||
7014              MI->getOpcode() == PPC::SELECT_F8 ||
7015              MI->getOpcode() == PPC::SELECT_VRRC) {
7016     // The incoming instruction knows the destination vreg to set, the
7017     // condition code register to branch on, the true/false values to
7018     // select between, and a branch opcode to use.
7019
7020     //  thisMBB:
7021     //  ...
7022     //   TrueVal = ...
7023     //   cmpTY ccX, r1, r2
7024     //   bCC copy1MBB
7025     //   fallthrough --> copy0MBB
7026     MachineBasicBlock *thisMBB = BB;
7027     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7028     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7029     DebugLoc dl = MI->getDebugLoc();
7030     F->insert(It, copy0MBB);
7031     F->insert(It, sinkMBB);
7032
7033     // Transfer the remainder of BB and its successor edges to sinkMBB.
7034     sinkMBB->splice(sinkMBB->begin(), BB,
7035                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7036     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7037
7038     // Next, add the true and fallthrough blocks as its successors.
7039     BB->addSuccessor(copy0MBB);
7040     BB->addSuccessor(sinkMBB);
7041
7042     if (MI->getOpcode() == PPC::SELECT_I4 ||
7043         MI->getOpcode() == PPC::SELECT_I8 ||
7044         MI->getOpcode() == PPC::SELECT_F4 ||
7045         MI->getOpcode() == PPC::SELECT_F8 ||
7046         MI->getOpcode() == PPC::SELECT_VRRC) {
7047       BuildMI(BB, dl, TII->get(PPC::BC))
7048         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7049     } else {
7050       unsigned SelectPred = MI->getOperand(4).getImm();
7051       BuildMI(BB, dl, TII->get(PPC::BCC))
7052         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7053     }
7054
7055     //  copy0MBB:
7056     //   %FalseValue = ...
7057     //   # fallthrough to sinkMBB
7058     BB = copy0MBB;
7059
7060     // Update machine-CFG edges
7061     BB->addSuccessor(sinkMBB);
7062
7063     //  sinkMBB:
7064     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7065     //  ...
7066     BB = sinkMBB;
7067     BuildMI(*BB, BB->begin(), dl,
7068             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7069       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7070       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7071   }
7072   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7073     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7074   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7075     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7076   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7077     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7078   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7079     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7080
7081   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7082     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7083   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7084     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7085   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7086     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7087   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7088     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7089
7090   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7091     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7092   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7093     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7094   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7095     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7096   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7097     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7098
7099   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7100     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7101   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7102     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7103   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7104     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7105   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7106     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7107
7108   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7109     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7110   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7111     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7112   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7113     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7114   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7115     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7116
7117   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7118     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7119   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7120     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7121   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7122     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7123   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7124     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7125
7126   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7127     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7128   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7129     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7130   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7131     BB = EmitAtomicBinary(MI, BB, false, 0);
7132   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7133     BB = EmitAtomicBinary(MI, BB, true, 0);
7134
7135   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7136            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7137     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7138
7139     unsigned dest   = MI->getOperand(0).getReg();
7140     unsigned ptrA   = MI->getOperand(1).getReg();
7141     unsigned ptrB   = MI->getOperand(2).getReg();
7142     unsigned oldval = MI->getOperand(3).getReg();
7143     unsigned newval = MI->getOperand(4).getReg();
7144     DebugLoc dl     = MI->getDebugLoc();
7145
7146     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7147     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7148     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7149     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7150     F->insert(It, loop1MBB);
7151     F->insert(It, loop2MBB);
7152     F->insert(It, midMBB);
7153     F->insert(It, exitMBB);
7154     exitMBB->splice(exitMBB->begin(), BB,
7155                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7156     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7157
7158     //  thisMBB:
7159     //   ...
7160     //   fallthrough --> loopMBB
7161     BB->addSuccessor(loop1MBB);
7162
7163     // loop1MBB:
7164     //   l[wd]arx dest, ptr
7165     //   cmp[wd] dest, oldval
7166     //   bne- midMBB
7167     // loop2MBB:
7168     //   st[wd]cx. newval, ptr
7169     //   bne- loopMBB
7170     //   b exitBB
7171     // midMBB:
7172     //   st[wd]cx. dest, ptr
7173     // exitBB:
7174     BB = loop1MBB;
7175     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7176       .addReg(ptrA).addReg(ptrB);
7177     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7178       .addReg(oldval).addReg(dest);
7179     BuildMI(BB, dl, TII->get(PPC::BCC))
7180       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7181     BB->addSuccessor(loop2MBB);
7182     BB->addSuccessor(midMBB);
7183
7184     BB = loop2MBB;
7185     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7186       .addReg(newval).addReg(ptrA).addReg(ptrB);
7187     BuildMI(BB, dl, TII->get(PPC::BCC))
7188       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7189     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7190     BB->addSuccessor(loop1MBB);
7191     BB->addSuccessor(exitMBB);
7192
7193     BB = midMBB;
7194     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7195       .addReg(dest).addReg(ptrA).addReg(ptrB);
7196     BB->addSuccessor(exitMBB);
7197
7198     //  exitMBB:
7199     //   ...
7200     BB = exitMBB;
7201   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7202              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7203     // We must use 64-bit registers for addresses when targeting 64-bit,
7204     // since we're actually doing arithmetic on them.  Other registers
7205     // can be 32-bit.
7206     bool is64bit = Subtarget.isPPC64();
7207     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7208
7209     unsigned dest   = MI->getOperand(0).getReg();
7210     unsigned ptrA   = MI->getOperand(1).getReg();
7211     unsigned ptrB   = MI->getOperand(2).getReg();
7212     unsigned oldval = MI->getOperand(3).getReg();
7213     unsigned newval = MI->getOperand(4).getReg();
7214     DebugLoc dl     = MI->getDebugLoc();
7215
7216     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7217     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7218     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7219     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7220     F->insert(It, loop1MBB);
7221     F->insert(It, loop2MBB);
7222     F->insert(It, midMBB);
7223     F->insert(It, exitMBB);
7224     exitMBB->splice(exitMBB->begin(), BB,
7225                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7226     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7227
7228     MachineRegisterInfo &RegInfo = F->getRegInfo();
7229     const TargetRegisterClass *RC =
7230       is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
7231                 (const TargetRegisterClass *) &PPC::GPRCRegClass;
7232     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7233     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7234     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7235     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7236     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7237     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7238     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7239     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7240     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7241     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7242     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7243     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7244     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7245     unsigned Ptr1Reg;
7246     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7247     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7248     //  thisMBB:
7249     //   ...
7250     //   fallthrough --> loopMBB
7251     BB->addSuccessor(loop1MBB);
7252
7253     // The 4-byte load must be aligned, while a char or short may be
7254     // anywhere in the word.  Hence all this nasty bookkeeping code.
7255     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7256     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7257     //   xori shift, shift1, 24 [16]
7258     //   rlwinm ptr, ptr1, 0, 0, 29
7259     //   slw newval2, newval, shift
7260     //   slw oldval2, oldval,shift
7261     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7262     //   slw mask, mask2, shift
7263     //   and newval3, newval2, mask
7264     //   and oldval3, oldval2, mask
7265     // loop1MBB:
7266     //   lwarx tmpDest, ptr
7267     //   and tmp, tmpDest, mask
7268     //   cmpw tmp, oldval3
7269     //   bne- midMBB
7270     // loop2MBB:
7271     //   andc tmp2, tmpDest, mask
7272     //   or tmp4, tmp2, newval3
7273     //   stwcx. tmp4, ptr
7274     //   bne- loop1MBB
7275     //   b exitBB
7276     // midMBB:
7277     //   stwcx. tmpDest, ptr
7278     // exitBB:
7279     //   srw dest, tmpDest, shift
7280     if (ptrA != ZeroReg) {
7281       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7282       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7283         .addReg(ptrA).addReg(ptrB);
7284     } else {
7285       Ptr1Reg = ptrB;
7286     }
7287     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7288         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7289     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7290         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7291     if (is64bit)
7292       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7293         .addReg(Ptr1Reg).addImm(0).addImm(61);
7294     else
7295       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7296         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7297     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7298         .addReg(newval).addReg(ShiftReg);
7299     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7300         .addReg(oldval).addReg(ShiftReg);
7301     if (is8bit)
7302       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7303     else {
7304       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7305       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7306         .addReg(Mask3Reg).addImm(65535);
7307     }
7308     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7309         .addReg(Mask2Reg).addReg(ShiftReg);
7310     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7311         .addReg(NewVal2Reg).addReg(MaskReg);
7312     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7313         .addReg(OldVal2Reg).addReg(MaskReg);
7314
7315     BB = loop1MBB;
7316     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7317         .addReg(ZeroReg).addReg(PtrReg);
7318     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7319         .addReg(TmpDestReg).addReg(MaskReg);
7320     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7321         .addReg(TmpReg).addReg(OldVal3Reg);
7322     BuildMI(BB, dl, TII->get(PPC::BCC))
7323         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7324     BB->addSuccessor(loop2MBB);
7325     BB->addSuccessor(midMBB);
7326
7327     BB = loop2MBB;
7328     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7329         .addReg(TmpDestReg).addReg(MaskReg);
7330     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7331         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7332     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7333         .addReg(ZeroReg).addReg(PtrReg);
7334     BuildMI(BB, dl, TII->get(PPC::BCC))
7335       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7336     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7337     BB->addSuccessor(loop1MBB);
7338     BB->addSuccessor(exitMBB);
7339
7340     BB = midMBB;
7341     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7342       .addReg(ZeroReg).addReg(PtrReg);
7343     BB->addSuccessor(exitMBB);
7344
7345     //  exitMBB:
7346     //   ...
7347     BB = exitMBB;
7348     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7349       .addReg(ShiftReg);
7350   } else if (MI->getOpcode() == PPC::FADDrtz) {
7351     // This pseudo performs an FADD with rounding mode temporarily forced
7352     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7353     // is not modeled at the SelectionDAG level.
7354     unsigned Dest = MI->getOperand(0).getReg();
7355     unsigned Src1 = MI->getOperand(1).getReg();
7356     unsigned Src2 = MI->getOperand(2).getReg();
7357     DebugLoc dl   = MI->getDebugLoc();
7358
7359     MachineRegisterInfo &RegInfo = F->getRegInfo();
7360     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7361
7362     // Save FPSCR value.
7363     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7364
7365     // Set rounding mode to round-to-zero.
7366     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7367     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7368
7369     // Perform addition.
7370     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7371
7372     // Restore FPSCR value.
7373     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7374   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7375              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7376              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7377              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7378     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7379                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7380                       PPC::ANDIo8 : PPC::ANDIo;
7381     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7382                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7383
7384     MachineRegisterInfo &RegInfo = F->getRegInfo();
7385     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7386                                                   &PPC::GPRCRegClass :
7387                                                   &PPC::G8RCRegClass);
7388
7389     DebugLoc dl   = MI->getDebugLoc();
7390     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7391       .addReg(MI->getOperand(1).getReg()).addImm(1);
7392     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7393             MI->getOperand(0).getReg())
7394       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7395   } else {
7396     llvm_unreachable("Unexpected instr type to insert");
7397   }
7398
7399   MI->eraseFromParent();   // The pseudo instruction is gone now.
7400   return BB;
7401 }
7402
7403 //===----------------------------------------------------------------------===//
7404 // Target Optimization Hooks
7405 //===----------------------------------------------------------------------===//
7406
7407 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
7408                                                DAGCombinerInfo &DCI) const {
7409   if (DCI.isAfterLegalizeVectorOps())
7410     return SDValue();
7411
7412   EVT VT = Op.getValueType();
7413
7414   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7415       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7416       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7417       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7418
7419     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7420     // For the reciprocal, we need to find the zero of the function:
7421     //   F(X) = A X - 1 [which has a zero at X = 1/A]
7422     //     =>
7423     //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
7424     //     does not require additional intermediate precision]
7425
7426     // Convergence is quadratic, so we essentially double the number of digits
7427     // correct after every iteration. The minimum architected relative
7428     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7429     // 23 digits and double has 52 digits.
7430     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7431     if (VT.getScalarType() == MVT::f64)
7432       ++Iterations;
7433
7434     SelectionDAG &DAG = DCI.DAG;
7435     SDLoc dl(Op);
7436
7437     SDValue FPOne =
7438       DAG.getConstantFP(1.0, VT.getScalarType());
7439     if (VT.isVector()) {
7440       assert(VT.getVectorNumElements() == 4 &&
7441              "Unknown vector type");
7442       FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7443                           FPOne, FPOne, FPOne, FPOne);
7444     }
7445
7446     SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
7447     DCI.AddToWorklist(Est.getNode());
7448
7449     // Newton iterations: Est = Est + Est (1 - Arg * Est)
7450     for (int i = 0; i < Iterations; ++i) {
7451       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
7452       DCI.AddToWorklist(NewEst.getNode());
7453
7454       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
7455       DCI.AddToWorklist(NewEst.getNode());
7456
7457       NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7458       DCI.AddToWorklist(NewEst.getNode());
7459
7460       Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
7461       DCI.AddToWorklist(Est.getNode());
7462     }
7463
7464     return Est;
7465   }
7466
7467   return SDValue();
7468 }
7469
7470 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
7471                                              DAGCombinerInfo &DCI) const {
7472   if (DCI.isAfterLegalizeVectorOps())
7473     return SDValue();
7474
7475   EVT VT = Op.getValueType();
7476
7477   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7478       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7479       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7480       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7481
7482     // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
7483     // For the reciprocal sqrt, we need to find the zero of the function:
7484     //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
7485     //     =>
7486     //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
7487     // As a result, we precompute A/2 prior to the iteration loop.
7488
7489     // Convergence is quadratic, so we essentially double the number of digits
7490     // correct after every iteration. The minimum architected relative
7491     // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
7492     // 23 digits and double has 52 digits.
7493     int Iterations = Subtarget.hasRecipPrec() ? 1 : 3;
7494     if (VT.getScalarType() == MVT::f64)
7495       ++Iterations;
7496
7497     SelectionDAG &DAG = DCI.DAG;
7498     SDLoc dl(Op);
7499
7500     SDValue FPThreeHalves =
7501       DAG.getConstantFP(1.5, VT.getScalarType());
7502     if (VT.isVector()) {
7503       assert(VT.getVectorNumElements() == 4 &&
7504              "Unknown vector type");
7505       FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
7506                                   FPThreeHalves, FPThreeHalves,
7507                                   FPThreeHalves, FPThreeHalves);
7508     }
7509
7510     SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
7511     DCI.AddToWorklist(Est.getNode());
7512
7513     // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
7514     // this entire sequence requires only one FP constant.
7515     SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
7516     DCI.AddToWorklist(HalfArg.getNode());
7517
7518     HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
7519     DCI.AddToWorklist(HalfArg.getNode());
7520
7521     // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
7522     for (int i = 0; i < Iterations; ++i) {
7523       SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
7524       DCI.AddToWorklist(NewEst.getNode());
7525
7526       NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
7527       DCI.AddToWorklist(NewEst.getNode());
7528
7529       NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
7530       DCI.AddToWorklist(NewEst.getNode());
7531
7532       Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
7533       DCI.AddToWorklist(Est.getNode());
7534     }
7535
7536     return Est;
7537   }
7538
7539   return SDValue();
7540 }
7541
7542 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7543                             unsigned Bytes, int Dist,
7544                             SelectionDAG &DAG) {
7545   if (VT.getSizeInBits() / 8 != Bytes)
7546     return false;
7547
7548   SDValue BaseLoc = Base->getBasePtr();
7549   if (Loc.getOpcode() == ISD::FrameIndex) {
7550     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7551       return false;
7552     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7553     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7554     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7555     int FS  = MFI->getObjectSize(FI);
7556     int BFS = MFI->getObjectSize(BFI);
7557     if (FS != BFS || FS != (int)Bytes) return false;
7558     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7559   }
7560
7561   // Handle X+C
7562   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7563       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7564     return true;
7565
7566   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7567   const GlobalValue *GV1 = nullptr;
7568   const GlobalValue *GV2 = nullptr;
7569   int64_t Offset1 = 0;
7570   int64_t Offset2 = 0;
7571   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7572   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7573   if (isGA1 && isGA2 && GV1 == GV2)
7574     return Offset1 == (Offset2 + Dist*Bytes);
7575   return false;
7576 }
7577
7578 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7579 // not enforce equality of the chain operands.
7580 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7581                             unsigned Bytes, int Dist,
7582                             SelectionDAG &DAG) {
7583   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7584     EVT VT = LS->getMemoryVT();
7585     SDValue Loc = LS->getBasePtr();
7586     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7587   }
7588
7589   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7590     EVT VT;
7591     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7592     default: return false;
7593     case Intrinsic::ppc_altivec_lvx:
7594     case Intrinsic::ppc_altivec_lvxl:
7595       VT = MVT::v4i32;
7596       break;
7597     case Intrinsic::ppc_altivec_lvebx:
7598       VT = MVT::i8;
7599       break;
7600     case Intrinsic::ppc_altivec_lvehx:
7601       VT = MVT::i16;
7602       break;
7603     case Intrinsic::ppc_altivec_lvewx:
7604       VT = MVT::i32;
7605       break;
7606     }
7607
7608     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7609   }
7610
7611   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7612     EVT VT;
7613     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7614     default: return false;
7615     case Intrinsic::ppc_altivec_stvx:
7616     case Intrinsic::ppc_altivec_stvxl:
7617       VT = MVT::v4i32;
7618       break;
7619     case Intrinsic::ppc_altivec_stvebx:
7620       VT = MVT::i8;
7621       break;
7622     case Intrinsic::ppc_altivec_stvehx:
7623       VT = MVT::i16;
7624       break;
7625     case Intrinsic::ppc_altivec_stvewx:
7626       VT = MVT::i32;
7627       break;
7628     }
7629
7630     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7631   }
7632
7633   return false;
7634 }
7635
7636 // Return true is there is a nearyby consecutive load to the one provided
7637 // (regardless of alignment). We search up and down the chain, looking though
7638 // token factors and other loads (but nothing else). As a result, a true result
7639 // indicates that it is safe to create a new consecutive load adjacent to the
7640 // load provided.
7641 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7642   SDValue Chain = LD->getChain();
7643   EVT VT = LD->getMemoryVT();
7644
7645   SmallSet<SDNode *, 16> LoadRoots;
7646   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7647   SmallSet<SDNode *, 16> Visited;
7648
7649   // First, search up the chain, branching to follow all token-factor operands.
7650   // If we find a consecutive load, then we're done, otherwise, record all
7651   // nodes just above the top-level loads and token factors.
7652   while (!Queue.empty()) {
7653     SDNode *ChainNext = Queue.pop_back_val();
7654     if (!Visited.insert(ChainNext))
7655       continue;
7656
7657     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7658       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7659         return true;
7660
7661       if (!Visited.count(ChainLD->getChain().getNode()))
7662         Queue.push_back(ChainLD->getChain().getNode());
7663     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7664       for (const SDUse &O : ChainNext->ops())
7665         if (!Visited.count(O.getNode()))
7666           Queue.push_back(O.getNode());
7667     } else
7668       LoadRoots.insert(ChainNext);
7669   }
7670
7671   // Second, search down the chain, starting from the top-level nodes recorded
7672   // in the first phase. These top-level nodes are the nodes just above all
7673   // loads and token factors. Starting with their uses, recursively look though
7674   // all loads (just the chain uses) and token factors to find a consecutive
7675   // load.
7676   Visited.clear();
7677   Queue.clear();
7678
7679   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7680        IE = LoadRoots.end(); I != IE; ++I) {
7681     Queue.push_back(*I);
7682        
7683     while (!Queue.empty()) {
7684       SDNode *LoadRoot = Queue.pop_back_val();
7685       if (!Visited.insert(LoadRoot))
7686         continue;
7687
7688       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7689         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7690           return true;
7691
7692       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7693            UE = LoadRoot->use_end(); UI != UE; ++UI)
7694         if (((isa<MemSDNode>(*UI) &&
7695             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7696             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7697           Queue.push_back(*UI);
7698     }
7699   }
7700
7701   return false;
7702 }
7703
7704 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7705                                                   DAGCombinerInfo &DCI) const {
7706   SelectionDAG &DAG = DCI.DAG;
7707   SDLoc dl(N);
7708
7709   assert(Subtarget.useCRBits() &&
7710          "Expecting to be tracking CR bits");
7711   // If we're tracking CR bits, we need to be careful that we don't have:
7712   //   trunc(binary-ops(zext(x), zext(y)))
7713   // or
7714   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7715   // such that we're unnecessarily moving things into GPRs when it would be
7716   // better to keep them in CR bits.
7717
7718   // Note that trunc here can be an actual i1 trunc, or can be the effective
7719   // truncation that comes from a setcc or select_cc.
7720   if (N->getOpcode() == ISD::TRUNCATE &&
7721       N->getValueType(0) != MVT::i1)
7722     return SDValue();
7723
7724   if (N->getOperand(0).getValueType() != MVT::i32 &&
7725       N->getOperand(0).getValueType() != MVT::i64)
7726     return SDValue();
7727
7728   if (N->getOpcode() == ISD::SETCC ||
7729       N->getOpcode() == ISD::SELECT_CC) {
7730     // If we're looking at a comparison, then we need to make sure that the
7731     // high bits (all except for the first) don't matter the result.
7732     ISD::CondCode CC =
7733       cast<CondCodeSDNode>(N->getOperand(
7734         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7735     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7736
7737     if (ISD::isSignedIntSetCC(CC)) {
7738       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7739           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7740         return SDValue();
7741     } else if (ISD::isUnsignedIntSetCC(CC)) {
7742       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7743                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7744           !DAG.MaskedValueIsZero(N->getOperand(1),
7745                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7746         return SDValue();
7747     } else {
7748       // This is neither a signed nor an unsigned comparison, just make sure
7749       // that the high bits are equal.
7750       APInt Op1Zero, Op1One;
7751       APInt Op2Zero, Op2One;
7752       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7753       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7754
7755       // We don't really care about what is known about the first bit (if
7756       // anything), so clear it in all masks prior to comparing them.
7757       Op1Zero.clearBit(0); Op1One.clearBit(0);
7758       Op2Zero.clearBit(0); Op2One.clearBit(0);
7759
7760       if (Op1Zero != Op2Zero || Op1One != Op2One)
7761         return SDValue();
7762     }
7763   }
7764
7765   // We now know that the higher-order bits are irrelevant, we just need to
7766   // make sure that all of the intermediate operations are bit operations, and
7767   // all inputs are extensions.
7768   if (N->getOperand(0).getOpcode() != ISD::AND &&
7769       N->getOperand(0).getOpcode() != ISD::OR  &&
7770       N->getOperand(0).getOpcode() != ISD::XOR &&
7771       N->getOperand(0).getOpcode() != ISD::SELECT &&
7772       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7773       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7774       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7775       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7776       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7777     return SDValue();
7778
7779   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7780       N->getOperand(1).getOpcode() != ISD::AND &&
7781       N->getOperand(1).getOpcode() != ISD::OR  &&
7782       N->getOperand(1).getOpcode() != ISD::XOR &&
7783       N->getOperand(1).getOpcode() != ISD::SELECT &&
7784       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7785       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7786       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7787       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7788       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7789     return SDValue();
7790
7791   SmallVector<SDValue, 4> Inputs;
7792   SmallVector<SDValue, 8> BinOps, PromOps;
7793   SmallPtrSet<SDNode *, 16> Visited;
7794
7795   for (unsigned i = 0; i < 2; ++i) {
7796     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7797           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7798           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7799           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7800         isa<ConstantSDNode>(N->getOperand(i)))
7801       Inputs.push_back(N->getOperand(i));
7802     else
7803       BinOps.push_back(N->getOperand(i));
7804
7805     if (N->getOpcode() == ISD::TRUNCATE)
7806       break;
7807   }
7808
7809   // Visit all inputs, collect all binary operations (and, or, xor and
7810   // select) that are all fed by extensions. 
7811   while (!BinOps.empty()) {
7812     SDValue BinOp = BinOps.back();
7813     BinOps.pop_back();
7814
7815     if (!Visited.insert(BinOp.getNode()))
7816       continue;
7817
7818     PromOps.push_back(BinOp);
7819
7820     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7821       // The condition of the select is not promoted.
7822       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7823         continue;
7824       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7825         continue;
7826
7827       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7828             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7829             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7830            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7831           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7832         Inputs.push_back(BinOp.getOperand(i)); 
7833       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7834                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7835                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7836                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7837                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7838                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7839                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7840                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7841                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7842         BinOps.push_back(BinOp.getOperand(i));
7843       } else {
7844         // We have an input that is not an extension or another binary
7845         // operation; we'll abort this transformation.
7846         return SDValue();
7847       }
7848     }
7849   }
7850
7851   // Make sure that this is a self-contained cluster of operations (which
7852   // is not quite the same thing as saying that everything has only one
7853   // use).
7854   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7855     if (isa<ConstantSDNode>(Inputs[i]))
7856       continue;
7857
7858     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7859                               UE = Inputs[i].getNode()->use_end();
7860          UI != UE; ++UI) {
7861       SDNode *User = *UI;
7862       if (User != N && !Visited.count(User))
7863         return SDValue();
7864
7865       // Make sure that we're not going to promote the non-output-value
7866       // operand(s) or SELECT or SELECT_CC.
7867       // FIXME: Although we could sometimes handle this, and it does occur in
7868       // practice that one of the condition inputs to the select is also one of
7869       // the outputs, we currently can't deal with this.
7870       if (User->getOpcode() == ISD::SELECT) {
7871         if (User->getOperand(0) == Inputs[i])
7872           return SDValue();
7873       } else if (User->getOpcode() == ISD::SELECT_CC) {
7874         if (User->getOperand(0) == Inputs[i] ||
7875             User->getOperand(1) == Inputs[i])
7876           return SDValue();
7877       }
7878     }
7879   }
7880
7881   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7882     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7883                               UE = PromOps[i].getNode()->use_end();
7884          UI != UE; ++UI) {
7885       SDNode *User = *UI;
7886       if (User != N && !Visited.count(User))
7887         return SDValue();
7888
7889       // Make sure that we're not going to promote the non-output-value
7890       // operand(s) or SELECT or SELECT_CC.
7891       // FIXME: Although we could sometimes handle this, and it does occur in
7892       // practice that one of the condition inputs to the select is also one of
7893       // the outputs, we currently can't deal with this.
7894       if (User->getOpcode() == ISD::SELECT) {
7895         if (User->getOperand(0) == PromOps[i])
7896           return SDValue();
7897       } else if (User->getOpcode() == ISD::SELECT_CC) {
7898         if (User->getOperand(0) == PromOps[i] ||
7899             User->getOperand(1) == PromOps[i])
7900           return SDValue();
7901       }
7902     }
7903   }
7904
7905   // Replace all inputs with the extension operand.
7906   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7907     // Constants may have users outside the cluster of to-be-promoted nodes,
7908     // and so we need to replace those as we do the promotions.
7909     if (isa<ConstantSDNode>(Inputs[i]))
7910       continue;
7911     else
7912       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
7913   }
7914
7915   // Replace all operations (these are all the same, but have a different
7916   // (i1) return type). DAG.getNode will validate that the types of
7917   // a binary operator match, so go through the list in reverse so that
7918   // we've likely promoted both operands first. Any intermediate truncations or
7919   // extensions disappear.
7920   while (!PromOps.empty()) {
7921     SDValue PromOp = PromOps.back();
7922     PromOps.pop_back();
7923
7924     if (PromOp.getOpcode() == ISD::TRUNCATE ||
7925         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
7926         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
7927         PromOp.getOpcode() == ISD::ANY_EXTEND) {
7928       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
7929           PromOp.getOperand(0).getValueType() != MVT::i1) {
7930         // The operand is not yet ready (see comment below).
7931         PromOps.insert(PromOps.begin(), PromOp);
7932         continue;
7933       }
7934
7935       SDValue RepValue = PromOp.getOperand(0);
7936       if (isa<ConstantSDNode>(RepValue))
7937         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
7938
7939       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
7940       continue;
7941     }
7942
7943     unsigned C;
7944     switch (PromOp.getOpcode()) {
7945     default:             C = 0; break;
7946     case ISD::SELECT:    C = 1; break;
7947     case ISD::SELECT_CC: C = 2; break;
7948     }
7949
7950     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
7951          PromOp.getOperand(C).getValueType() != MVT::i1) ||
7952         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
7953          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
7954       // The to-be-promoted operands of this node have not yet been
7955       // promoted (this should be rare because we're going through the
7956       // list backward, but if one of the operands has several users in
7957       // this cluster of to-be-promoted nodes, it is possible).
7958       PromOps.insert(PromOps.begin(), PromOp);
7959       continue;
7960     }
7961
7962     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
7963                                 PromOp.getNode()->op_end());
7964
7965     // If there are any constant inputs, make sure they're replaced now.
7966     for (unsigned i = 0; i < 2; ++i)
7967       if (isa<ConstantSDNode>(Ops[C+i]))
7968         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
7969
7970     DAG.ReplaceAllUsesOfValueWith(PromOp,
7971       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
7972   }
7973
7974   // Now we're left with the initial truncation itself.
7975   if (N->getOpcode() == ISD::TRUNCATE)
7976     return N->getOperand(0);
7977
7978   // Otherwise, this is a comparison. The operands to be compared have just
7979   // changed type (to i1), but everything else is the same.
7980   return SDValue(N, 0);
7981 }
7982
7983 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
7984                                                   DAGCombinerInfo &DCI) const {
7985   SelectionDAG &DAG = DCI.DAG;
7986   SDLoc dl(N);
7987
7988   // If we're tracking CR bits, we need to be careful that we don't have:
7989   //   zext(binary-ops(trunc(x), trunc(y)))
7990   // or
7991   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
7992   // such that we're unnecessarily moving things into CR bits that can more
7993   // efficiently stay in GPRs. Note that if we're not certain that the high
7994   // bits are set as required by the final extension, we still may need to do
7995   // some masking to get the proper behavior.
7996
7997   // This same functionality is important on PPC64 when dealing with
7998   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
7999   // the return values of functions. Because it is so similar, it is handled
8000   // here as well.
8001
8002   if (N->getValueType(0) != MVT::i32 &&
8003       N->getValueType(0) != MVT::i64)
8004     return SDValue();
8005
8006   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8007         Subtarget.useCRBits()) ||
8008        (N->getOperand(0).getValueType() == MVT::i32 &&
8009         Subtarget.isPPC64())))
8010     return SDValue();
8011
8012   if (N->getOperand(0).getOpcode() != ISD::AND &&
8013       N->getOperand(0).getOpcode() != ISD::OR  &&
8014       N->getOperand(0).getOpcode() != ISD::XOR &&
8015       N->getOperand(0).getOpcode() != ISD::SELECT &&
8016       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8017     return SDValue();
8018
8019   SmallVector<SDValue, 4> Inputs;
8020   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8021   SmallPtrSet<SDNode *, 16> Visited;
8022
8023   // Visit all inputs, collect all binary operations (and, or, xor and
8024   // select) that are all fed by truncations. 
8025   while (!BinOps.empty()) {
8026     SDValue BinOp = BinOps.back();
8027     BinOps.pop_back();
8028
8029     if (!Visited.insert(BinOp.getNode()))
8030       continue;
8031
8032     PromOps.push_back(BinOp);
8033
8034     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8035       // The condition of the select is not promoted.
8036       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8037         continue;
8038       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8039         continue;
8040
8041       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8042           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8043         Inputs.push_back(BinOp.getOperand(i)); 
8044       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8045                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8046                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8047                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8048                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8049         BinOps.push_back(BinOp.getOperand(i));
8050       } else {
8051         // We have an input that is not a truncation or another binary
8052         // operation; we'll abort this transformation.
8053         return SDValue();
8054       }
8055     }
8056   }
8057
8058   // Make sure that this is a self-contained cluster of operations (which
8059   // is not quite the same thing as saying that everything has only one
8060   // use).
8061   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8062     if (isa<ConstantSDNode>(Inputs[i]))
8063       continue;
8064
8065     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8066                               UE = Inputs[i].getNode()->use_end();
8067          UI != UE; ++UI) {
8068       SDNode *User = *UI;
8069       if (User != N && !Visited.count(User))
8070         return SDValue();
8071
8072       // Make sure that we're not going to promote the non-output-value
8073       // operand(s) or SELECT or SELECT_CC.
8074       // FIXME: Although we could sometimes handle this, and it does occur in
8075       // practice that one of the condition inputs to the select is also one of
8076       // the outputs, we currently can't deal with this.
8077       if (User->getOpcode() == ISD::SELECT) {
8078         if (User->getOperand(0) == Inputs[i])
8079           return SDValue();
8080       } else if (User->getOpcode() == ISD::SELECT_CC) {
8081         if (User->getOperand(0) == Inputs[i] ||
8082             User->getOperand(1) == Inputs[i])
8083           return SDValue();
8084       }
8085     }
8086   }
8087
8088   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8089     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8090                               UE = PromOps[i].getNode()->use_end();
8091          UI != UE; ++UI) {
8092       SDNode *User = *UI;
8093       if (User != N && !Visited.count(User))
8094         return SDValue();
8095
8096       // Make sure that we're not going to promote the non-output-value
8097       // operand(s) or SELECT or SELECT_CC.
8098       // FIXME: Although we could sometimes handle this, and it does occur in
8099       // practice that one of the condition inputs to the select is also one of
8100       // the outputs, we currently can't deal with this.
8101       if (User->getOpcode() == ISD::SELECT) {
8102         if (User->getOperand(0) == PromOps[i])
8103           return SDValue();
8104       } else if (User->getOpcode() == ISD::SELECT_CC) {
8105         if (User->getOperand(0) == PromOps[i] ||
8106             User->getOperand(1) == PromOps[i])
8107           return SDValue();
8108       }
8109     }
8110   }
8111
8112   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8113   bool ReallyNeedsExt = false;
8114   if (N->getOpcode() != ISD::ANY_EXTEND) {
8115     // If all of the inputs are not already sign/zero extended, then
8116     // we'll still need to do that at the end.
8117     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8118       if (isa<ConstantSDNode>(Inputs[i]))
8119         continue;
8120
8121       unsigned OpBits =
8122         Inputs[i].getOperand(0).getValueSizeInBits();
8123       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8124
8125       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8126            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8127                                   APInt::getHighBitsSet(OpBits,
8128                                                         OpBits-PromBits))) ||
8129           (N->getOpcode() == ISD::SIGN_EXTEND &&
8130            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8131              (OpBits-(PromBits-1)))) {
8132         ReallyNeedsExt = true;
8133         break;
8134       }
8135     }
8136   }
8137
8138   // Replace all inputs, either with the truncation operand, or a
8139   // truncation or extension to the final output type.
8140   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8141     // Constant inputs need to be replaced with the to-be-promoted nodes that
8142     // use them because they might have users outside of the cluster of
8143     // promoted nodes.
8144     if (isa<ConstantSDNode>(Inputs[i]))
8145       continue;
8146
8147     SDValue InSrc = Inputs[i].getOperand(0);
8148     if (Inputs[i].getValueType() == N->getValueType(0))
8149       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8150     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8151       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8152         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8153     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8154       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8155         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8156     else
8157       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8158         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8159   }
8160
8161   // Replace all operations (these are all the same, but have a different
8162   // (promoted) return type). DAG.getNode will validate that the types of
8163   // a binary operator match, so go through the list in reverse so that
8164   // we've likely promoted both operands first.
8165   while (!PromOps.empty()) {
8166     SDValue PromOp = PromOps.back();
8167     PromOps.pop_back();
8168
8169     unsigned C;
8170     switch (PromOp.getOpcode()) {
8171     default:             C = 0; break;
8172     case ISD::SELECT:    C = 1; break;
8173     case ISD::SELECT_CC: C = 2; break;
8174     }
8175
8176     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8177          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8178         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8179          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8180       // The to-be-promoted operands of this node have not yet been
8181       // promoted (this should be rare because we're going through the
8182       // list backward, but if one of the operands has several users in
8183       // this cluster of to-be-promoted nodes, it is possible).
8184       PromOps.insert(PromOps.begin(), PromOp);
8185       continue;
8186     }
8187
8188     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8189                                 PromOp.getNode()->op_end());
8190
8191     // If this node has constant inputs, then they'll need to be promoted here.
8192     for (unsigned i = 0; i < 2; ++i) {
8193       if (!isa<ConstantSDNode>(Ops[C+i]))
8194         continue;
8195       if (Ops[C+i].getValueType() == N->getValueType(0))
8196         continue;
8197
8198       if (N->getOpcode() == ISD::SIGN_EXTEND)
8199         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8200       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8201         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8202       else
8203         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8204     }
8205
8206     DAG.ReplaceAllUsesOfValueWith(PromOp,
8207       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8208   }
8209
8210   // Now we're left with the initial extension itself.
8211   if (!ReallyNeedsExt)
8212     return N->getOperand(0);
8213
8214   // To zero extend, just mask off everything except for the first bit (in the
8215   // i1 case).
8216   if (N->getOpcode() == ISD::ZERO_EXTEND)
8217     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8218                        DAG.getConstant(APInt::getLowBitsSet(
8219                                          N->getValueSizeInBits(0), PromBits),
8220                                        N->getValueType(0)));
8221
8222   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8223          "Invalid extension type");
8224   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8225   SDValue ShiftCst =
8226     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8227   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8228                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8229                                  N->getOperand(0), ShiftCst), ShiftCst);
8230 }
8231
8232 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8233                                              DAGCombinerInfo &DCI) const {
8234   const TargetMachine &TM = getTargetMachine();
8235   SelectionDAG &DAG = DCI.DAG;
8236   SDLoc dl(N);
8237   switch (N->getOpcode()) {
8238   default: break;
8239   case PPCISD::SHL:
8240     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8241       if (C->isNullValue())   // 0 << V -> 0.
8242         return N->getOperand(0);
8243     }
8244     break;
8245   case PPCISD::SRL:
8246     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8247       if (C->isNullValue())   // 0 >>u V -> 0.
8248         return N->getOperand(0);
8249     }
8250     break;
8251   case PPCISD::SRA:
8252     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8253       if (C->isNullValue() ||   //  0 >>s V -> 0.
8254           C->isAllOnesValue())    // -1 >>s V -> -1.
8255         return N->getOperand(0);
8256     }
8257     break;
8258   case ISD::SIGN_EXTEND:
8259   case ISD::ZERO_EXTEND:
8260   case ISD::ANY_EXTEND: 
8261     return DAGCombineExtBoolTrunc(N, DCI);
8262   case ISD::TRUNCATE:
8263   case ISD::SETCC:
8264   case ISD::SELECT_CC:
8265     return DAGCombineTruncBoolExt(N, DCI);
8266   case ISD::FDIV: {
8267     assert(TM.Options.UnsafeFPMath &&
8268            "Reciprocal estimates require UnsafeFPMath");
8269
8270     if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
8271       SDValue RV =
8272         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
8273       if (RV.getNode()) {
8274         DCI.AddToWorklist(RV.getNode());
8275         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8276                            N->getOperand(0), RV);
8277       }
8278     } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
8279                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8280       SDValue RV =
8281         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8282                                  DCI);
8283       if (RV.getNode()) {
8284         DCI.AddToWorklist(RV.getNode());
8285         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
8286                          N->getValueType(0), RV);
8287         DCI.AddToWorklist(RV.getNode());
8288         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8289                            N->getOperand(0), RV);
8290       }
8291     } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
8292                N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
8293       SDValue RV =
8294         DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
8295                                  DCI);
8296       if (RV.getNode()) {
8297         DCI.AddToWorklist(RV.getNode());
8298         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
8299                          N->getValueType(0), RV,
8300                          N->getOperand(1).getOperand(1));
8301         DCI.AddToWorklist(RV.getNode());
8302         return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8303                            N->getOperand(0), RV);
8304       }
8305     }
8306
8307     SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
8308     if (RV.getNode()) {
8309       DCI.AddToWorklist(RV.getNode());
8310       return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
8311                          N->getOperand(0), RV);
8312     }
8313
8314     }
8315     break;
8316   case ISD::FSQRT: {
8317     assert(TM.Options.UnsafeFPMath &&
8318            "Reciprocal estimates require UnsafeFPMath");
8319
8320     // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
8321     // reciprocal sqrt.
8322     SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
8323     if (RV.getNode()) {
8324       DCI.AddToWorklist(RV.getNode());
8325       RV = DAGCombineFastRecip(RV, DCI);
8326       if (RV.getNode()) {
8327         // Unfortunately, RV is now NaN if the input was exactly 0. Select out
8328         // this case and force the answer to 0.
8329
8330         EVT VT = RV.getValueType();
8331
8332         SDValue Zero = DAG.getConstantFP(0.0, VT.getScalarType());
8333         if (VT.isVector()) {
8334           assert(VT.getVectorNumElements() == 4 && "Unknown vector type");
8335           Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Zero, Zero, Zero, Zero);
8336         }
8337
8338         SDValue ZeroCmp =
8339           DAG.getSetCC(dl, getSetCCResultType(*DAG.getContext(), VT),
8340                        N->getOperand(0), Zero, ISD::SETEQ);
8341         DCI.AddToWorklist(ZeroCmp.getNode());
8342         DCI.AddToWorklist(RV.getNode());
8343
8344         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, dl, VT,
8345                          ZeroCmp, Zero, RV);
8346         return RV;
8347       }
8348     }
8349
8350     }
8351     break;
8352   case ISD::SINT_TO_FP:
8353     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8354       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8355         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8356         // We allow the src/dst to be either f32/f64, but the intermediate
8357         // type must be i64.
8358         if (N->getOperand(0).getValueType() == MVT::i64 &&
8359             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8360           SDValue Val = N->getOperand(0).getOperand(0);
8361           if (Val.getValueType() == MVT::f32) {
8362             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8363             DCI.AddToWorklist(Val.getNode());
8364           }
8365
8366           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8367           DCI.AddToWorklist(Val.getNode());
8368           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8369           DCI.AddToWorklist(Val.getNode());
8370           if (N->getValueType(0) == MVT::f32) {
8371             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8372                               DAG.getIntPtrConstant(0));
8373             DCI.AddToWorklist(Val.getNode());
8374           }
8375           return Val;
8376         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8377           // If the intermediate type is i32, we can avoid the load/store here
8378           // too.
8379         }
8380       }
8381     }
8382     break;
8383   case ISD::STORE:
8384     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8385     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8386         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8387         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8388         N->getOperand(1).getValueType() == MVT::i32 &&
8389         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8390       SDValue Val = N->getOperand(1).getOperand(0);
8391       if (Val.getValueType() == MVT::f32) {
8392         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8393         DCI.AddToWorklist(Val.getNode());
8394       }
8395       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8396       DCI.AddToWorklist(Val.getNode());
8397
8398       SDValue Ops[] = {
8399         N->getOperand(0), Val, N->getOperand(2),
8400         DAG.getValueType(N->getOperand(1).getValueType())
8401       };
8402
8403       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8404               DAG.getVTList(MVT::Other), Ops,
8405               cast<StoreSDNode>(N)->getMemoryVT(),
8406               cast<StoreSDNode>(N)->getMemOperand());
8407       DCI.AddToWorklist(Val.getNode());
8408       return Val;
8409     }
8410
8411     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8412     if (cast<StoreSDNode>(N)->isUnindexed() &&
8413         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8414         N->getOperand(1).getNode()->hasOneUse() &&
8415         (N->getOperand(1).getValueType() == MVT::i32 ||
8416          N->getOperand(1).getValueType() == MVT::i16 ||
8417          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8418           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8419           N->getOperand(1).getValueType() == MVT::i64))) {
8420       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8421       // Do an any-extend to 32-bits if this is a half-word input.
8422       if (BSwapOp.getValueType() == MVT::i16)
8423         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8424
8425       SDValue Ops[] = {
8426         N->getOperand(0), BSwapOp, N->getOperand(2),
8427         DAG.getValueType(N->getOperand(1).getValueType())
8428       };
8429       return
8430         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8431                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8432                                 cast<StoreSDNode>(N)->getMemOperand());
8433     }
8434     break;
8435   case ISD::LOAD: {
8436     LoadSDNode *LD = cast<LoadSDNode>(N);
8437     EVT VT = LD->getValueType(0);
8438     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8439     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8440     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8441         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8442         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8443          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8444         LD->getAlignment() < ABIAlignment) {
8445       // This is a type-legal unaligned Altivec load.
8446       SDValue Chain = LD->getChain();
8447       SDValue Ptr = LD->getBasePtr();
8448       bool isLittleEndian = Subtarget.isLittleEndian();
8449
8450       // This implements the loading of unaligned vectors as described in
8451       // the venerable Apple Velocity Engine overview. Specifically:
8452       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8453       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8454       //
8455       // The general idea is to expand a sequence of one or more unaligned
8456       // loads into an alignment-based permutation-control instruction (lvsl
8457       // or lvsr), a series of regular vector loads (which always truncate
8458       // their input address to an aligned address), and a series of
8459       // permutations.  The results of these permutations are the requested
8460       // loaded values.  The trick is that the last "extra" load is not taken
8461       // from the address you might suspect (sizeof(vector) bytes after the
8462       // last requested load), but rather sizeof(vector) - 1 bytes after the
8463       // last requested vector. The point of this is to avoid a page fault if
8464       // the base address happened to be aligned. This works because if the
8465       // base address is aligned, then adding less than a full vector length
8466       // will cause the last vector in the sequence to be (re)loaded.
8467       // Otherwise, the next vector will be fetched as you might suspect was
8468       // necessary.
8469
8470       // We might be able to reuse the permutation generation from
8471       // a different base address offset from this one by an aligned amount.
8472       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8473       // optimization later.
8474       Intrinsic::ID Intr = (isLittleEndian ?
8475                             Intrinsic::ppc_altivec_lvsr :
8476                             Intrinsic::ppc_altivec_lvsl);
8477       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8478
8479       // Create the new MMO for the new base load. It is like the original MMO,
8480       // but represents an area in memory almost twice the vector size centered
8481       // on the original address. If the address is unaligned, we might start
8482       // reading up to (sizeof(vector)-1) bytes below the address of the
8483       // original unaligned load.
8484       MachineFunction &MF = DAG.getMachineFunction();
8485       MachineMemOperand *BaseMMO =
8486         MF.getMachineMemOperand(LD->getMemOperand(),
8487                                 -LD->getMemoryVT().getStoreSize()+1,
8488                                 2*LD->getMemoryVT().getStoreSize()-1);
8489
8490       // Create the new base load.
8491       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8492                                                getPointerTy());
8493       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8494       SDValue BaseLoad =
8495         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8496                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8497                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8498
8499       // Note that the value of IncOffset (which is provided to the next
8500       // load's pointer info offset value, and thus used to calculate the
8501       // alignment), and the value of IncValue (which is actually used to
8502       // increment the pointer value) are different! This is because we
8503       // require the next load to appear to be aligned, even though it
8504       // is actually offset from the base pointer by a lesser amount.
8505       int IncOffset = VT.getSizeInBits() / 8;
8506       int IncValue = IncOffset;
8507
8508       // Walk (both up and down) the chain looking for another load at the real
8509       // (aligned) offset (the alignment of the other load does not matter in
8510       // this case). If found, then do not use the offset reduction trick, as
8511       // that will prevent the loads from being later combined (as they would
8512       // otherwise be duplicates).
8513       if (!findConsecutiveLoad(LD, DAG))
8514         --IncValue;
8515
8516       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8517       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8518
8519       MachineMemOperand *ExtraMMO =
8520         MF.getMachineMemOperand(LD->getMemOperand(),
8521                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8522       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8523       SDValue ExtraLoad =
8524         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8525                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8526                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8527
8528       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8529         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8530
8531       // Because vperm has a big-endian bias, we must reverse the order
8532       // of the input vectors and complement the permute control vector
8533       // when generating little endian code.  We have already handled the
8534       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8535       // and ExtraLoad here.
8536       SDValue Perm;
8537       if (isLittleEndian)
8538         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8539                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8540       else
8541         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8542                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8543
8544       if (VT != MVT::v4i32)
8545         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8546
8547       // The output of the permutation is our loaded result, the TokenFactor is
8548       // our new chain.
8549       DCI.CombineTo(N, Perm, TF);
8550       return SDValue(N, 0);
8551     }
8552     }
8553     break;
8554   case ISD::INTRINSIC_WO_CHAIN: {
8555     bool isLittleEndian = Subtarget.isLittleEndian();
8556     Intrinsic::ID Intr = (isLittleEndian ?
8557                           Intrinsic::ppc_altivec_lvsr :
8558                           Intrinsic::ppc_altivec_lvsl);
8559     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8560         N->getOperand(1)->getOpcode() == ISD::ADD) {
8561       SDValue Add = N->getOperand(1);
8562
8563       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8564             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8565               Add.getValueType().getScalarType().getSizeInBits()))) {
8566         SDNode *BasePtr = Add->getOperand(0).getNode();
8567         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8568              UE = BasePtr->use_end(); UI != UE; ++UI) {
8569           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8570               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8571                 Intr) {
8572             // We've found another LVSL/LVSR, and this address is an aligned
8573             // multiple of that one. The results will be the same, so use the
8574             // one we've just found instead.
8575
8576             return SDValue(*UI, 0);
8577           }
8578         }
8579       }
8580     }
8581     }
8582
8583     break;
8584   case ISD::BSWAP:
8585     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8586     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8587         N->getOperand(0).hasOneUse() &&
8588         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8589          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8590           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8591           N->getValueType(0) == MVT::i64))) {
8592       SDValue Load = N->getOperand(0);
8593       LoadSDNode *LD = cast<LoadSDNode>(Load);
8594       // Create the byte-swapping load.
8595       SDValue Ops[] = {
8596         LD->getChain(),    // Chain
8597         LD->getBasePtr(),  // Ptr
8598         DAG.getValueType(N->getValueType(0)) // VT
8599       };
8600       SDValue BSLoad =
8601         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8602                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8603                                               MVT::i64 : MVT::i32, MVT::Other),
8604                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8605
8606       // If this is an i16 load, insert the truncate.
8607       SDValue ResVal = BSLoad;
8608       if (N->getValueType(0) == MVT::i16)
8609         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8610
8611       // First, combine the bswap away.  This makes the value produced by the
8612       // load dead.
8613       DCI.CombineTo(N, ResVal);
8614
8615       // Next, combine the load away, we give it a bogus result value but a real
8616       // chain result.  The result value is dead because the bswap is dead.
8617       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8618
8619       // Return N so it doesn't get rechecked!
8620       return SDValue(N, 0);
8621     }
8622
8623     break;
8624   case PPCISD::VCMP: {
8625     // If a VCMPo node already exists with exactly the same operands as this
8626     // node, use its result instead of this node (VCMPo computes both a CR6 and
8627     // a normal output).
8628     //
8629     if (!N->getOperand(0).hasOneUse() &&
8630         !N->getOperand(1).hasOneUse() &&
8631         !N->getOperand(2).hasOneUse()) {
8632
8633       // Scan all of the users of the LHS, looking for VCMPo's that match.
8634       SDNode *VCMPoNode = nullptr;
8635
8636       SDNode *LHSN = N->getOperand(0).getNode();
8637       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8638            UI != E; ++UI)
8639         if (UI->getOpcode() == PPCISD::VCMPo &&
8640             UI->getOperand(1) == N->getOperand(1) &&
8641             UI->getOperand(2) == N->getOperand(2) &&
8642             UI->getOperand(0) == N->getOperand(0)) {
8643           VCMPoNode = *UI;
8644           break;
8645         }
8646
8647       // If there is no VCMPo node, or if the flag value has a single use, don't
8648       // transform this.
8649       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8650         break;
8651
8652       // Look at the (necessarily single) use of the flag value.  If it has a
8653       // chain, this transformation is more complex.  Note that multiple things
8654       // could use the value result, which we should ignore.
8655       SDNode *FlagUser = nullptr;
8656       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8657            FlagUser == nullptr; ++UI) {
8658         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8659         SDNode *User = *UI;
8660         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8661           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8662             FlagUser = User;
8663             break;
8664           }
8665         }
8666       }
8667
8668       // If the user is a MFOCRF instruction, we know this is safe.
8669       // Otherwise we give up for right now.
8670       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8671         return SDValue(VCMPoNode, 0);
8672     }
8673     break;
8674   }
8675   case ISD::BRCOND: {
8676     SDValue Cond = N->getOperand(1);
8677     SDValue Target = N->getOperand(2);
8678  
8679     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8680         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8681           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8682
8683       // We now need to make the intrinsic dead (it cannot be instruction
8684       // selected).
8685       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8686       assert(Cond.getNode()->hasOneUse() &&
8687              "Counter decrement has more than one use");
8688
8689       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8690                          N->getOperand(0), Target);
8691     }
8692   }
8693   break;
8694   case ISD::BR_CC: {
8695     // If this is a branch on an altivec predicate comparison, lower this so
8696     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8697     // lowering is done pre-legalize, because the legalizer lowers the predicate
8698     // compare down to code that is difficult to reassemble.
8699     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8700     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8701
8702     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8703     // value. If so, pass-through the AND to get to the intrinsic.
8704     if (LHS.getOpcode() == ISD::AND &&
8705         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8706         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8707           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8708         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8709         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8710           isZero())
8711       LHS = LHS.getOperand(0);
8712
8713     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8714         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8715           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8716         isa<ConstantSDNode>(RHS)) {
8717       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8718              "Counter decrement comparison is not EQ or NE");
8719
8720       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8721       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8722                     (CC == ISD::SETNE && !Val);
8723
8724       // We now need to make the intrinsic dead (it cannot be instruction
8725       // selected).
8726       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8727       assert(LHS.getNode()->hasOneUse() &&
8728              "Counter decrement has more than one use");
8729
8730       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8731                          N->getOperand(0), N->getOperand(4));
8732     }
8733
8734     int CompareOpc;
8735     bool isDot;
8736
8737     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8738         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8739         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8740       assert(isDot && "Can't compare against a vector result!");
8741
8742       // If this is a comparison against something other than 0/1, then we know
8743       // that the condition is never/always true.
8744       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8745       if (Val != 0 && Val != 1) {
8746         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8747           return N->getOperand(0);
8748         // Always !=, turn it into an unconditional branch.
8749         return DAG.getNode(ISD::BR, dl, MVT::Other,
8750                            N->getOperand(0), N->getOperand(4));
8751       }
8752
8753       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8754
8755       // Create the PPCISD altivec 'dot' comparison node.
8756       SDValue Ops[] = {
8757         LHS.getOperand(2),  // LHS of compare
8758         LHS.getOperand(3),  // RHS of compare
8759         DAG.getConstant(CompareOpc, MVT::i32)
8760       };
8761       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8762       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8763
8764       // Unpack the result based on how the target uses it.
8765       PPC::Predicate CompOpc;
8766       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8767       default:  // Can't happen, don't crash on invalid number though.
8768       case 0:   // Branch on the value of the EQ bit of CR6.
8769         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8770         break;
8771       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8772         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8773         break;
8774       case 2:   // Branch on the value of the LT bit of CR6.
8775         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8776         break;
8777       case 3:   // Branch on the inverted value of the LT bit of CR6.
8778         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8779         break;
8780       }
8781
8782       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8783                          DAG.getConstant(CompOpc, MVT::i32),
8784                          DAG.getRegister(PPC::CR6, MVT::i32),
8785                          N->getOperand(4), CompNode.getValue(1));
8786     }
8787     break;
8788   }
8789   }
8790
8791   return SDValue();
8792 }
8793
8794 //===----------------------------------------------------------------------===//
8795 // Inline Assembly Support
8796 //===----------------------------------------------------------------------===//
8797
8798 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
8799                                                       APInt &KnownZero,
8800                                                       APInt &KnownOne,
8801                                                       const SelectionDAG &DAG,
8802                                                       unsigned Depth) const {
8803   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
8804   switch (Op.getOpcode()) {
8805   default: break;
8806   case PPCISD::LBRX: {
8807     // lhbrx is known to have the top bits cleared out.
8808     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
8809       KnownZero = 0xFFFF0000;
8810     break;
8811   }
8812   case ISD::INTRINSIC_WO_CHAIN: {
8813     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
8814     default: break;
8815     case Intrinsic::ppc_altivec_vcmpbfp_p:
8816     case Intrinsic::ppc_altivec_vcmpeqfp_p:
8817     case Intrinsic::ppc_altivec_vcmpequb_p:
8818     case Intrinsic::ppc_altivec_vcmpequh_p:
8819     case Intrinsic::ppc_altivec_vcmpequw_p:
8820     case Intrinsic::ppc_altivec_vcmpgefp_p:
8821     case Intrinsic::ppc_altivec_vcmpgtfp_p:
8822     case Intrinsic::ppc_altivec_vcmpgtsb_p:
8823     case Intrinsic::ppc_altivec_vcmpgtsh_p:
8824     case Intrinsic::ppc_altivec_vcmpgtsw_p:
8825     case Intrinsic::ppc_altivec_vcmpgtub_p:
8826     case Intrinsic::ppc_altivec_vcmpgtuh_p:
8827     case Intrinsic::ppc_altivec_vcmpgtuw_p:
8828       KnownZero = ~1U;  // All bits but the low one are known to be zero.
8829       break;
8830     }
8831   }
8832   }
8833 }
8834
8835
8836 /// getConstraintType - Given a constraint, return the type of
8837 /// constraint it is for this target.
8838 PPCTargetLowering::ConstraintType
8839 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
8840   if (Constraint.size() == 1) {
8841     switch (Constraint[0]) {
8842     default: break;
8843     case 'b':
8844     case 'r':
8845     case 'f':
8846     case 'v':
8847     case 'y':
8848       return C_RegisterClass;
8849     case 'Z':
8850       // FIXME: While Z does indicate a memory constraint, it specifically
8851       // indicates an r+r address (used in conjunction with the 'y' modifier
8852       // in the replacement string). Currently, we're forcing the base
8853       // register to be r0 in the asm printer (which is interpreted as zero)
8854       // and forming the complete address in the second register. This is
8855       // suboptimal.
8856       return C_Memory;
8857     }
8858   } else if (Constraint == "wc") { // individual CR bits.
8859     return C_RegisterClass;
8860   } else if (Constraint == "wa" || Constraint == "wd" ||
8861              Constraint == "wf" || Constraint == "ws") {
8862     return C_RegisterClass; // VSX registers.
8863   }
8864   return TargetLowering::getConstraintType(Constraint);
8865 }
8866
8867 /// Examine constraint type and operand type and determine a weight value.
8868 /// This object must already have been set up with the operand type
8869 /// and the current alternative constraint selected.
8870 TargetLowering::ConstraintWeight
8871 PPCTargetLowering::getSingleConstraintMatchWeight(
8872     AsmOperandInfo &info, const char *constraint) const {
8873   ConstraintWeight weight = CW_Invalid;
8874   Value *CallOperandVal = info.CallOperandVal;
8875     // If we don't have a value, we can't do a match,
8876     // but allow it at the lowest weight.
8877   if (!CallOperandVal)
8878     return CW_Default;
8879   Type *type = CallOperandVal->getType();
8880
8881   // Look at the constraint type.
8882   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
8883     return CW_Register; // an individual CR bit.
8884   else if ((StringRef(constraint) == "wa" ||
8885             StringRef(constraint) == "wd" ||
8886             StringRef(constraint) == "wf") &&
8887            type->isVectorTy())
8888     return CW_Register;
8889   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
8890     return CW_Register;
8891
8892   switch (*constraint) {
8893   default:
8894     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
8895     break;
8896   case 'b':
8897     if (type->isIntegerTy())
8898       weight = CW_Register;
8899     break;
8900   case 'f':
8901     if (type->isFloatTy())
8902       weight = CW_Register;
8903     break;
8904   case 'd':
8905     if (type->isDoubleTy())
8906       weight = CW_Register;
8907     break;
8908   case 'v':
8909     if (type->isVectorTy())
8910       weight = CW_Register;
8911     break;
8912   case 'y':
8913     weight = CW_Register;
8914     break;
8915   case 'Z':
8916     weight = CW_Memory;
8917     break;
8918   }
8919   return weight;
8920 }
8921
8922 std::pair<unsigned, const TargetRegisterClass*>
8923 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8924                                                 MVT VT) const {
8925   if (Constraint.size() == 1) {
8926     // GCC RS6000 Constraint Letters
8927     switch (Constraint[0]) {
8928     case 'b':   // R1-R31
8929       if (VT == MVT::i64 && Subtarget.isPPC64())
8930         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
8931       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
8932     case 'r':   // R0-R31
8933       if (VT == MVT::i64 && Subtarget.isPPC64())
8934         return std::make_pair(0U, &PPC::G8RCRegClass);
8935       return std::make_pair(0U, &PPC::GPRCRegClass);
8936     case 'f':
8937       if (VT == MVT::f32 || VT == MVT::i32)
8938         return std::make_pair(0U, &PPC::F4RCRegClass);
8939       if (VT == MVT::f64 || VT == MVT::i64)
8940         return std::make_pair(0U, &PPC::F8RCRegClass);
8941       break;
8942     case 'v':
8943       return std::make_pair(0U, &PPC::VRRCRegClass);
8944     case 'y':   // crrc
8945       return std::make_pair(0U, &PPC::CRRCRegClass);
8946     }
8947   } else if (Constraint == "wc") { // an individual CR bit.
8948     return std::make_pair(0U, &PPC::CRBITRCRegClass);
8949   } else if (Constraint == "wa" || Constraint == "wd" ||
8950              Constraint == "wf") {
8951     return std::make_pair(0U, &PPC::VSRCRegClass);
8952   } else if (Constraint == "ws") {
8953     return std::make_pair(0U, &PPC::VSFRCRegClass);
8954   }
8955
8956   std::pair<unsigned, const TargetRegisterClass*> R =
8957     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8958
8959   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
8960   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
8961   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
8962   // register.
8963   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
8964   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
8965   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
8966       PPC::GPRCRegClass.contains(R.first)) {
8967     const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
8968     return std::make_pair(TRI->getMatchingSuperReg(R.first,
8969                             PPC::sub_32, &PPC::G8RCRegClass),
8970                           &PPC::G8RCRegClass);
8971   }
8972
8973   return R;
8974 }
8975
8976
8977 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8978 /// vector.  If it is invalid, don't add anything to Ops.
8979 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8980                                                      std::string &Constraint,
8981                                                      std::vector<SDValue>&Ops,
8982                                                      SelectionDAG &DAG) const {
8983   SDValue Result;
8984
8985   // Only support length 1 constraints.
8986   if (Constraint.length() > 1) return;
8987
8988   char Letter = Constraint[0];
8989   switch (Letter) {
8990   default: break;
8991   case 'I':
8992   case 'J':
8993   case 'K':
8994   case 'L':
8995   case 'M':
8996   case 'N':
8997   case 'O':
8998   case 'P': {
8999     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9000     if (!CST) return; // Must be an immediate to match.
9001     unsigned Value = CST->getZExtValue();
9002     switch (Letter) {
9003     default: llvm_unreachable("Unknown constraint letter!");
9004     case 'I':  // "I" is a signed 16-bit constant.
9005       if ((short)Value == (int)Value)
9006         Result = DAG.getTargetConstant(Value, Op.getValueType());
9007       break;
9008     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9009     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9010       if ((short)Value == 0)
9011         Result = DAG.getTargetConstant(Value, Op.getValueType());
9012       break;
9013     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9014       if ((Value >> 16) == 0)
9015         Result = DAG.getTargetConstant(Value, Op.getValueType());
9016       break;
9017     case 'M':  // "M" is a constant that is greater than 31.
9018       if (Value > 31)
9019         Result = DAG.getTargetConstant(Value, Op.getValueType());
9020       break;
9021     case 'N':  // "N" is a positive constant that is an exact power of two.
9022       if ((int)Value > 0 && isPowerOf2_32(Value))
9023         Result = DAG.getTargetConstant(Value, Op.getValueType());
9024       break;
9025     case 'O':  // "O" is the constant zero.
9026       if (Value == 0)
9027         Result = DAG.getTargetConstant(Value, Op.getValueType());
9028       break;
9029     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9030       if ((short)-Value == (int)-Value)
9031         Result = DAG.getTargetConstant(Value, Op.getValueType());
9032       break;
9033     }
9034     break;
9035   }
9036   }
9037
9038   if (Result.getNode()) {
9039     Ops.push_back(Result);
9040     return;
9041   }
9042
9043   // Handle standard constraint letters.
9044   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9045 }
9046
9047 // isLegalAddressingMode - Return true if the addressing mode represented
9048 // by AM is legal for this target, for a load/store of the specified type.
9049 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9050                                               Type *Ty) const {
9051   // FIXME: PPC does not allow r+i addressing modes for vectors!
9052
9053   // PPC allows a sign-extended 16-bit immediate field.
9054   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9055     return false;
9056
9057   // No global is ever allowed as a base.
9058   if (AM.BaseGV)
9059     return false;
9060
9061   // PPC only support r+r,
9062   switch (AM.Scale) {
9063   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9064     break;
9065   case 1:
9066     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9067       return false;
9068     // Otherwise we have r+r or r+i.
9069     break;
9070   case 2:
9071     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9072       return false;
9073     // Allow 2*r as r+r.
9074     break;
9075   default:
9076     // No other scales are supported.
9077     return false;
9078   }
9079
9080   return true;
9081 }
9082
9083 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9084                                            SelectionDAG &DAG) const {
9085   MachineFunction &MF = DAG.getMachineFunction();
9086   MachineFrameInfo *MFI = MF.getFrameInfo();
9087   MFI->setReturnAddressIsTaken(true);
9088
9089   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9090     return SDValue();
9091
9092   SDLoc dl(Op);
9093   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9094
9095   // Make sure the function does not optimize away the store of the RA to
9096   // the stack.
9097   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9098   FuncInfo->setLRStoreRequired();
9099   bool isPPC64 = Subtarget.isPPC64();
9100   bool isDarwinABI = Subtarget.isDarwinABI();
9101
9102   if (Depth > 0) {
9103     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9104     SDValue Offset =
9105
9106       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9107                       isPPC64? MVT::i64 : MVT::i32);
9108     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9109                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9110                                    FrameAddr, Offset),
9111                        MachinePointerInfo(), false, false, false, 0);
9112   }
9113
9114   // Just load the return address off the stack.
9115   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9116   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9117                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9118 }
9119
9120 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9121                                           SelectionDAG &DAG) const {
9122   SDLoc dl(Op);
9123   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9124
9125   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9126   bool isPPC64 = PtrVT == MVT::i64;
9127
9128   MachineFunction &MF = DAG.getMachineFunction();
9129   MachineFrameInfo *MFI = MF.getFrameInfo();
9130   MFI->setFrameAddressIsTaken(true);
9131
9132   // Naked functions never have a frame pointer, and so we use r1. For all
9133   // other functions, this decision must be delayed until during PEI.
9134   unsigned FrameReg;
9135   if (MF.getFunction()->getAttributes().hasAttribute(
9136         AttributeSet::FunctionIndex, Attribute::Naked))
9137     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9138   else
9139     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9140
9141   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9142                                          PtrVT);
9143   while (Depth--)
9144     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9145                             FrameAddr, MachinePointerInfo(), false, false,
9146                             false, 0);
9147   return FrameAddr;
9148 }
9149
9150 // FIXME? Maybe this could be a TableGen attribute on some registers and
9151 // this table could be generated automatically from RegInfo.
9152 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9153                                               EVT VT) const {
9154   bool isPPC64 = Subtarget.isPPC64();
9155   bool isDarwinABI = Subtarget.isDarwinABI();
9156
9157   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9158       (!isPPC64 && VT != MVT::i32))
9159     report_fatal_error("Invalid register global variable type");
9160
9161   bool is64Bit = isPPC64 && VT == MVT::i64;
9162   unsigned Reg = StringSwitch<unsigned>(RegName)
9163                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9164                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9165                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9166                                   (is64Bit ? PPC::X13 : PPC::R13))
9167                    .Default(0);
9168
9169   if (Reg)
9170     return Reg;
9171   report_fatal_error("Invalid register name global variable");
9172 }
9173
9174 bool
9175 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9176   // The PowerPC target isn't yet aware of offsets.
9177   return false;
9178 }
9179
9180 /// getOptimalMemOpType - Returns the target specific optimal type for load
9181 /// and store operations as a result of memset, memcpy, and memmove
9182 /// lowering. If DstAlign is zero that means it's safe to destination
9183 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9184 /// means there isn't a need to check it against alignment requirement,
9185 /// probably because the source does not need to be loaded. If 'IsMemset' is
9186 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9187 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9188 /// source is constant so it does not need to be loaded.
9189 /// It returns EVT::Other if the type should be determined using generic
9190 /// target-independent logic.
9191 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9192                                            unsigned DstAlign, unsigned SrcAlign,
9193                                            bool IsMemset, bool ZeroMemset,
9194                                            bool MemcpyStrSrc,
9195                                            MachineFunction &MF) const {
9196   if (Subtarget.isPPC64()) {
9197     return MVT::i64;
9198   } else {
9199     return MVT::i32;
9200   }
9201 }
9202
9203 /// \brief Returns true if it is beneficial to convert a load of a constant
9204 /// to just the constant itself.
9205 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9206                                                           Type *Ty) const {
9207   assert(Ty->isIntegerTy());
9208
9209   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9210   if (BitSize == 0 || BitSize > 64)
9211     return false;
9212   return true;
9213 }
9214
9215 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9216   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9217     return false;
9218   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9219   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9220   return NumBits1 == 64 && NumBits2 == 32;
9221 }
9222
9223 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9224   if (!VT1.isInteger() || !VT2.isInteger())
9225     return false;
9226   unsigned NumBits1 = VT1.getSizeInBits();
9227   unsigned NumBits2 = VT2.getSizeInBits();
9228   return NumBits1 == 64 && NumBits2 == 32;
9229 }
9230
9231 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9232   return isInt<16>(Imm) || isUInt<16>(Imm);
9233 }
9234
9235 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9236   return isInt<16>(Imm) || isUInt<16>(Imm);
9237 }
9238
9239 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9240                                                        unsigned,
9241                                                        unsigned,
9242                                                        bool *Fast) const {
9243   if (DisablePPCUnaligned)
9244     return false;
9245
9246   // PowerPC supports unaligned memory access for simple non-vector types.
9247   // Although accessing unaligned addresses is not as efficient as accessing
9248   // aligned addresses, it is generally more efficient than manual expansion,
9249   // and generally only traps for software emulation when crossing page
9250   // boundaries.
9251
9252   if (!VT.isSimple())
9253     return false;
9254
9255   if (VT.getSimpleVT().isVector()) {
9256     if (Subtarget.hasVSX()) {
9257       if (VT != MVT::v2f64 && VT != MVT::v2i64)
9258         return false;
9259     } else {
9260       return false;
9261     }
9262   }
9263
9264   if (VT == MVT::ppcf128)
9265     return false;
9266
9267   if (Fast)
9268     *Fast = true;
9269
9270   return true;
9271 }
9272
9273 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9274   VT = VT.getScalarType();
9275
9276   if (!VT.isSimple())
9277     return false;
9278
9279   switch (VT.getSimpleVT().SimpleTy) {
9280   case MVT::f32:
9281   case MVT::f64:
9282     return true;
9283   default:
9284     break;
9285   }
9286
9287   return false;
9288 }
9289
9290 bool
9291 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9292                      EVT VT , unsigned DefinedValues) const {
9293   if (VT == MVT::v2i64)
9294     return false;
9295
9296   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9297 }
9298
9299 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9300   if (DisableILPPref || Subtarget.enableMachineScheduler())
9301     return TargetLowering::getSchedulingPreference(N);
9302
9303   return Sched::ILP;
9304 }
9305
9306 // Create a fast isel object.
9307 FastISel *
9308 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9309                                   const TargetLibraryInfo *LibInfo) const {
9310   return PPC::createFastISel(FuncInfo, LibInfo);
9311 }