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