[PowerPC/BlockPlacement] Allow target to provide a per-loop alignment preference
[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/MachineLoopInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetOptions.h"
41 using namespace llvm;
42
43 // FIXME: Remove this once soft-float is supported.
44 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
45 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
46
47 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
48 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
49
50 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
51 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
52
53 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
54 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
55
56 // FIXME: Remove this once the bug has been fixed!
57 extern cl::opt<bool> ANDIGlueBug;
58
59 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
60     : TargetLowering(TM),
61       Subtarget(*TM.getSubtargetImpl()) {
62   // Use _setjmp/_longjmp instead of setjmp/longjmp.
63   setUseUnderscoreSetJmp(true);
64   setUseUnderscoreLongJmp(true);
65
66   // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
67   // arguments are at least 4/8 bytes aligned.
68   bool isPPC64 = Subtarget.isPPC64();
69   setMinStackArgumentAlignment(isPPC64 ? 8:4);
70
71   // Set up the register classes.
72   addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
73   addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
74   addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
75
76   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
77   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
78   setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
79
80   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
81
82   // PowerPC has pre-inc load and store's.
83   setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
84   setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
85   setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
86   setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
87   setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
88   setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
89   setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
90   setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
91   setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
92   setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
93
94   if (Subtarget.useCRBits()) {
95     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
96
97     if (isPPC64 || Subtarget.hasFPCVT()) {
98       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
99       AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
100                          isPPC64 ? MVT::i64 : MVT::i32);
101       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
102       AddPromotedToType (ISD::UINT_TO_FP, MVT::i1, 
103                          isPPC64 ? MVT::i64 : MVT::i32);
104     } else {
105       setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
106       setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
107     }
108
109     // PowerPC does not support direct load / store of condition registers
110     setOperationAction(ISD::LOAD, MVT::i1, Custom);
111     setOperationAction(ISD::STORE, MVT::i1, Custom);
112
113     // FIXME: Remove this once the ANDI glue bug is fixed:
114     if (ANDIGlueBug)
115       setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
116
117     setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
118     setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119     setTruncStoreAction(MVT::i64, MVT::i1, Expand);
120     setTruncStoreAction(MVT::i32, MVT::i1, Expand);
121     setTruncStoreAction(MVT::i16, MVT::i1, Expand);
122     setTruncStoreAction(MVT::i8, MVT::i1, Expand);
123
124     addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
125   }
126
127   // This is used in the ppcf128->int sequence.  Note it has different semantics
128   // from FP_ROUND:  that rounds to nearest, this rounds to zero.
129   setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
130
131   // We do not currently implement these libm ops for PowerPC.
132   setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
133   setOperationAction(ISD::FCEIL,  MVT::ppcf128, Expand);
134   setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
135   setOperationAction(ISD::FRINT,  MVT::ppcf128, Expand);
136   setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
137   setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
138
139   // PowerPC has no SREM/UREM instructions
140   setOperationAction(ISD::SREM, MVT::i32, Expand);
141   setOperationAction(ISD::UREM, MVT::i32, Expand);
142   setOperationAction(ISD::SREM, MVT::i64, Expand);
143   setOperationAction(ISD::UREM, MVT::i64, Expand);
144
145   // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
146   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
147   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
148   setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
149   setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
150   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
151   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
152   setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
153   setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
154
155   // We don't support sin/cos/sqrt/fmod/pow
156   setOperationAction(ISD::FSIN , MVT::f64, Expand);
157   setOperationAction(ISD::FCOS , MVT::f64, Expand);
158   setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
159   setOperationAction(ISD::FREM , MVT::f64, Expand);
160   setOperationAction(ISD::FPOW , MVT::f64, Expand);
161   setOperationAction(ISD::FMA  , MVT::f64, Legal);
162   setOperationAction(ISD::FSIN , MVT::f32, Expand);
163   setOperationAction(ISD::FCOS , MVT::f32, Expand);
164   setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
165   setOperationAction(ISD::FREM , MVT::f32, Expand);
166   setOperationAction(ISD::FPOW , MVT::f32, Expand);
167   setOperationAction(ISD::FMA  , MVT::f32, Legal);
168
169   setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
170
171   // If we're enabling GP optimizations, use hardware square root
172   if (!Subtarget.hasFSQRT() &&
173       !(TM.Options.UnsafeFPMath &&
174         Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
175     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
176
177   if (!Subtarget.hasFSQRT() &&
178       !(TM.Options.UnsafeFPMath &&
179         Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
180     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
181
182   if (Subtarget.hasFCPSGN()) {
183     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
184     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
185   } else {
186     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
187     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
188   }
189
190   if (Subtarget.hasFPRND()) {
191     setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
192     setOperationAction(ISD::FCEIL,  MVT::f64, Legal);
193     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
194     setOperationAction(ISD::FROUND, MVT::f64, Legal);
195
196     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
197     setOperationAction(ISD::FCEIL,  MVT::f32, Legal);
198     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
199     setOperationAction(ISD::FROUND, MVT::f32, Legal);
200   }
201
202   // PowerPC does not have BSWAP, CTPOP or CTTZ
203   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
204   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
205   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
206   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
207   setOperationAction(ISD::BSWAP, MVT::i64  , Expand);
208   setOperationAction(ISD::CTTZ , MVT::i64  , Expand);
209   setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
210   setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
211
212   if (Subtarget.hasPOPCNTD()) {
213     setOperationAction(ISD::CTPOP, MVT::i32  , Legal);
214     setOperationAction(ISD::CTPOP, MVT::i64  , Legal);
215   } else {
216     setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
217     setOperationAction(ISD::CTPOP, MVT::i64  , Expand);
218   }
219
220   // PowerPC does not have ROTR
221   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
222   setOperationAction(ISD::ROTR, MVT::i64   , Expand);
223
224   if (!Subtarget.useCRBits()) {
225     // PowerPC does not have Select
226     setOperationAction(ISD::SELECT, MVT::i32, Expand);
227     setOperationAction(ISD::SELECT, MVT::i64, Expand);
228     setOperationAction(ISD::SELECT, MVT::f32, Expand);
229     setOperationAction(ISD::SELECT, MVT::f64, Expand);
230   }
231
232   // PowerPC wants to turn select_cc of FP into fsel when possible.
233   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
234   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
235
236   // PowerPC wants to optimize integer setcc a bit
237   if (!Subtarget.useCRBits())
238     setOperationAction(ISD::SETCC, MVT::i32, Custom);
239
240   // PowerPC does not have BRCOND which requires SetCC
241   if (!Subtarget.useCRBits())
242     setOperationAction(ISD::BRCOND, MVT::Other, Expand);
243
244   setOperationAction(ISD::BR_JT,  MVT::Other, Expand);
245
246   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
247   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
248
249   // PowerPC does not have [U|S]INT_TO_FP
250   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
251   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
252
253   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
254   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
255   setOperationAction(ISD::BITCAST, MVT::i64, Expand);
256   setOperationAction(ISD::BITCAST, MVT::f64, Expand);
257
258   // We cannot sextinreg(i1).  Expand to shifts.
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
260
261   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
262   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
263   // support continuation, user-level threading, and etc.. As a result, no
264   // other SjLj exception interfaces are implemented and please don't build
265   // your own exception handling based on them.
266   // LLVM/Clang supports zero-cost DWARF exception handling.
267   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
268   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
269
270   // We want to legalize GlobalAddress and ConstantPool nodes into the
271   // appropriate instructions to materialize the address.
272   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
273   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
274   setOperationAction(ISD::BlockAddress,  MVT::i32, Custom);
275   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
276   setOperationAction(ISD::JumpTable,     MVT::i32, Custom);
277   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
278   setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
279   setOperationAction(ISD::BlockAddress,  MVT::i64, Custom);
280   setOperationAction(ISD::ConstantPool,  MVT::i64, Custom);
281   setOperationAction(ISD::JumpTable,     MVT::i64, Custom);
282
283   // TRAP is legal.
284   setOperationAction(ISD::TRAP, MVT::Other, Legal);
285
286   // TRAMPOLINE is custom lowered.
287   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
288   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
289
290   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
291   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
292
293   if (Subtarget.isSVR4ABI()) {
294     if (isPPC64) {
295       // VAARG always uses double-word chunks, so promote anything smaller.
296       setOperationAction(ISD::VAARG, MVT::i1, Promote);
297       AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
298       setOperationAction(ISD::VAARG, MVT::i8, Promote);
299       AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
300       setOperationAction(ISD::VAARG, MVT::i16, Promote);
301       AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
302       setOperationAction(ISD::VAARG, MVT::i32, Promote);
303       AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
304       setOperationAction(ISD::VAARG, MVT::Other, Expand);
305     } else {
306       // VAARG is custom lowered with the 32-bit SVR4 ABI.
307       setOperationAction(ISD::VAARG, MVT::Other, Custom);
308       setOperationAction(ISD::VAARG, MVT::i64, Custom);
309     }
310   } else
311     setOperationAction(ISD::VAARG, MVT::Other, Expand);
312
313   if (Subtarget.isSVR4ABI() && !isPPC64)
314     // VACOPY is custom lowered with the 32-bit SVR4 ABI.
315     setOperationAction(ISD::VACOPY            , MVT::Other, Custom);
316   else
317     setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
318
319   // Use the default implementation.
320   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
321   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
322   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Custom);
323   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
324   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64  , Custom);
325
326   // We want to custom lower some of our intrinsics.
327   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
328
329   // To handle counter-based loop conditions.
330   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
331
332   // Comparisons that require checking two conditions.
333   setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
334   setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
335   setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
336   setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
337   setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
338   setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
339   setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
340   setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
341   setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
342   setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
343   setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
344   setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
345
346   if (Subtarget.has64BitSupport()) {
347     // They also have instructions for converting between i64 and fp.
348     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
349     setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
350     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
351     setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
352     // This is just the low 32 bits of a (signed) fp->i64 conversion.
353     // We cannot do this with Promote because i64 is not a legal type.
354     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
355
356     if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
357       setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
358   } else {
359     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
360     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
361   }
362
363   // With the instructions enabled under FPCVT, we can do everything.
364   if (Subtarget.hasFPCVT()) {
365     if (Subtarget.has64BitSupport()) {
366       setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
367       setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
368       setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
369       setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
370     }
371
372     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
373     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
374     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
375     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
376   }
377
378   if (Subtarget.use64BitRegs()) {
379     // 64-bit PowerPC implementations can support i64 types directly
380     addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
381     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
382     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
383     // 64-bit PowerPC wants to expand i128 shifts itself.
384     setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
385     setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
386     setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
387   } else {
388     // 32-bit PowerPC wants to expand i64 shifts itself.
389     setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
390     setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
391     setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
392   }
393
394   if (Subtarget.hasAltivec()) {
395     // First set operation action for all vector types to expand. Then we
396     // will selectively turn on ones that can be effectively codegen'd.
397     for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
398          i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
399       MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
400
401       // add/sub are legal for all supported vector VT's.
402       setOperationAction(ISD::ADD , VT, Legal);
403       setOperationAction(ISD::SUB , VT, Legal);
404
405       // We promote all shuffles to v16i8.
406       setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
407       AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
408
409       // We promote all non-typed operations to v4i32.
410       setOperationAction(ISD::AND   , VT, Promote);
411       AddPromotedToType (ISD::AND   , VT, MVT::v4i32);
412       setOperationAction(ISD::OR    , VT, Promote);
413       AddPromotedToType (ISD::OR    , VT, MVT::v4i32);
414       setOperationAction(ISD::XOR   , VT, Promote);
415       AddPromotedToType (ISD::XOR   , VT, MVT::v4i32);
416       setOperationAction(ISD::LOAD  , VT, Promote);
417       AddPromotedToType (ISD::LOAD  , VT, MVT::v4i32);
418       setOperationAction(ISD::SELECT, VT, Promote);
419       AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
420       setOperationAction(ISD::STORE, VT, Promote);
421       AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
422
423       // No other operations are legal.
424       setOperationAction(ISD::MUL , VT, Expand);
425       setOperationAction(ISD::SDIV, VT, Expand);
426       setOperationAction(ISD::SREM, VT, Expand);
427       setOperationAction(ISD::UDIV, VT, Expand);
428       setOperationAction(ISD::UREM, VT, Expand);
429       setOperationAction(ISD::FDIV, VT, Expand);
430       setOperationAction(ISD::FREM, VT, Expand);
431       setOperationAction(ISD::FNEG, VT, Expand);
432       setOperationAction(ISD::FSQRT, VT, Expand);
433       setOperationAction(ISD::FLOG, VT, Expand);
434       setOperationAction(ISD::FLOG10, VT, Expand);
435       setOperationAction(ISD::FLOG2, VT, Expand);
436       setOperationAction(ISD::FEXP, VT, Expand);
437       setOperationAction(ISD::FEXP2, VT, Expand);
438       setOperationAction(ISD::FSIN, VT, Expand);
439       setOperationAction(ISD::FCOS, VT, Expand);
440       setOperationAction(ISD::FABS, VT, Expand);
441       setOperationAction(ISD::FPOWI, VT, Expand);
442       setOperationAction(ISD::FFLOOR, VT, Expand);
443       setOperationAction(ISD::FCEIL,  VT, Expand);
444       setOperationAction(ISD::FTRUNC, VT, Expand);
445       setOperationAction(ISD::FRINT,  VT, Expand);
446       setOperationAction(ISD::FNEARBYINT, VT, Expand);
447       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
448       setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
449       setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
450       setOperationAction(ISD::MULHU, VT, Expand);
451       setOperationAction(ISD::MULHS, VT, Expand);
452       setOperationAction(ISD::UMUL_LOHI, VT, Expand);
453       setOperationAction(ISD::SMUL_LOHI, VT, Expand);
454       setOperationAction(ISD::UDIVREM, VT, Expand);
455       setOperationAction(ISD::SDIVREM, VT, Expand);
456       setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
457       setOperationAction(ISD::FPOW, VT, Expand);
458       setOperationAction(ISD::BSWAP, VT, Expand);
459       setOperationAction(ISD::CTPOP, VT, Expand);
460       setOperationAction(ISD::CTLZ, VT, Expand);
461       setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
462       setOperationAction(ISD::CTTZ, VT, Expand);
463       setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
464       setOperationAction(ISD::VSELECT, VT, Expand);
465       setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
466
467       for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
468            j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
469         MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
470         setTruncStoreAction(VT, InnerVT, Expand);
471       }
472       setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
473       setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
474       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
475     }
476
477     // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
478     // with merges, splats, etc.
479     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
480
481     setOperationAction(ISD::AND   , MVT::v4i32, Legal);
482     setOperationAction(ISD::OR    , MVT::v4i32, Legal);
483     setOperationAction(ISD::XOR   , MVT::v4i32, Legal);
484     setOperationAction(ISD::LOAD  , MVT::v4i32, Legal);
485     setOperationAction(ISD::SELECT, MVT::v4i32,
486                        Subtarget.useCRBits() ? Legal : Expand);
487     setOperationAction(ISD::STORE , MVT::v4i32, Legal);
488     setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
489     setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
490     setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
491     setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
492     setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
493     setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
494     setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
495     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
496
497     addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
498     addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
499     addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
500     addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
501
502     setOperationAction(ISD::MUL, MVT::v4f32, Legal);
503     setOperationAction(ISD::FMA, MVT::v4f32, Legal);
504
505     if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
506       setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
507       setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
508     }
509
510     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
511     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
512     setOperationAction(ISD::MUL, MVT::v16i8, Custom);
513
514     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
515     setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
516
517     setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
518     setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
519     setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
520     setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
521
522     // Altivec does not contain unordered floating-point compare instructions
523     setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
524     setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
525     setCondCodeAction(ISD::SETO,   MVT::v4f32, Expand);
526     setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
527
528     if (Subtarget.hasVSX()) {
529       setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
530       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
531
532       setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
533       setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
534       setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
535       setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
536       setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
537
538       setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
539
540       setOperationAction(ISD::MUL, MVT::v2f64, Legal);
541       setOperationAction(ISD::FMA, MVT::v2f64, Legal);
542
543       setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
544       setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
545
546       setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
547       setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
548       setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
549       setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
550       setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
551
552       // Share the Altivec comparison restrictions.
553       setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
554       setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
555       setCondCodeAction(ISD::SETO,   MVT::v2f64, Expand);
556       setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
557
558       setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
559       setOperationAction(ISD::STORE, MVT::v2f64, Legal);
560
561       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
562
563       addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
564
565       addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
566       addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
567
568       // VSX v2i64 only supports non-arithmetic operations.
569       setOperationAction(ISD::ADD, MVT::v2i64, Expand);
570       setOperationAction(ISD::SUB, MVT::v2i64, Expand);
571
572       setOperationAction(ISD::SHL, MVT::v2i64, Expand);
573       setOperationAction(ISD::SRA, MVT::v2i64, Expand);
574       setOperationAction(ISD::SRL, MVT::v2i64, Expand);
575
576       setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
577
578       setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
579       AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
580       setOperationAction(ISD::STORE, MVT::v2i64, Promote);
581       AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
582
583       setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
584
585       setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
586       setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
587       setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
588       setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
589
590       // Vector operation legalization checks the result type of
591       // SIGN_EXTEND_INREG, overall legalization checks the inner type.
592       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
593       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
594       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
595       setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
596
597       addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
598     }
599   }
600
601   if (Subtarget.has64BitSupport())
602     setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
603
604   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
605
606   if (!isPPC64) {
607     setOperationAction(ISD::ATOMIC_LOAD,  MVT::i64, Expand);
608     setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
609   }
610
611   setBooleanContents(ZeroOrOneBooleanContent);
612   // Altivec instructions set fields to all zeros or all ones.
613   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
614
615   if (!isPPC64) {
616     // These libcalls are not available in 32-bit.
617     setLibcallName(RTLIB::SHL_I128, nullptr);
618     setLibcallName(RTLIB::SRL_I128, nullptr);
619     setLibcallName(RTLIB::SRA_I128, nullptr);
620   }
621
622   if (isPPC64) {
623     setStackPointerRegisterToSaveRestore(PPC::X1);
624     setExceptionPointerRegister(PPC::X3);
625     setExceptionSelectorRegister(PPC::X4);
626   } else {
627     setStackPointerRegisterToSaveRestore(PPC::R1);
628     setExceptionPointerRegister(PPC::R3);
629     setExceptionSelectorRegister(PPC::R4);
630   }
631
632   // We have target-specific dag combine patterns for the following nodes:
633   setTargetDAGCombine(ISD::SINT_TO_FP);
634   setTargetDAGCombine(ISD::LOAD);
635   setTargetDAGCombine(ISD::STORE);
636   setTargetDAGCombine(ISD::BR_CC);
637   if (Subtarget.useCRBits())
638     setTargetDAGCombine(ISD::BRCOND);
639   setTargetDAGCombine(ISD::BSWAP);
640   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
641   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
642   setTargetDAGCombine(ISD::INTRINSIC_VOID);
643
644   setTargetDAGCombine(ISD::SIGN_EXTEND);
645   setTargetDAGCombine(ISD::ZERO_EXTEND);
646   setTargetDAGCombine(ISD::ANY_EXTEND);
647
648   if (Subtarget.useCRBits()) {
649     setTargetDAGCombine(ISD::TRUNCATE);
650     setTargetDAGCombine(ISD::SETCC);
651     setTargetDAGCombine(ISD::SELECT_CC);
652   }
653
654   // Use reciprocal estimates.
655   if (TM.Options.UnsafeFPMath) {
656     setTargetDAGCombine(ISD::FDIV);
657     setTargetDAGCombine(ISD::FSQRT);
658   }
659
660   // Darwin long double math library functions have $LDBL128 appended.
661   if (Subtarget.isDarwin()) {
662     setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
663     setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
664     setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
665     setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
666     setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
667     setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
668     setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
669     setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
670     setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
671     setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
672   }
673
674   // With 32 condition bits, we don't need to sink (and duplicate) compares
675   // aggressively in CodeGenPrep.
676   if (Subtarget.useCRBits())
677     setHasMultipleConditionRegisters();
678
679   setMinFunctionAlignment(2);
680   if (Subtarget.isDarwin())
681     setPrefFunctionAlignment(4);
682
683   switch (Subtarget.getDarwinDirective()) {
684   default: break;
685   case PPC::DIR_970:
686   case PPC::DIR_A2:
687   case PPC::DIR_E500mc:
688   case PPC::DIR_E5500:
689   case PPC::DIR_PWR4:
690   case PPC::DIR_PWR5:
691   case PPC::DIR_PWR5X:
692   case PPC::DIR_PWR6:
693   case PPC::DIR_PWR6X:
694   case PPC::DIR_PWR7:
695   case PPC::DIR_PWR8:
696     setPrefFunctionAlignment(4);
697     setPrefLoopAlignment(4);
698     break;
699   }
700
701   setInsertFencesForAtomic(true);
702
703   if (Subtarget.enableMachineScheduler())
704     setSchedulingPreference(Sched::Source);
705   else
706     setSchedulingPreference(Sched::Hybrid);
707
708   computeRegisterProperties();
709
710   // The Freescale cores do better with aggressive inlining of memcpy and
711   // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
712   if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
713       Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
714     MaxStoresPerMemset = 32;
715     MaxStoresPerMemsetOptSize = 16;
716     MaxStoresPerMemcpy = 32;
717     MaxStoresPerMemcpyOptSize = 8;
718     MaxStoresPerMemmove = 32;
719     MaxStoresPerMemmoveOptSize = 8;
720   }
721 }
722
723 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
724 /// the desired ByVal argument alignment.
725 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
726                              unsigned MaxMaxAlign) {
727   if (MaxAlign == MaxMaxAlign)
728     return;
729   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
730     if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
731       MaxAlign = 32;
732     else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
733       MaxAlign = 16;
734   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
735     unsigned EltAlign = 0;
736     getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
737     if (EltAlign > MaxAlign)
738       MaxAlign = EltAlign;
739   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
740     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
741       unsigned EltAlign = 0;
742       getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
743       if (EltAlign > MaxAlign)
744         MaxAlign = EltAlign;
745       if (MaxAlign == MaxMaxAlign)
746         break;
747     }
748   }
749 }
750
751 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
752 /// function arguments in the caller parameter area.
753 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
754   // Darwin passes everything on 4 byte boundary.
755   if (Subtarget.isDarwin())
756     return 4;
757
758   // 16byte and wider vectors are passed on 16byte boundary.
759   // The rest is 8 on PPC64 and 4 on PPC32 boundary.
760   unsigned Align = Subtarget.isPPC64() ? 8 : 4;
761   if (Subtarget.hasAltivec() || Subtarget.hasQPX())
762     getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
763   return Align;
764 }
765
766 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
767   switch (Opcode) {
768   default: return nullptr;
769   case PPCISD::FSEL:            return "PPCISD::FSEL";
770   case PPCISD::FCFID:           return "PPCISD::FCFID";
771   case PPCISD::FCTIDZ:          return "PPCISD::FCTIDZ";
772   case PPCISD::FCTIWZ:          return "PPCISD::FCTIWZ";
773   case PPCISD::FRE:             return "PPCISD::FRE";
774   case PPCISD::FRSQRTE:         return "PPCISD::FRSQRTE";
775   case PPCISD::STFIWX:          return "PPCISD::STFIWX";
776   case PPCISD::VMADDFP:         return "PPCISD::VMADDFP";
777   case PPCISD::VNMSUBFP:        return "PPCISD::VNMSUBFP";
778   case PPCISD::VPERM:           return "PPCISD::VPERM";
779   case PPCISD::CMPB:            return "PPCISD::CMPB";
780   case PPCISD::Hi:              return "PPCISD::Hi";
781   case PPCISD::Lo:              return "PPCISD::Lo";
782   case PPCISD::TOC_ENTRY:       return "PPCISD::TOC_ENTRY";
783   case PPCISD::LOAD:            return "PPCISD::LOAD";
784   case PPCISD::LOAD_TOC:        return "PPCISD::LOAD_TOC";
785   case PPCISD::DYNALLOC:        return "PPCISD::DYNALLOC";
786   case PPCISD::GlobalBaseReg:   return "PPCISD::GlobalBaseReg";
787   case PPCISD::SRL:             return "PPCISD::SRL";
788   case PPCISD::SRA:             return "PPCISD::SRA";
789   case PPCISD::SHL:             return "PPCISD::SHL";
790   case PPCISD::CALL:            return "PPCISD::CALL";
791   case PPCISD::CALL_NOP:        return "PPCISD::CALL_NOP";
792   case PPCISD::CALL_TLS:        return "PPCISD::CALL_TLS";
793   case PPCISD::CALL_NOP_TLS:    return "PPCISD::CALL_NOP_TLS";
794   case PPCISD::MTCTR:           return "PPCISD::MTCTR";
795   case PPCISD::BCTRL:           return "PPCISD::BCTRL";
796   case PPCISD::BCTRL_LOAD_TOC:  return "PPCISD::BCTRL_LOAD_TOC";
797   case PPCISD::RET_FLAG:        return "PPCISD::RET_FLAG";
798   case PPCISD::READ_TIME_BASE:  return "PPCISD::READ_TIME_BASE";
799   case PPCISD::EH_SJLJ_SETJMP:  return "PPCISD::EH_SJLJ_SETJMP";
800   case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
801   case PPCISD::MFOCRF:          return "PPCISD::MFOCRF";
802   case PPCISD::VCMP:            return "PPCISD::VCMP";
803   case PPCISD::VCMPo:           return "PPCISD::VCMPo";
804   case PPCISD::LBRX:            return "PPCISD::LBRX";
805   case PPCISD::STBRX:           return "PPCISD::STBRX";
806   case PPCISD::LARX:            return "PPCISD::LARX";
807   case PPCISD::STCX:            return "PPCISD::STCX";
808   case PPCISD::COND_BRANCH:     return "PPCISD::COND_BRANCH";
809   case PPCISD::BDNZ:            return "PPCISD::BDNZ";
810   case PPCISD::BDZ:             return "PPCISD::BDZ";
811   case PPCISD::MFFS:            return "PPCISD::MFFS";
812   case PPCISD::FADDRTZ:         return "PPCISD::FADDRTZ";
813   case PPCISD::TC_RETURN:       return "PPCISD::TC_RETURN";
814   case PPCISD::CR6SET:          return "PPCISD::CR6SET";
815   case PPCISD::CR6UNSET:        return "PPCISD::CR6UNSET";
816   case PPCISD::ADDIS_TOC_HA:    return "PPCISD::ADDIS_TOC_HA";
817   case PPCISD::LD_TOC_L:        return "PPCISD::LD_TOC_L";
818   case PPCISD::ADDI_TOC_L:      return "PPCISD::ADDI_TOC_L";
819   case PPCISD::PPC32_GOT:       return "PPCISD::PPC32_GOT";
820   case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
821   case PPCISD::LD_GOT_TPREL_L:  return "PPCISD::LD_GOT_TPREL_L";
822   case PPCISD::ADD_TLS:         return "PPCISD::ADD_TLS";
823   case PPCISD::ADDIS_TLSGD_HA:  return "PPCISD::ADDIS_TLSGD_HA";
824   case PPCISD::ADDI_TLSGD_L:    return "PPCISD::ADDI_TLSGD_L";
825   case PPCISD::ADDIS_TLSLD_HA:  return "PPCISD::ADDIS_TLSLD_HA";
826   case PPCISD::ADDI_TLSLD_L:    return "PPCISD::ADDI_TLSLD_L";
827   case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
828   case PPCISD::ADDI_DTPREL_L:   return "PPCISD::ADDI_DTPREL_L";
829   case PPCISD::VADD_SPLAT:      return "PPCISD::VADD_SPLAT";
830   case PPCISD::SC:              return "PPCISD::SC";
831   }
832 }
833
834 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
835   if (!VT.isVector())
836     return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
837   return VT.changeVectorElementTypeToInteger();
838 }
839
840 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
841   assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
842   return true;
843 }
844
845 //===----------------------------------------------------------------------===//
846 // Node matching predicates, for use by the tblgen matching code.
847 //===----------------------------------------------------------------------===//
848
849 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
850 static bool isFloatingPointZero(SDValue Op) {
851   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
852     return CFP->getValueAPF().isZero();
853   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
854     // Maybe this has already been legalized into the constant pool?
855     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
856       if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
857         return CFP->getValueAPF().isZero();
858   }
859   return false;
860 }
861
862 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode.  Return
863 /// true if Op is undef or if it matches the specified value.
864 static bool isConstantOrUndef(int Op, int Val) {
865   return Op < 0 || Op == Val;
866 }
867
868 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
869 /// VPKUHUM instruction.
870 /// The ShuffleKind distinguishes between big-endian operations with
871 /// two different inputs (0), either-endian operations with two identical
872 /// inputs (1), and little-endian operantion with two different inputs (2).
873 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
874 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
875                                SelectionDAG &DAG) {
876   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
877   if (ShuffleKind == 0) {
878     if (IsLE)
879       return false;
880     for (unsigned i = 0; i != 16; ++i)
881       if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
882         return false;
883   } else if (ShuffleKind == 2) {
884     if (!IsLE)
885       return false;
886     for (unsigned i = 0; i != 16; ++i)
887       if (!isConstantOrUndef(N->getMaskElt(i), i*2))
888         return false;
889   } else if (ShuffleKind == 1) {
890     unsigned j = IsLE ? 0 : 1;
891     for (unsigned i = 0; i != 8; ++i)
892       if (!isConstantOrUndef(N->getMaskElt(i),    i*2+j) ||
893           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j))
894         return false;
895   }
896   return true;
897 }
898
899 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
900 /// VPKUWUM instruction.
901 /// The ShuffleKind distinguishes between big-endian operations with
902 /// two different inputs (0), either-endian operations with two identical
903 /// inputs (1), and little-endian operantion with two different inputs (2).
904 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
905 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
906                                SelectionDAG &DAG) {
907   bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
908   if (ShuffleKind == 0) {
909     if (IsLE)
910       return false;
911     for (unsigned i = 0; i != 16; i += 2)
912       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+2) ||
913           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+3))
914         return false;
915   } else if (ShuffleKind == 2) {
916     if (!IsLE)
917       return false;
918     for (unsigned i = 0; i != 16; i += 2)
919       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2) ||
920           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+1))
921         return false;
922   } else if (ShuffleKind == 1) {
923     unsigned j = IsLE ? 0 : 2;
924     for (unsigned i = 0; i != 8; i += 2)
925       if (!isConstantOrUndef(N->getMaskElt(i  ),  i*2+j)   ||
926           !isConstantOrUndef(N->getMaskElt(i+1),  i*2+j+1) ||
927           !isConstantOrUndef(N->getMaskElt(i+8),  i*2+j)   ||
928           !isConstantOrUndef(N->getMaskElt(i+9),  i*2+j+1))
929         return false;
930   }
931   return true;
932 }
933
934 /// isVMerge - Common function, used to match vmrg* shuffles.
935 ///
936 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
937                      unsigned LHSStart, unsigned RHSStart) {
938   if (N->getValueType(0) != MVT::v16i8)
939     return false;
940   assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
941          "Unsupported merge size!");
942
943   for (unsigned i = 0; i != 8/UnitSize; ++i)     // Step over units
944     for (unsigned j = 0; j != UnitSize; ++j) {   // Step over bytes within unit
945       if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
946                              LHSStart+j+i*UnitSize) ||
947           !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
948                              RHSStart+j+i*UnitSize))
949         return false;
950     }
951   return true;
952 }
953
954 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
955 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
956 /// The ShuffleKind distinguishes between big-endian merges with two 
957 /// different inputs (0), either-endian merges with two identical inputs (1),
958 /// and little-endian merges with two different inputs (2).  For the latter,
959 /// the input operands are swapped (see PPCInstrAltivec.td).
960 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
961                              unsigned ShuffleKind, SelectionDAG &DAG) {
962   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
963     if (ShuffleKind == 1) // unary
964       return isVMerge(N, UnitSize, 0, 0);
965     else if (ShuffleKind == 2) // swapped
966       return isVMerge(N, UnitSize, 0, 16);
967     else
968       return false;
969   } else {
970     if (ShuffleKind == 1) // unary
971       return isVMerge(N, UnitSize, 8, 8);
972     else if (ShuffleKind == 0) // normal
973       return isVMerge(N, UnitSize, 8, 24);
974     else
975       return false;
976   }
977 }
978
979 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
980 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
981 /// The ShuffleKind distinguishes between big-endian merges with two 
982 /// different inputs (0), either-endian merges with two identical inputs (1),
983 /// and little-endian merges with two different inputs (2).  For the latter,
984 /// the input operands are swapped (see PPCInstrAltivec.td).
985 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
986                              unsigned ShuffleKind, SelectionDAG &DAG) {
987   if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
988     if (ShuffleKind == 1) // unary
989       return isVMerge(N, UnitSize, 8, 8);
990     else if (ShuffleKind == 2) // swapped
991       return isVMerge(N, UnitSize, 8, 24);
992     else
993       return false;
994   } else {
995     if (ShuffleKind == 1) // unary
996       return isVMerge(N, UnitSize, 0, 0);
997     else if (ShuffleKind == 0) // normal
998       return isVMerge(N, UnitSize, 0, 16);
999     else
1000       return false;
1001   }
1002 }
1003
1004
1005 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1006 /// amount, otherwise return -1.
1007 /// The ShuffleKind distinguishes between big-endian operations with two 
1008 /// different inputs (0), either-endian operations with two identical inputs
1009 /// (1), and little-endian operations with two different inputs (2).  For the
1010 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1011 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1012                              SelectionDAG &DAG) {
1013   if (N->getValueType(0) != MVT::v16i8)
1014     return -1;
1015
1016   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1017
1018   // Find the first non-undef value in the shuffle mask.
1019   unsigned i;
1020   for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1021     /*search*/;
1022
1023   if (i == 16) return -1;  // all undef.
1024
1025   // Otherwise, check to see if the rest of the elements are consecutively
1026   // numbered from this value.
1027   unsigned ShiftAmt = SVOp->getMaskElt(i);
1028   if (ShiftAmt < i) return -1;
1029
1030   ShiftAmt -= i;
1031   bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1032     isLittleEndian();
1033
1034   if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1035     // Check the rest of the elements to see if they are consecutive.
1036     for (++i; i != 16; ++i)
1037       if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1038         return -1;
1039   } else if (ShuffleKind == 1) {
1040     // Check the rest of the elements to see if they are consecutive.
1041     for (++i; i != 16; ++i)
1042       if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1043         return -1;
1044   } else
1045     return -1;
1046
1047   if (ShuffleKind == 2 && isLE)
1048     ShiftAmt = 16 - ShiftAmt;
1049
1050   return ShiftAmt;
1051 }
1052
1053 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1054 /// specifies a splat of a single element that is suitable for input to
1055 /// VSPLTB/VSPLTH/VSPLTW.
1056 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1057   assert(N->getValueType(0) == MVT::v16i8 &&
1058          (EltSize == 1 || EltSize == 2 || EltSize == 4));
1059
1060   // This is a splat operation if each element of the permute is the same, and
1061   // if the value doesn't reference the second vector.
1062   unsigned ElementBase = N->getMaskElt(0);
1063
1064   // FIXME: Handle UNDEF elements too!
1065   if (ElementBase >= 16)
1066     return false;
1067
1068   // Check that the indices are consecutive, in the case of a multi-byte element
1069   // splatted with a v16i8 mask.
1070   for (unsigned i = 1; i != EltSize; ++i)
1071     if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1072       return false;
1073
1074   for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1075     if (N->getMaskElt(i) < 0) continue;
1076     for (unsigned j = 0; j != EltSize; ++j)
1077       if (N->getMaskElt(i+j) != N->getMaskElt(j))
1078         return false;
1079   }
1080   return true;
1081 }
1082
1083 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1084 /// are -0.0.
1085 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1086   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1087
1088   APInt APVal, APUndef;
1089   unsigned BitSize;
1090   bool HasAnyUndefs;
1091
1092   if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1093     if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1094       return CFP->getValueAPF().isNegZero();
1095
1096   return false;
1097 }
1098
1099 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1100 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1101 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1102                                 SelectionDAG &DAG) {
1103   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1104   assert(isSplatShuffleMask(SVOp, EltSize));
1105   if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1106     return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1107   else
1108     return SVOp->getMaskElt(0) / EltSize;
1109 }
1110
1111 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1112 /// by using a vspltis[bhw] instruction of the specified element size, return
1113 /// the constant being splatted.  The ByteSize field indicates the number of
1114 /// bytes of each element [124] -> [bhw].
1115 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1116   SDValue OpVal(nullptr, 0);
1117
1118   // If ByteSize of the splat is bigger than the element size of the
1119   // build_vector, then we have a case where we are checking for a splat where
1120   // multiple elements of the buildvector are folded together into a single
1121   // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1122   unsigned EltSize = 16/N->getNumOperands();
1123   if (EltSize < ByteSize) {
1124     unsigned Multiple = ByteSize/EltSize;   // Number of BV entries per spltval.
1125     SDValue UniquedVals[4];
1126     assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1127
1128     // See if all of the elements in the buildvector agree across.
1129     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1130       if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1131       // If the element isn't a constant, bail fully out.
1132       if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1133
1134
1135       if (!UniquedVals[i&(Multiple-1)].getNode())
1136         UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1137       else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1138         return SDValue();  // no match.
1139     }
1140
1141     // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1142     // either constant or undef values that are identical for each chunk.  See
1143     // if these chunks can form into a larger vspltis*.
1144
1145     // Check to see if all of the leading entries are either 0 or -1.  If
1146     // neither, then this won't fit into the immediate field.
1147     bool LeadingZero = true;
1148     bool LeadingOnes = true;
1149     for (unsigned i = 0; i != Multiple-1; ++i) {
1150       if (!UniquedVals[i].getNode()) continue;  // Must have been undefs.
1151
1152       LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1153       LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1154     }
1155     // Finally, check the least significant entry.
1156     if (LeadingZero) {
1157       if (!UniquedVals[Multiple-1].getNode())
1158         return DAG.getTargetConstant(0, MVT::i32);  // 0,0,0,undef
1159       int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1160       if (Val < 16)
1161         return DAG.getTargetConstant(Val, MVT::i32);  // 0,0,0,4 -> vspltisw(4)
1162     }
1163     if (LeadingOnes) {
1164       if (!UniquedVals[Multiple-1].getNode())
1165         return DAG.getTargetConstant(~0U, MVT::i32);  // -1,-1,-1,undef
1166       int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1167       if (Val >= -16)                            // -1,-1,-1,-2 -> vspltisw(-2)
1168         return DAG.getTargetConstant(Val, MVT::i32);
1169     }
1170
1171     return SDValue();
1172   }
1173
1174   // Check to see if this buildvec has a single non-undef value in its elements.
1175   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1176     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1177     if (!OpVal.getNode())
1178       OpVal = N->getOperand(i);
1179     else if (OpVal != N->getOperand(i))
1180       return SDValue();
1181   }
1182
1183   if (!OpVal.getNode()) return SDValue();  // All UNDEF: use implicit def.
1184
1185   unsigned ValSizeInBytes = EltSize;
1186   uint64_t Value = 0;
1187   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1188     Value = CN->getZExtValue();
1189   } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1190     assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1191     Value = FloatToBits(CN->getValueAPF().convertToFloat());
1192   }
1193
1194   // If the splat value is larger than the element value, then we can never do
1195   // this splat.  The only case that we could fit the replicated bits into our
1196   // immediate field for would be zero, and we prefer to use vxor for it.
1197   if (ValSizeInBytes < ByteSize) return SDValue();
1198
1199   // If the element value is larger than the splat value, cut it in half and
1200   // check to see if the two halves are equal.  Continue doing this until we
1201   // get to ByteSize.  This allows us to handle 0x01010101 as 0x01.
1202   while (ValSizeInBytes > ByteSize) {
1203     ValSizeInBytes >>= 1;
1204
1205     // If the top half equals the bottom half, we're still ok.
1206     if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1207          (Value                        & ((1 << (8*ValSizeInBytes))-1)))
1208       return SDValue();
1209   }
1210
1211   // Properly sign extend the value.
1212   int MaskVal = SignExtend32(Value, ByteSize * 8);
1213
1214   // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1215   if (MaskVal == 0) return SDValue();
1216
1217   // Finally, if this value fits in a 5 bit sext field, return it
1218   if (SignExtend32<5>(MaskVal) == MaskVal)
1219     return DAG.getTargetConstant(MaskVal, MVT::i32);
1220   return SDValue();
1221 }
1222
1223 //===----------------------------------------------------------------------===//
1224 //  Addressing Mode Selection
1225 //===----------------------------------------------------------------------===//
1226
1227 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1228 /// or 64-bit immediate, and if the value can be accurately represented as a
1229 /// sign extension from a 16-bit value.  If so, this returns true and the
1230 /// immediate.
1231 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1232   if (!isa<ConstantSDNode>(N))
1233     return false;
1234
1235   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1236   if (N->getValueType(0) == MVT::i32)
1237     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1238   else
1239     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1240 }
1241 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1242   return isIntS16Immediate(Op.getNode(), Imm);
1243 }
1244
1245
1246 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1247 /// can be represented as an indexed [r+r] operation.  Returns false if it
1248 /// can be more efficiently represented with [r+imm].
1249 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1250                                             SDValue &Index,
1251                                             SelectionDAG &DAG) const {
1252   short imm = 0;
1253   if (N.getOpcode() == ISD::ADD) {
1254     if (isIntS16Immediate(N.getOperand(1), imm))
1255       return false;    // r+i
1256     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1257       return false;    // r+i
1258
1259     Base = N.getOperand(0);
1260     Index = N.getOperand(1);
1261     return true;
1262   } else if (N.getOpcode() == ISD::OR) {
1263     if (isIntS16Immediate(N.getOperand(1), imm))
1264       return false;    // r+i can fold it if we can.
1265
1266     // If this is an or of disjoint bitfields, we can codegen this as an add
1267     // (for better address arithmetic) if the LHS and RHS of the OR are provably
1268     // disjoint.
1269     APInt LHSKnownZero, LHSKnownOne;
1270     APInt RHSKnownZero, RHSKnownOne;
1271     DAG.computeKnownBits(N.getOperand(0),
1272                          LHSKnownZero, LHSKnownOne);
1273
1274     if (LHSKnownZero.getBoolValue()) {
1275       DAG.computeKnownBits(N.getOperand(1),
1276                            RHSKnownZero, RHSKnownOne);
1277       // If all of the bits are known zero on the LHS or RHS, the add won't
1278       // carry.
1279       if (~(LHSKnownZero | RHSKnownZero) == 0) {
1280         Base = N.getOperand(0);
1281         Index = N.getOperand(1);
1282         return true;
1283       }
1284     }
1285   }
1286
1287   return false;
1288 }
1289
1290 // If we happen to be doing an i64 load or store into a stack slot that has
1291 // less than a 4-byte alignment, then the frame-index elimination may need to
1292 // use an indexed load or store instruction (because the offset may not be a
1293 // multiple of 4). The extra register needed to hold the offset comes from the
1294 // register scavenger, and it is possible that the scavenger will need to use
1295 // an emergency spill slot. As a result, we need to make sure that a spill slot
1296 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1297 // stack slot.
1298 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1299   // FIXME: This does not handle the LWA case.
1300   if (VT != MVT::i64)
1301     return;
1302
1303   // NOTE: We'll exclude negative FIs here, which come from argument
1304   // lowering, because there are no known test cases triggering this problem
1305   // using packed structures (or similar). We can remove this exclusion if
1306   // we find such a test case. The reason why this is so test-case driven is
1307   // because this entire 'fixup' is only to prevent crashes (from the
1308   // register scavenger) on not-really-valid inputs. For example, if we have:
1309   //   %a = alloca i1
1310   //   %b = bitcast i1* %a to i64*
1311   //   store i64* a, i64 b
1312   // then the store should really be marked as 'align 1', but is not. If it
1313   // were marked as 'align 1' then the indexed form would have been
1314   // instruction-selected initially, and the problem this 'fixup' is preventing
1315   // won't happen regardless.
1316   if (FrameIdx < 0)
1317     return;
1318
1319   MachineFunction &MF = DAG.getMachineFunction();
1320   MachineFrameInfo *MFI = MF.getFrameInfo();
1321
1322   unsigned Align = MFI->getObjectAlignment(FrameIdx);
1323   if (Align >= 4)
1324     return;
1325
1326   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1327   FuncInfo->setHasNonRISpills();
1328 }
1329
1330 /// Returns true if the address N can be represented by a base register plus
1331 /// a signed 16-bit displacement [r+imm], and if it is not better
1332 /// represented as reg+reg.  If Aligned is true, only accept displacements
1333 /// suitable for STD and friends, i.e. multiples of 4.
1334 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1335                                             SDValue &Base,
1336                                             SelectionDAG &DAG,
1337                                             bool Aligned) const {
1338   // FIXME dl should come from parent load or store, not from address
1339   SDLoc dl(N);
1340   // If this can be more profitably realized as r+r, fail.
1341   if (SelectAddressRegReg(N, Disp, Base, DAG))
1342     return false;
1343
1344   if (N.getOpcode() == ISD::ADD) {
1345     short imm = 0;
1346     if (isIntS16Immediate(N.getOperand(1), imm) &&
1347         (!Aligned || (imm & 3) == 0)) {
1348       Disp = DAG.getTargetConstant(imm, N.getValueType());
1349       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1350         Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1351         fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1352       } else {
1353         Base = N.getOperand(0);
1354       }
1355       return true; // [r+i]
1356     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1357       // Match LOAD (ADD (X, Lo(G))).
1358       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1359              && "Cannot handle constant offsets yet!");
1360       Disp = N.getOperand(1).getOperand(0);  // The global address.
1361       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1362              Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1363              Disp.getOpcode() == ISD::TargetConstantPool ||
1364              Disp.getOpcode() == ISD::TargetJumpTable);
1365       Base = N.getOperand(0);
1366       return true;  // [&g+r]
1367     }
1368   } else if (N.getOpcode() == ISD::OR) {
1369     short imm = 0;
1370     if (isIntS16Immediate(N.getOperand(1), imm) &&
1371         (!Aligned || (imm & 3) == 0)) {
1372       // If this is an or of disjoint bitfields, we can codegen this as an add
1373       // (for better address arithmetic) if the LHS and RHS of the OR are
1374       // provably disjoint.
1375       APInt LHSKnownZero, LHSKnownOne;
1376       DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1377
1378       if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1379         // If all of the bits are known zero on the LHS or RHS, the add won't
1380         // carry.
1381         if (FrameIndexSDNode *FI =
1382               dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1383           Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1384           fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1385         } else {
1386           Base = N.getOperand(0);
1387         }
1388         Disp = DAG.getTargetConstant(imm, N.getValueType());
1389         return true;
1390       }
1391     }
1392   } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1393     // Loading from a constant address.
1394
1395     // If this address fits entirely in a 16-bit sext immediate field, codegen
1396     // this as "d, 0"
1397     short Imm;
1398     if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1399       Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1400       Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1401                              CN->getValueType(0));
1402       return true;
1403     }
1404
1405     // Handle 32-bit sext immediates with LIS + addr mode.
1406     if ((CN->getValueType(0) == MVT::i32 ||
1407          (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1408         (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1409       int Addr = (int)CN->getZExtValue();
1410
1411       // Otherwise, break this down into an LIS + disp.
1412       Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1413
1414       Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1415       unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1416       Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1417       return true;
1418     }
1419   }
1420
1421   Disp = DAG.getTargetConstant(0, getPointerTy());
1422   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1423     Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1424     fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1425   } else
1426     Base = N;
1427   return true;      // [r+0]
1428 }
1429
1430 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1431 /// represented as an indexed [r+r] operation.
1432 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1433                                                 SDValue &Index,
1434                                                 SelectionDAG &DAG) const {
1435   // Check to see if we can easily represent this as an [r+r] address.  This
1436   // will fail if it thinks that the address is more profitably represented as
1437   // reg+imm, e.g. where imm = 0.
1438   if (SelectAddressRegReg(N, Base, Index, DAG))
1439     return true;
1440
1441   // If the operand is an addition, always emit this as [r+r], since this is
1442   // better (for code size, and execution, as the memop does the add for free)
1443   // than emitting an explicit add.
1444   if (N.getOpcode() == ISD::ADD) {
1445     Base = N.getOperand(0);
1446     Index = N.getOperand(1);
1447     return true;
1448   }
1449
1450   // Otherwise, do it the hard way, using R0 as the base register.
1451   Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1452                          N.getValueType());
1453   Index = N;
1454   return true;
1455 }
1456
1457 /// getPreIndexedAddressParts - returns true by value, base pointer and
1458 /// offset pointer and addressing mode by reference if the node's address
1459 /// can be legally represented as pre-indexed load / store address.
1460 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1461                                                   SDValue &Offset,
1462                                                   ISD::MemIndexedMode &AM,
1463                                                   SelectionDAG &DAG) const {
1464   if (DisablePPCPreinc) return false;
1465
1466   bool isLoad = true;
1467   SDValue Ptr;
1468   EVT VT;
1469   unsigned Alignment;
1470   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1471     Ptr = LD->getBasePtr();
1472     VT = LD->getMemoryVT();
1473     Alignment = LD->getAlignment();
1474   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1475     Ptr = ST->getBasePtr();
1476     VT  = ST->getMemoryVT();
1477     Alignment = ST->getAlignment();
1478     isLoad = false;
1479   } else
1480     return false;
1481
1482   // PowerPC doesn't have preinc load/store instructions for vectors.
1483   if (VT.isVector())
1484     return false;
1485
1486   if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1487
1488     // Common code will reject creating a pre-inc form if the base pointer
1489     // is a frame index, or if N is a store and the base pointer is either
1490     // the same as or a predecessor of the value being stored.  Check for
1491     // those situations here, and try with swapped Base/Offset instead.
1492     bool Swap = false;
1493
1494     if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1495       Swap = true;
1496     else if (!isLoad) {
1497       SDValue Val = cast<StoreSDNode>(N)->getValue();
1498       if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1499         Swap = true;
1500     }
1501
1502     if (Swap)
1503       std::swap(Base, Offset);
1504
1505     AM = ISD::PRE_INC;
1506     return true;
1507   }
1508
1509   // LDU/STU can only handle immediates that are a multiple of 4.
1510   if (VT != MVT::i64) {
1511     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1512       return false;
1513   } else {
1514     // LDU/STU need an address with at least 4-byte alignment.
1515     if (Alignment < 4)
1516       return false;
1517
1518     if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1519       return false;
1520   }
1521
1522   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1523     // PPC64 doesn't have lwau, but it does have lwaux.  Reject preinc load of
1524     // sext i32 to i64 when addr mode is r+i.
1525     if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1526         LD->getExtensionType() == ISD::SEXTLOAD &&
1527         isa<ConstantSDNode>(Offset))
1528       return false;
1529   }
1530
1531   AM = ISD::PRE_INC;
1532   return true;
1533 }
1534
1535 //===----------------------------------------------------------------------===//
1536 //  LowerOperation implementation
1537 //===----------------------------------------------------------------------===//
1538
1539 /// GetLabelAccessInfo - Return true if we should reference labels using a
1540 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1541 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1542                                unsigned &LoOpFlags,
1543                                const GlobalValue *GV = nullptr) {
1544   HiOpFlags = PPCII::MO_HA;
1545   LoOpFlags = PPCII::MO_LO;
1546
1547   // Don't use the pic base if not in PIC relocation model.
1548   bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1549
1550   if (isPIC) {
1551     HiOpFlags |= PPCII::MO_PIC_FLAG;
1552     LoOpFlags |= PPCII::MO_PIC_FLAG;
1553   }
1554
1555   // If this is a reference to a global value that requires a non-lazy-ptr, make
1556   // sure that instruction lowering adds it.
1557   if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1558     HiOpFlags |= PPCII::MO_NLP_FLAG;
1559     LoOpFlags |= PPCII::MO_NLP_FLAG;
1560
1561     if (GV->hasHiddenVisibility()) {
1562       HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1563       LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1564     }
1565   }
1566
1567   return isPIC;
1568 }
1569
1570 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1571                              SelectionDAG &DAG) {
1572   EVT PtrVT = HiPart.getValueType();
1573   SDValue Zero = DAG.getConstant(0, PtrVT);
1574   SDLoc DL(HiPart);
1575
1576   SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1577   SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1578
1579   // With PIC, the first instruction is actually "GR+hi(&G)".
1580   if (isPIC)
1581     Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1582                      DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1583
1584   // Generate non-pic code that has direct accesses to the constant pool.
1585   // The address of the global is just (hi(&g)+lo(&g)).
1586   return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1587 }
1588
1589 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1590                                              SelectionDAG &DAG) const {
1591   EVT PtrVT = Op.getValueType();
1592   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1593   const Constant *C = CP->getConstVal();
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.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1599     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), 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.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1608                                            PPCII::MO_PIC_FLAG);
1609     SDLoc DL(CP);
1610     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1611                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1612   }
1613
1614   SDValue CPIHi =
1615     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1616   SDValue CPILo =
1617     DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1618   return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1619 }
1620
1621 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1622   EVT PtrVT = Op.getValueType();
1623   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1624
1625   // 64-bit SVR4 ABI code is always position-independent.
1626   // The actual address of the GlobalValue is stored in the TOC.
1627   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1628     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1629     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1630                        DAG.getRegister(PPC::X2, MVT::i64));
1631   }
1632
1633   unsigned MOHiFlag, MOLoFlag;
1634   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1635
1636   if (isPIC && Subtarget.isSVR4ABI()) {
1637     SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1638                                         PPCII::MO_PIC_FLAG);
1639     SDLoc DL(GA);
1640     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1641                        DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1642   }
1643
1644   SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1645   SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1646   return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1647 }
1648
1649 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1650                                              SelectionDAG &DAG) const {
1651   EVT PtrVT = Op.getValueType();
1652   BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1653   const BlockAddress *BA = BASDN->getBlockAddress();
1654
1655   // 64-bit SVR4 ABI code is always position-independent.
1656   // The actual BlockAddress is stored in the TOC.
1657   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1658     SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1659     return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1660                        DAG.getRegister(PPC::X2, MVT::i64));
1661   }
1662
1663   unsigned MOHiFlag, MOLoFlag;
1664   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1665   SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1666   SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1667   return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1668 }
1669
1670 // Generate a call to __tls_get_addr for the given GOT entry Op.
1671 std::pair<SDValue,SDValue>
1672 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1673                                 SelectionDAG &DAG) const {
1674
1675   Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1676   TargetLowering::ArgListTy Args;
1677   TargetLowering::ArgListEntry Entry;
1678   Entry.Node = Op;
1679   Entry.Ty = IntPtrTy;
1680   Args.push_back(Entry);
1681
1682   TargetLowering::CallLoweringInfo CLI(DAG);
1683   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1684     .setCallee(CallingConv::C, IntPtrTy,
1685                DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1686                std::move(Args), 0);
1687
1688   return LowerCallTo(CLI);
1689 }
1690
1691 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1692                                               SelectionDAG &DAG) const {
1693
1694   // FIXME: TLS addresses currently use medium model code sequences,
1695   // which is the most useful form.  Eventually support for small and
1696   // large models could be added if users need it, at the cost of
1697   // additional complexity.
1698   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1699   SDLoc dl(GA);
1700   const GlobalValue *GV = GA->getGlobal();
1701   EVT PtrVT = getPointerTy();
1702   bool is64bit = Subtarget.isPPC64();
1703   const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1704   PICLevel::Level picLevel = M->getPICLevel();
1705
1706   TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1707
1708   if (Model == TLSModel::LocalExec) {
1709     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1710                                                PPCII::MO_TPREL_HA);
1711     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1712                                                PPCII::MO_TPREL_LO);
1713     SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1714                                      is64bit ? MVT::i64 : MVT::i32);
1715     SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1716     return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1717   }
1718
1719   if (Model == TLSModel::InitialExec) {
1720     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1721     SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1722                                                 PPCII::MO_TLS);
1723     SDValue GOTPtr;
1724     if (is64bit) {
1725       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1726       GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1727                            PtrVT, GOTReg, TGA);
1728     } else
1729       GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1730     SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1731                                    PtrVT, TGA, GOTPtr);
1732     return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1733   }
1734
1735   if (Model == TLSModel::GeneralDynamic) {
1736     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1737                                              PPCII::MO_TLSGD);
1738     SDValue GOTPtr;
1739     if (is64bit) {
1740       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1741       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1742                                    GOTReg, TGA);
1743     } else {
1744       if (picLevel == PICLevel::Small)
1745         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1746       else
1747         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1748     }
1749     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1750                                    GOTPtr, TGA);
1751     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1752     return CallResult.first;
1753   }
1754
1755   if (Model == TLSModel::LocalDynamic) {
1756     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1757                                              PPCII::MO_TLSLD);
1758     SDValue GOTPtr;
1759     if (is64bit) {
1760       SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1761       GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1762                            GOTReg, TGA);
1763     } else {
1764       if (picLevel == PICLevel::Small)
1765         GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1766       else
1767         GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1768     }
1769     SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1770                                    GOTPtr, TGA);
1771     std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1772     SDValue TLSAddr = CallResult.first;
1773     SDValue Chain = CallResult.second;
1774     SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1775                                       Chain, TLSAddr, TGA);
1776     return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1777   }
1778
1779   llvm_unreachable("Unknown TLS model!");
1780 }
1781
1782 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1783                                               SelectionDAG &DAG) const {
1784   EVT PtrVT = Op.getValueType();
1785   GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1786   SDLoc DL(GSDN);
1787   const GlobalValue *GV = GSDN->getGlobal();
1788
1789   // 64-bit SVR4 ABI code is always position-independent.
1790   // The actual address of the GlobalValue is stored in the TOC.
1791   if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1792     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1793     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1794                        DAG.getRegister(PPC::X2, MVT::i64));
1795   }
1796
1797   unsigned MOHiFlag, MOLoFlag;
1798   bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1799
1800   if (isPIC && Subtarget.isSVR4ABI()) {
1801     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1802                                             GSDN->getOffset(),
1803                                             PPCII::MO_PIC_FLAG);
1804     return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1805                        DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1806   }
1807
1808   SDValue GAHi =
1809     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1810   SDValue GALo =
1811     DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1812
1813   SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1814
1815   // If the global reference is actually to a non-lazy-pointer, we have to do an
1816   // extra load to get the address of the global.
1817   if (MOHiFlag & PPCII::MO_NLP_FLAG)
1818     Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1819                       false, false, false, 0);
1820   return Ptr;
1821 }
1822
1823 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1824   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1825   SDLoc dl(Op);
1826
1827   if (Op.getValueType() == MVT::v2i64) {
1828     // When the operands themselves are v2i64 values, we need to do something
1829     // special because VSX has no underlying comparison operations for these.
1830     if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1831       // Equality can be handled by casting to the legal type for Altivec
1832       // comparisons, everything else needs to be expanded.
1833       if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1834         return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1835                  DAG.getSetCC(dl, MVT::v4i32,
1836                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1837                    DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1838                    CC));
1839       }
1840
1841       return SDValue();
1842     }
1843
1844     // We handle most of these in the usual way.
1845     return Op;
1846   }
1847
1848   // If we're comparing for equality to zero, expose the fact that this is
1849   // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1850   // fold the new nodes.
1851   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1852     if (C->isNullValue() && CC == ISD::SETEQ) {
1853       EVT VT = Op.getOperand(0).getValueType();
1854       SDValue Zext = Op.getOperand(0);
1855       if (VT.bitsLT(MVT::i32)) {
1856         VT = MVT::i32;
1857         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1858       }
1859       unsigned Log2b = Log2_32(VT.getSizeInBits());
1860       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1861       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1862                                 DAG.getConstant(Log2b, MVT::i32));
1863       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1864     }
1865     // Leave comparisons against 0 and -1 alone for now, since they're usually
1866     // optimized.  FIXME: revisit this when we can custom lower all setcc
1867     // optimizations.
1868     if (C->isAllOnesValue() || C->isNullValue())
1869       return SDValue();
1870   }
1871
1872   // If we have an integer seteq/setne, turn it into a compare against zero
1873   // by xor'ing the rhs with the lhs, which is faster than setting a
1874   // condition register, reading it back out, and masking the correct bit.  The
1875   // normal approach here uses sub to do this instead of xor.  Using xor exposes
1876   // the result to other bit-twiddling opportunities.
1877   EVT LHSVT = Op.getOperand(0).getValueType();
1878   if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1879     EVT VT = Op.getValueType();
1880     SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1881                                 Op.getOperand(1));
1882     return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1883   }
1884   return SDValue();
1885 }
1886
1887 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1888                                       const PPCSubtarget &Subtarget) const {
1889   SDNode *Node = Op.getNode();
1890   EVT VT = Node->getValueType(0);
1891   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1892   SDValue InChain = Node->getOperand(0);
1893   SDValue VAListPtr = Node->getOperand(1);
1894   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1895   SDLoc dl(Node);
1896
1897   assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1898
1899   // gpr_index
1900   SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1901                                     VAListPtr, MachinePointerInfo(SV), MVT::i8,
1902                                     false, false, false, 0);
1903   InChain = GprIndex.getValue(1);
1904
1905   if (VT == MVT::i64) {
1906     // Check if GprIndex is even
1907     SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1908                                  DAG.getConstant(1, MVT::i32));
1909     SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1910                                 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1911     SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1912                                           DAG.getConstant(1, MVT::i32));
1913     // Align GprIndex to be even if it isn't
1914     GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1915                            GprIndex);
1916   }
1917
1918   // fpr index is 1 byte after gpr
1919   SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1920                                DAG.getConstant(1, MVT::i32));
1921
1922   // fpr
1923   SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1924                                     FprPtr, MachinePointerInfo(SV), MVT::i8,
1925                                     false, false, false, 0);
1926   InChain = FprIndex.getValue(1);
1927
1928   SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1929                                        DAG.getConstant(8, MVT::i32));
1930
1931   SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1932                                         DAG.getConstant(4, MVT::i32));
1933
1934   // areas
1935   SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1936                                      MachinePointerInfo(), false, false,
1937                                      false, 0);
1938   InChain = OverflowArea.getValue(1);
1939
1940   SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1941                                     MachinePointerInfo(), false, false,
1942                                     false, 0);
1943   InChain = RegSaveArea.getValue(1);
1944
1945   // select overflow_area if index > 8
1946   SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1947                             DAG.getConstant(8, MVT::i32), ISD::SETLT);
1948
1949   // adjustment constant gpr_index * 4/8
1950   SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1951                                     VT.isInteger() ? GprIndex : FprIndex,
1952                                     DAG.getConstant(VT.isInteger() ? 4 : 8,
1953                                                     MVT::i32));
1954
1955   // OurReg = RegSaveArea + RegConstant
1956   SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1957                                RegConstant);
1958
1959   // Floating types are 32 bytes into RegSaveArea
1960   if (VT.isFloatingPoint())
1961     OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1962                          DAG.getConstant(32, MVT::i32));
1963
1964   // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1965   SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1966                                    VT.isInteger() ? GprIndex : FprIndex,
1967                                    DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1968                                                    MVT::i32));
1969
1970   InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1971                               VT.isInteger() ? VAListPtr : FprPtr,
1972                               MachinePointerInfo(SV),
1973                               MVT::i8, false, false, 0);
1974
1975   // determine if we should load from reg_save_area or overflow_area
1976   SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1977
1978   // increase overflow_area by 4/8 if gpr/fpr > 8
1979   SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1980                                           DAG.getConstant(VT.isInteger() ? 4 : 8,
1981                                           MVT::i32));
1982
1983   OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1984                              OverflowAreaPlusN);
1985
1986   InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1987                               OverflowAreaPtr,
1988                               MachinePointerInfo(),
1989                               MVT::i32, false, false, 0);
1990
1991   return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1992                      false, false, false, 0);
1993 }
1994
1995 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
1996                                        const PPCSubtarget &Subtarget) const {
1997   assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
1998
1999   // We have to copy the entire va_list struct:
2000   // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2001   return DAG.getMemcpy(Op.getOperand(0), Op,
2002                        Op.getOperand(1), Op.getOperand(2),
2003                        DAG.getConstant(12, MVT::i32), 8, false, true,
2004                        MachinePointerInfo(), MachinePointerInfo());
2005 }
2006
2007 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2008                                                   SelectionDAG &DAG) const {
2009   return Op.getOperand(0);
2010 }
2011
2012 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2013                                                 SelectionDAG &DAG) const {
2014   SDValue Chain = Op.getOperand(0);
2015   SDValue Trmp = Op.getOperand(1); // trampoline
2016   SDValue FPtr = Op.getOperand(2); // nested function
2017   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2018   SDLoc dl(Op);
2019
2020   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2021   bool isPPC64 = (PtrVT == MVT::i64);
2022   Type *IntPtrTy =
2023     DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2024                                                              *DAG.getContext());
2025
2026   TargetLowering::ArgListTy Args;
2027   TargetLowering::ArgListEntry Entry;
2028
2029   Entry.Ty = IntPtrTy;
2030   Entry.Node = Trmp; Args.push_back(Entry);
2031
2032   // TrampSize == (isPPC64 ? 48 : 40);
2033   Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2034                                isPPC64 ? MVT::i64 : MVT::i32);
2035   Args.push_back(Entry);
2036
2037   Entry.Node = FPtr; Args.push_back(Entry);
2038   Entry.Node = Nest; Args.push_back(Entry);
2039
2040   // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2041   TargetLowering::CallLoweringInfo CLI(DAG);
2042   CLI.setDebugLoc(dl).setChain(Chain)
2043     .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2044                DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2045                std::move(Args), 0);
2046
2047   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2048   return CallResult.second;
2049 }
2050
2051 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2052                                         const PPCSubtarget &Subtarget) const {
2053   MachineFunction &MF = DAG.getMachineFunction();
2054   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2055
2056   SDLoc dl(Op);
2057
2058   if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2059     // vastart just stores the address of the VarArgsFrameIndex slot into the
2060     // memory location argument.
2061     EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2062     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2063     const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2064     return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2065                         MachinePointerInfo(SV),
2066                         false, false, 0);
2067   }
2068
2069   // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2070   // We suppose the given va_list is already allocated.
2071   //
2072   // typedef struct {
2073   //  char gpr;     /* index into the array of 8 GPRs
2074   //                 * stored in the register save area
2075   //                 * gpr=0 corresponds to r3,
2076   //                 * gpr=1 to r4, etc.
2077   //                 */
2078   //  char fpr;     /* index into the array of 8 FPRs
2079   //                 * stored in the register save area
2080   //                 * fpr=0 corresponds to f1,
2081   //                 * fpr=1 to f2, etc.
2082   //                 */
2083   //  char *overflow_arg_area;
2084   //                /* location on stack that holds
2085   //                 * the next overflow argument
2086   //                 */
2087   //  char *reg_save_area;
2088   //               /* where r3:r10 and f1:f8 (if saved)
2089   //                * are stored
2090   //                */
2091   // } va_list[1];
2092
2093
2094   SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2095   SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2096
2097
2098   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2099
2100   SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2101                                             PtrVT);
2102   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2103                                  PtrVT);
2104
2105   uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2106   SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2107
2108   uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2109   SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2110
2111   uint64_t FPROffset = 1;
2112   SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2113
2114   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2115
2116   // Store first byte : number of int regs
2117   SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2118                                          Op.getOperand(1),
2119                                          MachinePointerInfo(SV),
2120                                          MVT::i8, false, false, 0);
2121   uint64_t nextOffset = FPROffset;
2122   SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2123                                   ConstFPROffset);
2124
2125   // Store second byte : number of float regs
2126   SDValue secondStore =
2127     DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2128                       MachinePointerInfo(SV, nextOffset), MVT::i8,
2129                       false, false, 0);
2130   nextOffset += StackOffset;
2131   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2132
2133   // Store second word : arguments given on stack
2134   SDValue thirdStore =
2135     DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2136                  MachinePointerInfo(SV, nextOffset),
2137                  false, false, 0);
2138   nextOffset += FrameOffset;
2139   nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2140
2141   // Store third word : arguments given in registers
2142   return DAG.getStore(thirdStore, dl, FR, nextPtr,
2143                       MachinePointerInfo(SV, nextOffset),
2144                       false, false, 0);
2145
2146 }
2147
2148 #include "PPCGenCallingConv.inc"
2149
2150 // Function whose sole purpose is to kill compiler warnings 
2151 // stemming from unused functions included from PPCGenCallingConv.inc.
2152 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2153   return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2154 }
2155
2156 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2157                                       CCValAssign::LocInfo &LocInfo,
2158                                       ISD::ArgFlagsTy &ArgFlags,
2159                                       CCState &State) {
2160   return true;
2161 }
2162
2163 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2164                                              MVT &LocVT,
2165                                              CCValAssign::LocInfo &LocInfo,
2166                                              ISD::ArgFlagsTy &ArgFlags,
2167                                              CCState &State) {
2168   static const MCPhysReg ArgRegs[] = {
2169     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2170     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2171   };
2172   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2173
2174   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2175
2176   // Skip one register if the first unallocated register has an even register
2177   // number and there are still argument registers available which have not been
2178   // allocated yet. RegNum is actually an index into ArgRegs, which means we
2179   // need to skip a register if RegNum is odd.
2180   if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2181     State.AllocateReg(ArgRegs[RegNum]);
2182   }
2183
2184   // Always return false here, as this function only makes sure that the first
2185   // unallocated register has an odd register number and does not actually
2186   // allocate a register for the current argument.
2187   return false;
2188 }
2189
2190 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2191                                                MVT &LocVT,
2192                                                CCValAssign::LocInfo &LocInfo,
2193                                                ISD::ArgFlagsTy &ArgFlags,
2194                                                CCState &State) {
2195   static const MCPhysReg ArgRegs[] = {
2196     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2197     PPC::F8
2198   };
2199
2200   const unsigned NumArgRegs = array_lengthof(ArgRegs);
2201
2202   unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2203
2204   // If there is only one Floating-point register left we need to put both f64
2205   // values of a split ppc_fp128 value on the stack.
2206   if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2207     State.AllocateReg(ArgRegs[RegNum]);
2208   }
2209
2210   // Always return false here, as this function only makes sure that the two f64
2211   // values a ppc_fp128 value is split into are both passed in registers or both
2212   // passed on the stack and does not actually allocate a register for the
2213   // current argument.
2214   return false;
2215 }
2216
2217 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2218 /// on Darwin.
2219 static const MCPhysReg *GetFPR() {
2220   static const MCPhysReg FPR[] = {
2221     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2222     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2223   };
2224
2225   return FPR;
2226 }
2227
2228 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2229 /// the stack.
2230 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2231                                        unsigned PtrByteSize) {
2232   unsigned ArgSize = ArgVT.getStoreSize();
2233   if (Flags.isByVal())
2234     ArgSize = Flags.getByValSize();
2235
2236   // Round up to multiples of the pointer size, except for array members,
2237   // which are always packed.
2238   if (!Flags.isInConsecutiveRegs())
2239     ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2240
2241   return ArgSize;
2242 }
2243
2244 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2245 /// on the stack.
2246 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2247                                             ISD::ArgFlagsTy Flags,
2248                                             unsigned PtrByteSize) {
2249   unsigned Align = PtrByteSize;
2250
2251   // Altivec parameters are padded to a 16 byte boundary.
2252   if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2253       ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2254       ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2255     Align = 16;
2256
2257   // ByVal parameters are aligned as requested.
2258   if (Flags.isByVal()) {
2259     unsigned BVAlign = Flags.getByValAlign();
2260     if (BVAlign > PtrByteSize) {
2261       if (BVAlign % PtrByteSize != 0)
2262           llvm_unreachable(
2263             "ByVal alignment is not a multiple of the pointer size");
2264
2265       Align = BVAlign;
2266     }
2267   }
2268
2269   // Array members are always packed to their original alignment.
2270   if (Flags.isInConsecutiveRegs()) {
2271     // If the array member was split into multiple registers, the first
2272     // needs to be aligned to the size of the full type.  (Except for
2273     // ppcf128, which is only aligned as its f64 components.)
2274     if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2275       Align = OrigVT.getStoreSize();
2276     else
2277       Align = ArgVT.getStoreSize();
2278   }
2279
2280   return Align;
2281 }
2282
2283 /// CalculateStackSlotUsed - Return whether this argument will use its
2284 /// stack slot (instead of being passed in registers).  ArgOffset,
2285 /// AvailableFPRs, and AvailableVRs must hold the current argument
2286 /// position, and will be updated to account for this argument.
2287 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2288                                    ISD::ArgFlagsTy Flags,
2289                                    unsigned PtrByteSize,
2290                                    unsigned LinkageSize,
2291                                    unsigned ParamAreaSize,
2292                                    unsigned &ArgOffset,
2293                                    unsigned &AvailableFPRs,
2294                                    unsigned &AvailableVRs) {
2295   bool UseMemory = false;
2296
2297   // Respect alignment of argument on the stack.
2298   unsigned Align =
2299     CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2300   ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2301   // If there's no space left in the argument save area, we must
2302   // use memory (this check also catches zero-sized arguments).
2303   if (ArgOffset >= LinkageSize + ParamAreaSize)
2304     UseMemory = true;
2305
2306   // Allocate argument on the stack.
2307   ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2308   if (Flags.isInConsecutiveRegsLast())
2309     ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2310   // If we overran the argument save area, we must use memory
2311   // (this check catches arguments passed partially in memory)
2312   if (ArgOffset > LinkageSize + ParamAreaSize)
2313     UseMemory = true;
2314
2315   // However, if the argument is actually passed in an FPR or a VR,
2316   // we don't use memory after all.
2317   if (!Flags.isByVal()) {
2318     if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2319       if (AvailableFPRs > 0) {
2320         --AvailableFPRs;
2321         return false;
2322       }
2323     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2324         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2325         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2326       if (AvailableVRs > 0) {
2327         --AvailableVRs;
2328         return false;
2329       }
2330   }
2331
2332   return UseMemory;
2333 }
2334
2335 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2336 /// ensure minimum alignment required for target.
2337 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2338                                      unsigned NumBytes) {
2339   unsigned TargetAlign =
2340       Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2341   unsigned AlignMask = TargetAlign - 1;
2342   NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2343   return NumBytes;
2344 }
2345
2346 SDValue
2347 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2348                                         CallingConv::ID CallConv, bool isVarArg,
2349                                         const SmallVectorImpl<ISD::InputArg>
2350                                           &Ins,
2351                                         SDLoc dl, SelectionDAG &DAG,
2352                                         SmallVectorImpl<SDValue> &InVals)
2353                                           const {
2354   if (Subtarget.isSVR4ABI()) {
2355     if (Subtarget.isPPC64())
2356       return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2357                                          dl, DAG, InVals);
2358     else
2359       return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2360                                          dl, DAG, InVals);
2361   } else {
2362     return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2363                                        dl, DAG, InVals);
2364   }
2365 }
2366
2367 SDValue
2368 PPCTargetLowering::LowerFormalArguments_32SVR4(
2369                                       SDValue Chain,
2370                                       CallingConv::ID CallConv, bool isVarArg,
2371                                       const SmallVectorImpl<ISD::InputArg>
2372                                         &Ins,
2373                                       SDLoc dl, SelectionDAG &DAG,
2374                                       SmallVectorImpl<SDValue> &InVals) const {
2375
2376   // 32-bit SVR4 ABI Stack Frame Layout:
2377   //              +-----------------------------------+
2378   //        +-->  |            Back chain             |
2379   //        |     +-----------------------------------+
2380   //        |     | Floating-point register save area |
2381   //        |     +-----------------------------------+
2382   //        |     |    General register save area     |
2383   //        |     +-----------------------------------+
2384   //        |     |          CR save word             |
2385   //        |     +-----------------------------------+
2386   //        |     |         VRSAVE save word          |
2387   //        |     +-----------------------------------+
2388   //        |     |         Alignment padding         |
2389   //        |     +-----------------------------------+
2390   //        |     |     Vector register save area     |
2391   //        |     +-----------------------------------+
2392   //        |     |       Local variable space        |
2393   //        |     +-----------------------------------+
2394   //        |     |        Parameter list area        |
2395   //        |     +-----------------------------------+
2396   //        |     |           LR save word            |
2397   //        |     +-----------------------------------+
2398   // SP-->  +---  |            Back chain             |
2399   //              +-----------------------------------+
2400   //
2401   // Specifications:
2402   //   System V Application Binary Interface PowerPC Processor Supplement
2403   //   AltiVec Technology Programming Interface Manual
2404
2405   MachineFunction &MF = DAG.getMachineFunction();
2406   MachineFrameInfo *MFI = MF.getFrameInfo();
2407   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2408
2409   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2410   // Potential tail calls could cause overwriting of argument stack slots.
2411   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2412                        (CallConv == CallingConv::Fast));
2413   unsigned PtrByteSize = 4;
2414
2415   // Assign locations to all of the incoming arguments.
2416   SmallVector<CCValAssign, 16> ArgLocs;
2417   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2418                  *DAG.getContext());
2419
2420   // Reserve space for the linkage area on the stack.
2421   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2422   CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2423
2424   CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2425
2426   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2427     CCValAssign &VA = ArgLocs[i];
2428
2429     // Arguments stored in registers.
2430     if (VA.isRegLoc()) {
2431       const TargetRegisterClass *RC;
2432       EVT ValVT = VA.getValVT();
2433
2434       switch (ValVT.getSimpleVT().SimpleTy) {
2435         default:
2436           llvm_unreachable("ValVT not supported by formal arguments Lowering");
2437         case MVT::i1:
2438         case MVT::i32:
2439           RC = &PPC::GPRCRegClass;
2440           break;
2441         case MVT::f32:
2442           RC = &PPC::F4RCRegClass;
2443           break;
2444         case MVT::f64:
2445           if (Subtarget.hasVSX())
2446             RC = &PPC::VSFRCRegClass;
2447           else
2448             RC = &PPC::F8RCRegClass;
2449           break;
2450         case MVT::v16i8:
2451         case MVT::v8i16:
2452         case MVT::v4i32:
2453         case MVT::v4f32:
2454           RC = &PPC::VRRCRegClass;
2455           break;
2456         case MVT::v2f64:
2457         case MVT::v2i64:
2458           RC = &PPC::VSHRCRegClass;
2459           break;
2460       }
2461
2462       // Transform the arguments stored in physical registers into virtual ones.
2463       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2464       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2465                                             ValVT == MVT::i1 ? MVT::i32 : ValVT);
2466
2467       if (ValVT == MVT::i1)
2468         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2469
2470       InVals.push_back(ArgValue);
2471     } else {
2472       // Argument stored in memory.
2473       assert(VA.isMemLoc());
2474
2475       unsigned ArgSize = VA.getLocVT().getStoreSize();
2476       int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2477                                       isImmutable);
2478
2479       // Create load nodes to retrieve arguments from the stack.
2480       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2481       InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2482                                    MachinePointerInfo(),
2483                                    false, false, false, 0));
2484     }
2485   }
2486
2487   // Assign locations to all of the incoming aggregate by value arguments.
2488   // Aggregates passed by value are stored in the local variable space of the
2489   // caller's stack frame, right above the parameter list area.
2490   SmallVector<CCValAssign, 16> ByValArgLocs;
2491   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2492                       ByValArgLocs, *DAG.getContext());
2493
2494   // Reserve stack space for the allocations in CCInfo.
2495   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2496
2497   CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2498
2499   // Area that is at least reserved in the caller of this function.
2500   unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2501   MinReservedArea = std::max(MinReservedArea, LinkageSize);
2502
2503   // Set the size that is at least reserved in caller of this function.  Tail
2504   // call optimized function's reserved stack space needs to be aligned so that
2505   // taking the difference between two stack areas will result in an aligned
2506   // stack.
2507   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2508   FuncInfo->setMinReservedArea(MinReservedArea);
2509
2510   SmallVector<SDValue, 8> MemOps;
2511
2512   // If the function takes variable number of arguments, make a frame index for
2513   // the start of the first vararg value... for expansion of llvm.va_start.
2514   if (isVarArg) {
2515     static const MCPhysReg GPArgRegs[] = {
2516       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2517       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2518     };
2519     const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2520
2521     static const MCPhysReg FPArgRegs[] = {
2522       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2523       PPC::F8
2524     };
2525     unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2526     if (DisablePPCFloatInVariadic)
2527       NumFPArgRegs = 0;
2528
2529     FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2530                                                           NumGPArgRegs));
2531     FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2532                                                           NumFPArgRegs));
2533
2534     // Make room for NumGPArgRegs and NumFPArgRegs.
2535     int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2536                 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2537
2538     FuncInfo->setVarArgsStackOffset(
2539       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2540                              CCInfo.getNextStackOffset(), true));
2541
2542     FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2543     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2544
2545     // The fixed integer arguments of a variadic function are stored to the
2546     // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2547     // the result of va_next.
2548     for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2549       // Get an existing live-in vreg, or add a new one.
2550       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2551       if (!VReg)
2552         VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2553
2554       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2555       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2556                                    MachinePointerInfo(), false, false, 0);
2557       MemOps.push_back(Store);
2558       // Increment the address by four for the next argument to store
2559       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2560       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2561     }
2562
2563     // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2564     // is set.
2565     // The double arguments are stored to the VarArgsFrameIndex
2566     // on the stack.
2567     for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2568       // Get an existing live-in vreg, or add a new one.
2569       unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2570       if (!VReg)
2571         VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2572
2573       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2574       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2575                                    MachinePointerInfo(), false, false, 0);
2576       MemOps.push_back(Store);
2577       // Increment the address by eight for the next argument to store
2578       SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2579                                          PtrVT);
2580       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2581     }
2582   }
2583
2584   if (!MemOps.empty())
2585     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2586
2587   return Chain;
2588 }
2589
2590 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2591 // value to MVT::i64 and then truncate to the correct register size.
2592 SDValue
2593 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2594                                      SelectionDAG &DAG, SDValue ArgVal,
2595                                      SDLoc dl) const {
2596   if (Flags.isSExt())
2597     ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2598                          DAG.getValueType(ObjectVT));
2599   else if (Flags.isZExt())
2600     ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2601                          DAG.getValueType(ObjectVT));
2602
2603   return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2604 }
2605
2606 SDValue
2607 PPCTargetLowering::LowerFormalArguments_64SVR4(
2608                                       SDValue Chain,
2609                                       CallingConv::ID CallConv, bool isVarArg,
2610                                       const SmallVectorImpl<ISD::InputArg>
2611                                         &Ins,
2612                                       SDLoc dl, SelectionDAG &DAG,
2613                                       SmallVectorImpl<SDValue> &InVals) const {
2614   // TODO: add description of PPC stack frame format, or at least some docs.
2615   //
2616   bool isELFv2ABI = Subtarget.isELFv2ABI();
2617   bool isLittleEndian = Subtarget.isLittleEndian();
2618   MachineFunction &MF = DAG.getMachineFunction();
2619   MachineFrameInfo *MFI = MF.getFrameInfo();
2620   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2621
2622   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2623   // Potential tail calls could cause overwriting of argument stack slots.
2624   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2625                        (CallConv == CallingConv::Fast));
2626   unsigned PtrByteSize = 8;
2627
2628   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2629                                                           isELFv2ABI);
2630
2631   static const MCPhysReg GPR[] = {
2632     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2633     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2634   };
2635
2636   static const MCPhysReg *FPR = GetFPR();
2637
2638   static const MCPhysReg VR[] = {
2639     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2640     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2641   };
2642   static const MCPhysReg VSRH[] = {
2643     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2644     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2645   };
2646
2647   const unsigned Num_GPR_Regs = array_lengthof(GPR);
2648   const unsigned Num_FPR_Regs = 13;
2649   const unsigned Num_VR_Regs  = array_lengthof(VR);
2650
2651   // Do a first pass over the arguments to determine whether the ABI
2652   // guarantees that our caller has allocated the parameter save area
2653   // on its stack frame.  In the ELFv1 ABI, this is always the case;
2654   // in the ELFv2 ABI, it is true if this is a vararg function or if
2655   // any parameter is located in a stack slot.
2656
2657   bool HasParameterArea = !isELFv2ABI || isVarArg;
2658   unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2659   unsigned NumBytes = LinkageSize;
2660   unsigned AvailableFPRs = Num_FPR_Regs;
2661   unsigned AvailableVRs = Num_VR_Regs;
2662   for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2663     if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2664                                PtrByteSize, LinkageSize, ParamAreaSize,
2665                                NumBytes, AvailableFPRs, AvailableVRs))
2666       HasParameterArea = true;
2667
2668   // Add DAG nodes to load the arguments or copy them out of registers.  On
2669   // entry to a function on PPC, the arguments start after the linkage area,
2670   // although the first ones are often in registers.
2671
2672   unsigned ArgOffset = LinkageSize;
2673   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2674   SmallVector<SDValue, 8> MemOps;
2675   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2676   unsigned CurArgIdx = 0;
2677   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2678     SDValue ArgVal;
2679     bool needsLoad = false;
2680     EVT ObjectVT = Ins[ArgNo].VT;
2681     EVT OrigVT = Ins[ArgNo].ArgVT;
2682     unsigned ObjSize = ObjectVT.getStoreSize();
2683     unsigned ArgSize = ObjSize;
2684     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2685     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2686     CurArgIdx = Ins[ArgNo].OrigArgIndex;
2687
2688     /* Respect alignment of argument on the stack.  */
2689     unsigned Align =
2690       CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2691     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2692     unsigned CurArgOffset = ArgOffset;
2693
2694     /* Compute GPR index associated with argument offset.  */
2695     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2696     GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2697
2698     // FIXME the codegen can be much improved in some cases.
2699     // We do not have to keep everything in memory.
2700     if (Flags.isByVal()) {
2701       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2702       ObjSize = Flags.getByValSize();
2703       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2704       // Empty aggregate parameters do not take up registers.  Examples:
2705       //   struct { } a;
2706       //   union  { } b;
2707       //   int c[0];
2708       // etc.  However, we have to provide a place-holder in InVals, so
2709       // pretend we have an 8-byte item at the current address for that
2710       // purpose.
2711       if (!ObjSize) {
2712         int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2713         SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2714         InVals.push_back(FIN);
2715         continue;
2716       }
2717
2718       // Create a stack object covering all stack doublewords occupied
2719       // by the argument.  If the argument is (fully or partially) on
2720       // the stack, or if the argument is fully in registers but the
2721       // caller has allocated the parameter save anyway, we can refer
2722       // directly to the caller's stack frame.  Otherwise, create a
2723       // local copy in our own frame.
2724       int FI;
2725       if (HasParameterArea ||
2726           ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2727         FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2728       else
2729         FI = MFI->CreateStackObject(ArgSize, Align, false);
2730       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2731
2732       // Handle aggregates smaller than 8 bytes.
2733       if (ObjSize < PtrByteSize) {
2734         // The value of the object is its address, which differs from the
2735         // address of the enclosing doubleword on big-endian systems.
2736         SDValue Arg = FIN;
2737         if (!isLittleEndian) {
2738           SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2739           Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2740         }
2741         InVals.push_back(Arg);
2742
2743         if (GPR_idx != Num_GPR_Regs) {
2744           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2745           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2746           SDValue Store;
2747
2748           if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2749             EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2750                            (ObjSize == 2 ? MVT::i16 : MVT::i32));
2751             Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2752                                       MachinePointerInfo(FuncArg),
2753                                       ObjType, false, false, 0);
2754           } else {
2755             // For sizes that don't fit a truncating store (3, 5, 6, 7),
2756             // store the whole register as-is to the parameter save area
2757             // slot.
2758             Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2759                                  MachinePointerInfo(FuncArg),
2760                                  false, false, 0);
2761           }
2762
2763           MemOps.push_back(Store);
2764         }
2765         // Whether we copied from a register or not, advance the offset
2766         // into the parameter save area by a full doubleword.
2767         ArgOffset += PtrByteSize;
2768         continue;
2769       }
2770
2771       // The value of the object is its address, which is the address of
2772       // its first stack doubleword.
2773       InVals.push_back(FIN);
2774
2775       // Store whatever pieces of the object are in registers to memory.
2776       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2777         if (GPR_idx == Num_GPR_Regs)
2778           break;
2779
2780         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2781         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2782         SDValue Addr = FIN;
2783         if (j) {
2784           SDValue Off = DAG.getConstant(j, PtrVT);
2785           Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2786         }
2787         SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2788                                      MachinePointerInfo(FuncArg, j),
2789                                      false, false, 0);
2790         MemOps.push_back(Store);
2791         ++GPR_idx;
2792       }
2793       ArgOffset += ArgSize;
2794       continue;
2795     }
2796
2797     switch (ObjectVT.getSimpleVT().SimpleTy) {
2798     default: llvm_unreachable("Unhandled argument type!");
2799     case MVT::i1:
2800     case MVT::i32:
2801     case MVT::i64:
2802       // These can be scalar arguments or elements of an integer array type
2803       // passed directly.  Clang may use those instead of "byval" aggregate
2804       // types to avoid forcing arguments to memory unnecessarily.
2805       if (GPR_idx != Num_GPR_Regs) {
2806         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2807         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2808
2809         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2810           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2811           // value to MVT::i64 and then truncate to the correct register size.
2812           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2813       } else {
2814         needsLoad = true;
2815         ArgSize = PtrByteSize;
2816       }
2817       ArgOffset += 8;
2818       break;
2819
2820     case MVT::f32:
2821     case MVT::f64:
2822       // These can be scalar arguments or elements of a float array type
2823       // passed directly.  The latter are used to implement ELFv2 homogenous
2824       // float aggregates.
2825       if (FPR_idx != Num_FPR_Regs) {
2826         unsigned VReg;
2827
2828         if (ObjectVT == MVT::f32)
2829           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2830         else
2831           VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2832                                             &PPC::VSFRCRegClass :
2833                                             &PPC::F8RCRegClass);
2834
2835         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2836         ++FPR_idx;
2837       } else if (GPR_idx != Num_GPR_Regs) {
2838         // This can only ever happen in the presence of f32 array types,
2839         // since otherwise we never run out of FPRs before running out
2840         // of GPRs.
2841         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2842         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2843
2844         if (ObjectVT == MVT::f32) {
2845           if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2846             ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2847                                  DAG.getConstant(32, MVT::i32));
2848           ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2849         }
2850
2851         ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2852       } else {
2853         needsLoad = true;
2854       }
2855
2856       // When passing an array of floats, the array occupies consecutive
2857       // space in the argument area; only round up to the next doubleword
2858       // at the end of the array.  Otherwise, each float takes 8 bytes.
2859       ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2860       ArgOffset += ArgSize;
2861       if (Flags.isInConsecutiveRegsLast())
2862         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2863       break;
2864     case MVT::v4f32:
2865     case MVT::v4i32:
2866     case MVT::v8i16:
2867     case MVT::v16i8:
2868     case MVT::v2f64:
2869     case MVT::v2i64:
2870       // These can be scalar arguments or elements of a vector array type
2871       // passed directly.  The latter are used to implement ELFv2 homogenous
2872       // vector aggregates.
2873       if (VR_idx != Num_VR_Regs) {
2874         unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2875                         MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2876                         MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2877         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2878         ++VR_idx;
2879       } else {
2880         needsLoad = true;
2881       }
2882       ArgOffset += 16;
2883       break;
2884     }
2885
2886     // We need to load the argument to a virtual register if we determined
2887     // above that we ran out of physical registers of the appropriate type.
2888     if (needsLoad) {
2889       if (ObjSize < ArgSize && !isLittleEndian)
2890         CurArgOffset += ArgSize - ObjSize;
2891       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2892       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2893       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2894                            false, false, false, 0);
2895     }
2896
2897     InVals.push_back(ArgVal);
2898   }
2899
2900   // Area that is at least reserved in the caller of this function.
2901   unsigned MinReservedArea;
2902   if (HasParameterArea)
2903     MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2904   else
2905     MinReservedArea = LinkageSize;
2906
2907   // Set the size that is at least reserved in caller of this function.  Tail
2908   // call optimized functions' reserved stack space needs to be aligned so that
2909   // taking the difference between two stack areas will result in an aligned
2910   // stack.
2911   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2912   FuncInfo->setMinReservedArea(MinReservedArea);
2913
2914   // If the function takes variable number of arguments, make a frame index for
2915   // the start of the first vararg value... for expansion of llvm.va_start.
2916   if (isVarArg) {
2917     int Depth = ArgOffset;
2918
2919     FuncInfo->setVarArgsFrameIndex(
2920       MFI->CreateFixedObject(PtrByteSize, Depth, true));
2921     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2922
2923     // If this function is vararg, store any remaining integer argument regs
2924     // to their spots on the stack so that they may be loaded by deferencing the
2925     // result of va_next.
2926     for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2927          GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2928       unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2929       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2930       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2931                                    MachinePointerInfo(), false, false, 0);
2932       MemOps.push_back(Store);
2933       // Increment the address by four for the next argument to store
2934       SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2935       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2936     }
2937   }
2938
2939   if (!MemOps.empty())
2940     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2941
2942   return Chain;
2943 }
2944
2945 SDValue
2946 PPCTargetLowering::LowerFormalArguments_Darwin(
2947                                       SDValue Chain,
2948                                       CallingConv::ID CallConv, bool isVarArg,
2949                                       const SmallVectorImpl<ISD::InputArg>
2950                                         &Ins,
2951                                       SDLoc dl, SelectionDAG &DAG,
2952                                       SmallVectorImpl<SDValue> &InVals) const {
2953   // TODO: add description of PPC stack frame format, or at least some docs.
2954   //
2955   MachineFunction &MF = DAG.getMachineFunction();
2956   MachineFrameInfo *MFI = MF.getFrameInfo();
2957   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2958
2959   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2960   bool isPPC64 = PtrVT == MVT::i64;
2961   // Potential tail calls could cause overwriting of argument stack slots.
2962   bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2963                        (CallConv == CallingConv::Fast));
2964   unsigned PtrByteSize = isPPC64 ? 8 : 4;
2965
2966   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2967                                                           false);
2968   unsigned ArgOffset = LinkageSize;
2969   // Area that is at least reserved in caller of this function.
2970   unsigned MinReservedArea = ArgOffset;
2971
2972   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
2973     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2974     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2975   };
2976   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
2977     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2978     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2979   };
2980
2981   static const MCPhysReg *FPR = GetFPR();
2982
2983   static const MCPhysReg VR[] = {
2984     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2985     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2986   };
2987
2988   const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2989   const unsigned Num_FPR_Regs = 13;
2990   const unsigned Num_VR_Regs  = array_lengthof( VR);
2991
2992   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2993
2994   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
2995
2996   // In 32-bit non-varargs functions, the stack space for vectors is after the
2997   // stack space for non-vectors.  We do not use this space unless we have
2998   // too many vectors to fit in registers, something that only occurs in
2999   // constructed examples:), but we have to walk the arglist to figure
3000   // that out...for the pathological case, compute VecArgOffset as the
3001   // start of the vector parameter area.  Computing VecArgOffset is the
3002   // entire point of the following loop.
3003   unsigned VecArgOffset = ArgOffset;
3004   if (!isVarArg && !isPPC64) {
3005     for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3006          ++ArgNo) {
3007       EVT ObjectVT = Ins[ArgNo].VT;
3008       ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3009
3010       if (Flags.isByVal()) {
3011         // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3012         unsigned ObjSize = Flags.getByValSize();
3013         unsigned ArgSize =
3014                 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3015         VecArgOffset += ArgSize;
3016         continue;
3017       }
3018
3019       switch(ObjectVT.getSimpleVT().SimpleTy) {
3020       default: llvm_unreachable("Unhandled argument type!");
3021       case MVT::i1:
3022       case MVT::i32:
3023       case MVT::f32:
3024         VecArgOffset += 4;
3025         break;
3026       case MVT::i64:  // PPC64
3027       case MVT::f64:
3028         // FIXME: We are guaranteed to be !isPPC64 at this point.
3029         // Does MVT::i64 apply?
3030         VecArgOffset += 8;
3031         break;
3032       case MVT::v4f32:
3033       case MVT::v4i32:
3034       case MVT::v8i16:
3035       case MVT::v16i8:
3036         // Nothing to do, we're only looking at Nonvector args here.
3037         break;
3038       }
3039     }
3040   }
3041   // We've found where the vector parameter area in memory is.  Skip the
3042   // first 12 parameters; these don't use that memory.
3043   VecArgOffset = ((VecArgOffset+15)/16)*16;
3044   VecArgOffset += 12*16;
3045
3046   // Add DAG nodes to load the arguments or copy them out of registers.  On
3047   // entry to a function on PPC, the arguments start after the linkage area,
3048   // although the first ones are often in registers.
3049
3050   SmallVector<SDValue, 8> MemOps;
3051   unsigned nAltivecParamsAtEnd = 0;
3052   Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3053   unsigned CurArgIdx = 0;
3054   for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3055     SDValue ArgVal;
3056     bool needsLoad = false;
3057     EVT ObjectVT = Ins[ArgNo].VT;
3058     unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3059     unsigned ArgSize = ObjSize;
3060     ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3061     std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3062     CurArgIdx = Ins[ArgNo].OrigArgIndex;
3063
3064     unsigned CurArgOffset = ArgOffset;
3065
3066     // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3067     if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3068         ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3069       if (isVarArg || isPPC64) {
3070         MinReservedArea = ((MinReservedArea+15)/16)*16;
3071         MinReservedArea += CalculateStackSlotSize(ObjectVT,
3072                                                   Flags,
3073                                                   PtrByteSize);
3074       } else  nAltivecParamsAtEnd++;
3075     } else
3076       // Calculate min reserved area.
3077       MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3078                                                 Flags,
3079                                                 PtrByteSize);
3080
3081     // FIXME the codegen can be much improved in some cases.
3082     // We do not have to keep everything in memory.
3083     if (Flags.isByVal()) {
3084       // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3085       ObjSize = Flags.getByValSize();
3086       ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3087       // Objects of size 1 and 2 are right justified, everything else is
3088       // left justified.  This means the memory address is adjusted forwards.
3089       if (ObjSize==1 || ObjSize==2) {
3090         CurArgOffset = CurArgOffset + (4 - ObjSize);
3091       }
3092       // The value of the object is its address.
3093       int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3094       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3095       InVals.push_back(FIN);
3096       if (ObjSize==1 || ObjSize==2) {
3097         if (GPR_idx != Num_GPR_Regs) {
3098           unsigned VReg;
3099           if (isPPC64)
3100             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3101           else
3102             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3103           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3104           EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3105           SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3106                                             MachinePointerInfo(FuncArg),
3107                                             ObjType, false, false, 0);
3108           MemOps.push_back(Store);
3109           ++GPR_idx;
3110         }
3111
3112         ArgOffset += PtrByteSize;
3113
3114         continue;
3115       }
3116       for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3117         // Store whatever pieces of the object are in registers
3118         // to memory.  ArgOffset will be the address of the beginning
3119         // of the object.
3120         if (GPR_idx != Num_GPR_Regs) {
3121           unsigned VReg;
3122           if (isPPC64)
3123             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3124           else
3125             VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3126           int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3127           SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3128           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3129           SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3130                                        MachinePointerInfo(FuncArg, j),
3131                                        false, false, 0);
3132           MemOps.push_back(Store);
3133           ++GPR_idx;
3134           ArgOffset += PtrByteSize;
3135         } else {
3136           ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3137           break;
3138         }
3139       }
3140       continue;
3141     }
3142
3143     switch (ObjectVT.getSimpleVT().SimpleTy) {
3144     default: llvm_unreachable("Unhandled argument type!");
3145     case MVT::i1:
3146     case MVT::i32:
3147       if (!isPPC64) {
3148         if (GPR_idx != Num_GPR_Regs) {
3149           unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3150           ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3151
3152           if (ObjectVT == MVT::i1)
3153             ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3154
3155           ++GPR_idx;
3156         } else {
3157           needsLoad = true;
3158           ArgSize = PtrByteSize;
3159         }
3160         // All int arguments reserve stack space in the Darwin ABI.
3161         ArgOffset += PtrByteSize;
3162         break;
3163       }
3164       // FALLTHROUGH
3165     case MVT::i64:  // PPC64
3166       if (GPR_idx != Num_GPR_Regs) {
3167         unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3168         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3169
3170         if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3171           // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3172           // value to MVT::i64 and then truncate to the correct register size.
3173           ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3174
3175         ++GPR_idx;
3176       } else {
3177         needsLoad = true;
3178         ArgSize = PtrByteSize;
3179       }
3180       // All int arguments reserve stack space in the Darwin ABI.
3181       ArgOffset += 8;
3182       break;
3183
3184     case MVT::f32:
3185     case MVT::f64:
3186       // Every 4 bytes of argument space consumes one of the GPRs available for
3187       // argument passing.
3188       if (GPR_idx != Num_GPR_Regs) {
3189         ++GPR_idx;
3190         if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3191           ++GPR_idx;
3192       }
3193       if (FPR_idx != Num_FPR_Regs) {
3194         unsigned VReg;
3195
3196         if (ObjectVT == MVT::f32)
3197           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3198         else
3199           VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3200
3201         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3202         ++FPR_idx;
3203       } else {
3204         needsLoad = true;
3205       }
3206
3207       // All FP arguments reserve stack space in the Darwin ABI.
3208       ArgOffset += isPPC64 ? 8 : ObjSize;
3209       break;
3210     case MVT::v4f32:
3211     case MVT::v4i32:
3212     case MVT::v8i16:
3213     case MVT::v16i8:
3214       // Note that vector arguments in registers don't reserve stack space,
3215       // except in varargs functions.
3216       if (VR_idx != Num_VR_Regs) {
3217         unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3218         ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3219         if (isVarArg) {
3220           while ((ArgOffset % 16) != 0) {
3221             ArgOffset += PtrByteSize;
3222             if (GPR_idx != Num_GPR_Regs)
3223               GPR_idx++;
3224           }
3225           ArgOffset += 16;
3226           GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3227         }
3228         ++VR_idx;
3229       } else {
3230         if (!isVarArg && !isPPC64) {
3231           // Vectors go after all the nonvectors.
3232           CurArgOffset = VecArgOffset;
3233           VecArgOffset += 16;
3234         } else {
3235           // Vectors are aligned.
3236           ArgOffset = ((ArgOffset+15)/16)*16;
3237           CurArgOffset = ArgOffset;
3238           ArgOffset += 16;
3239         }
3240         needsLoad = true;
3241       }
3242       break;
3243     }
3244
3245     // We need to load the argument to a virtual register if we determined above
3246     // that we ran out of physical registers of the appropriate type.
3247     if (needsLoad) {
3248       int FI = MFI->CreateFixedObject(ObjSize,
3249                                       CurArgOffset + (ArgSize - ObjSize),
3250                                       isImmutable);
3251       SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3252       ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3253                            false, false, false, 0);
3254     }
3255
3256     InVals.push_back(ArgVal);
3257   }
3258
3259   // Allow for Altivec parameters at the end, if needed.
3260   if (nAltivecParamsAtEnd) {
3261     MinReservedArea = ((MinReservedArea+15)/16)*16;
3262     MinReservedArea += 16*nAltivecParamsAtEnd;
3263   }
3264
3265   // Area that is at least reserved in the caller of this function.
3266   MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3267
3268   // Set the size that is at least reserved in caller of this function.  Tail
3269   // call optimized functions' reserved stack space needs to be aligned so that
3270   // taking the difference between two stack areas will result in an aligned
3271   // stack.
3272   MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3273   FuncInfo->setMinReservedArea(MinReservedArea);
3274
3275   // If the function takes variable number of arguments, make a frame index for
3276   // the start of the first vararg value... for expansion of llvm.va_start.
3277   if (isVarArg) {
3278     int Depth = ArgOffset;
3279
3280     FuncInfo->setVarArgsFrameIndex(
3281       MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3282                              Depth, true));
3283     SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3284
3285     // If this function is vararg, store any remaining integer argument regs
3286     // to their spots on the stack so that they may be loaded by deferencing the
3287     // result of va_next.
3288     for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3289       unsigned VReg;
3290
3291       if (isPPC64)
3292         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3293       else
3294         VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3295
3296       SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3297       SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3298                                    MachinePointerInfo(), false, false, 0);
3299       MemOps.push_back(Store);
3300       // Increment the address by four for the next argument to store
3301       SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3302       FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3303     }
3304   }
3305
3306   if (!MemOps.empty())
3307     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3308
3309   return Chain;
3310 }
3311
3312 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3313 /// adjusted to accommodate the arguments for the tailcall.
3314 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3315                                    unsigned ParamSize) {
3316
3317   if (!isTailCall) return 0;
3318
3319   PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3320   unsigned CallerMinReservedArea = FI->getMinReservedArea();
3321   int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3322   // Remember only if the new adjustement is bigger.
3323   if (SPDiff < FI->getTailCallSPDelta())
3324     FI->setTailCallSPDelta(SPDiff);
3325
3326   return SPDiff;
3327 }
3328
3329 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3330 /// for tail call optimization. Targets which want to do tail call
3331 /// optimization should implement this function.
3332 bool
3333 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3334                                                      CallingConv::ID CalleeCC,
3335                                                      bool isVarArg,
3336                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3337                                                      SelectionDAG& DAG) const {
3338   if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3339     return false;
3340
3341   // Variable argument functions are not supported.
3342   if (isVarArg)
3343     return false;
3344
3345   MachineFunction &MF = DAG.getMachineFunction();
3346   CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3347   if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3348     // Functions containing by val parameters are not supported.
3349     for (unsigned i = 0; i != Ins.size(); i++) {
3350        ISD::ArgFlagsTy Flags = Ins[i].Flags;
3351        if (Flags.isByVal()) return false;
3352     }
3353
3354     // Non-PIC/GOT tail calls are supported.
3355     if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3356       return true;
3357
3358     // At the moment we can only do local tail calls (in same module, hidden
3359     // or protected) if we are generating PIC.
3360     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3361       return G->getGlobal()->hasHiddenVisibility()
3362           || G->getGlobal()->hasProtectedVisibility();
3363   }
3364
3365   return false;
3366 }
3367
3368 /// isCallCompatibleAddress - Return the immediate to use if the specified
3369 /// 32-bit value is representable in the immediate field of a BxA instruction.
3370 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3371   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3372   if (!C) return nullptr;
3373
3374   int Addr = C->getZExtValue();
3375   if ((Addr & 3) != 0 ||  // Low 2 bits are implicitly zero.
3376       SignExtend32<26>(Addr) != Addr)
3377     return nullptr;  // Top 6 bits have to be sext of immediate.
3378
3379   return DAG.getConstant((int)C->getZExtValue() >> 2,
3380                          DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3381 }
3382
3383 namespace {
3384
3385 struct TailCallArgumentInfo {
3386   SDValue Arg;
3387   SDValue FrameIdxOp;
3388   int       FrameIdx;
3389
3390   TailCallArgumentInfo() : FrameIdx(0) {}
3391 };
3392
3393 }
3394
3395 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3396 static void
3397 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3398                                            SDValue Chain,
3399                    const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3400                    SmallVectorImpl<SDValue> &MemOpChains,
3401                    SDLoc dl) {
3402   for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3403     SDValue Arg = TailCallArgs[i].Arg;
3404     SDValue FIN = TailCallArgs[i].FrameIdxOp;
3405     int FI = TailCallArgs[i].FrameIdx;
3406     // Store relative to framepointer.
3407     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3408                                        MachinePointerInfo::getFixedStack(FI),
3409                                        false, false, 0));
3410   }
3411 }
3412
3413 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3414 /// the appropriate stack slot for the tail call optimized function call.
3415 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3416                                                MachineFunction &MF,
3417                                                SDValue Chain,
3418                                                SDValue OldRetAddr,
3419                                                SDValue OldFP,
3420                                                int SPDiff,
3421                                                bool isPPC64,
3422                                                bool isDarwinABI,
3423                                                SDLoc dl) {
3424   if (SPDiff) {
3425     // Calculate the new stack slot for the return address.
3426     int SlotSize = isPPC64 ? 8 : 4;
3427     int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3428                                                                    isDarwinABI);
3429     int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3430                                                           NewRetAddrLoc, true);
3431     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3432     SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3433     Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3434                          MachinePointerInfo::getFixedStack(NewRetAddr),
3435                          false, false, 0);
3436
3437     // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3438     // slot as the FP is never overwritten.
3439     if (isDarwinABI) {
3440       int NewFPLoc =
3441         SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3442       int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3443                                                           true);
3444       SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3445       Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3446                            MachinePointerInfo::getFixedStack(NewFPIdx),
3447                            false, false, 0);
3448     }
3449   }
3450   return Chain;
3451 }
3452
3453 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3454 /// the position of the argument.
3455 static void
3456 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3457                          SDValue Arg, int SPDiff, unsigned ArgOffset,
3458                      SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3459   int Offset = ArgOffset + SPDiff;
3460   uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3461   int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3462   EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3463   SDValue FIN = DAG.getFrameIndex(FI, VT);
3464   TailCallArgumentInfo Info;
3465   Info.Arg = Arg;
3466   Info.FrameIdxOp = FIN;
3467   Info.FrameIdx = FI;
3468   TailCallArguments.push_back(Info);
3469 }
3470
3471 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3472 /// stack slot. Returns the chain as result and the loaded frame pointers in
3473 /// LROpOut/FPOpout. Used when tail calling.
3474 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3475                                                         int SPDiff,
3476                                                         SDValue Chain,
3477                                                         SDValue &LROpOut,
3478                                                         SDValue &FPOpOut,
3479                                                         bool isDarwinABI,
3480                                                         SDLoc dl) const {
3481   if (SPDiff) {
3482     // Load the LR and FP stack slot for later adjusting.
3483     EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3484     LROpOut = getReturnAddrFrameIndex(DAG);
3485     LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3486                           false, false, false, 0);
3487     Chain = SDValue(LROpOut.getNode(), 1);
3488
3489     // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3490     // slot as the FP is never overwritten.
3491     if (isDarwinABI) {
3492       FPOpOut = getFramePointerFrameIndex(DAG);
3493       FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3494                             false, false, false, 0);
3495       Chain = SDValue(FPOpOut.getNode(), 1);
3496     }
3497   }
3498   return Chain;
3499 }
3500
3501 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3502 /// by "Src" to address "Dst" of size "Size".  Alignment information is
3503 /// specified by the specific parameter attribute. The copy will be passed as
3504 /// a byval function parameter.
3505 /// Sometimes what we are copying is the end of a larger object, the part that
3506 /// does not fit in registers.
3507 static SDValue
3508 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3509                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3510                           SDLoc dl) {
3511   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3512   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3513                        false, false, MachinePointerInfo(),
3514                        MachinePointerInfo());
3515 }
3516
3517 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3518 /// tail calls.
3519 static void
3520 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3521                  SDValue Arg, SDValue PtrOff, int SPDiff,
3522                  unsigned ArgOffset, bool isPPC64, bool isTailCall,
3523                  bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3524                  SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3525                  SDLoc dl) {
3526   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3527   if (!isTailCall) {
3528     if (isVector) {
3529       SDValue StackPtr;
3530       if (isPPC64)
3531         StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3532       else
3533         StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3534       PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3535                            DAG.getConstant(ArgOffset, PtrVT));
3536     }
3537     MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3538                                        MachinePointerInfo(), false, false, 0));
3539   // Calculate and remember argument location.
3540   } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3541                                   TailCallArguments);
3542 }
3543
3544 static
3545 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3546                      SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3547                      SDValue LROp, SDValue FPOp, bool isDarwinABI,
3548                      SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3549   MachineFunction &MF = DAG.getMachineFunction();
3550
3551   // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3552   // might overwrite each other in case of tail call optimization.
3553   SmallVector<SDValue, 8> MemOpChains2;
3554   // Do not flag preceding copytoreg stuff together with the following stuff.
3555   InFlag = SDValue();
3556   StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3557                                     MemOpChains2, dl);
3558   if (!MemOpChains2.empty())
3559     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3560
3561   // Store the return address to the appropriate stack slot.
3562   Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3563                                         isPPC64, isDarwinABI, dl);
3564
3565   // Emit callseq_end just before tailcall node.
3566   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3567                              DAG.getIntPtrConstant(0, true), InFlag, dl);
3568   InFlag = Chain.getValue(1);
3569 }
3570
3571 static
3572 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3573                      SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3574                      SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3575                      SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3576                      const PPCSubtarget &Subtarget) {
3577
3578   bool isPPC64 = Subtarget.isPPC64();
3579   bool isSVR4ABI = Subtarget.isSVR4ABI();
3580   bool isELFv2ABI = Subtarget.isELFv2ABI();
3581
3582   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3583   NodeTys.push_back(MVT::Other);   // Returns a chain
3584   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
3585
3586   unsigned CallOpc = PPCISD::CALL;
3587
3588   bool needIndirectCall = true;
3589   if (!isSVR4ABI || !isPPC64)
3590     if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3591       // If this is an absolute destination address, use the munged value.
3592       Callee = SDValue(Dest, 0);
3593       needIndirectCall = false;
3594     }
3595
3596   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3597     unsigned OpFlags = 0;
3598     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3599          (Subtarget.getTargetTriple().isMacOSX() &&
3600           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3601          (G->getGlobal()->isDeclaration() ||
3602           G->getGlobal()->isWeakForLinker())) ||
3603         (Subtarget.isTargetELF() && !isPPC64 &&
3604          !G->getGlobal()->hasLocalLinkage() &&
3605          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3606       // PC-relative references to external symbols should go through $stub,
3607       // unless we're building with the leopard linker or later, which
3608       // automatically synthesizes these stubs.
3609       OpFlags = PPCII::MO_PLT_OR_STUB;
3610     }
3611
3612     // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3613     // every direct call is) turn it into a TargetGlobalAddress /
3614     // TargetExternalSymbol node so that legalize doesn't hack it.
3615     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3616                                         Callee.getValueType(), 0, OpFlags);
3617     needIndirectCall = false;
3618   }
3619
3620   if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3621     unsigned char OpFlags = 0;
3622
3623     if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3624          (Subtarget.getTargetTriple().isMacOSX() &&
3625           Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3626         (Subtarget.isTargetELF() && !isPPC64 &&
3627          DAG.getTarget().getRelocationModel() == Reloc::PIC_)   ) {
3628       // PC-relative references to external symbols should go through $stub,
3629       // unless we're building with the leopard linker or later, which
3630       // automatically synthesizes these stubs.
3631       OpFlags = PPCII::MO_PLT_OR_STUB;
3632     }
3633
3634     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3635                                          OpFlags);
3636     needIndirectCall = false;
3637   }
3638
3639   if (needIndirectCall) {
3640     // Otherwise, this is an indirect call.  We have to use a MTCTR/BCTRL pair
3641     // to do the call, we can't use PPCISD::CALL.
3642     SDValue MTCTROps[] = {Chain, Callee, InFlag};
3643
3644     if (isSVR4ABI && isPPC64 && !isELFv2ABI) {
3645       // Function pointers in the 64-bit SVR4 ABI do not point to the function
3646       // entry point, but to the function descriptor (the function entry point
3647       // address is part of the function descriptor though).
3648       // The function descriptor is a three doubleword structure with the
3649       // following fields: function entry point, TOC base address and
3650       // environment pointer.
3651       // Thus for a call through a function pointer, the following actions need
3652       // to be performed:
3653       //   1. Save the TOC of the caller in the TOC save area of its stack
3654       //      frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3655       //   2. Load the address of the function entry point from the function
3656       //      descriptor.
3657       //   3. Load the TOC of the callee from the function descriptor into r2.
3658       //   4. Load the environment pointer from the function descriptor into
3659       //      r11.
3660       //   5. Branch to the function entry point address.
3661       //   6. On return of the callee, the TOC of the caller needs to be
3662       //      restored (this is done in FinishCall()).
3663       //
3664       // All those operations are flagged together to ensure that no other
3665       // operations can be scheduled in between. E.g. without flagging the
3666       // operations together, a TOC access in the caller could be scheduled
3667       // between the load of the callee TOC and the branch to the callee, which
3668       // results in the TOC access going through the TOC of the callee instead
3669       // of going through the TOC of the caller, which leads to incorrect code.
3670
3671       // Load the address of the function entry point from the function
3672       // descriptor.
3673       SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3674       SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3675                               makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3676       Chain = LoadFuncPtr.getValue(1);
3677       InFlag = LoadFuncPtr.getValue(2);
3678
3679       // Load environment pointer into r11.
3680       // Offset of the environment pointer within the function descriptor.
3681       SDValue PtrOff = DAG.getIntPtrConstant(16);
3682
3683       SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3684       SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3685                                        InFlag);
3686       Chain = LoadEnvPtr.getValue(1);
3687       InFlag = LoadEnvPtr.getValue(2);
3688
3689       SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3690                                         InFlag);
3691       Chain = EnvVal.getValue(0);
3692       InFlag = EnvVal.getValue(1);
3693
3694       // Load TOC of the callee into r2. We are using a target-specific load
3695       // with r2 hard coded, because the result of a target-independent load
3696       // would never go directly into r2, since r2 is a reserved register (which
3697       // prevents the register allocator from allocating it), resulting in an
3698       // additional register being allocated and an unnecessary move instruction
3699       // being generated.
3700       VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3701       SDValue TOCOff = DAG.getIntPtrConstant(8);
3702       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3703       SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3704                                        AddTOC, InFlag);
3705       Chain = LoadTOCPtr.getValue(0);
3706       InFlag = LoadTOCPtr.getValue(1);
3707
3708       MTCTROps[0] = Chain;
3709       MTCTROps[1] = LoadFuncPtr;
3710       MTCTROps[2] = InFlag;
3711     }
3712
3713     Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3714                         makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3715     InFlag = Chain.getValue(1);
3716
3717     NodeTys.clear();
3718     NodeTys.push_back(MVT::Other);
3719     NodeTys.push_back(MVT::Glue);
3720     Ops.push_back(Chain);
3721     CallOpc = PPCISD::BCTRL;
3722     Callee.setNode(nullptr);
3723     // Add use of X11 (holding environment pointer)
3724     if (isSVR4ABI && isPPC64 && !isELFv2ABI)
3725       Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3726     // Add CTR register as callee so a bctr can be emitted later.
3727     if (isTailCall)
3728       Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3729   }
3730
3731   // If this is a direct call, pass the chain and the callee.
3732   if (Callee.getNode()) {
3733     Ops.push_back(Chain);
3734     Ops.push_back(Callee);
3735
3736     // If this is a call to __tls_get_addr, find the symbol whose address
3737     // is to be taken and add it to the list.  This will be used to 
3738     // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3739     // We find the symbol by walking the chain to the CopyFromReg, walking
3740     // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3741     // pulling the symbol from that node.
3742     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3743       if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3744         assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3745         SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3746         SDValue TGTAddr = AddI->getOperand(1);
3747         assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3748                "Didn't find target global TLS address where we expected one");
3749         Ops.push_back(TGTAddr);
3750         CallOpc = PPCISD::CALL_TLS;
3751       }
3752   }
3753   // If this is a tail call add stack pointer delta.
3754   if (isTailCall)
3755     Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3756
3757   // Add argument registers to the end of the list so that they are known live
3758   // into the call.
3759   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3760     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3761                                   RegsToPass[i].second.getValueType()));
3762
3763   // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3764   if (Callee.getNode() && isELFv2ABI)
3765     Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3766
3767   return CallOpc;
3768 }
3769
3770 static
3771 bool isLocalCall(const SDValue &Callee)
3772 {
3773   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3774     return !G->getGlobal()->isDeclaration() &&
3775            !G->getGlobal()->isWeakForLinker();
3776   return false;
3777 }
3778
3779 SDValue
3780 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3781                                    CallingConv::ID CallConv, bool isVarArg,
3782                                    const SmallVectorImpl<ISD::InputArg> &Ins,
3783                                    SDLoc dl, SelectionDAG &DAG,
3784                                    SmallVectorImpl<SDValue> &InVals) const {
3785
3786   SmallVector<CCValAssign, 16> RVLocs;
3787   CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3788                     *DAG.getContext());
3789   CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3790
3791   // Copy all of the result registers out of their specified physreg.
3792   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3793     CCValAssign &VA = RVLocs[i];
3794     assert(VA.isRegLoc() && "Can only return in registers!");
3795
3796     SDValue Val = DAG.getCopyFromReg(Chain, dl,
3797                                      VA.getLocReg(), VA.getLocVT(), InFlag);
3798     Chain = Val.getValue(1);
3799     InFlag = Val.getValue(2);
3800
3801     switch (VA.getLocInfo()) {
3802     default: llvm_unreachable("Unknown loc info!");
3803     case CCValAssign::Full: break;
3804     case CCValAssign::AExt:
3805       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3806       break;
3807     case CCValAssign::ZExt:
3808       Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3809                         DAG.getValueType(VA.getValVT()));
3810       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3811       break;
3812     case CCValAssign::SExt:
3813       Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3814                         DAG.getValueType(VA.getValVT()));
3815       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3816       break;
3817     }
3818
3819     InVals.push_back(Val);
3820   }
3821
3822   return Chain;
3823 }
3824
3825 SDValue
3826 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3827                               bool isTailCall, bool isVarArg,
3828                               SelectionDAG &DAG,
3829                               SmallVector<std::pair<unsigned, SDValue>, 8>
3830                                 &RegsToPass,
3831                               SDValue InFlag, SDValue Chain,
3832                               SDValue &Callee,
3833                               int SPDiff, unsigned NumBytes,
3834                               const SmallVectorImpl<ISD::InputArg> &Ins,
3835                               SmallVectorImpl<SDValue> &InVals) const {
3836
3837   bool isELFv2ABI = Subtarget.isELFv2ABI();
3838   std::vector<EVT> NodeTys;
3839   SmallVector<SDValue, 8> Ops;
3840   unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3841                                  isTailCall, RegsToPass, Ops, NodeTys,
3842                                  Subtarget);
3843
3844   // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3845   if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3846     Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3847
3848   // When performing tail call optimization the callee pops its arguments off
3849   // the stack. Account for this here so these bytes can be pushed back on in
3850   // PPCFrameLowering::eliminateCallFramePseudoInstr.
3851   int BytesCalleePops =
3852     (CallConv == CallingConv::Fast &&
3853      getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3854
3855   // Add a register mask operand representing the call-preserved registers.
3856   const TargetRegisterInfo *TRI =
3857       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3858   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3859   assert(Mask && "Missing call preserved mask for calling convention");
3860   Ops.push_back(DAG.getRegisterMask(Mask));
3861
3862   if (InFlag.getNode())
3863     Ops.push_back(InFlag);
3864
3865   // Emit tail call.
3866   if (isTailCall) {
3867     assert(((Callee.getOpcode() == ISD::Register &&
3868              cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3869             Callee.getOpcode() == ISD::TargetExternalSymbol ||
3870             Callee.getOpcode() == ISD::TargetGlobalAddress ||
3871             isa<ConstantSDNode>(Callee)) &&
3872     "Expecting an global address, external symbol, absolute value or register");
3873
3874     return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3875   }
3876
3877   // Add a NOP immediately after the branch instruction when using the 64-bit
3878   // SVR4 ABI. At link time, if caller and callee are in a different module and
3879   // thus have a different TOC, the call will be replaced with a call to a stub
3880   // function which saves the current TOC, loads the TOC of the callee and
3881   // branches to the callee. The NOP will be replaced with a load instruction
3882   // which restores the TOC of the caller from the TOC save slot of the current
3883   // stack frame. If caller and callee belong to the same module (and have the
3884   // same TOC), the NOP will remain unchanged.
3885
3886   if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3887     if (CallOpc == PPCISD::BCTRL) {
3888       // This is a call through a function pointer.
3889       // Restore the caller TOC from the save area into R2.
3890       // See PrepareCall() for more information about calls through function
3891       // pointers in the 64-bit SVR4 ABI.
3892       // We are using a target-specific load with r2 hard coded, because the
3893       // result of a target-independent load would never go directly into r2,
3894       // since r2 is a reserved register (which prevents the register allocator
3895       // from allocating it), resulting in an additional register being
3896       // allocated and an unnecessary move instruction being generated.
3897       CallOpc = PPCISD::BCTRL_LOAD_TOC;
3898
3899       EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3900       SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3901       unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3902       SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3903       SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3904
3905       // The address needs to go after the chain input but before the flag (or
3906       // any other variadic arguments).
3907       Ops.insert(std::next(Ops.begin()), AddTOC);
3908     } else if ((CallOpc == PPCISD::CALL) &&
3909                (!isLocalCall(Callee) ||
3910                 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3911       // Otherwise insert NOP for non-local calls.
3912       CallOpc = PPCISD::CALL_NOP;
3913     } else if (CallOpc == PPCISD::CALL_TLS)
3914       // For 64-bit SVR4, TLS calls are always non-local.
3915       CallOpc = PPCISD::CALL_NOP_TLS;
3916   }
3917
3918   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3919   InFlag = Chain.getValue(1);
3920
3921   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3922                              DAG.getIntPtrConstant(BytesCalleePops, true),
3923                              InFlag, dl);
3924   if (!Ins.empty())
3925     InFlag = Chain.getValue(1);
3926
3927   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3928                          Ins, dl, DAG, InVals);
3929 }
3930
3931 SDValue
3932 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3933                              SmallVectorImpl<SDValue> &InVals) const {
3934   SelectionDAG &DAG                     = CLI.DAG;
3935   SDLoc &dl                             = CLI.DL;
3936   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3937   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3938   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3939   SDValue Chain                         = CLI.Chain;
3940   SDValue Callee                        = CLI.Callee;
3941   bool &isTailCall                      = CLI.IsTailCall;
3942   CallingConv::ID CallConv              = CLI.CallConv;
3943   bool isVarArg                         = CLI.IsVarArg;
3944
3945   if (isTailCall)
3946     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3947                                                    Ins, DAG);
3948
3949   if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3950     report_fatal_error("failed to perform tail call elimination on a call "
3951                        "site marked musttail");
3952
3953   if (Subtarget.isSVR4ABI()) {
3954     if (Subtarget.isPPC64())
3955       return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3956                               isTailCall, Outs, OutVals, Ins,
3957                               dl, DAG, InVals);
3958     else
3959       return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3960                               isTailCall, Outs, OutVals, Ins,
3961                               dl, DAG, InVals);
3962   }
3963
3964   return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3965                           isTailCall, Outs, OutVals, Ins,
3966                           dl, DAG, InVals);
3967 }
3968
3969 SDValue
3970 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3971                                     CallingConv::ID CallConv, bool isVarArg,
3972                                     bool isTailCall,
3973                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3974                                     const SmallVectorImpl<SDValue> &OutVals,
3975                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3976                                     SDLoc dl, SelectionDAG &DAG,
3977                                     SmallVectorImpl<SDValue> &InVals) const {
3978   // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3979   // of the 32-bit SVR4 ABI stack frame layout.
3980
3981   assert((CallConv == CallingConv::C ||
3982           CallConv == CallingConv::Fast) && "Unknown calling convention!");
3983
3984   unsigned PtrByteSize = 4;
3985
3986   MachineFunction &MF = DAG.getMachineFunction();
3987
3988   // Mark this function as potentially containing a function that contains a
3989   // tail call. As a consequence the frame pointer will be used for dynamicalloc
3990   // and restoring the callers stack pointer in this functions epilog. This is
3991   // done because by tail calling the called function might overwrite the value
3992   // in this function's (MF) stack pointer stack slot 0(SP).
3993   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3994       CallConv == CallingConv::Fast)
3995     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3996
3997   // Count how many bytes are to be pushed on the stack, including the linkage
3998   // area, parameter list area and the part of the local variable space which
3999   // contains copies of aggregates which are passed by value.
4000
4001   // Assign locations to all of the outgoing arguments.
4002   SmallVector<CCValAssign, 16> ArgLocs;
4003   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4004                  *DAG.getContext());
4005
4006   // Reserve space for the linkage area on the stack.
4007   CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4008                        PtrByteSize);
4009
4010   if (isVarArg) {
4011     // Handle fixed and variable vector arguments differently.
4012     // Fixed vector arguments go into registers as long as registers are
4013     // available. Variable vector arguments always go into memory.
4014     unsigned NumArgs = Outs.size();
4015
4016     for (unsigned i = 0; i != NumArgs; ++i) {
4017       MVT ArgVT = Outs[i].VT;
4018       ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4019       bool Result;
4020
4021       if (Outs[i].IsFixed) {
4022         Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4023                                CCInfo);
4024       } else {
4025         Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4026                                       ArgFlags, CCInfo);
4027       }
4028
4029       if (Result) {
4030 #ifndef NDEBUG
4031         errs() << "Call operand #" << i << " has unhandled type "
4032              << EVT(ArgVT).getEVTString() << "\n";
4033 #endif
4034         llvm_unreachable(nullptr);
4035       }
4036     }
4037   } else {
4038     // All arguments are treated the same.
4039     CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4040   }
4041
4042   // Assign locations to all of the outgoing aggregate by value arguments.
4043   SmallVector<CCValAssign, 16> ByValArgLocs;
4044   CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4045                       ByValArgLocs, *DAG.getContext());
4046
4047   // Reserve stack space for the allocations in CCInfo.
4048   CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4049
4050   CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4051
4052   // Size of the linkage area, parameter list area and the part of the local
4053   // space variable where copies of aggregates which are passed by value are
4054   // stored.
4055   unsigned NumBytes = CCByValInfo.getNextStackOffset();
4056
4057   // Calculate by how many bytes the stack has to be adjusted in case of tail
4058   // call optimization.
4059   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4060
4061   // Adjust the stack pointer for the new arguments...
4062   // These operations are automatically eliminated by the prolog/epilog pass
4063   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4064                                dl);
4065   SDValue CallSeqStart = Chain;
4066
4067   // Load the return address and frame pointer so it can be moved somewhere else
4068   // later.
4069   SDValue LROp, FPOp;
4070   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4071                                        dl);
4072
4073   // Set up a copy of the stack pointer for use loading and storing any
4074   // arguments that may not fit in the registers available for argument
4075   // passing.
4076   SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4077
4078   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4079   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4080   SmallVector<SDValue, 8> MemOpChains;
4081
4082   bool seenFloatArg = false;
4083   // Walk the register/memloc assignments, inserting copies/loads.
4084   for (unsigned i = 0, j = 0, e = ArgLocs.size();
4085        i != e;
4086        ++i) {
4087     CCValAssign &VA = ArgLocs[i];
4088     SDValue Arg = OutVals[i];
4089     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4090
4091     if (Flags.isByVal()) {
4092       // Argument is an aggregate which is passed by value, thus we need to
4093       // create a copy of it in the local variable space of the current stack
4094       // frame (which is the stack frame of the caller) and pass the address of
4095       // this copy to the callee.
4096       assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4097       CCValAssign &ByValVA = ByValArgLocs[j++];
4098       assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4099
4100       // Memory reserved in the local variable space of the callers stack frame.
4101       unsigned LocMemOffset = ByValVA.getLocMemOffset();
4102
4103       SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4104       PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4105
4106       // Create a copy of the argument in the local area of the current
4107       // stack frame.
4108       SDValue MemcpyCall =
4109         CreateCopyOfByValArgument(Arg, PtrOff,
4110                                   CallSeqStart.getNode()->getOperand(0),
4111                                   Flags, DAG, dl);
4112
4113       // This must go outside the CALLSEQ_START..END.
4114       SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4115                            CallSeqStart.getNode()->getOperand(1),
4116                            SDLoc(MemcpyCall));
4117       DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4118                              NewCallSeqStart.getNode());
4119       Chain = CallSeqStart = NewCallSeqStart;
4120
4121       // Pass the address of the aggregate copy on the stack either in a
4122       // physical register or in the parameter list area of the current stack
4123       // frame to the callee.
4124       Arg = PtrOff;
4125     }
4126
4127     if (VA.isRegLoc()) {
4128       if (Arg.getValueType() == MVT::i1)
4129         Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4130
4131       seenFloatArg |= VA.getLocVT().isFloatingPoint();
4132       // Put argument in a physical register.
4133       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4134     } else {
4135       // Put argument in the parameter list area of the current stack frame.
4136       assert(VA.isMemLoc());
4137       unsigned LocMemOffset = VA.getLocMemOffset();
4138
4139       if (!isTailCall) {
4140         SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4141         PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4142
4143         MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4144                                            MachinePointerInfo(),
4145                                            false, false, 0));
4146       } else {
4147         // Calculate and remember argument location.
4148         CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4149                                  TailCallArguments);
4150       }
4151     }
4152   }
4153
4154   if (!MemOpChains.empty())
4155     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4156
4157   // Build a sequence of copy-to-reg nodes chained together with token chain
4158   // and flag operands which copy the outgoing args into the appropriate regs.
4159   SDValue InFlag;
4160   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4161     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4162                              RegsToPass[i].second, InFlag);
4163     InFlag = Chain.getValue(1);
4164   }
4165
4166   // Set CR bit 6 to true if this is a vararg call with floating args passed in
4167   // registers.
4168   if (isVarArg) {
4169     SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4170     SDValue Ops[] = { Chain, InFlag };
4171
4172     Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4173                         dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4174
4175     InFlag = Chain.getValue(1);
4176   }
4177
4178   if (isTailCall)
4179     PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4180                     false, TailCallArguments);
4181
4182   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4183                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4184                     Ins, InVals);
4185 }
4186
4187 // Copy an argument into memory, being careful to do this outside the
4188 // call sequence for the call to which the argument belongs.
4189 SDValue
4190 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4191                                               SDValue CallSeqStart,
4192                                               ISD::ArgFlagsTy Flags,
4193                                               SelectionDAG &DAG,
4194                                               SDLoc dl) const {
4195   SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4196                         CallSeqStart.getNode()->getOperand(0),
4197                         Flags, DAG, dl);
4198   // The MEMCPY must go outside the CALLSEQ_START..END.
4199   SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4200                              CallSeqStart.getNode()->getOperand(1),
4201                              SDLoc(MemcpyCall));
4202   DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4203                          NewCallSeqStart.getNode());
4204   return NewCallSeqStart;
4205 }
4206
4207 SDValue
4208 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4209                                     CallingConv::ID CallConv, bool isVarArg,
4210                                     bool isTailCall,
4211                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4212                                     const SmallVectorImpl<SDValue> &OutVals,
4213                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4214                                     SDLoc dl, SelectionDAG &DAG,
4215                                     SmallVectorImpl<SDValue> &InVals) const {
4216
4217   bool isELFv2ABI = Subtarget.isELFv2ABI();
4218   bool isLittleEndian = Subtarget.isLittleEndian();
4219   unsigned NumOps = Outs.size();
4220
4221   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4222   unsigned PtrByteSize = 8;
4223
4224   MachineFunction &MF = DAG.getMachineFunction();
4225
4226   // Mark this function as potentially containing a function that contains a
4227   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4228   // and restoring the callers stack pointer in this functions epilog. This is
4229   // done because by tail calling the called function might overwrite the value
4230   // in this function's (MF) stack pointer stack slot 0(SP).
4231   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4232       CallConv == CallingConv::Fast)
4233     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4234
4235   // Count how many bytes are to be pushed on the stack, including the linkage
4236   // area, and parameter passing area.  On ELFv1, the linkage area is 48 bytes
4237   // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4238   // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4239   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4240                                                           isELFv2ABI);
4241   unsigned NumBytes = LinkageSize;
4242
4243   // Add up all the space actually used.
4244   for (unsigned i = 0; i != NumOps; ++i) {
4245     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4246     EVT ArgVT = Outs[i].VT;
4247     EVT OrigVT = Outs[i].ArgVT;
4248
4249     /* Respect alignment of argument on the stack.  */
4250     unsigned Align =
4251       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4252     NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4253
4254     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4255     if (Flags.isInConsecutiveRegsLast())
4256       NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4257   }
4258
4259   unsigned NumBytesActuallyUsed = NumBytes;
4260
4261   // The prolog code of the callee may store up to 8 GPR argument registers to
4262   // the stack, allowing va_start to index over them in memory if its varargs.
4263   // Because we cannot tell if this is needed on the caller side, we have to
4264   // conservatively assume that it is needed.  As such, make sure we have at
4265   // least enough stack space for the caller to store the 8 GPRs.
4266   // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4267   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4268
4269   // Tail call needs the stack to be aligned.
4270   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4271       CallConv == CallingConv::Fast)
4272     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4273
4274   // Calculate by how many bytes the stack has to be adjusted in case of tail
4275   // call optimization.
4276   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4277
4278   // To protect arguments on the stack from being clobbered in a tail call,
4279   // force all the loads to happen before doing any other lowering.
4280   if (isTailCall)
4281     Chain = DAG.getStackArgumentTokenFactor(Chain);
4282
4283   // Adjust the stack pointer for the new arguments...
4284   // These operations are automatically eliminated by the prolog/epilog pass
4285   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4286                                dl);
4287   SDValue CallSeqStart = Chain;
4288
4289   // Load the return address and frame pointer so it can be move somewhere else
4290   // later.
4291   SDValue LROp, FPOp;
4292   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4293                                        dl);
4294
4295   // Set up a copy of the stack pointer for use loading and storing any
4296   // arguments that may not fit in the registers available for argument
4297   // passing.
4298   SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4299
4300   // Figure out which arguments are going to go in registers, and which in
4301   // memory.  Also, if this is a vararg function, floating point operations
4302   // must be stored to our stack, and loaded into integer regs as well, if
4303   // any integer regs are available for argument passing.
4304   unsigned ArgOffset = LinkageSize;
4305   unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4306
4307   static const MCPhysReg GPR[] = {
4308     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4309     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4310   };
4311   static const MCPhysReg *FPR = GetFPR();
4312
4313   static const MCPhysReg VR[] = {
4314     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4315     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4316   };
4317   static const MCPhysReg VSRH[] = {
4318     PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4319     PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4320   };
4321
4322   const unsigned NumGPRs = array_lengthof(GPR);
4323   const unsigned NumFPRs = 13;
4324   const unsigned NumVRs  = array_lengthof(VR);
4325
4326   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4327   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4328
4329   SmallVector<SDValue, 8> MemOpChains;
4330   for (unsigned i = 0; i != NumOps; ++i) {
4331     SDValue Arg = OutVals[i];
4332     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4333     EVT ArgVT = Outs[i].VT;
4334     EVT OrigVT = Outs[i].ArgVT;
4335
4336     /* Respect alignment of argument on the stack.  */
4337     unsigned Align =
4338       CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4339     ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4340
4341     /* Compute GPR index associated with argument offset.  */
4342     GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4343     GPR_idx = std::min(GPR_idx, NumGPRs);
4344
4345     // PtrOff will be used to store the current argument to the stack if a
4346     // register cannot be found for it.
4347     SDValue PtrOff;
4348
4349     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4350
4351     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4352
4353     // Promote integers to 64-bit values.
4354     if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4355       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4356       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4357       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4358     }
4359
4360     // FIXME memcpy is used way more than necessary.  Correctness first.
4361     // Note: "by value" is code for passing a structure by value, not
4362     // basic types.
4363     if (Flags.isByVal()) {
4364       // Note: Size includes alignment padding, so
4365       //   struct x { short a; char b; }
4366       // will have Size = 4.  With #pragma pack(1), it will have Size = 3.
4367       // These are the proper values we need for right-justifying the
4368       // aggregate in a parameter register.
4369       unsigned Size = Flags.getByValSize();
4370
4371       // An empty aggregate parameter takes up no storage and no
4372       // registers.
4373       if (Size == 0)
4374         continue;
4375
4376       // All aggregates smaller than 8 bytes must be passed right-justified.
4377       if (Size==1 || Size==2 || Size==4) {
4378         EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4379         if (GPR_idx != NumGPRs) {
4380           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4381                                         MachinePointerInfo(), VT,
4382                                         false, false, false, 0);
4383           MemOpChains.push_back(Load.getValue(1));
4384           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4385
4386           ArgOffset += PtrByteSize;
4387           continue;
4388         }
4389       }
4390
4391       if (GPR_idx == NumGPRs && Size < 8) {
4392         SDValue AddPtr = PtrOff;
4393         if (!isLittleEndian) {
4394           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4395                                           PtrOff.getValueType());
4396           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4397         }
4398         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4399                                                           CallSeqStart,
4400                                                           Flags, DAG, dl);
4401         ArgOffset += PtrByteSize;
4402         continue;
4403       }
4404       // Copy entire object into memory.  There are cases where gcc-generated
4405       // code assumes it is there, even if it could be put entirely into
4406       // registers.  (This is not what the doc says.)
4407
4408       // FIXME: The above statement is likely due to a misunderstanding of the
4409       // documents.  All arguments must be copied into the parameter area BY
4410       // THE CALLEE in the event that the callee takes the address of any
4411       // formal argument.  That has not yet been implemented.  However, it is
4412       // reasonable to use the stack area as a staging area for the register
4413       // load.
4414
4415       // Skip this for small aggregates, as we will use the same slot for a
4416       // right-justified copy, below.
4417       if (Size >= 8)
4418         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4419                                                           CallSeqStart,
4420                                                           Flags, DAG, dl);
4421
4422       // When a register is available, pass a small aggregate right-justified.
4423       if (Size < 8 && GPR_idx != NumGPRs) {
4424         // The easiest way to get this right-justified in a register
4425         // is to copy the structure into the rightmost portion of a
4426         // local variable slot, then load the whole slot into the
4427         // register.
4428         // FIXME: The memcpy seems to produce pretty awful code for
4429         // small aggregates, particularly for packed ones.
4430         // FIXME: It would be preferable to use the slot in the
4431         // parameter save area instead of a new local variable.
4432         SDValue AddPtr = PtrOff;
4433         if (!isLittleEndian) {
4434           SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4435           AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4436         }
4437         Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4438                                                           CallSeqStart,
4439                                                           Flags, DAG, dl);
4440
4441         // Load the slot into the register.
4442         SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4443                                    MachinePointerInfo(),
4444                                    false, false, false, 0);
4445         MemOpChains.push_back(Load.getValue(1));
4446         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4447
4448         // Done with this argument.
4449         ArgOffset += PtrByteSize;
4450         continue;
4451       }
4452
4453       // For aggregates larger than PtrByteSize, copy the pieces of the
4454       // object that fit into registers from the parameter save area.
4455       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4456         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4457         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4458         if (GPR_idx != NumGPRs) {
4459           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4460                                      MachinePointerInfo(),
4461                                      false, false, false, 0);
4462           MemOpChains.push_back(Load.getValue(1));
4463           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4464           ArgOffset += PtrByteSize;
4465         } else {
4466           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4467           break;
4468         }
4469       }
4470       continue;
4471     }
4472
4473     switch (Arg.getSimpleValueType().SimpleTy) {
4474     default: llvm_unreachable("Unexpected ValueType for argument!");
4475     case MVT::i1:
4476     case MVT::i32:
4477     case MVT::i64:
4478       // These can be scalar arguments or elements of an integer array type
4479       // passed directly.  Clang may use those instead of "byval" aggregate
4480       // types to avoid forcing arguments to memory unnecessarily.
4481       if (GPR_idx != NumGPRs) {
4482         RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4483       } else {
4484         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4485                          true, isTailCall, false, MemOpChains,
4486                          TailCallArguments, dl);
4487       }
4488       ArgOffset += PtrByteSize;
4489       break;
4490     case MVT::f32:
4491     case MVT::f64: {
4492       // These can be scalar arguments or elements of a float array type
4493       // passed directly.  The latter are used to implement ELFv2 homogenous
4494       // float aggregates.
4495
4496       // Named arguments go into FPRs first, and once they overflow, the
4497       // remaining arguments go into GPRs and then the parameter save area.
4498       // Unnamed arguments for vararg functions always go to GPRs and
4499       // then the parameter save area.  For now, put all arguments to vararg
4500       // routines always in both locations (FPR *and* GPR or stack slot).
4501       bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4502
4503       // First load the argument into the next available FPR.
4504       if (FPR_idx != NumFPRs)
4505         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4506
4507       // Next, load the argument into GPR or stack slot if needed.
4508       if (!NeedGPROrStack)
4509         ;
4510       else if (GPR_idx != NumGPRs) {
4511         // In the non-vararg case, this can only ever happen in the
4512         // presence of f32 array types, since otherwise we never run
4513         // out of FPRs before running out of GPRs.
4514         SDValue ArgVal;
4515
4516         // Double values are always passed in a single GPR.
4517         if (Arg.getValueType() != MVT::f32) {
4518           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4519
4520         // Non-array float values are extended and passed in a GPR.
4521         } else if (!Flags.isInConsecutiveRegs()) {
4522           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4523           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4524
4525         // If we have an array of floats, we collect every odd element
4526         // together with its predecessor into one GPR.
4527         } else if (ArgOffset % PtrByteSize != 0) {
4528           SDValue Lo, Hi;
4529           Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4530           Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4531           if (!isLittleEndian)
4532             std::swap(Lo, Hi);
4533           ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4534
4535         // The final element, if even, goes into the first half of a GPR.
4536         } else if (Flags.isInConsecutiveRegsLast()) {
4537           ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4538           ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4539           if (!isLittleEndian)
4540             ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4541                                  DAG.getConstant(32, MVT::i32));
4542
4543         // Non-final even elements are skipped; they will be handled
4544         // together the with subsequent argument on the next go-around.
4545         } else
4546           ArgVal = SDValue();
4547
4548         if (ArgVal.getNode())
4549           RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4550       } else {
4551         // Single-precision floating-point values are mapped to the
4552         // second (rightmost) word of the stack doubleword.
4553         if (Arg.getValueType() == MVT::f32 &&
4554             !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4555           SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4556           PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4557         }
4558
4559         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4560                          true, isTailCall, false, MemOpChains,
4561                          TailCallArguments, dl);
4562       }
4563       // When passing an array of floats, the array occupies consecutive
4564       // space in the argument area; only round up to the next doubleword
4565       // at the end of the array.  Otherwise, each float takes 8 bytes.
4566       ArgOffset += (Arg.getValueType() == MVT::f32 &&
4567                     Flags.isInConsecutiveRegs()) ? 4 : 8;
4568       if (Flags.isInConsecutiveRegsLast())
4569         ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4570       break;
4571     }
4572     case MVT::v4f32:
4573     case MVT::v4i32:
4574     case MVT::v8i16:
4575     case MVT::v16i8:
4576     case MVT::v2f64:
4577     case MVT::v2i64:
4578       // These can be scalar arguments or elements of a vector array type
4579       // passed directly.  The latter are used to implement ELFv2 homogenous
4580       // vector aggregates.
4581
4582       // For a varargs call, named arguments go into VRs or on the stack as
4583       // usual; unnamed arguments always go to the stack or the corresponding
4584       // GPRs when within range.  For now, we always put the value in both
4585       // locations (or even all three).
4586       if (isVarArg) {
4587         // We could elide this store in the case where the object fits
4588         // entirely in R registers.  Maybe later.
4589         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4590                                      MachinePointerInfo(), false, false, 0);
4591         MemOpChains.push_back(Store);
4592         if (VR_idx != NumVRs) {
4593           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4594                                      MachinePointerInfo(),
4595                                      false, false, false, 0);
4596           MemOpChains.push_back(Load.getValue(1));
4597
4598           unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4599                            Arg.getSimpleValueType() == MVT::v2i64) ?
4600                           VSRH[VR_idx] : VR[VR_idx];
4601           ++VR_idx;
4602
4603           RegsToPass.push_back(std::make_pair(VReg, Load));
4604         }
4605         ArgOffset += 16;
4606         for (unsigned i=0; i<16; i+=PtrByteSize) {
4607           if (GPR_idx == NumGPRs)
4608             break;
4609           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4610                                   DAG.getConstant(i, PtrVT));
4611           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4612                                      false, false, false, 0);
4613           MemOpChains.push_back(Load.getValue(1));
4614           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4615         }
4616         break;
4617       }
4618
4619       // Non-varargs Altivec params go into VRs or on the stack.
4620       if (VR_idx != NumVRs) {
4621         unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4622                          Arg.getSimpleValueType() == MVT::v2i64) ?
4623                         VSRH[VR_idx] : VR[VR_idx];
4624         ++VR_idx;
4625
4626         RegsToPass.push_back(std::make_pair(VReg, Arg));
4627       } else {
4628         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4629                          true, isTailCall, true, MemOpChains,
4630                          TailCallArguments, dl);
4631       }
4632       ArgOffset += 16;
4633       break;
4634     }
4635   }
4636
4637   assert(NumBytesActuallyUsed == ArgOffset);
4638   (void)NumBytesActuallyUsed;
4639
4640   if (!MemOpChains.empty())
4641     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4642
4643   // Check if this is an indirect call (MTCTR/BCTRL).
4644   // See PrepareCall() for more information about calls through function
4645   // pointers in the 64-bit SVR4 ABI.
4646   if (!isTailCall &&
4647       !dyn_cast<GlobalAddressSDNode>(Callee) &&
4648       !dyn_cast<ExternalSymbolSDNode>(Callee)) {
4649     // Load r2 into a virtual register and store it to the TOC save area.
4650     SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4651     // TOC save area offset.
4652     unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4653     SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4654     SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4655     Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4656                          false, false, 0);
4657     // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4658     // This does not mean the MTCTR instruction must use R12; it's easier
4659     // to model this as an extra parameter, so do that.
4660     if (isELFv2ABI)
4661       RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4662   }
4663
4664   // Build a sequence of copy-to-reg nodes chained together with token chain
4665   // and flag operands which copy the outgoing args into the appropriate regs.
4666   SDValue InFlag;
4667   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4668     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4669                              RegsToPass[i].second, InFlag);
4670     InFlag = Chain.getValue(1);
4671   }
4672
4673   if (isTailCall)
4674     PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4675                     FPOp, true, TailCallArguments);
4676
4677   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4678                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4679                     Ins, InVals);
4680 }
4681
4682 SDValue
4683 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4684                                     CallingConv::ID CallConv, bool isVarArg,
4685                                     bool isTailCall,
4686                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
4687                                     const SmallVectorImpl<SDValue> &OutVals,
4688                                     const SmallVectorImpl<ISD::InputArg> &Ins,
4689                                     SDLoc dl, SelectionDAG &DAG,
4690                                     SmallVectorImpl<SDValue> &InVals) const {
4691
4692   unsigned NumOps = Outs.size();
4693
4694   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4695   bool isPPC64 = PtrVT == MVT::i64;
4696   unsigned PtrByteSize = isPPC64 ? 8 : 4;
4697
4698   MachineFunction &MF = DAG.getMachineFunction();
4699
4700   // Mark this function as potentially containing a function that contains a
4701   // tail call. As a consequence the frame pointer will be used for dynamicalloc
4702   // and restoring the callers stack pointer in this functions epilog. This is
4703   // done because by tail calling the called function might overwrite the value
4704   // in this function's (MF) stack pointer stack slot 0(SP).
4705   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4706       CallConv == CallingConv::Fast)
4707     MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4708
4709   // Count how many bytes are to be pushed on the stack, including the linkage
4710   // area, and parameter passing area.  We start with 24/48 bytes, which is
4711   // prereserved space for [SP][CR][LR][3 x unused].
4712   unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4713                                                           false);
4714   unsigned NumBytes = LinkageSize;
4715
4716   // Add up all the space actually used.
4717   // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4718   // they all go in registers, but we must reserve stack space for them for
4719   // possible use by the caller.  In varargs or 64-bit calls, parameters are
4720   // assigned stack space in order, with padding so Altivec parameters are
4721   // 16-byte aligned.
4722   unsigned nAltivecParamsAtEnd = 0;
4723   for (unsigned i = 0; i != NumOps; ++i) {
4724     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4725     EVT ArgVT = Outs[i].VT;
4726     // Varargs Altivec parameters are padded to a 16 byte boundary.
4727     if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4728         ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4729         ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4730       if (!isVarArg && !isPPC64) {
4731         // Non-varargs Altivec parameters go after all the non-Altivec
4732         // parameters; handle those later so we know how much padding we need.
4733         nAltivecParamsAtEnd++;
4734         continue;
4735       }
4736       // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4737       NumBytes = ((NumBytes+15)/16)*16;
4738     }
4739     NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4740   }
4741
4742   // Allow for Altivec parameters at the end, if needed.
4743   if (nAltivecParamsAtEnd) {
4744     NumBytes = ((NumBytes+15)/16)*16;
4745     NumBytes += 16*nAltivecParamsAtEnd;
4746   }
4747
4748   // The prolog code of the callee may store up to 8 GPR argument registers to
4749   // the stack, allowing va_start to index over them in memory if its varargs.
4750   // Because we cannot tell if this is needed on the caller side, we have to
4751   // conservatively assume that it is needed.  As such, make sure we have at
4752   // least enough stack space for the caller to store the 8 GPRs.
4753   NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4754
4755   // Tail call needs the stack to be aligned.
4756   if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4757       CallConv == CallingConv::Fast)
4758     NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4759
4760   // Calculate by how many bytes the stack has to be adjusted in case of tail
4761   // call optimization.
4762   int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4763
4764   // To protect arguments on the stack from being clobbered in a tail call,
4765   // force all the loads to happen before doing any other lowering.
4766   if (isTailCall)
4767     Chain = DAG.getStackArgumentTokenFactor(Chain);
4768
4769   // Adjust the stack pointer for the new arguments...
4770   // These operations are automatically eliminated by the prolog/epilog pass
4771   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4772                                dl);
4773   SDValue CallSeqStart = Chain;
4774
4775   // Load the return address and frame pointer so it can be move somewhere else
4776   // later.
4777   SDValue LROp, FPOp;
4778   Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4779                                        dl);
4780
4781   // Set up a copy of the stack pointer for use loading and storing any
4782   // arguments that may not fit in the registers available for argument
4783   // passing.
4784   SDValue StackPtr;
4785   if (isPPC64)
4786     StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4787   else
4788     StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4789
4790   // Figure out which arguments are going to go in registers, and which in
4791   // memory.  Also, if this is a vararg function, floating point operations
4792   // must be stored to our stack, and loaded into integer regs as well, if
4793   // any integer regs are available for argument passing.
4794   unsigned ArgOffset = LinkageSize;
4795   unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4796
4797   static const MCPhysReg GPR_32[] = {           // 32-bit registers.
4798     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4799     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4800   };
4801   static const MCPhysReg GPR_64[] = {           // 64-bit registers.
4802     PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4803     PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4804   };
4805   static const MCPhysReg *FPR = GetFPR();
4806
4807   static const MCPhysReg VR[] = {
4808     PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4809     PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4810   };
4811   const unsigned NumGPRs = array_lengthof(GPR_32);
4812   const unsigned NumFPRs = 13;
4813   const unsigned NumVRs  = array_lengthof(VR);
4814
4815   const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4816
4817   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4818   SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4819
4820   SmallVector<SDValue, 8> MemOpChains;
4821   for (unsigned i = 0; i != NumOps; ++i) {
4822     SDValue Arg = OutVals[i];
4823     ISD::ArgFlagsTy Flags = Outs[i].Flags;
4824
4825     // PtrOff will be used to store the current argument to the stack if a
4826     // register cannot be found for it.
4827     SDValue PtrOff;
4828
4829     PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4830
4831     PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4832
4833     // On PPC64, promote integers to 64-bit values.
4834     if (isPPC64 && Arg.getValueType() == MVT::i32) {
4835       // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4836       unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4837       Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4838     }
4839
4840     // FIXME memcpy is used way more than necessary.  Correctness first.
4841     // Note: "by value" is code for passing a structure by value, not
4842     // basic types.
4843     if (Flags.isByVal()) {
4844       unsigned Size = Flags.getByValSize();
4845       // Very small objects are passed right-justified.  Everything else is
4846       // passed left-justified.
4847       if (Size==1 || Size==2) {
4848         EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4849         if (GPR_idx != NumGPRs) {
4850           SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4851                                         MachinePointerInfo(), VT,
4852                                         false, false, false, 0);
4853           MemOpChains.push_back(Load.getValue(1));
4854           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4855
4856           ArgOffset += PtrByteSize;
4857         } else {
4858           SDValue Const = DAG.getConstant(PtrByteSize - Size,
4859                                           PtrOff.getValueType());
4860           SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4861           Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4862                                                             CallSeqStart,
4863                                                             Flags, DAG, dl);
4864           ArgOffset += PtrByteSize;
4865         }
4866         continue;
4867       }
4868       // Copy entire object into memory.  There are cases where gcc-generated
4869       // code assumes it is there, even if it could be put entirely into
4870       // registers.  (This is not what the doc says.)
4871       Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4872                                                         CallSeqStart,
4873                                                         Flags, DAG, dl);
4874
4875       // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4876       // copy the pieces of the object that fit into registers from the
4877       // parameter save area.
4878       for (unsigned j=0; j<Size; j+=PtrByteSize) {
4879         SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4880         SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4881         if (GPR_idx != NumGPRs) {
4882           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4883                                      MachinePointerInfo(),
4884                                      false, false, false, 0);
4885           MemOpChains.push_back(Load.getValue(1));
4886           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4887           ArgOffset += PtrByteSize;
4888         } else {
4889           ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4890           break;
4891         }
4892       }
4893       continue;
4894     }
4895
4896     switch (Arg.getSimpleValueType().SimpleTy) {
4897     default: llvm_unreachable("Unexpected ValueType for argument!");
4898     case MVT::i1:
4899     case MVT::i32:
4900     case MVT::i64:
4901       if (GPR_idx != NumGPRs) {
4902         if (Arg.getValueType() == MVT::i1)
4903           Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4904
4905         RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4906       } else {
4907         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4908                          isPPC64, isTailCall, false, MemOpChains,
4909                          TailCallArguments, dl);
4910       }
4911       ArgOffset += PtrByteSize;
4912       break;
4913     case MVT::f32:
4914     case MVT::f64:
4915       if (FPR_idx != NumFPRs) {
4916         RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4917
4918         if (isVarArg) {
4919           SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4920                                        MachinePointerInfo(), false, false, 0);
4921           MemOpChains.push_back(Store);
4922
4923           // Float varargs are always shadowed in available integer registers
4924           if (GPR_idx != NumGPRs) {
4925             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4926                                        MachinePointerInfo(), false, false,
4927                                        false, 0);
4928             MemOpChains.push_back(Load.getValue(1));
4929             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4930           }
4931           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4932             SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4933             PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4934             SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4935                                        MachinePointerInfo(),
4936                                        false, false, false, 0);
4937             MemOpChains.push_back(Load.getValue(1));
4938             RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4939           }
4940         } else {
4941           // If we have any FPRs remaining, we may also have GPRs remaining.
4942           // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4943           // GPRs.
4944           if (GPR_idx != NumGPRs)
4945             ++GPR_idx;
4946           if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4947               !isPPC64)  // PPC64 has 64-bit GPR's obviously :)
4948             ++GPR_idx;
4949         }
4950       } else
4951         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4952                          isPPC64, isTailCall, false, MemOpChains,
4953                          TailCallArguments, dl);
4954       if (isPPC64)
4955         ArgOffset += 8;
4956       else
4957         ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4958       break;
4959     case MVT::v4f32:
4960     case MVT::v4i32:
4961     case MVT::v8i16:
4962     case MVT::v16i8:
4963       if (isVarArg) {
4964         // These go aligned on the stack, or in the corresponding R registers
4965         // when within range.  The Darwin PPC ABI doc claims they also go in
4966         // V registers; in fact gcc does this only for arguments that are
4967         // prototyped, not for those that match the ...  We do it for all
4968         // arguments, seems to work.
4969         while (ArgOffset % 16 !=0) {
4970           ArgOffset += PtrByteSize;
4971           if (GPR_idx != NumGPRs)
4972             GPR_idx++;
4973         }
4974         // We could elide this store in the case where the object fits
4975         // entirely in R registers.  Maybe later.
4976         PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4977                             DAG.getConstant(ArgOffset, PtrVT));
4978         SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4979                                      MachinePointerInfo(), false, false, 0);
4980         MemOpChains.push_back(Store);
4981         if (VR_idx != NumVRs) {
4982           SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4983                                      MachinePointerInfo(),
4984                                      false, false, false, 0);
4985           MemOpChains.push_back(Load.getValue(1));
4986           RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4987         }
4988         ArgOffset += 16;
4989         for (unsigned i=0; i<16; i+=PtrByteSize) {
4990           if (GPR_idx == NumGPRs)
4991             break;
4992           SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4993                                   DAG.getConstant(i, PtrVT));
4994           SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4995                                      false, false, false, 0);
4996           MemOpChains.push_back(Load.getValue(1));
4997           RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4998         }
4999         break;
5000       }
5001
5002       // Non-varargs Altivec params generally go in registers, but have
5003       // stack space allocated at the end.
5004       if (VR_idx != NumVRs) {
5005         // Doesn't have GPR space allocated.
5006         RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5007       } else if (nAltivecParamsAtEnd==0) {
5008         // We are emitting Altivec params in order.
5009         LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5010                          isPPC64, isTailCall, true, MemOpChains,
5011                          TailCallArguments, dl);
5012         ArgOffset += 16;
5013       }
5014       break;
5015     }
5016   }
5017   // If all Altivec parameters fit in registers, as they usually do,
5018   // they get stack space following the non-Altivec parameters.  We
5019   // don't track this here because nobody below needs it.
5020   // If there are more Altivec parameters than fit in registers emit
5021   // the stores here.
5022   if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5023     unsigned j = 0;
5024     // Offset is aligned; skip 1st 12 params which go in V registers.
5025     ArgOffset = ((ArgOffset+15)/16)*16;
5026     ArgOffset += 12*16;
5027     for (unsigned i = 0; i != NumOps; ++i) {
5028       SDValue Arg = OutVals[i];
5029       EVT ArgType = Outs[i].VT;
5030       if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5031           ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5032         if (++j > NumVRs) {
5033           SDValue PtrOff;
5034           // We are emitting Altivec params in order.
5035           LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5036                            isPPC64, isTailCall, true, MemOpChains,
5037                            TailCallArguments, dl);
5038           ArgOffset += 16;
5039         }
5040       }
5041     }
5042   }
5043
5044   if (!MemOpChains.empty())
5045     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5046
5047   // On Darwin, R12 must contain the address of an indirect callee.  This does
5048   // not mean the MTCTR instruction must use R12; it's easier to model this as
5049   // an extra parameter, so do that.
5050   if (!isTailCall &&
5051       !dyn_cast<GlobalAddressSDNode>(Callee) &&
5052       !dyn_cast<ExternalSymbolSDNode>(Callee) &&
5053       !isBLACompatibleAddress(Callee, DAG))
5054     RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5055                                                    PPC::R12), Callee));
5056
5057   // Build a sequence of copy-to-reg nodes chained together with token chain
5058   // and flag operands which copy the outgoing args into the appropriate regs.
5059   SDValue InFlag;
5060   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5061     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5062                              RegsToPass[i].second, InFlag);
5063     InFlag = Chain.getValue(1);
5064   }
5065
5066   if (isTailCall)
5067     PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5068                     FPOp, true, TailCallArguments);
5069
5070   return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
5071                     RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5072                     Ins, InVals);
5073 }
5074
5075 bool
5076 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5077                                   MachineFunction &MF, bool isVarArg,
5078                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
5079                                   LLVMContext &Context) const {
5080   SmallVector<CCValAssign, 16> RVLocs;
5081   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5082   return CCInfo.CheckReturn(Outs, RetCC_PPC);
5083 }
5084
5085 SDValue
5086 PPCTargetLowering::LowerReturn(SDValue Chain,
5087                                CallingConv::ID CallConv, bool isVarArg,
5088                                const SmallVectorImpl<ISD::OutputArg> &Outs,
5089                                const SmallVectorImpl<SDValue> &OutVals,
5090                                SDLoc dl, SelectionDAG &DAG) const {
5091
5092   SmallVector<CCValAssign, 16> RVLocs;
5093   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5094                  *DAG.getContext());
5095   CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5096
5097   SDValue Flag;
5098   SmallVector<SDValue, 4> RetOps(1, Chain);
5099
5100   // Copy the result values into the output registers.
5101   for (unsigned i = 0; i != RVLocs.size(); ++i) {
5102     CCValAssign &VA = RVLocs[i];
5103     assert(VA.isRegLoc() && "Can only return in registers!");
5104
5105     SDValue Arg = OutVals[i];
5106
5107     switch (VA.getLocInfo()) {
5108     default: llvm_unreachable("Unknown loc info!");
5109     case CCValAssign::Full: break;
5110     case CCValAssign::AExt:
5111       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5112       break;
5113     case CCValAssign::ZExt:
5114       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5115       break;
5116     case CCValAssign::SExt:
5117       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5118       break;
5119     }
5120
5121     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5122     Flag = Chain.getValue(1);
5123     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5124   }
5125
5126   RetOps[0] = Chain;  // Update chain.
5127
5128   // Add the flag if we have it.
5129   if (Flag.getNode())
5130     RetOps.push_back(Flag);
5131
5132   return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5133 }
5134
5135 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5136                                    const PPCSubtarget &Subtarget) const {
5137   // When we pop the dynamic allocation we need to restore the SP link.
5138   SDLoc dl(Op);
5139
5140   // Get the corect type for pointers.
5141   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5142
5143   // Construct the stack pointer operand.
5144   bool isPPC64 = Subtarget.isPPC64();
5145   unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5146   SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5147
5148   // Get the operands for the STACKRESTORE.
5149   SDValue Chain = Op.getOperand(0);
5150   SDValue SaveSP = Op.getOperand(1);
5151
5152   // Load the old link SP.
5153   SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5154                                    MachinePointerInfo(),
5155                                    false, false, false, 0);
5156
5157   // Restore the stack pointer.
5158   Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5159
5160   // Store the old link SP.
5161   return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5162                       false, false, 0);
5163 }
5164
5165
5166
5167 SDValue
5168 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5169   MachineFunction &MF = DAG.getMachineFunction();
5170   bool isPPC64 = Subtarget.isPPC64();
5171   bool isDarwinABI = Subtarget.isDarwinABI();
5172   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5173
5174   // Get current frame pointer save index.  The users of this index will be
5175   // primarily DYNALLOC instructions.
5176   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5177   int RASI = FI->getReturnAddrSaveIndex();
5178
5179   // If the frame pointer save index hasn't been defined yet.
5180   if (!RASI) {
5181     // Find out what the fix offset of the frame pointer save area.
5182     int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5183     // Allocate the frame index for frame pointer save area.
5184     RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5185     // Save the result.
5186     FI->setReturnAddrSaveIndex(RASI);
5187   }
5188   return DAG.getFrameIndex(RASI, PtrVT);
5189 }
5190
5191 SDValue
5192 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5193   MachineFunction &MF = DAG.getMachineFunction();
5194   bool isPPC64 = Subtarget.isPPC64();
5195   bool isDarwinABI = Subtarget.isDarwinABI();
5196   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5197
5198   // Get current frame pointer save index.  The users of this index will be
5199   // primarily DYNALLOC instructions.
5200   PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5201   int FPSI = FI->getFramePointerSaveIndex();
5202
5203   // If the frame pointer save index hasn't been defined yet.
5204   if (!FPSI) {
5205     // Find out what the fix offset of the frame pointer save area.
5206     int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5207                                                            isDarwinABI);
5208
5209     // Allocate the frame index for frame pointer save area.
5210     FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5211     // Save the result.
5212     FI->setFramePointerSaveIndex(FPSI);
5213   }
5214   return DAG.getFrameIndex(FPSI, PtrVT);
5215 }
5216
5217 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5218                                          SelectionDAG &DAG,
5219                                          const PPCSubtarget &Subtarget) const {
5220   // Get the inputs.
5221   SDValue Chain = Op.getOperand(0);
5222   SDValue Size  = Op.getOperand(1);
5223   SDLoc dl(Op);
5224
5225   // Get the corect type for pointers.
5226   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5227   // Negate the size.
5228   SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5229                                   DAG.getConstant(0, PtrVT), Size);
5230   // Construct a node for the frame pointer save index.
5231   SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5232   // Build a DYNALLOC node.
5233   SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5234   SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5235   return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5236 }
5237
5238 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5239                                                SelectionDAG &DAG) const {
5240   SDLoc DL(Op);
5241   return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5242                      DAG.getVTList(MVT::i32, MVT::Other),
5243                      Op.getOperand(0), Op.getOperand(1));
5244 }
5245
5246 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5247                                                 SelectionDAG &DAG) const {
5248   SDLoc DL(Op);
5249   return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5250                      Op.getOperand(0), Op.getOperand(1));
5251 }
5252
5253 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5254   assert(Op.getValueType() == MVT::i1 &&
5255          "Custom lowering only for i1 loads");
5256
5257   // First, load 8 bits into 32 bits, then truncate to 1 bit.
5258
5259   SDLoc dl(Op);
5260   LoadSDNode *LD = cast<LoadSDNode>(Op);
5261
5262   SDValue Chain = LD->getChain();
5263   SDValue BasePtr = LD->getBasePtr();
5264   MachineMemOperand *MMO = LD->getMemOperand();
5265
5266   SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5267                                  BasePtr, MVT::i8, MMO);
5268   SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5269
5270   SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5271   return DAG.getMergeValues(Ops, dl);
5272 }
5273
5274 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5275   assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5276          "Custom lowering only for i1 stores");
5277
5278   // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5279
5280   SDLoc dl(Op);
5281   StoreSDNode *ST = cast<StoreSDNode>(Op);
5282
5283   SDValue Chain = ST->getChain();
5284   SDValue BasePtr = ST->getBasePtr();
5285   SDValue Value = ST->getValue();
5286   MachineMemOperand *MMO = ST->getMemOperand();
5287
5288   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5289   return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5290 }
5291
5292 // FIXME: Remove this once the ANDI glue bug is fixed:
5293 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5294   assert(Op.getValueType() == MVT::i1 &&
5295          "Custom lowering only for i1 results");
5296
5297   SDLoc DL(Op);
5298   return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5299                      Op.getOperand(0));
5300 }
5301
5302 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5303 /// possible.
5304 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5305   // Not FP? Not a fsel.
5306   if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5307       !Op.getOperand(2).getValueType().isFloatingPoint())
5308     return Op;
5309
5310   // We might be able to do better than this under some circumstances, but in
5311   // general, fsel-based lowering of select is a finite-math-only optimization.
5312   // For more information, see section F.3 of the 2.06 ISA specification.
5313   if (!DAG.getTarget().Options.NoInfsFPMath ||
5314       !DAG.getTarget().Options.NoNaNsFPMath)
5315     return Op;
5316
5317   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5318
5319   EVT ResVT = Op.getValueType();
5320   EVT CmpVT = Op.getOperand(0).getValueType();
5321   SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5322   SDValue TV  = Op.getOperand(2), FV  = Op.getOperand(3);
5323   SDLoc dl(Op);
5324
5325   // If the RHS of the comparison is a 0.0, we don't need to do the
5326   // subtraction at all.
5327   SDValue Sel1;
5328   if (isFloatingPointZero(RHS))
5329     switch (CC) {
5330     default: break;       // SETUO etc aren't handled by fsel.
5331     case ISD::SETNE:
5332       std::swap(TV, FV);
5333     case ISD::SETEQ:
5334       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5335         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5336       Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5337       if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5338         Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5339       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5340                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5341     case ISD::SETULT:
5342     case ISD::SETLT:
5343       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5344     case ISD::SETOGE:
5345     case ISD::SETGE:
5346       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5347         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5348       return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5349     case ISD::SETUGT:
5350     case ISD::SETGT:
5351       std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
5352     case ISD::SETOLE:
5353     case ISD::SETLE:
5354       if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
5355         LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5356       return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5357                          DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5358     }
5359
5360   SDValue Cmp;
5361   switch (CC) {
5362   default: break;       // SETUO etc aren't handled by fsel.
5363   case ISD::SETNE:
5364     std::swap(TV, FV);
5365   case ISD::SETEQ:
5366     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5367     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5368       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5369     Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5370     if (Sel1.getValueType() == MVT::f32)   // Comparison is always 64-bits
5371       Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5372     return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5373                        DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5374   case ISD::SETULT:
5375   case ISD::SETLT:
5376     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5377     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5378       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5379     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5380   case ISD::SETOGE:
5381   case ISD::SETGE:
5382     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5383     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5384       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5385     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5386   case ISD::SETUGT:
5387   case ISD::SETGT:
5388     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5389     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5390       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5391     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5392   case ISD::SETOLE:
5393   case ISD::SETLE:
5394     Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5395     if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
5396       Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5397     return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5398   }
5399   return Op;
5400 }
5401
5402 // FIXME: Split this code up when LegalizeDAGTypes lands.
5403 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5404                                            SDLoc dl) const {
5405   assert(Op.getOperand(0).getValueType().isFloatingPoint());
5406   SDValue Src = Op.getOperand(0);
5407   if (Src.getValueType() == MVT::f32)
5408     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5409
5410   SDValue Tmp;
5411   switch (Op.getSimpleValueType().SimpleTy) {
5412   default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5413   case MVT::i32:
5414     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5415                         (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5416                                                    PPCISD::FCTIDZ),
5417                       dl, MVT::f64, Src);
5418     break;
5419   case MVT::i64:
5420     assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5421            "i64 FP_TO_UINT is supported only with FPCVT");
5422     Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5423                                                         PPCISD::FCTIDUZ,
5424                       dl, MVT::f64, Src);
5425     break;
5426   }
5427
5428   // Convert the FP value to an int value through memory.
5429   bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5430     (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5431   SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5432   int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5433   MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5434
5435   // Emit a store to the stack slot.
5436   SDValue Chain;
5437   if (i32Stack) {
5438     MachineFunction &MF = DAG.getMachineFunction();
5439     MachineMemOperand *MMO =
5440       MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5441     SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5442     Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5443               DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5444   } else
5445     Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5446                          MPI, false, false, 0);
5447
5448   // Result is a load from the stack slot.  If loading 4 bytes, make sure to
5449   // add in a bias.
5450   if (Op.getValueType() == MVT::i32 && !i32Stack) {
5451     FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5452                         DAG.getConstant(4, FIPtr.getValueType()));
5453     MPI = MachinePointerInfo();
5454   }
5455
5456   return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
5457                      false, false, false, 0);
5458 }
5459
5460 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5461                                            SelectionDAG &DAG) const {
5462   SDLoc dl(Op);
5463   // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5464   if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5465     return SDValue();
5466
5467   if (Op.getOperand(0).getValueType() == MVT::i1)
5468     return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5469                        DAG.getConstantFP(1.0, Op.getValueType()),
5470                        DAG.getConstantFP(0.0, Op.getValueType()));
5471
5472   assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5473          "UINT_TO_FP is supported only with FPCVT");
5474
5475   // If we have FCFIDS, then use it when converting to single-precision.
5476   // Otherwise, convert to double-precision and then round.
5477   unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5478                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5479                     PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5480                    (Op.getOpcode() == ISD::UINT_TO_FP ?
5481                     PPCISD::FCFIDU : PPCISD::FCFID);
5482   MVT      FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5483                    MVT::f32 : MVT::f64;
5484
5485   if (Op.getOperand(0).getValueType() == MVT::i64) {
5486     SDValue SINT = Op.getOperand(0);
5487     // When converting to single-precision, we actually need to convert
5488     // to double-precision first and then round to single-precision.
5489     // To avoid double-rounding effects during that operation, we have
5490     // to prepare the input operand.  Bits that might be truncated when
5491     // converting to double-precision are replaced by a bit that won't
5492     // be lost at this stage, but is below the single-precision rounding
5493     // position.
5494     //
5495     // However, if -enable-unsafe-fp-math is in effect, accept double
5496     // rounding to avoid the extra overhead.
5497     if (Op.getValueType() == MVT::f32 &&
5498         !Subtarget.hasFPCVT() &&
5499         !DAG.getTarget().Options.UnsafeFPMath) {
5500
5501       // Twiddle input to make sure the low 11 bits are zero.  (If this
5502       // is the case, we are guaranteed the value will fit into the 53 bit
5503       // mantissa of an IEEE double-precision value without rounding.)
5504       // If any of those low 11 bits were not zero originally, make sure
5505       // bit 12 (value 2048) is set instead, so that the final rounding
5506       // to single-precision gets the correct result.
5507       SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5508                                   SINT, DAG.getConstant(2047, MVT::i64));
5509       Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5510                           Round, DAG.getConstant(2047, MVT::i64));
5511       Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5512       Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5513                           Round, DAG.getConstant(-2048, MVT::i64));
5514
5515       // However, we cannot use that value unconditionally: if the magnitude
5516       // of the input value is small, the bit-twiddling we did above might
5517       // end up visibly changing the output.  Fortunately, in that case, we
5518       // don't need to twiddle bits since the original input will convert
5519       // exactly to double-precision floating-point already.  Therefore,
5520       // construct a conditional to use the original value if the top 11
5521       // bits are all sign-bit copies, and use the rounded value computed
5522       // above otherwise.
5523       SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5524                                  SINT, DAG.getConstant(53, MVT::i32));
5525       Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5526                          Cond, DAG.getConstant(1, MVT::i64));
5527       Cond = DAG.getSetCC(dl, MVT::i32,
5528                           Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5529
5530       SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5531     }
5532
5533     SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5534     SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5535
5536     if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5537       FP = DAG.getNode(ISD::FP_ROUND, dl,
5538                        MVT::f32, FP, DAG.getIntPtrConstant(0));
5539     return FP;
5540   }
5541
5542   assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5543          "Unhandled INT_TO_FP type in custom expander!");
5544   // Since we only generate this in 64-bit mode, we can take advantage of
5545   // 64-bit registers.  In particular, sign extend the input value into the
5546   // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5547   // then lfd it and fcfid it.
5548   MachineFunction &MF = DAG.getMachineFunction();
5549   MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5550   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5551
5552   SDValue Ld;
5553   if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5554     int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5555     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5556
5557     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5558                                  MachinePointerInfo::getFixedStack(FrameIdx),
5559                                  false, false, 0);
5560
5561     assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5562            "Expected an i32 store");
5563     MachineMemOperand *MMO =
5564       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
5565                               MachineMemOperand::MOLoad, 4, 4);
5566     SDValue Ops[] = { Store, FIdx };
5567     Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5568                                    PPCISD::LFIWZX : PPCISD::LFIWAX,
5569                                  dl, DAG.getVTList(MVT::f64, MVT::Other),
5570                                  Ops, MVT::i32, MMO);
5571   } else {
5572     assert(Subtarget.isPPC64() &&
5573            "i32->FP without LFIWAX supported only on PPC64");
5574
5575     int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5576     SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5577
5578     SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5579                                 Op.getOperand(0));
5580
5581     // STD the extended value into the stack slot.
5582     SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5583                                  MachinePointerInfo::getFixedStack(FrameIdx),
5584                                  false, false, 0);
5585
5586     // Load the value as a double.
5587     Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5588                      MachinePointerInfo::getFixedStack(FrameIdx),
5589                      false, false, false, 0);
5590   }
5591
5592   // FCFID it and return it.
5593   SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5594   if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5595     FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5596   return FP;
5597 }
5598
5599 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5600                                             SelectionDAG &DAG) const {
5601   SDLoc dl(Op);
5602   /*
5603    The rounding mode is in bits 30:31 of FPSR, and has the following
5604    settings:
5605      00 Round to nearest
5606      01 Round to 0
5607      10 Round to +inf
5608      11 Round to -inf
5609
5610   FLT_ROUNDS, on the other hand, expects the following:
5611     -1 Undefined
5612      0 Round to 0
5613      1 Round to nearest
5614      2 Round to +inf
5615      3 Round to -inf
5616
5617   To perform the conversion, we do:
5618     ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5619   */
5620
5621   MachineFunction &MF = DAG.getMachineFunction();
5622   EVT VT = Op.getValueType();
5623   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5624
5625   // Save FP Control Word to register
5626   EVT NodeTys[] = {
5627     MVT::f64,    // return register
5628     MVT::Glue    // unused in this context
5629   };
5630   SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5631
5632   // Save FP register to stack slot
5633   int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5634   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5635   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5636                                StackSlot, MachinePointerInfo(), false, false,0);
5637
5638   // Load FP Control Word from low 32 bits of stack slot.
5639   SDValue Four = DAG.getConstant(4, PtrVT);
5640   SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5641   SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5642                             false, false, false, 0);
5643
5644   // Transform as necessary
5645   SDValue CWD1 =
5646     DAG.getNode(ISD::AND, dl, MVT::i32,
5647                 CWD, DAG.getConstant(3, MVT::i32));
5648   SDValue CWD2 =
5649     DAG.getNode(ISD::SRL, dl, MVT::i32,
5650                 DAG.getNode(ISD::AND, dl, MVT::i32,
5651                             DAG.getNode(ISD::XOR, dl, MVT::i32,
5652                                         CWD, DAG.getConstant(3, MVT::i32)),
5653                             DAG.getConstant(3, MVT::i32)),
5654                 DAG.getConstant(1, MVT::i32));
5655
5656   SDValue RetVal =
5657     DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5658
5659   return DAG.getNode((VT.getSizeInBits() < 16 ?
5660                       ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5661 }
5662
5663 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5664   EVT VT = Op.getValueType();
5665   unsigned BitWidth = VT.getSizeInBits();
5666   SDLoc dl(Op);
5667   assert(Op.getNumOperands() == 3 &&
5668          VT == Op.getOperand(1).getValueType() &&
5669          "Unexpected SHL!");
5670
5671   // Expand into a bunch of logical ops.  Note that these ops
5672   // depend on the PPC behavior for oversized shift amounts.
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::SHL, dl, VT, Hi, Amt);
5681   SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, 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::SHL, dl, VT, Lo, Tmp5);
5686   SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5687   SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5688   SDValue OutOps[] = { OutLo, OutHi };
5689   return DAG.getMergeValues(OutOps, dl);
5690 }
5691
5692 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5693   EVT VT = Op.getValueType();
5694   SDLoc dl(Op);
5695   unsigned BitWidth = VT.getSizeInBits();
5696   assert(Op.getNumOperands() == 3 &&
5697          VT == Op.getOperand(1).getValueType() &&
5698          "Unexpected SRL!");
5699
5700   // Expand into a bunch of logical ops.  Note that these ops
5701   // depend on the PPC behavior for oversized shift amounts.
5702   SDValue Lo = Op.getOperand(0);
5703   SDValue Hi = Op.getOperand(1);
5704   SDValue Amt = Op.getOperand(2);
5705   EVT AmtVT = Amt.getValueType();
5706
5707   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5708                              DAG.getConstant(BitWidth, AmtVT), Amt);
5709   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5710   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5711   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5712   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5713                              DAG.getConstant(-BitWidth, AmtVT));
5714   SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5715   SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5716   SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5717   SDValue OutOps[] = { OutLo, OutHi };
5718   return DAG.getMergeValues(OutOps, dl);
5719 }
5720
5721 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5722   SDLoc dl(Op);
5723   EVT VT = Op.getValueType();
5724   unsigned BitWidth = VT.getSizeInBits();
5725   assert(Op.getNumOperands() == 3 &&
5726          VT == Op.getOperand(1).getValueType() &&
5727          "Unexpected SRA!");
5728
5729   // Expand into a bunch of logical ops, followed by a select_cc.
5730   SDValue Lo = Op.getOperand(0);
5731   SDValue Hi = Op.getOperand(1);
5732   SDValue Amt = Op.getOperand(2);
5733   EVT AmtVT = Amt.getValueType();
5734
5735   SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5736                              DAG.getConstant(BitWidth, AmtVT), Amt);
5737   SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5738   SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5739   SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5740   SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5741                              DAG.getConstant(-BitWidth, AmtVT));
5742   SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5743   SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5744   SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5745                                   Tmp4, Tmp6, ISD::SETLE);
5746   SDValue OutOps[] = { OutLo, OutHi };
5747   return DAG.getMergeValues(OutOps, dl);
5748 }
5749
5750 //===----------------------------------------------------------------------===//
5751 // Vector related lowering.
5752 //
5753
5754 /// BuildSplatI - Build a canonical splati of Val with an element size of
5755 /// SplatSize.  Cast the result to VT.
5756 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5757                              SelectionDAG &DAG, SDLoc dl) {
5758   assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5759
5760   static const EVT VTys[] = { // canonical VT to use for each size.
5761     MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5762   };
5763
5764   EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5765
5766   // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5767   if (Val == -1)
5768     SplatSize = 1;
5769
5770   EVT CanonicalVT = VTys[SplatSize-1];
5771
5772   // Build a canonical splat for this value.
5773   SDValue Elt = DAG.getConstant(Val, MVT::i32);
5774   SmallVector<SDValue, 8> Ops;
5775   Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5776   SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5777   return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5778 }
5779
5780 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5781 /// specified intrinsic ID.
5782 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5783                                 SelectionDAG &DAG, SDLoc dl,
5784                                 EVT DestVT = MVT::Other) {
5785   if (DestVT == MVT::Other) DestVT = Op.getValueType();
5786   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5787                      DAG.getConstant(IID, MVT::i32), Op);
5788 }
5789
5790 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5791 /// specified intrinsic ID.
5792 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5793                                 SelectionDAG &DAG, SDLoc dl,
5794                                 EVT DestVT = MVT::Other) {
5795   if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5796   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5797                      DAG.getConstant(IID, MVT::i32), LHS, RHS);
5798 }
5799
5800 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5801 /// specified intrinsic ID.
5802 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5803                                 SDValue Op2, SelectionDAG &DAG,
5804                                 SDLoc dl, EVT DestVT = MVT::Other) {
5805   if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5806   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5807                      DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5808 }
5809
5810
5811 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5812 /// amount.  The result has the specified value type.
5813 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5814                              EVT VT, SelectionDAG &DAG, SDLoc dl) {
5815   // Force LHS/RHS to be the right type.
5816   LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5817   RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5818
5819   int Ops[16];
5820   for (unsigned i = 0; i != 16; ++i)
5821     Ops[i] = i + Amt;
5822   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5823   return DAG.getNode(ISD::BITCAST, dl, VT, T);
5824 }
5825
5826 // If this is a case we can't handle, return null and let the default
5827 // expansion code take care of it.  If we CAN select this case, and if it
5828 // selects to a single instruction, return Op.  Otherwise, if we can codegen
5829 // this case more efficiently than a constant pool load, lower it to the
5830 // sequence of ops that should be used.
5831 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5832                                              SelectionDAG &DAG) const {
5833   SDLoc dl(Op);
5834   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5835   assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5836
5837   // Check if this is a splat of a constant value.
5838   APInt APSplatBits, APSplatUndef;
5839   unsigned SplatBitSize;
5840   bool HasAnyUndefs;
5841   if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5842                              HasAnyUndefs, 0, true) || SplatBitSize > 32)
5843     return SDValue();
5844
5845   unsigned SplatBits = APSplatBits.getZExtValue();
5846   unsigned SplatUndef = APSplatUndef.getZExtValue();
5847   unsigned SplatSize = SplatBitSize / 8;
5848
5849   // First, handle single instruction cases.
5850
5851   // All zeros?
5852   if (SplatBits == 0) {
5853     // Canonicalize all zero vectors to be v4i32.
5854     if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5855       SDValue Z = DAG.getConstant(0, MVT::i32);
5856       Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5857       Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5858     }
5859     return Op;
5860   }
5861
5862   // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5863   int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5864                     (32-SplatBitSize));
5865   if (SextVal >= -16 && SextVal <= 15)
5866     return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5867
5868
5869   // Two instruction sequences.
5870
5871   // If this value is in the range [-32,30] and is even, use:
5872   //     VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5873   // If this value is in the range [17,31] and is odd, use:
5874   //     VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5875   // If this value is in the range [-31,-17] and is odd, use:
5876   //     VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5877   // Note the last two are three-instruction sequences.
5878   if (SextVal >= -32 && SextVal <= 31) {
5879     // To avoid having these optimizations undone by constant folding,
5880     // we convert to a pseudo that will be expanded later into one of
5881     // the above forms.
5882     SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5883     EVT VT = (SplatSize == 1 ? MVT::v16i8 :
5884               (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
5885     SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
5886     SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5887     if (VT == Op.getValueType())
5888       return RetVal;
5889     else
5890       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
5891   }
5892
5893   // If this is 0x8000_0000 x 4, turn into vspltisw + vslw.  If it is
5894   // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000).  This is important
5895   // for fneg/fabs.
5896   if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5897     // Make -1 and vspltisw -1:
5898     SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5899
5900     // Make the VSLW intrinsic, computing 0x8000_0000.
5901     SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5902                                    OnesV, DAG, dl);
5903
5904     // xor by OnesV to invert it.
5905     Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5906     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5907   }
5908
5909   // The remaining cases assume either big endian element order or
5910   // a splat-size that equates to the element size of the vector
5911   // to be built.  An example that doesn't work for little endian is
5912   // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
5913   // and a vector element size of 16 bits.  The code below will
5914   // produce the vector in big endian element order, which for little
5915   // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
5916
5917   // For now, just avoid these optimizations in that case.
5918   // FIXME: Develop correct optimizations for LE with mismatched
5919   // splat and element sizes.
5920
5921   if (Subtarget.isLittleEndian() &&
5922       SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
5923     return SDValue();
5924
5925   // Check to see if this is a wide variety of vsplti*, binop self cases.
5926   static const signed char SplatCsts[] = {
5927     -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5928     -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5929   };
5930
5931   for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5932     // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5933     // cases which are ambiguous (e.g. formation of 0x8000_0000).  'vsplti -1'
5934     int i = SplatCsts[idx];
5935
5936     // Figure out what shift amount will be used by altivec if shifted by i in
5937     // this splat size.
5938     unsigned TypeShiftAmt = i & (SplatBitSize-1);
5939
5940     // vsplti + shl self.
5941     if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5942       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5943       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5944         Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5945         Intrinsic::ppc_altivec_vslw
5946       };
5947       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5948       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5949     }
5950
5951     // vsplti + srl self.
5952     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5953       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5954       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5955         Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5956         Intrinsic::ppc_altivec_vsrw
5957       };
5958       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5959       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5960     }
5961
5962     // vsplti + sra self.
5963     if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5964       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5965       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5966         Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5967         Intrinsic::ppc_altivec_vsraw
5968       };
5969       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5970       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5971     }
5972
5973     // vsplti + rol self.
5974     if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5975                          ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5976       SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5977       static const unsigned IIDs[] = { // Intrinsic to use for each size.
5978         Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5979         Intrinsic::ppc_altivec_vrlw
5980       };
5981       Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5982       return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5983     }
5984
5985     // t = vsplti c, result = vsldoi t, t, 1
5986     if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5987       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5988       return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5989     }
5990     // t = vsplti c, result = vsldoi t, t, 2
5991     if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5992       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5993       return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5994     }
5995     // t = vsplti c, result = vsldoi t, t, 3
5996     if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5997       SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5998       return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5999     }
6000   }
6001
6002   return SDValue();
6003 }
6004
6005 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6006 /// the specified operations to build the shuffle.
6007 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6008                                       SDValue RHS, SelectionDAG &DAG,
6009                                       SDLoc dl) {
6010   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6011   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6012   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6013
6014   enum {
6015     OP_COPY = 0,  // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6016     OP_VMRGHW,
6017     OP_VMRGLW,
6018     OP_VSPLTISW0,
6019     OP_VSPLTISW1,
6020     OP_VSPLTISW2,
6021     OP_VSPLTISW3,
6022     OP_VSLDOI4,
6023     OP_VSLDOI8,
6024     OP_VSLDOI12
6025   };
6026
6027   if (OpNum == OP_COPY) {
6028     if (LHSID == (1*9+2)*9+3) return LHS;
6029     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6030     return RHS;
6031   }
6032
6033   SDValue OpLHS, OpRHS;
6034   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6035   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6036
6037   int ShufIdxs[16];
6038   switch (OpNum) {
6039   default: llvm_unreachable("Unknown i32 permute!");
6040   case OP_VMRGHW:
6041     ShufIdxs[ 0] =  0; ShufIdxs[ 1] =  1; ShufIdxs[ 2] =  2; ShufIdxs[ 3] =  3;
6042     ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6043     ShufIdxs[ 8] =  4; ShufIdxs[ 9] =  5; ShufIdxs[10] =  6; ShufIdxs[11] =  7;
6044     ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6045     break;
6046   case OP_VMRGLW:
6047     ShufIdxs[ 0] =  8; ShufIdxs[ 1] =  9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6048     ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6049     ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6050     ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6051     break;
6052   case OP_VSPLTISW0:
6053     for (unsigned i = 0; i != 16; ++i)
6054       ShufIdxs[i] = (i&3)+0;
6055     break;
6056   case OP_VSPLTISW1:
6057     for (unsigned i = 0; i != 16; ++i)
6058       ShufIdxs[i] = (i&3)+4;
6059     break;
6060   case OP_VSPLTISW2:
6061     for (unsigned i = 0; i != 16; ++i)
6062       ShufIdxs[i] = (i&3)+8;
6063     break;
6064   case OP_VSPLTISW3:
6065     for (unsigned i = 0; i != 16; ++i)
6066       ShufIdxs[i] = (i&3)+12;
6067     break;
6068   case OP_VSLDOI4:
6069     return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6070   case OP_VSLDOI8:
6071     return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6072   case OP_VSLDOI12:
6073     return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6074   }
6075   EVT VT = OpLHS.getValueType();
6076   OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6077   OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6078   SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6079   return DAG.getNode(ISD::BITCAST, dl, VT, T);
6080 }
6081
6082 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE.  If this
6083 /// is a shuffle we can handle in a single instruction, return it.  Otherwise,
6084 /// return the code it can be lowered into.  Worst case, it can always be
6085 /// lowered into a vperm.
6086 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6087                                                SelectionDAG &DAG) const {
6088   SDLoc dl(Op);
6089   SDValue V1 = Op.getOperand(0);
6090   SDValue V2 = Op.getOperand(1);
6091   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6092   EVT VT = Op.getValueType();
6093   bool isLittleEndian = Subtarget.isLittleEndian();
6094
6095   // Cases that are handled by instructions that take permute immediates
6096   // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6097   // selected by the instruction selector.
6098   if (V2.getOpcode() == ISD::UNDEF) {
6099     if (PPC::isSplatShuffleMask(SVOp, 1) ||
6100         PPC::isSplatShuffleMask(SVOp, 2) ||
6101         PPC::isSplatShuffleMask(SVOp, 4) ||
6102         PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6103         PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6104         PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6105         PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6106         PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6107         PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6108         PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6109         PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6110         PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6111       return Op;
6112     }
6113   }
6114
6115   // Altivec has a variety of "shuffle immediates" that take two vector inputs
6116   // and produce a fixed permutation.  If any of these match, do not lower to
6117   // VPERM.
6118   unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6119   if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6120       PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6121       PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6122       PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6123       PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6124       PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6125       PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6126       PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6127       PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6128     return Op;
6129
6130   // Check to see if this is a shuffle of 4-byte values.  If so, we can use our
6131   // perfect shuffle table to emit an optimal matching sequence.
6132   ArrayRef<int> PermMask = SVOp->getMask();
6133
6134   unsigned PFIndexes[4];
6135   bool isFourElementShuffle = true;
6136   for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6137     unsigned EltNo = 8;   // Start out undef.
6138     for (unsigned j = 0; j != 4; ++j) {  // Intra-element byte.
6139       if (PermMask[i*4+j] < 0)
6140         continue;   // Undef, ignore it.
6141
6142       unsigned ByteSource = PermMask[i*4+j];
6143       if ((ByteSource & 3) != j) {
6144         isFourElementShuffle = false;
6145         break;
6146       }
6147
6148       if (EltNo == 8) {
6149         EltNo = ByteSource/4;
6150       } else if (EltNo != ByteSource/4) {
6151         isFourElementShuffle = false;
6152         break;
6153       }
6154     }
6155     PFIndexes[i] = EltNo;
6156   }
6157
6158   // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6159   // perfect shuffle vector to determine if it is cost effective to do this as
6160   // discrete instructions, or whether we should use a vperm.
6161   // For now, we skip this for little endian until such time as we have a
6162   // little-endian perfect shuffle table.
6163   if (isFourElementShuffle && !isLittleEndian) {
6164     // Compute the index in the perfect shuffle table.
6165     unsigned PFTableIndex =
6166       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6167
6168     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6169     unsigned Cost  = (PFEntry >> 30);
6170
6171     // Determining when to avoid vperm is tricky.  Many things affect the cost
6172     // of vperm, particularly how many times the perm mask needs to be computed.
6173     // For example, if the perm mask can be hoisted out of a loop or is already
6174     // used (perhaps because there are multiple permutes with the same shuffle
6175     // mask?) the vperm has a cost of 1.  OTOH, hoisting the permute mask out of
6176     // the loop requires an extra register.
6177     //
6178     // As a compromise, we only emit discrete instructions if the shuffle can be
6179     // generated in 3 or fewer operations.  When we have loop information
6180     // available, if this block is within a loop, we should avoid using vperm
6181     // for 3-operation perms and use a constant pool load instead.
6182     if (Cost < 3)
6183       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6184   }
6185
6186   // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6187   // vector that will get spilled to the constant pool.
6188   if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6189
6190   // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6191   // that it is in input element units, not in bytes.  Convert now.
6192
6193   // For little endian, the order of the input vectors is reversed, and
6194   // the permutation mask is complemented with respect to 31.  This is
6195   // necessary to produce proper semantics with the big-endian-biased vperm
6196   // instruction.
6197   EVT EltVT = V1.getValueType().getVectorElementType();
6198   unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6199
6200   SmallVector<SDValue, 16> ResultMask;
6201   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6202     unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6203
6204     for (unsigned j = 0; j != BytesPerElement; ++j)
6205       if (isLittleEndian)
6206         ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6207                                              MVT::i32));
6208       else
6209         ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6210                                              MVT::i32));
6211   }
6212
6213   SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6214                                   ResultMask);
6215   if (isLittleEndian)
6216     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6217                        V2, V1, VPermMask);
6218   else
6219     return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6220                        V1, V2, VPermMask);
6221 }
6222
6223 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6224 /// altivec comparison.  If it is, return true and fill in Opc/isDot with
6225 /// information about the intrinsic.
6226 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6227                                   bool &isDot) {
6228   unsigned IntrinsicID =
6229     cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6230   CompareOpc = -1;
6231   isDot = false;
6232   switch (IntrinsicID) {
6233   default: return false;
6234     // Comparison predicates.
6235   case Intrinsic::ppc_altivec_vcmpbfp_p:  CompareOpc = 966; isDot = 1; break;
6236   case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6237   case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc =   6; isDot = 1; break;
6238   case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc =  70; isDot = 1; break;
6239   case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6240   case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6241   case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6242   case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6243   case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6244   case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6245   case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6246   case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6247   case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6248
6249     // Normal Comparisons.
6250   case Intrinsic::ppc_altivec_vcmpbfp:    CompareOpc = 966; isDot = 0; break;
6251   case Intrinsic::ppc_altivec_vcmpeqfp:   CompareOpc = 198; isDot = 0; break;
6252   case Intrinsic::ppc_altivec_vcmpequb:   CompareOpc =   6; isDot = 0; break;
6253   case Intrinsic::ppc_altivec_vcmpequh:   CompareOpc =  70; isDot = 0; break;
6254   case Intrinsic::ppc_altivec_vcmpequw:   CompareOpc = 134; isDot = 0; break;
6255   case Intrinsic::ppc_altivec_vcmpgefp:   CompareOpc = 454; isDot = 0; break;
6256   case Intrinsic::ppc_altivec_vcmpgtfp:   CompareOpc = 710; isDot = 0; break;
6257   case Intrinsic::ppc_altivec_vcmpgtsb:   CompareOpc = 774; isDot = 0; break;
6258   case Intrinsic::ppc_altivec_vcmpgtsh:   CompareOpc = 838; isDot = 0; break;
6259   case Intrinsic::ppc_altivec_vcmpgtsw:   CompareOpc = 902; isDot = 0; break;
6260   case Intrinsic::ppc_altivec_vcmpgtub:   CompareOpc = 518; isDot = 0; break;
6261   case Intrinsic::ppc_altivec_vcmpgtuh:   CompareOpc = 582; isDot = 0; break;
6262   case Intrinsic::ppc_altivec_vcmpgtuw:   CompareOpc = 646; isDot = 0; break;
6263   }
6264   return true;
6265 }
6266
6267 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6268 /// lower, do it, otherwise return null.
6269 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6270                                                    SelectionDAG &DAG) const {
6271   // If this is a lowered altivec predicate compare, CompareOpc is set to the
6272   // opcode number of the comparison.
6273   SDLoc dl(Op);
6274   int CompareOpc;
6275   bool isDot;
6276   if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6277     return SDValue();    // Don't custom lower most intrinsics.
6278
6279   // If this is a non-dot comparison, make the VCMP node and we are done.
6280   if (!isDot) {
6281     SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6282                               Op.getOperand(1), Op.getOperand(2),
6283                               DAG.getConstant(CompareOpc, MVT::i32));
6284     return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6285   }
6286
6287   // Create the PPCISD altivec 'dot' comparison node.
6288   SDValue Ops[] = {
6289     Op.getOperand(2),  // LHS
6290     Op.getOperand(3),  // RHS
6291     DAG.getConstant(CompareOpc, MVT::i32)
6292   };
6293   EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6294   SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6295
6296   // Now that we have the comparison, emit a copy from the CR to a GPR.
6297   // This is flagged to the above dot comparison.
6298   SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6299                                 DAG.getRegister(PPC::CR6, MVT::i32),
6300                                 CompNode.getValue(1));
6301
6302   // Unpack the result based on how the target uses it.
6303   unsigned BitNo;   // Bit # of CR6.
6304   bool InvertBit;   // Invert result?
6305   switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6306   default:  // Can't happen, don't crash on invalid number though.
6307   case 0:   // Return the value of the EQ bit of CR6.
6308     BitNo = 0; InvertBit = false;
6309     break;
6310   case 1:   // Return the inverted value of the EQ bit of CR6.
6311     BitNo = 0; InvertBit = true;
6312     break;
6313   case 2:   // Return the value of the LT bit of CR6.
6314     BitNo = 2; InvertBit = false;
6315     break;
6316   case 3:   // Return the inverted value of the LT bit of CR6.
6317     BitNo = 2; InvertBit = true;
6318     break;
6319   }
6320
6321   // Shift the bit into the low position.
6322   Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6323                       DAG.getConstant(8-(3-BitNo), MVT::i32));
6324   // Isolate the bit.
6325   Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6326                       DAG.getConstant(1, MVT::i32));
6327
6328   // If we are supposed to, toggle the bit.
6329   if (InvertBit)
6330     Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6331                         DAG.getConstant(1, MVT::i32));
6332   return Flags;
6333 }
6334
6335 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6336                                                   SelectionDAG &DAG) const {
6337   SDLoc dl(Op);
6338   // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6339   // instructions), but for smaller types, we need to first extend up to v2i32
6340   // before doing going farther.
6341   if (Op.getValueType() == MVT::v2i64) {
6342     EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6343     if (ExtVT != MVT::v2i32) {
6344       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6345       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6346                        DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6347                                         ExtVT.getVectorElementType(), 4)));
6348       Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6349       Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6350                        DAG.getValueType(MVT::v2i32));
6351     }
6352
6353     return Op;
6354   }
6355
6356   return SDValue();
6357 }
6358
6359 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6360                                                    SelectionDAG &DAG) const {
6361   SDLoc dl(Op);
6362   // Create a stack slot that is 16-byte aligned.
6363   MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6364   int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6365   EVT PtrVT = getPointerTy();
6366   SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6367
6368   // Store the input value into Value#0 of the stack slot.
6369   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6370                                Op.getOperand(0), FIdx, MachinePointerInfo(),
6371                                false, false, 0);
6372   // Load it out.
6373   return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6374                      false, false, false, 0);
6375 }
6376
6377 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6378   SDLoc dl(Op);
6379   if (Op.getValueType() == MVT::v4i32) {
6380     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6381
6382     SDValue Zero  = BuildSplatI(  0, 1, MVT::v4i32, DAG, dl);
6383     SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6384
6385     SDValue RHSSwap =   // = vrlw RHS, 16
6386       BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6387
6388     // Shrinkify inputs to v8i16.
6389     LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6390     RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6391     RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6392
6393     // Low parts multiplied together, generating 32-bit results (we ignore the
6394     // top parts).
6395     SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6396                                         LHS, RHS, DAG, dl, MVT::v4i32);
6397
6398     SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6399                                       LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6400     // Shift the high parts up 16 bits.
6401     HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6402                               Neg16, DAG, dl);
6403     return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6404   } else if (Op.getValueType() == MVT::v8i16) {
6405     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6406
6407     SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6408
6409     return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6410                             LHS, RHS, Zero, DAG, dl);
6411   } else if (Op.getValueType() == MVT::v16i8) {
6412     SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6413     bool isLittleEndian = Subtarget.isLittleEndian();
6414
6415     // Multiply the even 8-bit parts, producing 16-bit sums.
6416     SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6417                                            LHS, RHS, DAG, dl, MVT::v8i16);
6418     EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6419
6420     // Multiply the odd 8-bit parts, producing 16-bit sums.
6421     SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6422                                           LHS, RHS, DAG, dl, MVT::v8i16);
6423     OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6424
6425     // Merge the results together.  Because vmuleub and vmuloub are
6426     // instructions with a big-endian bias, we must reverse the
6427     // element numbering and reverse the meaning of "odd" and "even"
6428     // when generating little endian code.
6429     int Ops[16];
6430     for (unsigned i = 0; i != 8; ++i) {
6431       if (isLittleEndian) {
6432         Ops[i*2  ] = 2*i;
6433         Ops[i*2+1] = 2*i+16;
6434       } else {
6435         Ops[i*2  ] = 2*i+1;
6436         Ops[i*2+1] = 2*i+1+16;
6437       }
6438     }
6439     if (isLittleEndian)
6440       return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6441     else
6442       return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6443   } else {
6444     llvm_unreachable("Unknown mul to lower!");
6445   }
6446 }
6447
6448 /// LowerOperation - Provide custom lowering hooks for some operations.
6449 ///
6450 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6451   switch (Op.getOpcode()) {
6452   default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6453   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
6454   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
6455   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
6456   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
6457   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
6458   case ISD::SETCC:              return LowerSETCC(Op, DAG);
6459   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
6460   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
6461   case ISD::VASTART:
6462     return LowerVASTART(Op, DAG, Subtarget);
6463
6464   case ISD::VAARG:
6465     return LowerVAARG(Op, DAG, Subtarget);
6466
6467   case ISD::VACOPY:
6468     return LowerVACOPY(Op, DAG, Subtarget);
6469
6470   case ISD::STACKRESTORE:       return LowerSTACKRESTORE(Op, DAG, Subtarget);
6471   case ISD::DYNAMIC_STACKALLOC:
6472     return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6473
6474   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
6475   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
6476
6477   case ISD::LOAD:               return LowerLOAD(Op, DAG);
6478   case ISD::STORE:              return LowerSTORE(Op, DAG);
6479   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
6480   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
6481   case ISD::FP_TO_UINT:
6482   case ISD::FP_TO_SINT:         return LowerFP_TO_INT(Op, DAG,
6483                                                        SDLoc(Op));
6484   case ISD::UINT_TO_FP:
6485   case ISD::SINT_TO_FP:         return LowerINT_TO_FP(Op, DAG);
6486   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
6487
6488   // Lower 64-bit shifts.
6489   case ISD::SHL_PARTS:          return LowerSHL_PARTS(Op, DAG);
6490   case ISD::SRL_PARTS:          return LowerSRL_PARTS(Op, DAG);
6491   case ISD::SRA_PARTS:          return LowerSRA_PARTS(Op, DAG);
6492
6493   // Vector-related lowering.
6494   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
6495   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
6496   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6497   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
6498   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op, DAG);
6499   case ISD::MUL:                return LowerMUL(Op, DAG);
6500
6501   // For counter-based loop handling.
6502   case ISD::INTRINSIC_W_CHAIN:  return SDValue();
6503
6504   // Frame & Return address.
6505   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
6506   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
6507   }
6508 }
6509
6510 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6511                                            SmallVectorImpl<SDValue>&Results,
6512                                            SelectionDAG &DAG) const {
6513   const TargetMachine &TM = getTargetMachine();
6514   SDLoc dl(N);
6515   switch (N->getOpcode()) {
6516   default:
6517     llvm_unreachable("Do not know how to custom type legalize this operation!");
6518   case ISD::READCYCLECOUNTER: {
6519     SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6520     SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6521
6522     Results.push_back(RTB);
6523     Results.push_back(RTB.getValue(1));
6524     Results.push_back(RTB.getValue(2));
6525     break;
6526   }
6527   case ISD::INTRINSIC_W_CHAIN: {
6528     if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6529         Intrinsic::ppc_is_decremented_ctr_nonzero)
6530       break;
6531
6532     assert(N->getValueType(0) == MVT::i1 &&
6533            "Unexpected result type for CTR decrement intrinsic");
6534     EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6535     SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6536     SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6537                                  N->getOperand(1)); 
6538
6539     Results.push_back(NewInt);
6540     Results.push_back(NewInt.getValue(1));
6541     break;
6542   }
6543   case ISD::VAARG: {
6544     if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6545         || TM.getSubtarget<PPCSubtarget>().isPPC64())
6546       return;
6547
6548     EVT VT = N->getValueType(0);
6549
6550     if (VT == MVT::i64) {
6551       SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6552
6553       Results.push_back(NewNode);
6554       Results.push_back(NewNode.getValue(1));
6555     }
6556     return;
6557   }
6558   case ISD::FP_ROUND_INREG: {
6559     assert(N->getValueType(0) == MVT::ppcf128);
6560     assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6561     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6562                              MVT::f64, N->getOperand(0),
6563                              DAG.getIntPtrConstant(0));
6564     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6565                              MVT::f64, N->getOperand(0),
6566                              DAG.getIntPtrConstant(1));
6567
6568     // Add the two halves of the long double in round-to-zero mode.
6569     SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6570
6571     // We know the low half is about to be thrown away, so just use something
6572     // convenient.
6573     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6574                                 FPreg, FPreg));
6575     return;
6576   }
6577   case ISD::FP_TO_SINT:
6578     // LowerFP_TO_INT() can only handle f32 and f64.
6579     if (N->getOperand(0).getValueType() == MVT::ppcf128)
6580       return;
6581     Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6582     return;
6583   }
6584 }
6585
6586
6587 //===----------------------------------------------------------------------===//
6588 //  Other Lowering Code
6589 //===----------------------------------------------------------------------===//
6590
6591 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6592   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6593   Function *Func = Intrinsic::getDeclaration(M, Id);
6594   return Builder.CreateCall(Func);
6595 }
6596
6597 // The mappings for emitLeading/TrailingFence is taken from
6598 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6599 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6600                                          AtomicOrdering Ord, bool IsStore,
6601                                          bool IsLoad) const {
6602   if (Ord == SequentiallyConsistent)
6603     return callIntrinsic(Builder, Intrinsic::ppc_sync);
6604   else if (isAtLeastRelease(Ord))
6605     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6606   else
6607     return nullptr;
6608 }
6609
6610 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6611                                           AtomicOrdering Ord, bool IsStore,
6612                                           bool IsLoad) const {
6613   if (IsLoad && isAtLeastAcquire(Ord))
6614     return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6615   // FIXME: this is too conservative, a dependent branch + isync is enough.
6616   // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6617   // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6618   // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6619   else
6620     return nullptr;
6621 }
6622
6623 MachineBasicBlock *
6624 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6625                                     bool is64bit, unsigned BinOpcode) const {
6626   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6627   const TargetInstrInfo *TII =
6628       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6629
6630   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6631   MachineFunction *F = BB->getParent();
6632   MachineFunction::iterator It = BB;
6633   ++It;
6634
6635   unsigned dest = MI->getOperand(0).getReg();
6636   unsigned ptrA = MI->getOperand(1).getReg();
6637   unsigned ptrB = MI->getOperand(2).getReg();
6638   unsigned incr = MI->getOperand(3).getReg();
6639   DebugLoc dl = MI->getDebugLoc();
6640
6641   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6642   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6643   F->insert(It, loopMBB);
6644   F->insert(It, exitMBB);
6645   exitMBB->splice(exitMBB->begin(), BB,
6646                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6647   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6648
6649   MachineRegisterInfo &RegInfo = F->getRegInfo();
6650   unsigned TmpReg = (!BinOpcode) ? incr :
6651     RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6652                                            : &PPC::GPRCRegClass);
6653
6654   //  thisMBB:
6655   //   ...
6656   //   fallthrough --> loopMBB
6657   BB->addSuccessor(loopMBB);
6658
6659   //  loopMBB:
6660   //   l[wd]arx dest, ptr
6661   //   add r0, dest, incr
6662   //   st[wd]cx. r0, ptr
6663   //   bne- loopMBB
6664   //   fallthrough --> exitMBB
6665   BB = loopMBB;
6666   BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6667     .addReg(ptrA).addReg(ptrB);
6668   if (BinOpcode)
6669     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6670   BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6671     .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6672   BuildMI(BB, dl, TII->get(PPC::BCC))
6673     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6674   BB->addSuccessor(loopMBB);
6675   BB->addSuccessor(exitMBB);
6676
6677   //  exitMBB:
6678   //   ...
6679   BB = exitMBB;
6680   return BB;
6681 }
6682
6683 MachineBasicBlock *
6684 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6685                                             MachineBasicBlock *BB,
6686                                             bool is8bit,    // operation
6687                                             unsigned BinOpcode) const {
6688   // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6689   const TargetInstrInfo *TII =
6690       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6691   // In 64 bit mode we have to use 64 bits for addresses, even though the
6692   // lwarx/stwcx are 32 bits.  With the 32-bit atomics we can use address
6693   // registers without caring whether they're 32 or 64, but here we're
6694   // doing actual arithmetic on the addresses.
6695   bool is64bit = Subtarget.isPPC64();
6696   unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6697
6698   const BasicBlock *LLVM_BB = BB->getBasicBlock();
6699   MachineFunction *F = BB->getParent();
6700   MachineFunction::iterator It = BB;
6701   ++It;
6702
6703   unsigned dest = MI->getOperand(0).getReg();
6704   unsigned ptrA = MI->getOperand(1).getReg();
6705   unsigned ptrB = MI->getOperand(2).getReg();
6706   unsigned incr = MI->getOperand(3).getReg();
6707   DebugLoc dl = MI->getDebugLoc();
6708
6709   MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6710   MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6711   F->insert(It, loopMBB);
6712   F->insert(It, exitMBB);
6713   exitMBB->splice(exitMBB->begin(), BB,
6714                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
6715   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6716
6717   MachineRegisterInfo &RegInfo = F->getRegInfo();
6718   const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6719                                           : &PPC::GPRCRegClass;
6720   unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6721   unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6722   unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6723   unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6724   unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6725   unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6726   unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6727   unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6728   unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6729   unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6730   unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6731   unsigned Ptr1Reg;
6732   unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6733
6734   //  thisMBB:
6735   //   ...
6736   //   fallthrough --> loopMBB
6737   BB->addSuccessor(loopMBB);
6738
6739   // The 4-byte load must be aligned, while a char or short may be
6740   // anywhere in the word.  Hence all this nasty bookkeeping code.
6741   //   add ptr1, ptrA, ptrB [copy if ptrA==0]
6742   //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6743   //   xori shift, shift1, 24 [16]
6744   //   rlwinm ptr, ptr1, 0, 0, 29
6745   //   slw incr2, incr, shift
6746   //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6747   //   slw mask, mask2, shift
6748   //  loopMBB:
6749   //   lwarx tmpDest, ptr
6750   //   add tmp, tmpDest, incr2
6751   //   andc tmp2, tmpDest, mask
6752   //   and tmp3, tmp, mask
6753   //   or tmp4, tmp3, tmp2
6754   //   stwcx. tmp4, ptr
6755   //   bne- loopMBB
6756   //   fallthrough --> exitMBB
6757   //   srw dest, tmpDest, shift
6758   if (ptrA != ZeroReg) {
6759     Ptr1Reg = RegInfo.createVirtualRegister(RC);
6760     BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6761       .addReg(ptrA).addReg(ptrB);
6762   } else {
6763     Ptr1Reg = ptrB;
6764   }
6765   BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6766       .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6767   BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6768       .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6769   if (is64bit)
6770     BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6771       .addReg(Ptr1Reg).addImm(0).addImm(61);
6772   else
6773     BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6774       .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6775   BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6776       .addReg(incr).addReg(ShiftReg);
6777   if (is8bit)
6778     BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6779   else {
6780     BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6781     BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6782   }
6783   BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6784       .addReg(Mask2Reg).addReg(ShiftReg);
6785
6786   BB = loopMBB;
6787   BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6788     .addReg(ZeroReg).addReg(PtrReg);
6789   if (BinOpcode)
6790     BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6791       .addReg(Incr2Reg).addReg(TmpDestReg);
6792   BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6793     .addReg(TmpDestReg).addReg(MaskReg);
6794   BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6795     .addReg(TmpReg).addReg(MaskReg);
6796   BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6797     .addReg(Tmp3Reg).addReg(Tmp2Reg);
6798   BuildMI(BB, dl, TII->get(PPC::STWCX))
6799     .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6800   BuildMI(BB, dl, TII->get(PPC::BCC))
6801     .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6802   BB->addSuccessor(loopMBB);
6803   BB->addSuccessor(exitMBB);
6804
6805   //  exitMBB:
6806   //   ...
6807   BB = exitMBB;
6808   BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6809     .addReg(ShiftReg);
6810   return BB;
6811 }
6812
6813 llvm::MachineBasicBlock*
6814 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6815                                     MachineBasicBlock *MBB) const {
6816   DebugLoc DL = MI->getDebugLoc();
6817   const TargetInstrInfo *TII =
6818       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6819
6820   MachineFunction *MF = MBB->getParent();
6821   MachineRegisterInfo &MRI = MF->getRegInfo();
6822
6823   const BasicBlock *BB = MBB->getBasicBlock();
6824   MachineFunction::iterator I = MBB;
6825   ++I;
6826
6827   // Memory Reference
6828   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6829   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6830
6831   unsigned DstReg = MI->getOperand(0).getReg();
6832   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6833   assert(RC->hasType(MVT::i32) && "Invalid destination!");
6834   unsigned mainDstReg = MRI.createVirtualRegister(RC);
6835   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6836
6837   MVT PVT = getPointerTy();
6838   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6839          "Invalid Pointer Size!");
6840   // For v = setjmp(buf), we generate
6841   //
6842   // thisMBB:
6843   //  SjLjSetup mainMBB
6844   //  bl mainMBB
6845   //  v_restore = 1
6846   //  b sinkMBB
6847   //
6848   // mainMBB:
6849   //  buf[LabelOffset] = LR
6850   //  v_main = 0
6851   //
6852   // sinkMBB:
6853   //  v = phi(main, restore)
6854   //
6855
6856   MachineBasicBlock *thisMBB = MBB;
6857   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6858   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6859   MF->insert(I, mainMBB);
6860   MF->insert(I, sinkMBB);
6861
6862   MachineInstrBuilder MIB;
6863
6864   // Transfer the remainder of BB and its successor edges to sinkMBB.
6865   sinkMBB->splice(sinkMBB->begin(), MBB,
6866                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
6867   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6868
6869   // Note that the structure of the jmp_buf used here is not compatible
6870   // with that used by libc, and is not designed to be. Specifically, it
6871   // stores only those 'reserved' registers that LLVM does not otherwise
6872   // understand how to spill. Also, by convention, by the time this
6873   // intrinsic is called, Clang has already stored the frame address in the
6874   // first slot of the buffer and stack address in the third. Following the
6875   // X86 target code, we'll store the jump address in the second slot. We also
6876   // need to save the TOC pointer (R2) to handle jumps between shared
6877   // libraries, and that will be stored in the fourth slot. The thread
6878   // identifier (R13) is not affected.
6879
6880   // thisMBB:
6881   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6882   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6883   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6884
6885   // Prepare IP either in reg.
6886   const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6887   unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6888   unsigned BufReg = MI->getOperand(1).getReg();
6889
6890   if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
6891     MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6892             .addReg(PPC::X2)
6893             .addImm(TOCOffset)
6894             .addReg(BufReg);
6895     MIB.setMemRefs(MMOBegin, MMOEnd);
6896   }
6897
6898   // Naked functions never have a base pointer, and so we use r1. For all
6899   // other functions, this decision must be delayed until during PEI.
6900   unsigned BaseReg;
6901   if (MF->getFunction()->getAttributes().hasAttribute(
6902           AttributeSet::FunctionIndex, Attribute::Naked))
6903     BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
6904   else
6905     BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
6906
6907   MIB = BuildMI(*thisMBB, MI, DL,
6908                 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
6909           .addReg(BaseReg)
6910           .addImm(BPOffset)
6911           .addReg(BufReg);
6912   MIB.setMemRefs(MMOBegin, MMOEnd);
6913
6914   // Setup
6915   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6916   const PPCRegisterInfo *TRI =
6917       getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
6918   MIB.addRegMask(TRI->getNoPreservedMask());
6919
6920   BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6921
6922   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6923           .addMBB(mainMBB);
6924   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6925
6926   thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6927   thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6928
6929   // mainMBB:
6930   //  mainDstReg = 0
6931   MIB = BuildMI(mainMBB, DL,
6932     TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6933
6934   // Store IP
6935   if (Subtarget.isPPC64()) {
6936     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6937             .addReg(LabelReg)
6938             .addImm(LabelOffset)
6939             .addReg(BufReg);
6940   } else {
6941     MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6942             .addReg(LabelReg)
6943             .addImm(LabelOffset)
6944             .addReg(BufReg);
6945   }
6946
6947   MIB.setMemRefs(MMOBegin, MMOEnd);
6948
6949   BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6950   mainMBB->addSuccessor(sinkMBB);
6951
6952   // sinkMBB:
6953   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6954           TII->get(PPC::PHI), DstReg)
6955     .addReg(mainDstReg).addMBB(mainMBB)
6956     .addReg(restoreDstReg).addMBB(thisMBB);
6957
6958   MI->eraseFromParent();
6959   return sinkMBB;
6960 }
6961
6962 MachineBasicBlock *
6963 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6964                                      MachineBasicBlock *MBB) const {
6965   DebugLoc DL = MI->getDebugLoc();
6966   const TargetInstrInfo *TII =
6967       getTargetMachine().getSubtargetImpl()->getInstrInfo();
6968
6969   MachineFunction *MF = MBB->getParent();
6970   MachineRegisterInfo &MRI = MF->getRegInfo();
6971
6972   // Memory Reference
6973   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6974   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6975
6976   MVT PVT = getPointerTy();
6977   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6978          "Invalid Pointer Size!");
6979
6980   const TargetRegisterClass *RC =
6981     (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6982   unsigned Tmp = MRI.createVirtualRegister(RC);
6983   // Since FP is only updated here but NOT referenced, it's treated as GPR.
6984   unsigned FP  = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6985   unsigned SP  = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6986   unsigned BP  = (PVT == MVT::i64) ? PPC::X30 :
6987                   (Subtarget.isSVR4ABI() &&
6988                    MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
6989                      PPC::R29 : PPC::R30);
6990
6991   MachineInstrBuilder MIB;
6992
6993   const int64_t LabelOffset = 1 * PVT.getStoreSize();
6994   const int64_t SPOffset    = 2 * PVT.getStoreSize();
6995   const int64_t TOCOffset   = 3 * PVT.getStoreSize();
6996   const int64_t BPOffset    = 4 * PVT.getStoreSize();
6997
6998   unsigned BufReg = MI->getOperand(0).getReg();
6999
7000   // Reload FP (the jumped-to function may not have had a
7001   // frame pointer, and if so, then its r31 will be restored
7002   // as necessary).
7003   if (PVT == MVT::i64) {
7004     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7005             .addImm(0)
7006             .addReg(BufReg);
7007   } else {
7008     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7009             .addImm(0)
7010             .addReg(BufReg);
7011   }
7012   MIB.setMemRefs(MMOBegin, MMOEnd);
7013
7014   // Reload IP
7015   if (PVT == MVT::i64) {
7016     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7017             .addImm(LabelOffset)
7018             .addReg(BufReg);
7019   } else {
7020     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7021             .addImm(LabelOffset)
7022             .addReg(BufReg);
7023   }
7024   MIB.setMemRefs(MMOBegin, MMOEnd);
7025
7026   // Reload SP
7027   if (PVT == MVT::i64) {
7028     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7029             .addImm(SPOffset)
7030             .addReg(BufReg);
7031   } else {
7032     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7033             .addImm(SPOffset)
7034             .addReg(BufReg);
7035   }
7036   MIB.setMemRefs(MMOBegin, MMOEnd);
7037
7038   // Reload BP
7039   if (PVT == MVT::i64) {
7040     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7041             .addImm(BPOffset)
7042             .addReg(BufReg);
7043   } else {
7044     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7045             .addImm(BPOffset)
7046             .addReg(BufReg);
7047   }
7048   MIB.setMemRefs(MMOBegin, MMOEnd);
7049
7050   // Reload TOC
7051   if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7052     MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7053             .addImm(TOCOffset)
7054             .addReg(BufReg);
7055
7056     MIB.setMemRefs(MMOBegin, MMOEnd);
7057   }
7058
7059   // Jump
7060   BuildMI(*MBB, MI, DL,
7061           TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7062   BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7063
7064   MI->eraseFromParent();
7065   return MBB;
7066 }
7067
7068 MachineBasicBlock *
7069 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7070                                                MachineBasicBlock *BB) const {
7071   if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7072       MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7073     return emitEHSjLjSetJmp(MI, BB);
7074   } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7075              MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7076     return emitEHSjLjLongJmp(MI, BB);
7077   }
7078
7079   const TargetInstrInfo *TII =
7080       getTargetMachine().getSubtargetImpl()->getInstrInfo();
7081
7082   // To "insert" these instructions we actually have to insert their
7083   // control-flow patterns.
7084   const BasicBlock *LLVM_BB = BB->getBasicBlock();
7085   MachineFunction::iterator It = BB;
7086   ++It;
7087
7088   MachineFunction *F = BB->getParent();
7089
7090   if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7091                                  MI->getOpcode() == PPC::SELECT_CC_I8 ||
7092                                  MI->getOpcode() == PPC::SELECT_I4 ||
7093                                  MI->getOpcode() == PPC::SELECT_I8)) {
7094     SmallVector<MachineOperand, 2> Cond;
7095     if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7096         MI->getOpcode() == PPC::SELECT_CC_I8)
7097       Cond.push_back(MI->getOperand(4));
7098     else
7099       Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7100     Cond.push_back(MI->getOperand(1));
7101
7102     DebugLoc dl = MI->getDebugLoc();
7103     const TargetInstrInfo *TII =
7104         getTargetMachine().getSubtargetImpl()->getInstrInfo();
7105     TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7106                       Cond, MI->getOperand(2).getReg(),
7107                       MI->getOperand(3).getReg());
7108   } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7109              MI->getOpcode() == PPC::SELECT_CC_I8 ||
7110              MI->getOpcode() == PPC::SELECT_CC_F4 ||
7111              MI->getOpcode() == PPC::SELECT_CC_F8 ||
7112              MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7113              MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7114              MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7115              MI->getOpcode() == PPC::SELECT_I4 ||
7116              MI->getOpcode() == PPC::SELECT_I8 ||
7117              MI->getOpcode() == PPC::SELECT_F4 ||
7118              MI->getOpcode() == PPC::SELECT_F8 ||
7119              MI->getOpcode() == PPC::SELECT_VRRC ||
7120              MI->getOpcode() == PPC::SELECT_VSFRC ||
7121              MI->getOpcode() == PPC::SELECT_VSRC) {
7122     // The incoming instruction knows the destination vreg to set, the
7123     // condition code register to branch on, the true/false values to
7124     // select between, and a branch opcode to use.
7125
7126     //  thisMBB:
7127     //  ...
7128     //   TrueVal = ...
7129     //   cmpTY ccX, r1, r2
7130     //   bCC copy1MBB
7131     //   fallthrough --> copy0MBB
7132     MachineBasicBlock *thisMBB = BB;
7133     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7134     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7135     DebugLoc dl = MI->getDebugLoc();
7136     F->insert(It, copy0MBB);
7137     F->insert(It, sinkMBB);
7138
7139     // Transfer the remainder of BB and its successor edges to sinkMBB.
7140     sinkMBB->splice(sinkMBB->begin(), BB,
7141                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7142     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7143
7144     // Next, add the true and fallthrough blocks as its successors.
7145     BB->addSuccessor(copy0MBB);
7146     BB->addSuccessor(sinkMBB);
7147
7148     if (MI->getOpcode() == PPC::SELECT_I4 ||
7149         MI->getOpcode() == PPC::SELECT_I8 ||
7150         MI->getOpcode() == PPC::SELECT_F4 ||
7151         MI->getOpcode() == PPC::SELECT_F8 ||
7152         MI->getOpcode() == PPC::SELECT_VRRC ||
7153         MI->getOpcode() == PPC::SELECT_VSFRC ||
7154         MI->getOpcode() == PPC::SELECT_VSRC) {
7155       BuildMI(BB, dl, TII->get(PPC::BC))
7156         .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7157     } else {
7158       unsigned SelectPred = MI->getOperand(4).getImm();
7159       BuildMI(BB, dl, TII->get(PPC::BCC))
7160         .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7161     }
7162
7163     //  copy0MBB:
7164     //   %FalseValue = ...
7165     //   # fallthrough to sinkMBB
7166     BB = copy0MBB;
7167
7168     // Update machine-CFG edges
7169     BB->addSuccessor(sinkMBB);
7170
7171     //  sinkMBB:
7172     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7173     //  ...
7174     BB = sinkMBB;
7175     BuildMI(*BB, BB->begin(), dl,
7176             TII->get(PPC::PHI), MI->getOperand(0).getReg())
7177       .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7178       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7179   } else if (MI->getOpcode() == PPC::ReadTB) {
7180     // To read the 64-bit time-base register on a 32-bit target, we read the
7181     // two halves. Should the counter have wrapped while it was being read, we
7182     // need to try again.
7183     // ...
7184     // readLoop:
7185     // mfspr Rx,TBU # load from TBU
7186     // mfspr Ry,TB  # load from TB
7187     // mfspr Rz,TBU # load from TBU
7188     // cmpw crX,Rx,Rz # check if â€˜old’=’new’
7189     // bne readLoop   # branch if they're not equal
7190     // ...
7191
7192     MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7193     MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7194     DebugLoc dl = MI->getDebugLoc();
7195     F->insert(It, readMBB);
7196     F->insert(It, sinkMBB);
7197
7198     // Transfer the remainder of BB and its successor edges to sinkMBB.
7199     sinkMBB->splice(sinkMBB->begin(), BB,
7200                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7201     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7202
7203     BB->addSuccessor(readMBB);
7204     BB = readMBB;
7205
7206     MachineRegisterInfo &RegInfo = F->getRegInfo();
7207     unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7208     unsigned LoReg = MI->getOperand(0).getReg();
7209     unsigned HiReg = MI->getOperand(1).getReg();
7210
7211     BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7212     BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7213     BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7214
7215     unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7216
7217     BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7218       .addReg(HiReg).addReg(ReadAgainReg);
7219     BuildMI(BB, dl, TII->get(PPC::BCC))
7220       .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7221
7222     BB->addSuccessor(readMBB);
7223     BB->addSuccessor(sinkMBB);
7224   }
7225   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7226     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7227   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7228     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7229   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7230     BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7231   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7232     BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7233
7234   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7235     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7236   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7237     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7238   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7239     BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7240   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7241     BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7242
7243   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7244     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7245   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7246     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7247   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7248     BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7249   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7250     BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7251
7252   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7253     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7254   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7255     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7256   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7257     BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7258   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7259     BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7260
7261   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7262     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7263   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7264     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7265   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7266     BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7267   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7268     BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7269
7270   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7271     BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7272   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7273     BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7274   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7275     BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7276   else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7277     BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7278
7279   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7280     BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7281   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7282     BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7283   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7284     BB = EmitAtomicBinary(MI, BB, false, 0);
7285   else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7286     BB = EmitAtomicBinary(MI, BB, true, 0);
7287
7288   else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7289            MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7290     bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7291
7292     unsigned dest   = MI->getOperand(0).getReg();
7293     unsigned ptrA   = MI->getOperand(1).getReg();
7294     unsigned ptrB   = MI->getOperand(2).getReg();
7295     unsigned oldval = MI->getOperand(3).getReg();
7296     unsigned newval = MI->getOperand(4).getReg();
7297     DebugLoc dl     = MI->getDebugLoc();
7298
7299     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7300     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7301     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7302     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7303     F->insert(It, loop1MBB);
7304     F->insert(It, loop2MBB);
7305     F->insert(It, midMBB);
7306     F->insert(It, exitMBB);
7307     exitMBB->splice(exitMBB->begin(), BB,
7308                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7309     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7310
7311     //  thisMBB:
7312     //   ...
7313     //   fallthrough --> loopMBB
7314     BB->addSuccessor(loop1MBB);
7315
7316     // loop1MBB:
7317     //   l[wd]arx dest, ptr
7318     //   cmp[wd] dest, oldval
7319     //   bne- midMBB
7320     // loop2MBB:
7321     //   st[wd]cx. newval, ptr
7322     //   bne- loopMBB
7323     //   b exitBB
7324     // midMBB:
7325     //   st[wd]cx. dest, ptr
7326     // exitBB:
7327     BB = loop1MBB;
7328     BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7329       .addReg(ptrA).addReg(ptrB);
7330     BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7331       .addReg(oldval).addReg(dest);
7332     BuildMI(BB, dl, TII->get(PPC::BCC))
7333       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7334     BB->addSuccessor(loop2MBB);
7335     BB->addSuccessor(midMBB);
7336
7337     BB = loop2MBB;
7338     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7339       .addReg(newval).addReg(ptrA).addReg(ptrB);
7340     BuildMI(BB, dl, TII->get(PPC::BCC))
7341       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7342     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7343     BB->addSuccessor(loop1MBB);
7344     BB->addSuccessor(exitMBB);
7345
7346     BB = midMBB;
7347     BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7348       .addReg(dest).addReg(ptrA).addReg(ptrB);
7349     BB->addSuccessor(exitMBB);
7350
7351     //  exitMBB:
7352     //   ...
7353     BB = exitMBB;
7354   } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7355              MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7356     // We must use 64-bit registers for addresses when targeting 64-bit,
7357     // since we're actually doing arithmetic on them.  Other registers
7358     // can be 32-bit.
7359     bool is64bit = Subtarget.isPPC64();
7360     bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7361
7362     unsigned dest   = MI->getOperand(0).getReg();
7363     unsigned ptrA   = MI->getOperand(1).getReg();
7364     unsigned ptrB   = MI->getOperand(2).getReg();
7365     unsigned oldval = MI->getOperand(3).getReg();
7366     unsigned newval = MI->getOperand(4).getReg();
7367     DebugLoc dl     = MI->getDebugLoc();
7368
7369     MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7370     MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7371     MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7372     MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7373     F->insert(It, loop1MBB);
7374     F->insert(It, loop2MBB);
7375     F->insert(It, midMBB);
7376     F->insert(It, exitMBB);
7377     exitMBB->splice(exitMBB->begin(), BB,
7378                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
7379     exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7380
7381     MachineRegisterInfo &RegInfo = F->getRegInfo();
7382     const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7383                                             : &PPC::GPRCRegClass;
7384     unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7385     unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7386     unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7387     unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7388     unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7389     unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7390     unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7391     unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7392     unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7393     unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7394     unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7395     unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7396     unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7397     unsigned Ptr1Reg;
7398     unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7399     unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7400     //  thisMBB:
7401     //   ...
7402     //   fallthrough --> loopMBB
7403     BB->addSuccessor(loop1MBB);
7404
7405     // The 4-byte load must be aligned, while a char or short may be
7406     // anywhere in the word.  Hence all this nasty bookkeeping code.
7407     //   add ptr1, ptrA, ptrB [copy if ptrA==0]
7408     //   rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7409     //   xori shift, shift1, 24 [16]
7410     //   rlwinm ptr, ptr1, 0, 0, 29
7411     //   slw newval2, newval, shift
7412     //   slw oldval2, oldval,shift
7413     //   li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7414     //   slw mask, mask2, shift
7415     //   and newval3, newval2, mask
7416     //   and oldval3, oldval2, mask
7417     // loop1MBB:
7418     //   lwarx tmpDest, ptr
7419     //   and tmp, tmpDest, mask
7420     //   cmpw tmp, oldval3
7421     //   bne- midMBB
7422     // loop2MBB:
7423     //   andc tmp2, tmpDest, mask
7424     //   or tmp4, tmp2, newval3
7425     //   stwcx. tmp4, ptr
7426     //   bne- loop1MBB
7427     //   b exitBB
7428     // midMBB:
7429     //   stwcx. tmpDest, ptr
7430     // exitBB:
7431     //   srw dest, tmpDest, shift
7432     if (ptrA != ZeroReg) {
7433       Ptr1Reg = RegInfo.createVirtualRegister(RC);
7434       BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7435         .addReg(ptrA).addReg(ptrB);
7436     } else {
7437       Ptr1Reg = ptrB;
7438     }
7439     BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7440         .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7441     BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7442         .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7443     if (is64bit)
7444       BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7445         .addReg(Ptr1Reg).addImm(0).addImm(61);
7446     else
7447       BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7448         .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7449     BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7450         .addReg(newval).addReg(ShiftReg);
7451     BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7452         .addReg(oldval).addReg(ShiftReg);
7453     if (is8bit)
7454       BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7455     else {
7456       BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7457       BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7458         .addReg(Mask3Reg).addImm(65535);
7459     }
7460     BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7461         .addReg(Mask2Reg).addReg(ShiftReg);
7462     BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7463         .addReg(NewVal2Reg).addReg(MaskReg);
7464     BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7465         .addReg(OldVal2Reg).addReg(MaskReg);
7466
7467     BB = loop1MBB;
7468     BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7469         .addReg(ZeroReg).addReg(PtrReg);
7470     BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7471         .addReg(TmpDestReg).addReg(MaskReg);
7472     BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7473         .addReg(TmpReg).addReg(OldVal3Reg);
7474     BuildMI(BB, dl, TII->get(PPC::BCC))
7475         .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7476     BB->addSuccessor(loop2MBB);
7477     BB->addSuccessor(midMBB);
7478
7479     BB = loop2MBB;
7480     BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7481         .addReg(TmpDestReg).addReg(MaskReg);
7482     BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7483         .addReg(Tmp2Reg).addReg(NewVal3Reg);
7484     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7485         .addReg(ZeroReg).addReg(PtrReg);
7486     BuildMI(BB, dl, TII->get(PPC::BCC))
7487       .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7488     BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7489     BB->addSuccessor(loop1MBB);
7490     BB->addSuccessor(exitMBB);
7491
7492     BB = midMBB;
7493     BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7494       .addReg(ZeroReg).addReg(PtrReg);
7495     BB->addSuccessor(exitMBB);
7496
7497     //  exitMBB:
7498     //   ...
7499     BB = exitMBB;
7500     BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7501       .addReg(ShiftReg);
7502   } else if (MI->getOpcode() == PPC::FADDrtz) {
7503     // This pseudo performs an FADD with rounding mode temporarily forced
7504     // to round-to-zero.  We emit this via custom inserter since the FPSCR
7505     // is not modeled at the SelectionDAG level.
7506     unsigned Dest = MI->getOperand(0).getReg();
7507     unsigned Src1 = MI->getOperand(1).getReg();
7508     unsigned Src2 = MI->getOperand(2).getReg();
7509     DebugLoc dl   = MI->getDebugLoc();
7510
7511     MachineRegisterInfo &RegInfo = F->getRegInfo();
7512     unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7513
7514     // Save FPSCR value.
7515     BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7516
7517     // Set rounding mode to round-to-zero.
7518     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7519     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7520
7521     // Perform addition.
7522     BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7523
7524     // Restore FPSCR value.
7525     BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7526   } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7527              MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7528              MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7529              MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7530     unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7531                        MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7532                       PPC::ANDIo8 : PPC::ANDIo;
7533     bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7534                  MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7535
7536     MachineRegisterInfo &RegInfo = F->getRegInfo();
7537     unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7538                                                   &PPC::GPRCRegClass :
7539                                                   &PPC::G8RCRegClass);
7540
7541     DebugLoc dl   = MI->getDebugLoc();
7542     BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7543       .addReg(MI->getOperand(1).getReg()).addImm(1);
7544     BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7545             MI->getOperand(0).getReg())
7546       .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7547   } else {
7548     llvm_unreachable("Unexpected instr type to insert");
7549   }
7550
7551   MI->eraseFromParent();   // The pseudo instruction is gone now.
7552   return BB;
7553 }
7554
7555 //===----------------------------------------------------------------------===//
7556 // Target Optimization Hooks
7557 //===----------------------------------------------------------------------===//
7558
7559 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7560                                             DAGCombinerInfo &DCI,
7561                                             unsigned &RefinementSteps,
7562                                             bool &UseOneConstNR) const {
7563   EVT VT = Operand.getValueType();
7564   if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7565       (VT == MVT::f64 && Subtarget.hasFRSQRTE())  ||
7566       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7567       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7568     // Convergence is quadratic, so we essentially double the number of digits
7569     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7570     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7571     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7572     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7573     if (VT.getScalarType() == MVT::f64)
7574       ++RefinementSteps;
7575     UseOneConstNR = true;
7576     return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7577   }
7578   return SDValue();
7579 }
7580
7581 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7582                                             DAGCombinerInfo &DCI,
7583                                             unsigned &RefinementSteps) const {
7584   EVT VT = Operand.getValueType();
7585   if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7586       (VT == MVT::f64 && Subtarget.hasFRE())  ||
7587       (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7588       (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7589     // Convergence is quadratic, so we essentially double the number of digits
7590     // correct after every iteration. For both FRE and FRSQRTE, the minimum
7591     // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7592     // 2^-14. IEEE float has 23 digits and double has 52 digits.
7593     RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7594     if (VT.getScalarType() == MVT::f64)
7595       ++RefinementSteps;
7596     return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7597   }
7598   return SDValue();
7599 }
7600
7601 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7602   // Note: This functionality is used only when unsafe-fp-math is enabled, and
7603   // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7604   // enabled for division), this functionality is redundant with the default
7605   // combiner logic (once the division -> reciprocal/multiply transformation
7606   // has taken place). As a result, this matters more for older cores than for
7607   // newer ones.
7608
7609   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7610   // reciprocal if there are two or more FDIVs (for embedded cores with only
7611   // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7612   switch (Subtarget.getDarwinDirective()) {
7613   default:
7614     return NumUsers > 2;
7615   case PPC::DIR_440:
7616   case PPC::DIR_A2:
7617   case PPC::DIR_E500mc:
7618   case PPC::DIR_E5500:
7619     return NumUsers > 1;
7620   }
7621 }
7622
7623 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7624                             unsigned Bytes, int Dist,
7625                             SelectionDAG &DAG) {
7626   if (VT.getSizeInBits() / 8 != Bytes)
7627     return false;
7628
7629   SDValue BaseLoc = Base->getBasePtr();
7630   if (Loc.getOpcode() == ISD::FrameIndex) {
7631     if (BaseLoc.getOpcode() != ISD::FrameIndex)
7632       return false;
7633     const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7634     int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
7635     int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7636     int FS  = MFI->getObjectSize(FI);
7637     int BFS = MFI->getObjectSize(BFI);
7638     if (FS != BFS || FS != (int)Bytes) return false;
7639     return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7640   }
7641
7642   // Handle X+C
7643   if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7644       cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7645     return true;
7646
7647   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7648   const GlobalValue *GV1 = nullptr;
7649   const GlobalValue *GV2 = nullptr;
7650   int64_t Offset1 = 0;
7651   int64_t Offset2 = 0;
7652   bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7653   bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7654   if (isGA1 && isGA2 && GV1 == GV2)
7655     return Offset1 == (Offset2 + Dist*Bytes);
7656   return false;
7657 }
7658
7659 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7660 // not enforce equality of the chain operands.
7661 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7662                             unsigned Bytes, int Dist,
7663                             SelectionDAG &DAG) {
7664   if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7665     EVT VT = LS->getMemoryVT();
7666     SDValue Loc = LS->getBasePtr();
7667     return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7668   }
7669
7670   if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7671     EVT VT;
7672     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7673     default: return false;
7674     case Intrinsic::ppc_altivec_lvx:
7675     case Intrinsic::ppc_altivec_lvxl:
7676     case Intrinsic::ppc_vsx_lxvw4x:
7677       VT = MVT::v4i32;
7678       break;
7679     case Intrinsic::ppc_vsx_lxvd2x:
7680       VT = MVT::v2f64;
7681       break;
7682     case Intrinsic::ppc_altivec_lvebx:
7683       VT = MVT::i8;
7684       break;
7685     case Intrinsic::ppc_altivec_lvehx:
7686       VT = MVT::i16;
7687       break;
7688     case Intrinsic::ppc_altivec_lvewx:
7689       VT = MVT::i32;
7690       break;
7691     }
7692
7693     return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7694   }
7695
7696   if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7697     EVT VT;
7698     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7699     default: return false;
7700     case Intrinsic::ppc_altivec_stvx:
7701     case Intrinsic::ppc_altivec_stvxl:
7702     case Intrinsic::ppc_vsx_stxvw4x:
7703       VT = MVT::v4i32;
7704       break;
7705     case Intrinsic::ppc_vsx_stxvd2x:
7706       VT = MVT::v2f64;
7707       break;
7708     case Intrinsic::ppc_altivec_stvebx:
7709       VT = MVT::i8;
7710       break;
7711     case Intrinsic::ppc_altivec_stvehx:
7712       VT = MVT::i16;
7713       break;
7714     case Intrinsic::ppc_altivec_stvewx:
7715       VT = MVT::i32;
7716       break;
7717     }
7718
7719     return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7720   }
7721
7722   return false;
7723 }
7724
7725 // Return true is there is a nearyby consecutive load to the one provided
7726 // (regardless of alignment). We search up and down the chain, looking though
7727 // token factors and other loads (but nothing else). As a result, a true result
7728 // indicates that it is safe to create a new consecutive load adjacent to the
7729 // load provided.
7730 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7731   SDValue Chain = LD->getChain();
7732   EVT VT = LD->getMemoryVT();
7733
7734   SmallSet<SDNode *, 16> LoadRoots;
7735   SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7736   SmallSet<SDNode *, 16> Visited;
7737
7738   // First, search up the chain, branching to follow all token-factor operands.
7739   // If we find a consecutive load, then we're done, otherwise, record all
7740   // nodes just above the top-level loads and token factors.
7741   while (!Queue.empty()) {
7742     SDNode *ChainNext = Queue.pop_back_val();
7743     if (!Visited.insert(ChainNext).second)
7744       continue;
7745
7746     if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7747       if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7748         return true;
7749
7750       if (!Visited.count(ChainLD->getChain().getNode()))
7751         Queue.push_back(ChainLD->getChain().getNode());
7752     } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7753       for (const SDUse &O : ChainNext->ops())
7754         if (!Visited.count(O.getNode()))
7755           Queue.push_back(O.getNode());
7756     } else
7757       LoadRoots.insert(ChainNext);
7758   }
7759
7760   // Second, search down the chain, starting from the top-level nodes recorded
7761   // in the first phase. These top-level nodes are the nodes just above all
7762   // loads and token factors. Starting with their uses, recursively look though
7763   // all loads (just the chain uses) and token factors to find a consecutive
7764   // load.
7765   Visited.clear();
7766   Queue.clear();
7767
7768   for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7769        IE = LoadRoots.end(); I != IE; ++I) {
7770     Queue.push_back(*I);
7771        
7772     while (!Queue.empty()) {
7773       SDNode *LoadRoot = Queue.pop_back_val();
7774       if (!Visited.insert(LoadRoot).second)
7775         continue;
7776
7777       if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7778         if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7779           return true;
7780
7781       for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7782            UE = LoadRoot->use_end(); UI != UE; ++UI)
7783         if (((isa<MemSDNode>(*UI) &&
7784             cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7785             UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7786           Queue.push_back(*UI);
7787     }
7788   }
7789
7790   return false;
7791 }
7792
7793 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7794                                                   DAGCombinerInfo &DCI) const {
7795   SelectionDAG &DAG = DCI.DAG;
7796   SDLoc dl(N);
7797
7798   assert(Subtarget.useCRBits() &&
7799          "Expecting to be tracking CR bits");
7800   // If we're tracking CR bits, we need to be careful that we don't have:
7801   //   trunc(binary-ops(zext(x), zext(y)))
7802   // or
7803   //   trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7804   // such that we're unnecessarily moving things into GPRs when it would be
7805   // better to keep them in CR bits.
7806
7807   // Note that trunc here can be an actual i1 trunc, or can be the effective
7808   // truncation that comes from a setcc or select_cc.
7809   if (N->getOpcode() == ISD::TRUNCATE &&
7810       N->getValueType(0) != MVT::i1)
7811     return SDValue();
7812
7813   if (N->getOperand(0).getValueType() != MVT::i32 &&
7814       N->getOperand(0).getValueType() != MVT::i64)
7815     return SDValue();
7816
7817   if (N->getOpcode() == ISD::SETCC ||
7818       N->getOpcode() == ISD::SELECT_CC) {
7819     // If we're looking at a comparison, then we need to make sure that the
7820     // high bits (all except for the first) don't matter the result.
7821     ISD::CondCode CC =
7822       cast<CondCodeSDNode>(N->getOperand(
7823         N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
7824     unsigned OpBits = N->getOperand(0).getValueSizeInBits();
7825
7826     if (ISD::isSignedIntSetCC(CC)) {
7827       if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
7828           DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
7829         return SDValue();
7830     } else if (ISD::isUnsignedIntSetCC(CC)) {
7831       if (!DAG.MaskedValueIsZero(N->getOperand(0),
7832                                  APInt::getHighBitsSet(OpBits, OpBits-1)) ||
7833           !DAG.MaskedValueIsZero(N->getOperand(1),
7834                                  APInt::getHighBitsSet(OpBits, OpBits-1)))
7835         return SDValue();
7836     } else {
7837       // This is neither a signed nor an unsigned comparison, just make sure
7838       // that the high bits are equal.
7839       APInt Op1Zero, Op1One;
7840       APInt Op2Zero, Op2One;
7841       DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
7842       DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
7843
7844       // We don't really care about what is known about the first bit (if
7845       // anything), so clear it in all masks prior to comparing them.
7846       Op1Zero.clearBit(0); Op1One.clearBit(0);
7847       Op2Zero.clearBit(0); Op2One.clearBit(0);
7848
7849       if (Op1Zero != Op2Zero || Op1One != Op2One)
7850         return SDValue();
7851     }
7852   }
7853
7854   // We now know that the higher-order bits are irrelevant, we just need to
7855   // make sure that all of the intermediate operations are bit operations, and
7856   // all inputs are extensions.
7857   if (N->getOperand(0).getOpcode() != ISD::AND &&
7858       N->getOperand(0).getOpcode() != ISD::OR  &&
7859       N->getOperand(0).getOpcode() != ISD::XOR &&
7860       N->getOperand(0).getOpcode() != ISD::SELECT &&
7861       N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
7862       N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
7863       N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
7864       N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
7865       N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
7866     return SDValue();
7867
7868   if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
7869       N->getOperand(1).getOpcode() != ISD::AND &&
7870       N->getOperand(1).getOpcode() != ISD::OR  &&
7871       N->getOperand(1).getOpcode() != ISD::XOR &&
7872       N->getOperand(1).getOpcode() != ISD::SELECT &&
7873       N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
7874       N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
7875       N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
7876       N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
7877       N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
7878     return SDValue();
7879
7880   SmallVector<SDValue, 4> Inputs;
7881   SmallVector<SDValue, 8> BinOps, PromOps;
7882   SmallPtrSet<SDNode *, 16> Visited;
7883
7884   for (unsigned i = 0; i < 2; ++i) {
7885     if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7886           N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7887           N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7888           N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7889         isa<ConstantSDNode>(N->getOperand(i)))
7890       Inputs.push_back(N->getOperand(i));
7891     else
7892       BinOps.push_back(N->getOperand(i));
7893
7894     if (N->getOpcode() == ISD::TRUNCATE)
7895       break;
7896   }
7897
7898   // Visit all inputs, collect all binary operations (and, or, xor and
7899   // select) that are all fed by extensions. 
7900   while (!BinOps.empty()) {
7901     SDValue BinOp = BinOps.back();
7902     BinOps.pop_back();
7903
7904     if (!Visited.insert(BinOp.getNode()).second)
7905       continue;
7906
7907     PromOps.push_back(BinOp);
7908
7909     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
7910       // The condition of the select is not promoted.
7911       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
7912         continue;
7913       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
7914         continue;
7915
7916       if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7917             BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7918             BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
7919            BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
7920           isa<ConstantSDNode>(BinOp.getOperand(i))) {
7921         Inputs.push_back(BinOp.getOperand(i)); 
7922       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
7923                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
7924                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
7925                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
7926                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
7927                  BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
7928                  BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
7929                  BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
7930                  BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
7931         BinOps.push_back(BinOp.getOperand(i));
7932       } else {
7933         // We have an input that is not an extension or another binary
7934         // operation; we'll abort this transformation.
7935         return SDValue();
7936       }
7937     }
7938   }
7939
7940   // Make sure that this is a self-contained cluster of operations (which
7941   // is not quite the same thing as saying that everything has only one
7942   // use).
7943   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7944     if (isa<ConstantSDNode>(Inputs[i]))
7945       continue;
7946
7947     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
7948                               UE = Inputs[i].getNode()->use_end();
7949          UI != UE; ++UI) {
7950       SDNode *User = *UI;
7951       if (User != N && !Visited.count(User))
7952         return SDValue();
7953
7954       // Make sure that we're not going to promote the non-output-value
7955       // operand(s) or SELECT or SELECT_CC.
7956       // FIXME: Although we could sometimes handle this, and it does occur in
7957       // practice that one of the condition inputs to the select is also one of
7958       // the outputs, we currently can't deal with this.
7959       if (User->getOpcode() == ISD::SELECT) {
7960         if (User->getOperand(0) == Inputs[i])
7961           return SDValue();
7962       } else if (User->getOpcode() == ISD::SELECT_CC) {
7963         if (User->getOperand(0) == Inputs[i] ||
7964             User->getOperand(1) == Inputs[i])
7965           return SDValue();
7966       }
7967     }
7968   }
7969
7970   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
7971     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
7972                               UE = PromOps[i].getNode()->use_end();
7973          UI != UE; ++UI) {
7974       SDNode *User = *UI;
7975       if (User != N && !Visited.count(User))
7976         return SDValue();
7977
7978       // Make sure that we're not going to promote the non-output-value
7979       // operand(s) or SELECT or SELECT_CC.
7980       // FIXME: Although we could sometimes handle this, and it does occur in
7981       // practice that one of the condition inputs to the select is also one of
7982       // the outputs, we currently can't deal with this.
7983       if (User->getOpcode() == ISD::SELECT) {
7984         if (User->getOperand(0) == PromOps[i])
7985           return SDValue();
7986       } else if (User->getOpcode() == ISD::SELECT_CC) {
7987         if (User->getOperand(0) == PromOps[i] ||
7988             User->getOperand(1) == PromOps[i])
7989           return SDValue();
7990       }
7991     }
7992   }
7993
7994   // Replace all inputs with the extension operand.
7995   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
7996     // Constants may have users outside the cluster of to-be-promoted nodes,
7997     // and so we need to replace those as we do the promotions.
7998     if (isa<ConstantSDNode>(Inputs[i]))
7999       continue;
8000     else
8001       DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0)); 
8002   }
8003
8004   // Replace all operations (these are all the same, but have a different
8005   // (i1) return type). DAG.getNode will validate that the types of
8006   // a binary operator match, so go through the list in reverse so that
8007   // we've likely promoted both operands first. Any intermediate truncations or
8008   // extensions disappear.
8009   while (!PromOps.empty()) {
8010     SDValue PromOp = PromOps.back();
8011     PromOps.pop_back();
8012
8013     if (PromOp.getOpcode() == ISD::TRUNCATE ||
8014         PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8015         PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8016         PromOp.getOpcode() == ISD::ANY_EXTEND) {
8017       if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8018           PromOp.getOperand(0).getValueType() != MVT::i1) {
8019         // The operand is not yet ready (see comment below).
8020         PromOps.insert(PromOps.begin(), PromOp);
8021         continue;
8022       }
8023
8024       SDValue RepValue = PromOp.getOperand(0);
8025       if (isa<ConstantSDNode>(RepValue))
8026         RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8027
8028       DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8029       continue;
8030     }
8031
8032     unsigned C;
8033     switch (PromOp.getOpcode()) {
8034     default:             C = 0; break;
8035     case ISD::SELECT:    C = 1; break;
8036     case ISD::SELECT_CC: C = 2; break;
8037     }
8038
8039     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8040          PromOp.getOperand(C).getValueType() != MVT::i1) ||
8041         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8042          PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8043       // The to-be-promoted operands of this node have not yet been
8044       // promoted (this should be rare because we're going through the
8045       // list backward, but if one of the operands has several users in
8046       // this cluster of to-be-promoted nodes, it is possible).
8047       PromOps.insert(PromOps.begin(), PromOp);
8048       continue;
8049     }
8050
8051     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8052                                 PromOp.getNode()->op_end());
8053
8054     // If there are any constant inputs, make sure they're replaced now.
8055     for (unsigned i = 0; i < 2; ++i)
8056       if (isa<ConstantSDNode>(Ops[C+i]))
8057         Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8058
8059     DAG.ReplaceAllUsesOfValueWith(PromOp,
8060       DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8061   }
8062
8063   // Now we're left with the initial truncation itself.
8064   if (N->getOpcode() == ISD::TRUNCATE)
8065     return N->getOperand(0);
8066
8067   // Otherwise, this is a comparison. The operands to be compared have just
8068   // changed type (to i1), but everything else is the same.
8069   return SDValue(N, 0);
8070 }
8071
8072 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8073                                                   DAGCombinerInfo &DCI) const {
8074   SelectionDAG &DAG = DCI.DAG;
8075   SDLoc dl(N);
8076
8077   // If we're tracking CR bits, we need to be careful that we don't have:
8078   //   zext(binary-ops(trunc(x), trunc(y)))
8079   // or
8080   //   zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8081   // such that we're unnecessarily moving things into CR bits that can more
8082   // efficiently stay in GPRs. Note that if we're not certain that the high
8083   // bits are set as required by the final extension, we still may need to do
8084   // some masking to get the proper behavior.
8085
8086   // This same functionality is important on PPC64 when dealing with
8087   // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8088   // the return values of functions. Because it is so similar, it is handled
8089   // here as well.
8090
8091   if (N->getValueType(0) != MVT::i32 &&
8092       N->getValueType(0) != MVT::i64)
8093     return SDValue();
8094
8095   if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8096         Subtarget.useCRBits()) ||
8097        (N->getOperand(0).getValueType() == MVT::i32 &&
8098         Subtarget.isPPC64())))
8099     return SDValue();
8100
8101   if (N->getOperand(0).getOpcode() != ISD::AND &&
8102       N->getOperand(0).getOpcode() != ISD::OR  &&
8103       N->getOperand(0).getOpcode() != ISD::XOR &&
8104       N->getOperand(0).getOpcode() != ISD::SELECT &&
8105       N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8106     return SDValue();
8107
8108   SmallVector<SDValue, 4> Inputs;
8109   SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8110   SmallPtrSet<SDNode *, 16> Visited;
8111
8112   // Visit all inputs, collect all binary operations (and, or, xor and
8113   // select) that are all fed by truncations. 
8114   while (!BinOps.empty()) {
8115     SDValue BinOp = BinOps.back();
8116     BinOps.pop_back();
8117
8118     if (!Visited.insert(BinOp.getNode()).second)
8119       continue;
8120
8121     PromOps.push_back(BinOp);
8122
8123     for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8124       // The condition of the select is not promoted.
8125       if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8126         continue;
8127       if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8128         continue;
8129
8130       if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8131           isa<ConstantSDNode>(BinOp.getOperand(i))) {
8132         Inputs.push_back(BinOp.getOperand(i)); 
8133       } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8134                  BinOp.getOperand(i).getOpcode() == ISD::OR  ||
8135                  BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8136                  BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8137                  BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8138         BinOps.push_back(BinOp.getOperand(i));
8139       } else {
8140         // We have an input that is not a truncation or another binary
8141         // operation; we'll abort this transformation.
8142         return SDValue();
8143       }
8144     }
8145   }
8146
8147   // The operands of a select that must be truncated when the select is
8148   // promoted because the operand is actually part of the to-be-promoted set.
8149   DenseMap<SDNode *, EVT> SelectTruncOp[2];
8150
8151   // Make sure that this is a self-contained cluster of operations (which
8152   // is not quite the same thing as saying that everything has only one
8153   // use).
8154   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8155     if (isa<ConstantSDNode>(Inputs[i]))
8156       continue;
8157
8158     for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8159                               UE = Inputs[i].getNode()->use_end();
8160          UI != UE; ++UI) {
8161       SDNode *User = *UI;
8162       if (User != N && !Visited.count(User))
8163         return SDValue();
8164
8165       // If we're going to promote the non-output-value operand(s) or SELECT or
8166       // SELECT_CC, record them for truncation.
8167       if (User->getOpcode() == ISD::SELECT) {
8168         if (User->getOperand(0) == Inputs[i])
8169           SelectTruncOp[0].insert(std::make_pair(User,
8170                                     User->getOperand(0).getValueType()));
8171       } else if (User->getOpcode() == ISD::SELECT_CC) {
8172         if (User->getOperand(0) == Inputs[i])
8173           SelectTruncOp[0].insert(std::make_pair(User,
8174                                     User->getOperand(0).getValueType()));
8175         if (User->getOperand(1) == Inputs[i])
8176           SelectTruncOp[1].insert(std::make_pair(User,
8177                                     User->getOperand(1).getValueType()));
8178       }
8179     }
8180   }
8181
8182   for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8183     for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8184                               UE = PromOps[i].getNode()->use_end();
8185          UI != UE; ++UI) {
8186       SDNode *User = *UI;
8187       if (User != N && !Visited.count(User))
8188         return SDValue();
8189
8190       // If we're going to promote the non-output-value operand(s) or SELECT or
8191       // SELECT_CC, record them for truncation.
8192       if (User->getOpcode() == ISD::SELECT) {
8193         if (User->getOperand(0) == PromOps[i])
8194           SelectTruncOp[0].insert(std::make_pair(User,
8195                                     User->getOperand(0).getValueType()));
8196       } else if (User->getOpcode() == ISD::SELECT_CC) {
8197         if (User->getOperand(0) == PromOps[i])
8198           SelectTruncOp[0].insert(std::make_pair(User,
8199                                     User->getOperand(0).getValueType()));
8200         if (User->getOperand(1) == PromOps[i])
8201           SelectTruncOp[1].insert(std::make_pair(User,
8202                                     User->getOperand(1).getValueType()));
8203       }
8204     }
8205   }
8206
8207   unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8208   bool ReallyNeedsExt = false;
8209   if (N->getOpcode() != ISD::ANY_EXTEND) {
8210     // If all of the inputs are not already sign/zero extended, then
8211     // we'll still need to do that at the end.
8212     for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8213       if (isa<ConstantSDNode>(Inputs[i]))
8214         continue;
8215
8216       unsigned OpBits =
8217         Inputs[i].getOperand(0).getValueSizeInBits();
8218       assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8219
8220       if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8221            !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8222                                   APInt::getHighBitsSet(OpBits,
8223                                                         OpBits-PromBits))) ||
8224           (N->getOpcode() == ISD::SIGN_EXTEND &&
8225            DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8226              (OpBits-(PromBits-1)))) {
8227         ReallyNeedsExt = true;
8228         break;
8229       }
8230     }
8231   }
8232
8233   // Replace all inputs, either with the truncation operand, or a
8234   // truncation or extension to the final output type.
8235   for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8236     // Constant inputs need to be replaced with the to-be-promoted nodes that
8237     // use them because they might have users outside of the cluster of
8238     // promoted nodes.
8239     if (isa<ConstantSDNode>(Inputs[i]))
8240       continue;
8241
8242     SDValue InSrc = Inputs[i].getOperand(0);
8243     if (Inputs[i].getValueType() == N->getValueType(0))
8244       DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8245     else if (N->getOpcode() == ISD::SIGN_EXTEND)
8246       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8247         DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8248     else if (N->getOpcode() == ISD::ZERO_EXTEND)
8249       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8250         DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8251     else
8252       DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8253         DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8254   }
8255
8256   // Replace all operations (these are all the same, but have a different
8257   // (promoted) return type). DAG.getNode will validate that the types of
8258   // a binary operator match, so go through the list in reverse so that
8259   // we've likely promoted both operands first.
8260   while (!PromOps.empty()) {
8261     SDValue PromOp = PromOps.back();
8262     PromOps.pop_back();
8263
8264     unsigned C;
8265     switch (PromOp.getOpcode()) {
8266     default:             C = 0; break;
8267     case ISD::SELECT:    C = 1; break;
8268     case ISD::SELECT_CC: C = 2; break;
8269     }
8270
8271     if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8272          PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8273         (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8274          PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8275       // The to-be-promoted operands of this node have not yet been
8276       // promoted (this should be rare because we're going through the
8277       // list backward, but if one of the operands has several users in
8278       // this cluster of to-be-promoted nodes, it is possible).
8279       PromOps.insert(PromOps.begin(), PromOp);
8280       continue;
8281     }
8282
8283     // For SELECT and SELECT_CC nodes, we do a similar check for any
8284     // to-be-promoted comparison inputs.
8285     if (PromOp.getOpcode() == ISD::SELECT ||
8286         PromOp.getOpcode() == ISD::SELECT_CC) {
8287       if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8288            PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8289           (SelectTruncOp[1].count(PromOp.getNode()) &&
8290            PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8291         PromOps.insert(PromOps.begin(), PromOp);
8292         continue;
8293       }
8294     }
8295
8296     SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8297                                 PromOp.getNode()->op_end());
8298
8299     // If this node has constant inputs, then they'll need to be promoted here.
8300     for (unsigned i = 0; i < 2; ++i) {
8301       if (!isa<ConstantSDNode>(Ops[C+i]))
8302         continue;
8303       if (Ops[C+i].getValueType() == N->getValueType(0))
8304         continue;
8305
8306       if (N->getOpcode() == ISD::SIGN_EXTEND)
8307         Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8308       else if (N->getOpcode() == ISD::ZERO_EXTEND)
8309         Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8310       else
8311         Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8312     }
8313
8314     // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8315     // truncate them again to the original value type.
8316     if (PromOp.getOpcode() == ISD::SELECT ||
8317         PromOp.getOpcode() == ISD::SELECT_CC) {
8318       auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8319       if (SI0 != SelectTruncOp[0].end())
8320         Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8321       auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8322       if (SI1 != SelectTruncOp[1].end())
8323         Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8324     }
8325
8326     DAG.ReplaceAllUsesOfValueWith(PromOp,
8327       DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8328   }
8329
8330   // Now we're left with the initial extension itself.
8331   if (!ReallyNeedsExt)
8332     return N->getOperand(0);
8333
8334   // To zero extend, just mask off everything except for the first bit (in the
8335   // i1 case).
8336   if (N->getOpcode() == ISD::ZERO_EXTEND)
8337     return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8338                        DAG.getConstant(APInt::getLowBitsSet(
8339                                          N->getValueSizeInBits(0), PromBits),
8340                                        N->getValueType(0)));
8341
8342   assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8343          "Invalid extension type");
8344   EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8345   SDValue ShiftCst =
8346     DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8347   return DAG.getNode(ISD::SRA, dl, N->getValueType(0), 
8348                      DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8349                                  N->getOperand(0), ShiftCst), ShiftCst);
8350 }
8351
8352 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8353 // builtins) into loads with swaps.
8354 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8355                                               DAGCombinerInfo &DCI) const {
8356   SelectionDAG &DAG = DCI.DAG;
8357   SDLoc dl(N);
8358   SDValue Chain;
8359   SDValue Base;
8360   MachineMemOperand *MMO;
8361
8362   switch (N->getOpcode()) {
8363   default:
8364     llvm_unreachable("Unexpected opcode for little endian VSX load");
8365   case ISD::LOAD: {
8366     LoadSDNode *LD = cast<LoadSDNode>(N);
8367     Chain = LD->getChain();
8368     Base = LD->getBasePtr();
8369     MMO = LD->getMemOperand();
8370     // If the MMO suggests this isn't a load of a full vector, leave
8371     // things alone.  For a built-in, we have to make the change for
8372     // correctness, so if there is a size problem that will be a bug.
8373     if (MMO->getSize() < 16)
8374       return SDValue();
8375     break;
8376   }
8377   case ISD::INTRINSIC_W_CHAIN: {
8378     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8379     Chain = Intrin->getChain();
8380     Base = Intrin->getBasePtr();
8381     MMO = Intrin->getMemOperand();
8382     break;
8383   }
8384   }
8385
8386   MVT VecTy = N->getValueType(0).getSimpleVT();
8387   SDValue LoadOps[] = { Chain, Base };
8388   SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8389                                          DAG.getVTList(VecTy, MVT::Other),
8390                                          LoadOps, VecTy, MMO);
8391   DCI.AddToWorklist(Load.getNode());
8392   Chain = Load.getValue(1);
8393   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8394                              DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8395   DCI.AddToWorklist(Swap.getNode());
8396   return Swap;
8397 }
8398
8399 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8400 // builtins) into stores with swaps.
8401 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8402                                                DAGCombinerInfo &DCI) const {
8403   SelectionDAG &DAG = DCI.DAG;
8404   SDLoc dl(N);
8405   SDValue Chain;
8406   SDValue Base;
8407   unsigned SrcOpnd;
8408   MachineMemOperand *MMO;
8409
8410   switch (N->getOpcode()) {
8411   default:
8412     llvm_unreachable("Unexpected opcode for little endian VSX store");
8413   case ISD::STORE: {
8414     StoreSDNode *ST = cast<StoreSDNode>(N);
8415     Chain = ST->getChain();
8416     Base = ST->getBasePtr();
8417     MMO = ST->getMemOperand();
8418     SrcOpnd = 1;
8419     // If the MMO suggests this isn't a store of a full vector, leave
8420     // things alone.  For a built-in, we have to make the change for
8421     // correctness, so if there is a size problem that will be a bug.
8422     if (MMO->getSize() < 16)
8423       return SDValue();
8424     break;
8425   }
8426   case ISD::INTRINSIC_VOID: {
8427     MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8428     Chain = Intrin->getChain();
8429     // Intrin->getBasePtr() oddly does not get what we want.
8430     Base = Intrin->getOperand(3);
8431     MMO = Intrin->getMemOperand();
8432     SrcOpnd = 2;
8433     break;
8434   }
8435   }
8436
8437   SDValue Src = N->getOperand(SrcOpnd);
8438   MVT VecTy = Src.getValueType().getSimpleVT();
8439   SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8440                              DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8441   DCI.AddToWorklist(Swap.getNode());
8442   Chain = Swap.getValue(1);
8443   SDValue StoreOps[] = { Chain, Swap, Base };
8444   SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8445                                           DAG.getVTList(MVT::Other),
8446                                           StoreOps, VecTy, MMO);
8447   DCI.AddToWorklist(Store.getNode());
8448   return Store;
8449 }
8450
8451 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8452                                              DAGCombinerInfo &DCI) const {
8453   const TargetMachine &TM = getTargetMachine();
8454   SelectionDAG &DAG = DCI.DAG;
8455   SDLoc dl(N);
8456   switch (N->getOpcode()) {
8457   default: break;
8458   case PPCISD::SHL:
8459     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8460       if (C->isNullValue())   // 0 << V -> 0.
8461         return N->getOperand(0);
8462     }
8463     break;
8464   case PPCISD::SRL:
8465     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8466       if (C->isNullValue())   // 0 >>u V -> 0.
8467         return N->getOperand(0);
8468     }
8469     break;
8470   case PPCISD::SRA:
8471     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8472       if (C->isNullValue() ||   //  0 >>s V -> 0.
8473           C->isAllOnesValue())    // -1 >>s V -> -1.
8474         return N->getOperand(0);
8475     }
8476     break;
8477   case ISD::SIGN_EXTEND:
8478   case ISD::ZERO_EXTEND:
8479   case ISD::ANY_EXTEND: 
8480     return DAGCombineExtBoolTrunc(N, DCI);
8481   case ISD::TRUNCATE:
8482   case ISD::SETCC:
8483   case ISD::SELECT_CC:
8484     return DAGCombineTruncBoolExt(N, DCI);
8485   case ISD::SINT_TO_FP:
8486     if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
8487       if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
8488         // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
8489         // We allow the src/dst to be either f32/f64, but the intermediate
8490         // type must be i64.
8491         if (N->getOperand(0).getValueType() == MVT::i64 &&
8492             N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
8493           SDValue Val = N->getOperand(0).getOperand(0);
8494           if (Val.getValueType() == MVT::f32) {
8495             Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8496             DCI.AddToWorklist(Val.getNode());
8497           }
8498
8499           Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
8500           DCI.AddToWorklist(Val.getNode());
8501           Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
8502           DCI.AddToWorklist(Val.getNode());
8503           if (N->getValueType(0) == MVT::f32) {
8504             Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
8505                               DAG.getIntPtrConstant(0));
8506             DCI.AddToWorklist(Val.getNode());
8507           }
8508           return Val;
8509         } else if (N->getOperand(0).getValueType() == MVT::i32) {
8510           // If the intermediate type is i32, we can avoid the load/store here
8511           // too.
8512         }
8513       }
8514     }
8515     break;
8516   case ISD::STORE: {
8517     // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8518     if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8519         !cast<StoreSDNode>(N)->isTruncatingStore() &&
8520         N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8521         N->getOperand(1).getValueType() == MVT::i32 &&
8522         N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8523       SDValue Val = N->getOperand(1).getOperand(0);
8524       if (Val.getValueType() == MVT::f32) {
8525         Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8526         DCI.AddToWorklist(Val.getNode());
8527       }
8528       Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8529       DCI.AddToWorklist(Val.getNode());
8530
8531       SDValue Ops[] = {
8532         N->getOperand(0), Val, N->getOperand(2),
8533         DAG.getValueType(N->getOperand(1).getValueType())
8534       };
8535
8536       Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8537               DAG.getVTList(MVT::Other), Ops,
8538               cast<StoreSDNode>(N)->getMemoryVT(),
8539               cast<StoreSDNode>(N)->getMemOperand());
8540       DCI.AddToWorklist(Val.getNode());
8541       return Val;
8542     }
8543
8544     // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8545     if (cast<StoreSDNode>(N)->isUnindexed() &&
8546         N->getOperand(1).getOpcode() == ISD::BSWAP &&
8547         N->getOperand(1).getNode()->hasOneUse() &&
8548         (N->getOperand(1).getValueType() == MVT::i32 ||
8549          N->getOperand(1).getValueType() == MVT::i16 ||
8550          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8551           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8552           N->getOperand(1).getValueType() == MVT::i64))) {
8553       SDValue BSwapOp = N->getOperand(1).getOperand(0);
8554       // Do an any-extend to 32-bits if this is a half-word input.
8555       if (BSwapOp.getValueType() == MVT::i16)
8556         BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8557
8558       SDValue Ops[] = {
8559         N->getOperand(0), BSwapOp, N->getOperand(2),
8560         DAG.getValueType(N->getOperand(1).getValueType())
8561       };
8562       return
8563         DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8564                                 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8565                                 cast<StoreSDNode>(N)->getMemOperand());
8566     }
8567
8568     // For little endian, VSX stores require generating xxswapd/lxvd2x.
8569     EVT VT = N->getOperand(1).getValueType();
8570     if (VT.isSimple()) {
8571       MVT StoreVT = VT.getSimpleVT();
8572       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8573           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8574           (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8575            StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8576         return expandVSXStoreForLE(N, DCI);
8577     }
8578     break;
8579   }
8580   case ISD::LOAD: {
8581     LoadSDNode *LD = cast<LoadSDNode>(N);
8582     EVT VT = LD->getValueType(0);
8583
8584     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8585     if (VT.isSimple()) {
8586       MVT LoadVT = VT.getSimpleVT();
8587       if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8588           TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8589           (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8590            LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8591         return expandVSXLoadForLE(N, DCI);
8592     }
8593
8594     Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8595     unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8596     if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8597         TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8598         // P8 and later hardware should just use LOAD.
8599         !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8600         (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8601          VT == MVT::v4i32 || VT == MVT::v4f32) &&
8602         LD->getAlignment() < ABIAlignment) {
8603       // This is a type-legal unaligned Altivec load.
8604       SDValue Chain = LD->getChain();
8605       SDValue Ptr = LD->getBasePtr();
8606       bool isLittleEndian = Subtarget.isLittleEndian();
8607
8608       // This implements the loading of unaligned vectors as described in
8609       // the venerable Apple Velocity Engine overview. Specifically:
8610       // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8611       // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8612       //
8613       // The general idea is to expand a sequence of one or more unaligned
8614       // loads into an alignment-based permutation-control instruction (lvsl
8615       // or lvsr), a series of regular vector loads (which always truncate
8616       // their input address to an aligned address), and a series of
8617       // permutations.  The results of these permutations are the requested
8618       // loaded values.  The trick is that the last "extra" load is not taken
8619       // from the address you might suspect (sizeof(vector) bytes after the
8620       // last requested load), but rather sizeof(vector) - 1 bytes after the
8621       // last requested vector. The point of this is to avoid a page fault if
8622       // the base address happened to be aligned. This works because if the
8623       // base address is aligned, then adding less than a full vector length
8624       // will cause the last vector in the sequence to be (re)loaded.
8625       // Otherwise, the next vector will be fetched as you might suspect was
8626       // necessary.
8627
8628       // We might be able to reuse the permutation generation from
8629       // a different base address offset from this one by an aligned amount.
8630       // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8631       // optimization later.
8632       Intrinsic::ID Intr = (isLittleEndian ?
8633                             Intrinsic::ppc_altivec_lvsr :
8634                             Intrinsic::ppc_altivec_lvsl);
8635       SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8636
8637       // Create the new MMO for the new base load. It is like the original MMO,
8638       // but represents an area in memory almost twice the vector size centered
8639       // on the original address. If the address is unaligned, we might start
8640       // reading up to (sizeof(vector)-1) bytes below the address of the
8641       // original unaligned load.
8642       MachineFunction &MF = DAG.getMachineFunction();
8643       MachineMemOperand *BaseMMO =
8644         MF.getMachineMemOperand(LD->getMemOperand(),
8645                                 -LD->getMemoryVT().getStoreSize()+1,
8646                                 2*LD->getMemoryVT().getStoreSize()-1);
8647
8648       // Create the new base load.
8649       SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8650                                                getPointerTy());
8651       SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8652       SDValue BaseLoad =
8653         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8654                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8655                                 BaseLoadOps, MVT::v4i32, BaseMMO);
8656
8657       // Note that the value of IncOffset (which is provided to the next
8658       // load's pointer info offset value, and thus used to calculate the
8659       // alignment), and the value of IncValue (which is actually used to
8660       // increment the pointer value) are different! This is because we
8661       // require the next load to appear to be aligned, even though it
8662       // is actually offset from the base pointer by a lesser amount.
8663       int IncOffset = VT.getSizeInBits() / 8;
8664       int IncValue = IncOffset;
8665
8666       // Walk (both up and down) the chain looking for another load at the real
8667       // (aligned) offset (the alignment of the other load does not matter in
8668       // this case). If found, then do not use the offset reduction trick, as
8669       // that will prevent the loads from being later combined (as they would
8670       // otherwise be duplicates).
8671       if (!findConsecutiveLoad(LD, DAG))
8672         --IncValue;
8673
8674       SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8675       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8676
8677       MachineMemOperand *ExtraMMO =
8678         MF.getMachineMemOperand(LD->getMemOperand(),
8679                                 1, 2*LD->getMemoryVT().getStoreSize()-1);
8680       SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8681       SDValue ExtraLoad =
8682         DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8683                                 DAG.getVTList(MVT::v4i32, MVT::Other),
8684                                 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8685
8686       SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8687         BaseLoad.getValue(1), ExtraLoad.getValue(1));
8688
8689       // Because vperm has a big-endian bias, we must reverse the order
8690       // of the input vectors and complement the permute control vector
8691       // when generating little endian code.  We have already handled the
8692       // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8693       // and ExtraLoad here.
8694       SDValue Perm;
8695       if (isLittleEndian)
8696         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8697                                 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8698       else
8699         Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8700                                 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8701
8702       if (VT != MVT::v4i32)
8703         Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8704
8705       // The output of the permutation is our loaded result, the TokenFactor is
8706       // our new chain.
8707       DCI.CombineTo(N, Perm, TF);
8708       return SDValue(N, 0);
8709     }
8710     }
8711     break;
8712   case ISD::INTRINSIC_WO_CHAIN: {
8713     bool isLittleEndian = Subtarget.isLittleEndian();
8714     Intrinsic::ID Intr = (isLittleEndian ?
8715                           Intrinsic::ppc_altivec_lvsr :
8716                           Intrinsic::ppc_altivec_lvsl);
8717     if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8718         N->getOperand(1)->getOpcode() == ISD::ADD) {
8719       SDValue Add = N->getOperand(1);
8720
8721       if (DAG.MaskedValueIsZero(Add->getOperand(1),
8722             APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8723               Add.getValueType().getScalarType().getSizeInBits()))) {
8724         SDNode *BasePtr = Add->getOperand(0).getNode();
8725         for (SDNode::use_iterator UI = BasePtr->use_begin(),
8726              UE = BasePtr->use_end(); UI != UE; ++UI) {
8727           if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8728               cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8729                 Intr) {
8730             // We've found another LVSL/LVSR, and this address is an aligned
8731             // multiple of that one. The results will be the same, so use the
8732             // one we've just found instead.
8733
8734             return SDValue(*UI, 0);
8735           }
8736         }
8737       }
8738     }
8739     }
8740
8741     break;
8742   case ISD::INTRINSIC_W_CHAIN: {
8743     // For little endian, VSX loads require generating lxvd2x/xxswapd.
8744     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8745         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8746       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8747       default:
8748         break;
8749       case Intrinsic::ppc_vsx_lxvw4x:
8750       case Intrinsic::ppc_vsx_lxvd2x:
8751         return expandVSXLoadForLE(N, DCI);
8752       }
8753     }
8754     break;
8755   }
8756   case ISD::INTRINSIC_VOID: {
8757     // For little endian, VSX stores require generating xxswapd/stxvd2x.
8758     if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8759         TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8760       switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8761       default:
8762         break;
8763       case Intrinsic::ppc_vsx_stxvw4x:
8764       case Intrinsic::ppc_vsx_stxvd2x:
8765         return expandVSXStoreForLE(N, DCI);
8766       }
8767     }
8768     break;
8769   }
8770   case ISD::BSWAP:
8771     // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
8772     if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
8773         N->getOperand(0).hasOneUse() &&
8774         (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
8775          (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8776           TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8777           N->getValueType(0) == MVT::i64))) {
8778       SDValue Load = N->getOperand(0);
8779       LoadSDNode *LD = cast<LoadSDNode>(Load);
8780       // Create the byte-swapping load.
8781       SDValue Ops[] = {
8782         LD->getChain(),    // Chain
8783         LD->getBasePtr(),  // Ptr
8784         DAG.getValueType(N->getValueType(0)) // VT
8785       };
8786       SDValue BSLoad =
8787         DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
8788                                 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
8789                                               MVT::i64 : MVT::i32, MVT::Other),
8790                                 Ops, LD->getMemoryVT(), LD->getMemOperand());
8791
8792       // If this is an i16 load, insert the truncate.
8793       SDValue ResVal = BSLoad;
8794       if (N->getValueType(0) == MVT::i16)
8795         ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
8796
8797       // First, combine the bswap away.  This makes the value produced by the
8798       // load dead.
8799       DCI.CombineTo(N, ResVal);
8800
8801       // Next, combine the load away, we give it a bogus result value but a real
8802       // chain result.  The result value is dead because the bswap is dead.
8803       DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
8804
8805       // Return N so it doesn't get rechecked!
8806       return SDValue(N, 0);
8807     }
8808
8809     break;
8810   case PPCISD::VCMP: {
8811     // If a VCMPo node already exists with exactly the same operands as this
8812     // node, use its result instead of this node (VCMPo computes both a CR6 and
8813     // a normal output).
8814     //
8815     if (!N->getOperand(0).hasOneUse() &&
8816         !N->getOperand(1).hasOneUse() &&
8817         !N->getOperand(2).hasOneUse()) {
8818
8819       // Scan all of the users of the LHS, looking for VCMPo's that match.
8820       SDNode *VCMPoNode = nullptr;
8821
8822       SDNode *LHSN = N->getOperand(0).getNode();
8823       for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
8824            UI != E; ++UI)
8825         if (UI->getOpcode() == PPCISD::VCMPo &&
8826             UI->getOperand(1) == N->getOperand(1) &&
8827             UI->getOperand(2) == N->getOperand(2) &&
8828             UI->getOperand(0) == N->getOperand(0)) {
8829           VCMPoNode = *UI;
8830           break;
8831         }
8832
8833       // If there is no VCMPo node, or if the flag value has a single use, don't
8834       // transform this.
8835       if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
8836         break;
8837
8838       // Look at the (necessarily single) use of the flag value.  If it has a
8839       // chain, this transformation is more complex.  Note that multiple things
8840       // could use the value result, which we should ignore.
8841       SDNode *FlagUser = nullptr;
8842       for (SDNode::use_iterator UI = VCMPoNode->use_begin();
8843            FlagUser == nullptr; ++UI) {
8844         assert(UI != VCMPoNode->use_end() && "Didn't find user!");
8845         SDNode *User = *UI;
8846         for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
8847           if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
8848             FlagUser = User;
8849             break;
8850           }
8851         }
8852       }
8853
8854       // If the user is a MFOCRF instruction, we know this is safe.
8855       // Otherwise we give up for right now.
8856       if (FlagUser->getOpcode() == PPCISD::MFOCRF)
8857         return SDValue(VCMPoNode, 0);
8858     }
8859     break;
8860   }
8861   case ISD::BRCOND: {
8862     SDValue Cond = N->getOperand(1);
8863     SDValue Target = N->getOperand(2);
8864  
8865     if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8866         cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
8867           Intrinsic::ppc_is_decremented_ctr_nonzero) {
8868
8869       // We now need to make the intrinsic dead (it cannot be instruction
8870       // selected).
8871       DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
8872       assert(Cond.getNode()->hasOneUse() &&
8873              "Counter decrement has more than one use");
8874
8875       return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
8876                          N->getOperand(0), Target);
8877     }
8878   }
8879   break;
8880   case ISD::BR_CC: {
8881     // If this is a branch on an altivec predicate comparison, lower this so
8882     // that we don't have to do a MFOCRF: instead, branch directly on CR6.  This
8883     // lowering is done pre-legalize, because the legalizer lowers the predicate
8884     // compare down to code that is difficult to reassemble.
8885     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
8886     SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
8887
8888     // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
8889     // value. If so, pass-through the AND to get to the intrinsic.
8890     if (LHS.getOpcode() == ISD::AND &&
8891         LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8892         cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
8893           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8894         isa<ConstantSDNode>(LHS.getOperand(1)) &&
8895         !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
8896           isZero())
8897       LHS = LHS.getOperand(0);
8898
8899     if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
8900         cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
8901           Intrinsic::ppc_is_decremented_ctr_nonzero &&
8902         isa<ConstantSDNode>(RHS)) {
8903       assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
8904              "Counter decrement comparison is not EQ or NE");
8905
8906       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8907       bool isBDNZ = (CC == ISD::SETEQ && Val) ||
8908                     (CC == ISD::SETNE && !Val);
8909
8910       // We now need to make the intrinsic dead (it cannot be instruction
8911       // selected).
8912       DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
8913       assert(LHS.getNode()->hasOneUse() &&
8914              "Counter decrement has more than one use");
8915
8916       return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
8917                          N->getOperand(0), N->getOperand(4));
8918     }
8919
8920     int CompareOpc;
8921     bool isDot;
8922
8923     if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8924         isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
8925         getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
8926       assert(isDot && "Can't compare against a vector result!");
8927
8928       // If this is a comparison against something other than 0/1, then we know
8929       // that the condition is never/always true.
8930       unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
8931       if (Val != 0 && Val != 1) {
8932         if (CC == ISD::SETEQ)      // Cond never true, remove branch.
8933           return N->getOperand(0);
8934         // Always !=, turn it into an unconditional branch.
8935         return DAG.getNode(ISD::BR, dl, MVT::Other,
8936                            N->getOperand(0), N->getOperand(4));
8937       }
8938
8939       bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
8940
8941       // Create the PPCISD altivec 'dot' comparison node.
8942       SDValue Ops[] = {
8943         LHS.getOperand(2),  // LHS of compare
8944         LHS.getOperand(3),  // RHS of compare
8945         DAG.getConstant(CompareOpc, MVT::i32)
8946       };
8947       EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
8948       SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
8949
8950       // Unpack the result based on how the target uses it.
8951       PPC::Predicate CompOpc;
8952       switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
8953       default:  // Can't happen, don't crash on invalid number though.
8954       case 0:   // Branch on the value of the EQ bit of CR6.
8955         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
8956         break;
8957       case 1:   // Branch on the inverted value of the EQ bit of CR6.
8958         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
8959         break;
8960       case 2:   // Branch on the value of the LT bit of CR6.
8961         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
8962         break;
8963       case 3:   // Branch on the inverted value of the LT bit of CR6.
8964         CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
8965         break;
8966       }
8967
8968       return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
8969                          DAG.getConstant(CompOpc, MVT::i32),
8970                          DAG.getRegister(PPC::CR6, MVT::i32),
8971                          N->getOperand(4), CompNode.getValue(1));
8972     }
8973     break;
8974   }
8975   }
8976
8977   return SDValue();
8978 }
8979
8980 SDValue
8981 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8982                                   SelectionDAG &DAG,
8983                                   std::vector<SDNode *> *Created) const {
8984   // fold (sdiv X, pow2)
8985   EVT VT = N->getValueType(0);
8986   if (VT == MVT::i64 && !Subtarget.isPPC64())
8987     return SDValue();
8988   if ((VT != MVT::i32 && VT != MVT::i64) ||
8989       !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8990     return SDValue();
8991
8992   SDLoc DL(N);
8993   SDValue N0 = N->getOperand(0);
8994
8995   bool IsNegPow2 = (-Divisor).isPowerOf2();
8996   unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
8997   SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
8998
8999   SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9000   if (Created)
9001     Created->push_back(Op.getNode());
9002
9003   if (IsNegPow2) {
9004     Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9005     if (Created)
9006       Created->push_back(Op.getNode());
9007   }
9008
9009   return Op;
9010 }
9011
9012 //===----------------------------------------------------------------------===//
9013 // Inline Assembly Support
9014 //===----------------------------------------------------------------------===//
9015
9016 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9017                                                       APInt &KnownZero,
9018                                                       APInt &KnownOne,
9019                                                       const SelectionDAG &DAG,
9020                                                       unsigned Depth) const {
9021   KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9022   switch (Op.getOpcode()) {
9023   default: break;
9024   case PPCISD::LBRX: {
9025     // lhbrx is known to have the top bits cleared out.
9026     if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9027       KnownZero = 0xFFFF0000;
9028     break;
9029   }
9030   case ISD::INTRINSIC_WO_CHAIN: {
9031     switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9032     default: break;
9033     case Intrinsic::ppc_altivec_vcmpbfp_p:
9034     case Intrinsic::ppc_altivec_vcmpeqfp_p:
9035     case Intrinsic::ppc_altivec_vcmpequb_p:
9036     case Intrinsic::ppc_altivec_vcmpequh_p:
9037     case Intrinsic::ppc_altivec_vcmpequw_p:
9038     case Intrinsic::ppc_altivec_vcmpgefp_p:
9039     case Intrinsic::ppc_altivec_vcmpgtfp_p:
9040     case Intrinsic::ppc_altivec_vcmpgtsb_p:
9041     case Intrinsic::ppc_altivec_vcmpgtsh_p:
9042     case Intrinsic::ppc_altivec_vcmpgtsw_p:
9043     case Intrinsic::ppc_altivec_vcmpgtub_p:
9044     case Intrinsic::ppc_altivec_vcmpgtuh_p:
9045     case Intrinsic::ppc_altivec_vcmpgtuw_p:
9046       KnownZero = ~1U;  // All bits but the low one are known to be zero.
9047       break;
9048     }
9049   }
9050   }
9051 }
9052
9053 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9054   switch (Subtarget.getDarwinDirective()) {
9055   default: break;
9056   case PPC::DIR_970:
9057   case PPC::DIR_PWR4:
9058   case PPC::DIR_PWR5:
9059   case PPC::DIR_PWR5X:
9060   case PPC::DIR_PWR6:
9061   case PPC::DIR_PWR6X:
9062   case PPC::DIR_PWR7:
9063   case PPC::DIR_PWR8: {
9064     if (!ML)
9065       break;
9066
9067     const PPCInstrInfo *TII =
9068       static_cast<const PPCInstrInfo *>(getTargetMachine().getSubtargetImpl()->
9069                                           getInstrInfo());
9070
9071     // For small loops (between 5 and 8 instructions), align to a 32-byte
9072     // boundary so that the entire loop fits in one instruction-cache line.
9073     uint64_t LoopSize = 0;
9074     for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9075       for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9076         LoopSize += TII->GetInstSizeInBytes(J);
9077
9078     if (LoopSize > 16 && LoopSize <= 32)
9079       return 5;
9080
9081     break;
9082   }
9083   }
9084
9085   return TargetLowering::getPrefLoopAlignment(ML);
9086 }
9087
9088 /// getConstraintType - Given a constraint, return the type of
9089 /// constraint it is for this target.
9090 PPCTargetLowering::ConstraintType
9091 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9092   if (Constraint.size() == 1) {
9093     switch (Constraint[0]) {
9094     default: break;
9095     case 'b':
9096     case 'r':
9097     case 'f':
9098     case 'v':
9099     case 'y':
9100       return C_RegisterClass;
9101     case 'Z':
9102       // FIXME: While Z does indicate a memory constraint, it specifically
9103       // indicates an r+r address (used in conjunction with the 'y' modifier
9104       // in the replacement string). Currently, we're forcing the base
9105       // register to be r0 in the asm printer (which is interpreted as zero)
9106       // and forming the complete address in the second register. This is
9107       // suboptimal.
9108       return C_Memory;
9109     }
9110   } else if (Constraint == "wc") { // individual CR bits.
9111     return C_RegisterClass;
9112   } else if (Constraint == "wa" || Constraint == "wd" ||
9113              Constraint == "wf" || Constraint == "ws") {
9114     return C_RegisterClass; // VSX registers.
9115   }
9116   return TargetLowering::getConstraintType(Constraint);
9117 }
9118
9119 /// Examine constraint type and operand type and determine a weight value.
9120 /// This object must already have been set up with the operand type
9121 /// and the current alternative constraint selected.
9122 TargetLowering::ConstraintWeight
9123 PPCTargetLowering::getSingleConstraintMatchWeight(
9124     AsmOperandInfo &info, const char *constraint) const {
9125   ConstraintWeight weight = CW_Invalid;
9126   Value *CallOperandVal = info.CallOperandVal;
9127     // If we don't have a value, we can't do a match,
9128     // but allow it at the lowest weight.
9129   if (!CallOperandVal)
9130     return CW_Default;
9131   Type *type = CallOperandVal->getType();
9132
9133   // Look at the constraint type.
9134   if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9135     return CW_Register; // an individual CR bit.
9136   else if ((StringRef(constraint) == "wa" ||
9137             StringRef(constraint) == "wd" ||
9138             StringRef(constraint) == "wf") &&
9139            type->isVectorTy())
9140     return CW_Register;
9141   else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9142     return CW_Register;
9143
9144   switch (*constraint) {
9145   default:
9146     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9147     break;
9148   case 'b':
9149     if (type->isIntegerTy())
9150       weight = CW_Register;
9151     break;
9152   case 'f':
9153     if (type->isFloatTy())
9154       weight = CW_Register;
9155     break;
9156   case 'd':
9157     if (type->isDoubleTy())
9158       weight = CW_Register;
9159     break;
9160   case 'v':
9161     if (type->isVectorTy())
9162       weight = CW_Register;
9163     break;
9164   case 'y':
9165     weight = CW_Register;
9166     break;
9167   case 'Z':
9168     weight = CW_Memory;
9169     break;
9170   }
9171   return weight;
9172 }
9173
9174 std::pair<unsigned, const TargetRegisterClass*>
9175 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9176                                                 MVT VT) const {
9177   if (Constraint.size() == 1) {
9178     // GCC RS6000 Constraint Letters
9179     switch (Constraint[0]) {
9180     case 'b':   // R1-R31
9181       if (VT == MVT::i64 && Subtarget.isPPC64())
9182         return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9183       return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9184     case 'r':   // R0-R31
9185       if (VT == MVT::i64 && Subtarget.isPPC64())
9186         return std::make_pair(0U, &PPC::G8RCRegClass);
9187       return std::make_pair(0U, &PPC::GPRCRegClass);
9188     case 'f':
9189       if (VT == MVT::f32 || VT == MVT::i32)
9190         return std::make_pair(0U, &PPC::F4RCRegClass);
9191       if (VT == MVT::f64 || VT == MVT::i64)
9192         return std::make_pair(0U, &PPC::F8RCRegClass);
9193       break;
9194     case 'v':
9195       return std::make_pair(0U, &PPC::VRRCRegClass);
9196     case 'y':   // crrc
9197       return std::make_pair(0U, &PPC::CRRCRegClass);
9198     }
9199   } else if (Constraint == "wc") { // an individual CR bit.
9200     return std::make_pair(0U, &PPC::CRBITRCRegClass);
9201   } else if (Constraint == "wa" || Constraint == "wd" ||
9202              Constraint == "wf") {
9203     return std::make_pair(0U, &PPC::VSRCRegClass);
9204   } else if (Constraint == "ws") {
9205     return std::make_pair(0U, &PPC::VSFRCRegClass);
9206   }
9207
9208   std::pair<unsigned, const TargetRegisterClass*> R =
9209     TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9210
9211   // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9212   // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9213   // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9214   // register.
9215   // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9216   // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9217   if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9218       PPC::GPRCRegClass.contains(R.first)) {
9219     const TargetRegisterInfo *TRI =
9220         getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9221     return std::make_pair(TRI->getMatchingSuperReg(R.first,
9222                             PPC::sub_32, &PPC::G8RCRegClass),
9223                           &PPC::G8RCRegClass);
9224   }
9225
9226   // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9227   if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9228     R.first = PPC::CR0;
9229     R.second = &PPC::CRRCRegClass;
9230   }
9231
9232   return R;
9233 }
9234
9235
9236 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9237 /// vector.  If it is invalid, don't add anything to Ops.
9238 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9239                                                      std::string &Constraint,
9240                                                      std::vector<SDValue>&Ops,
9241                                                      SelectionDAG &DAG) const {
9242   SDValue Result;
9243
9244   // Only support length 1 constraints.
9245   if (Constraint.length() > 1) return;
9246
9247   char Letter = Constraint[0];
9248   switch (Letter) {
9249   default: break;
9250   case 'I':
9251   case 'J':
9252   case 'K':
9253   case 'L':
9254   case 'M':
9255   case 'N':
9256   case 'O':
9257   case 'P': {
9258     ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9259     if (!CST) return; // Must be an immediate to match.
9260     int64_t Value = CST->getSExtValue();
9261     EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9262                          // numbers are printed as such.
9263     switch (Letter) {
9264     default: llvm_unreachable("Unknown constraint letter!");
9265     case 'I':  // "I" is a signed 16-bit constant.
9266       if (isInt<16>(Value))
9267         Result = DAG.getTargetConstant(Value, TCVT);
9268       break;
9269     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
9270       if (isShiftedUInt<16, 16>(Value))
9271         Result = DAG.getTargetConstant(Value, TCVT);
9272       break;
9273     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
9274       if (isShiftedInt<16, 16>(Value))
9275         Result = DAG.getTargetConstant(Value, TCVT);
9276       break;
9277     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
9278       if (isUInt<16>(Value))
9279         Result = DAG.getTargetConstant(Value, TCVT);
9280       break;
9281     case 'M':  // "M" is a constant that is greater than 31.
9282       if (Value > 31)
9283         Result = DAG.getTargetConstant(Value, TCVT);
9284       break;
9285     case 'N':  // "N" is a positive constant that is an exact power of two.
9286       if (Value > 0 && isPowerOf2_64(Value))
9287         Result = DAG.getTargetConstant(Value, TCVT);
9288       break;
9289     case 'O':  // "O" is the constant zero.
9290       if (Value == 0)
9291         Result = DAG.getTargetConstant(Value, TCVT);
9292       break;
9293     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
9294       if (isInt<16>(-Value))
9295         Result = DAG.getTargetConstant(Value, TCVT);
9296       break;
9297     }
9298     break;
9299   }
9300   }
9301
9302   if (Result.getNode()) {
9303     Ops.push_back(Result);
9304     return;
9305   }
9306
9307   // Handle standard constraint letters.
9308   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9309 }
9310
9311 // isLegalAddressingMode - Return true if the addressing mode represented
9312 // by AM is legal for this target, for a load/store of the specified type.
9313 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9314                                               Type *Ty) const {
9315   // FIXME: PPC does not allow r+i addressing modes for vectors!
9316
9317   // PPC allows a sign-extended 16-bit immediate field.
9318   if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9319     return false;
9320
9321   // No global is ever allowed as a base.
9322   if (AM.BaseGV)
9323     return false;
9324
9325   // PPC only support r+r,
9326   switch (AM.Scale) {
9327   case 0:  // "r+i" or just "i", depending on HasBaseReg.
9328     break;
9329   case 1:
9330     if (AM.HasBaseReg && AM.BaseOffs)  // "r+r+i" is not allowed.
9331       return false;
9332     // Otherwise we have r+r or r+i.
9333     break;
9334   case 2:
9335     if (AM.HasBaseReg || AM.BaseOffs)  // 2*r+r  or  2*r+i is not allowed.
9336       return false;
9337     // Allow 2*r as r+r.
9338     break;
9339   default:
9340     // No other scales are supported.
9341     return false;
9342   }
9343
9344   return true;
9345 }
9346
9347 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9348                                            SelectionDAG &DAG) const {
9349   MachineFunction &MF = DAG.getMachineFunction();
9350   MachineFrameInfo *MFI = MF.getFrameInfo();
9351   MFI->setReturnAddressIsTaken(true);
9352
9353   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9354     return SDValue();
9355
9356   SDLoc dl(Op);
9357   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9358
9359   // Make sure the function does not optimize away the store of the RA to
9360   // the stack.
9361   PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9362   FuncInfo->setLRStoreRequired();
9363   bool isPPC64 = Subtarget.isPPC64();
9364   bool isDarwinABI = Subtarget.isDarwinABI();
9365
9366   if (Depth > 0) {
9367     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9368     SDValue Offset =
9369
9370       DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9371                       isPPC64? MVT::i64 : MVT::i32);
9372     return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9373                        DAG.getNode(ISD::ADD, dl, getPointerTy(),
9374                                    FrameAddr, Offset),
9375                        MachinePointerInfo(), false, false, false, 0);
9376   }
9377
9378   // Just load the return address off the stack.
9379   SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9380   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9381                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9382 }
9383
9384 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9385                                           SelectionDAG &DAG) const {
9386   SDLoc dl(Op);
9387   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9388
9389   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9390   bool isPPC64 = PtrVT == MVT::i64;
9391
9392   MachineFunction &MF = DAG.getMachineFunction();
9393   MachineFrameInfo *MFI = MF.getFrameInfo();
9394   MFI->setFrameAddressIsTaken(true);
9395
9396   // Naked functions never have a frame pointer, and so we use r1. For all
9397   // other functions, this decision must be delayed until during PEI.
9398   unsigned FrameReg;
9399   if (MF.getFunction()->getAttributes().hasAttribute(
9400         AttributeSet::FunctionIndex, Attribute::Naked))
9401     FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9402   else
9403     FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9404
9405   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9406                                          PtrVT);
9407   while (Depth--)
9408     FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9409                             FrameAddr, MachinePointerInfo(), false, false,
9410                             false, 0);
9411   return FrameAddr;
9412 }
9413
9414 // FIXME? Maybe this could be a TableGen attribute on some registers and
9415 // this table could be generated automatically from RegInfo.
9416 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9417                                               EVT VT) const {
9418   bool isPPC64 = Subtarget.isPPC64();
9419   bool isDarwinABI = Subtarget.isDarwinABI();
9420
9421   if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9422       (!isPPC64 && VT != MVT::i32))
9423     report_fatal_error("Invalid register global variable type");
9424
9425   bool is64Bit = isPPC64 && VT == MVT::i64;
9426   unsigned Reg = StringSwitch<unsigned>(RegName)
9427                    .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9428                    .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9429                    .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9430                                   (is64Bit ? PPC::X13 : PPC::R13))
9431                    .Default(0);
9432
9433   if (Reg)
9434     return Reg;
9435   report_fatal_error("Invalid register name global variable");
9436 }
9437
9438 bool
9439 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9440   // The PowerPC target isn't yet aware of offsets.
9441   return false;
9442 }
9443
9444 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9445                                            const CallInst &I,
9446                                            unsigned Intrinsic) const {
9447
9448   switch (Intrinsic) {
9449   case Intrinsic::ppc_altivec_lvx:
9450   case Intrinsic::ppc_altivec_lvxl:
9451   case Intrinsic::ppc_altivec_lvebx:
9452   case Intrinsic::ppc_altivec_lvehx:
9453   case Intrinsic::ppc_altivec_lvewx:
9454   case Intrinsic::ppc_vsx_lxvd2x:
9455   case Intrinsic::ppc_vsx_lxvw4x: {
9456     EVT VT;
9457     switch (Intrinsic) {
9458     case Intrinsic::ppc_altivec_lvebx:
9459       VT = MVT::i8;
9460       break;
9461     case Intrinsic::ppc_altivec_lvehx:
9462       VT = MVT::i16;
9463       break;
9464     case Intrinsic::ppc_altivec_lvewx:
9465       VT = MVT::i32;
9466       break;
9467     case Intrinsic::ppc_vsx_lxvd2x:
9468       VT = MVT::v2f64;
9469       break;
9470     default:
9471       VT = MVT::v4i32;
9472       break;
9473     }
9474
9475     Info.opc = ISD::INTRINSIC_W_CHAIN;
9476     Info.memVT = VT;
9477     Info.ptrVal = I.getArgOperand(0);
9478     Info.offset = -VT.getStoreSize()+1;
9479     Info.size = 2*VT.getStoreSize()-1;
9480     Info.align = 1;
9481     Info.vol = false;
9482     Info.readMem = true;
9483     Info.writeMem = false;
9484     return true;
9485   }
9486   case Intrinsic::ppc_altivec_stvx:
9487   case Intrinsic::ppc_altivec_stvxl:
9488   case Intrinsic::ppc_altivec_stvebx:
9489   case Intrinsic::ppc_altivec_stvehx:
9490   case Intrinsic::ppc_altivec_stvewx:
9491   case Intrinsic::ppc_vsx_stxvd2x:
9492   case Intrinsic::ppc_vsx_stxvw4x: {
9493     EVT VT;
9494     switch (Intrinsic) {
9495     case Intrinsic::ppc_altivec_stvebx:
9496       VT = MVT::i8;
9497       break;
9498     case Intrinsic::ppc_altivec_stvehx:
9499       VT = MVT::i16;
9500       break;
9501     case Intrinsic::ppc_altivec_stvewx:
9502       VT = MVT::i32;
9503       break;
9504     case Intrinsic::ppc_vsx_stxvd2x:
9505       VT = MVT::v2f64;
9506       break;
9507     default:
9508       VT = MVT::v4i32;
9509       break;
9510     }
9511
9512     Info.opc = ISD::INTRINSIC_VOID;
9513     Info.memVT = VT;
9514     Info.ptrVal = I.getArgOperand(1);
9515     Info.offset = -VT.getStoreSize()+1;
9516     Info.size = 2*VT.getStoreSize()-1;
9517     Info.align = 1;
9518     Info.vol = false;
9519     Info.readMem = false;
9520     Info.writeMem = true;
9521     return true;
9522   }
9523   default:
9524     break;
9525   }
9526
9527   return false;
9528 }
9529
9530 /// getOptimalMemOpType - Returns the target specific optimal type for load
9531 /// and store operations as a result of memset, memcpy, and memmove
9532 /// lowering. If DstAlign is zero that means it's safe to destination
9533 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9534 /// means there isn't a need to check it against alignment requirement,
9535 /// probably because the source does not need to be loaded. If 'IsMemset' is
9536 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9537 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9538 /// source is constant so it does not need to be loaded.
9539 /// It returns EVT::Other if the type should be determined using generic
9540 /// target-independent logic.
9541 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9542                                            unsigned DstAlign, unsigned SrcAlign,
9543                                            bool IsMemset, bool ZeroMemset,
9544                                            bool MemcpyStrSrc,
9545                                            MachineFunction &MF) const {
9546   if (Subtarget.isPPC64()) {
9547     return MVT::i64;
9548   } else {
9549     return MVT::i32;
9550   }
9551 }
9552
9553 /// \brief Returns true if it is beneficial to convert a load of a constant
9554 /// to just the constant itself.
9555 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9556                                                           Type *Ty) const {
9557   assert(Ty->isIntegerTy());
9558
9559   unsigned BitSize = Ty->getPrimitiveSizeInBits();
9560   if (BitSize == 0 || BitSize > 64)
9561     return false;
9562   return true;
9563 }
9564
9565 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9566   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9567     return false;
9568   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9569   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9570   return NumBits1 == 64 && NumBits2 == 32;
9571 }
9572
9573 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9574   if (!VT1.isInteger() || !VT2.isInteger())
9575     return false;
9576   unsigned NumBits1 = VT1.getSizeInBits();
9577   unsigned NumBits2 = VT2.getSizeInBits();
9578   return NumBits1 == 64 && NumBits2 == 32;
9579 }
9580
9581 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9582   return isInt<16>(Imm) || isUInt<16>(Imm);
9583 }
9584
9585 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9586   return isInt<16>(Imm) || isUInt<16>(Imm);
9587 }
9588
9589 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9590                                                        unsigned,
9591                                                        unsigned,
9592                                                        bool *Fast) const {
9593   if (DisablePPCUnaligned)
9594     return false;
9595
9596   // PowerPC supports unaligned memory access for simple non-vector types.
9597   // Although accessing unaligned addresses is not as efficient as accessing
9598   // aligned addresses, it is generally more efficient than manual expansion,
9599   // and generally only traps for software emulation when crossing page
9600   // boundaries.
9601
9602   if (!VT.isSimple())
9603     return false;
9604
9605   if (VT.getSimpleVT().isVector()) {
9606     if (Subtarget.hasVSX()) {
9607       if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9608           VT != MVT::v4f32 && VT != MVT::v4i32)
9609         return false;
9610     } else {
9611       return false;
9612     }
9613   }
9614
9615   if (VT == MVT::ppcf128)
9616     return false;
9617
9618   if (Fast)
9619     *Fast = true;
9620
9621   return true;
9622 }
9623
9624 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9625   VT = VT.getScalarType();
9626
9627   if (!VT.isSimple())
9628     return false;
9629
9630   switch (VT.getSimpleVT().SimpleTy) {
9631   case MVT::f32:
9632   case MVT::f64:
9633     return true;
9634   default:
9635     break;
9636   }
9637
9638   return false;
9639 }
9640
9641 bool
9642 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9643                      EVT VT , unsigned DefinedValues) const {
9644   if (VT == MVT::v2i64)
9645     return false;
9646
9647   return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9648 }
9649
9650 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9651   if (DisableILPPref || Subtarget.enableMachineScheduler())
9652     return TargetLowering::getSchedulingPreference(N);
9653
9654   return Sched::ILP;
9655 }
9656
9657 // Create a fast isel object.
9658 FastISel *
9659 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9660                                   const TargetLibraryInfo *LibInfo) const {
9661   return PPC::createFastISel(FuncInfo, LibInfo);
9662 }