1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
41 CCValAssign::LocInfo &LocInfo,
42 ISD::ArgFlagsTy &ArgFlags,
44 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
46 CCValAssign::LocInfo &LocInfo,
47 ISD::ArgFlagsTy &ArgFlags,
49 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
51 CCValAssign::LocInfo &LocInfo,
52 ISD::ArgFlagsTy &ArgFlags,
55 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
56 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
58 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
59 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
61 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
62 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
64 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
65 if (TM.getSubtargetImpl()->isDarwin())
66 return new TargetLoweringObjectFileMachO();
68 if (TM.getSubtargetImpl()->isSVR4ABI())
69 return new PPC64LinuxTargetObjectFile();
71 return new TargetLoweringObjectFileELF();
74 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
75 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
76 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
77 PPCRegInfo = TM.getRegisterInfo();
78 PPCII = TM.getInstrInfo();
82 // Use _setjmp/_longjmp instead of setjmp/longjmp.
83 setUseUnderscoreSetJmp(true);
84 setUseUnderscoreLongJmp(true);
86 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
87 // arguments are at least 4/8 bytes aligned.
88 bool isPPC64 = Subtarget->isPPC64();
89 setMinStackArgumentAlignment(isPPC64 ? 8:4);
91 // Set up the register classes.
92 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
93 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
94 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
96 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
97 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
98 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
100 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
102 // PowerPC has pre-inc load and store's.
103 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
104 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
105 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
106 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
107 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
108 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
109 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
110 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
111 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
112 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
114 // This is used in the ppcf128->int sequence. Note it has different semantics
115 // from FP_ROUND: that rounds to nearest, this rounds to zero.
116 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
118 // We do not currently implement these libm ops for PowerPC.
119 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
120 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
121 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
122 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
123 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
124 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
126 // PowerPC has no SREM/UREM instructions
127 setOperationAction(ISD::SREM, MVT::i32, Expand);
128 setOperationAction(ISD::UREM, MVT::i32, Expand);
129 setOperationAction(ISD::SREM, MVT::i64, Expand);
130 setOperationAction(ISD::UREM, MVT::i64, Expand);
132 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
133 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
134 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
135 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
136 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
137 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
138 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
139 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
140 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
142 // We don't support sin/cos/sqrt/fmod/pow
143 setOperationAction(ISD::FSIN , MVT::f64, Expand);
144 setOperationAction(ISD::FCOS , MVT::f64, Expand);
145 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
146 setOperationAction(ISD::FREM , MVT::f64, Expand);
147 setOperationAction(ISD::FPOW , MVT::f64, Expand);
148 setOperationAction(ISD::FMA , MVT::f64, Legal);
149 setOperationAction(ISD::FSIN , MVT::f32, Expand);
150 setOperationAction(ISD::FCOS , MVT::f32, Expand);
151 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
152 setOperationAction(ISD::FREM , MVT::f32, Expand);
153 setOperationAction(ISD::FPOW , MVT::f32, Expand);
154 setOperationAction(ISD::FMA , MVT::f32, Legal);
156 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
158 // If we're enabling GP optimizations, use hardware square root
159 if (!Subtarget->hasFSQRT() &&
160 !(TM.Options.UnsafeFPMath &&
161 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
162 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
164 if (!Subtarget->hasFSQRT() &&
165 !(TM.Options.UnsafeFPMath &&
166 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
167 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
169 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
170 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
172 if (Subtarget->hasFPRND()) {
173 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
174 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
175 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
177 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
178 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
179 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
181 // frin does not implement "ties to even." Thus, this is safe only in
183 if (TM.Options.UnsafeFPMath) {
184 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
185 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
187 // These need to set FE_INEXACT, and use a custom inserter.
188 setOperationAction(ISD::FRINT, MVT::f64, Legal);
189 setOperationAction(ISD::FRINT, MVT::f32, Legal);
193 // PowerPC does not have BSWAP, CTPOP or CTTZ
194 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
195 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
196 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
197 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
198 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
199 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
200 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
201 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
203 if (Subtarget->hasPOPCNTD()) {
204 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
205 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
207 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
208 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
211 // PowerPC does not have ROTR
212 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
213 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
215 // PowerPC does not have Select
216 setOperationAction(ISD::SELECT, MVT::i32, Expand);
217 setOperationAction(ISD::SELECT, MVT::i64, Expand);
218 setOperationAction(ISD::SELECT, MVT::f32, Expand);
219 setOperationAction(ISD::SELECT, MVT::f64, Expand);
221 // PowerPC wants to turn select_cc of FP into fsel when possible.
222 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
223 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
225 // PowerPC wants to optimize integer setcc a bit
226 setOperationAction(ISD::SETCC, MVT::i32, Custom);
228 // PowerPC does not have BRCOND which requires SetCC
229 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
231 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
233 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
234 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
236 // PowerPC does not have [U|S]INT_TO_FP
237 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
238 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
240 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
241 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
242 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
243 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
245 // We cannot sextinreg(i1). Expand to shifts.
246 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
248 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
249 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
250 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
251 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
253 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
254 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
255 // support continuation, user-level threading, and etc.. As a result, no
256 // other SjLj exception interfaces are implemented and please don't build
257 // your own exception handling based on them.
258 // LLVM/Clang supports zero-cost DWARF exception handling.
259 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
260 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
262 // We want to legalize GlobalAddress and ConstantPool nodes into the
263 // appropriate instructions to materialize the address.
264 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
265 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
266 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
267 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
268 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
269 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
270 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
271 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
272 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
273 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
276 setOperationAction(ISD::TRAP, MVT::Other, Legal);
278 // TRAMPOLINE is custom lowered.
279 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
280 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
282 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
283 setOperationAction(ISD::VASTART , MVT::Other, Custom);
285 if (Subtarget->isSVR4ABI()) {
287 // VAARG always uses double-word chunks, so promote anything smaller.
288 setOperationAction(ISD::VAARG, MVT::i1, Promote);
289 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
290 setOperationAction(ISD::VAARG, MVT::i8, Promote);
291 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
292 setOperationAction(ISD::VAARG, MVT::i16, Promote);
293 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
294 setOperationAction(ISD::VAARG, MVT::i32, Promote);
295 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
296 setOperationAction(ISD::VAARG, MVT::Other, Expand);
298 // VAARG is custom lowered with the 32-bit SVR4 ABI.
299 setOperationAction(ISD::VAARG, MVT::Other, Custom);
300 setOperationAction(ISD::VAARG, MVT::i64, Custom);
303 setOperationAction(ISD::VAARG, MVT::Other, Expand);
305 // Use the default implementation.
306 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
307 setOperationAction(ISD::VAEND , MVT::Other, Expand);
308 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
309 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
313 // We want to custom lower some of our intrinsics.
314 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
316 // To handle counter-based loop conditions.
317 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
319 // Comparisons that require checking two conditions.
320 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
321 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
322 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
323 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
324 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
325 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
326 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
327 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
328 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
329 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
330 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
331 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
333 if (Subtarget->has64BitSupport()) {
334 // They also have instructions for converting between i64 and fp.
335 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
336 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
337 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
338 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
339 // This is just the low 32 bits of a (signed) fp->i64 conversion.
340 // We cannot do this with Promote because i64 is not a legal type.
341 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
343 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
344 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
346 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
347 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
350 // With the instructions enabled under FPCVT, we can do everything.
351 if (PPCSubTarget.hasFPCVT()) {
352 if (Subtarget->has64BitSupport()) {
353 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
354 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
355 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
356 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
359 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
360 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
361 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
362 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
365 if (Subtarget->use64BitRegs()) {
366 // 64-bit PowerPC implementations can support i64 types directly
367 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
368 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
369 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
370 // 64-bit PowerPC wants to expand i128 shifts itself.
371 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
372 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
373 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
375 // 32-bit PowerPC wants to expand i64 shifts itself.
376 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
377 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
378 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
381 if (Subtarget->hasAltivec()) {
382 // First set operation action for all vector types to expand. Then we
383 // will selectively turn on ones that can be effectively codegen'd.
384 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
385 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
386 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
388 // add/sub are legal for all supported vector VT's.
389 setOperationAction(ISD::ADD , VT, Legal);
390 setOperationAction(ISD::SUB , VT, Legal);
392 // We promote all shuffles to v16i8.
393 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
394 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
396 // We promote all non-typed operations to v4i32.
397 setOperationAction(ISD::AND , VT, Promote);
398 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
399 setOperationAction(ISD::OR , VT, Promote);
400 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
401 setOperationAction(ISD::XOR , VT, Promote);
402 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
403 setOperationAction(ISD::LOAD , VT, Promote);
404 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
405 setOperationAction(ISD::SELECT, VT, Promote);
406 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
407 setOperationAction(ISD::STORE, VT, Promote);
408 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
410 // No other operations are legal.
411 setOperationAction(ISD::MUL , VT, Expand);
412 setOperationAction(ISD::SDIV, VT, Expand);
413 setOperationAction(ISD::SREM, VT, Expand);
414 setOperationAction(ISD::UDIV, VT, Expand);
415 setOperationAction(ISD::UREM, VT, Expand);
416 setOperationAction(ISD::FDIV, VT, Expand);
417 setOperationAction(ISD::FNEG, VT, Expand);
418 setOperationAction(ISD::FSQRT, VT, Expand);
419 setOperationAction(ISD::FLOG, VT, Expand);
420 setOperationAction(ISD::FLOG10, VT, Expand);
421 setOperationAction(ISD::FLOG2, VT, Expand);
422 setOperationAction(ISD::FEXP, VT, Expand);
423 setOperationAction(ISD::FEXP2, VT, Expand);
424 setOperationAction(ISD::FSIN, VT, Expand);
425 setOperationAction(ISD::FCOS, VT, Expand);
426 setOperationAction(ISD::FABS, VT, Expand);
427 setOperationAction(ISD::FPOWI, VT, Expand);
428 setOperationAction(ISD::FFLOOR, VT, Expand);
429 setOperationAction(ISD::FCEIL, VT, Expand);
430 setOperationAction(ISD::FTRUNC, VT, Expand);
431 setOperationAction(ISD::FRINT, VT, Expand);
432 setOperationAction(ISD::FNEARBYINT, VT, Expand);
433 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
434 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
435 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
436 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
437 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
438 setOperationAction(ISD::UDIVREM, VT, Expand);
439 setOperationAction(ISD::SDIVREM, VT, Expand);
440 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
441 setOperationAction(ISD::FPOW, VT, Expand);
442 setOperationAction(ISD::CTPOP, VT, Expand);
443 setOperationAction(ISD::CTLZ, VT, Expand);
444 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
445 setOperationAction(ISD::CTTZ, VT, Expand);
446 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
447 setOperationAction(ISD::VSELECT, VT, Expand);
448 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
450 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
451 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
452 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
453 setTruncStoreAction(VT, InnerVT, Expand);
455 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
456 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
457 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
460 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
461 // with merges, splats, etc.
462 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
464 setOperationAction(ISD::AND , MVT::v4i32, Legal);
465 setOperationAction(ISD::OR , MVT::v4i32, Legal);
466 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
467 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
468 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
469 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
470 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
471 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
472 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
473 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
474 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
475 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
476 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
477 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
479 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
480 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
481 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
482 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
484 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
485 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
487 if (TM.Options.UnsafeFPMath) {
488 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
489 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
492 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
493 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
494 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
496 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
497 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
499 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
500 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
501 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
502 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
504 // Altivec does not contain unordered floating-point compare instructions
505 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
506 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
507 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
508 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
509 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
510 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
513 if (Subtarget->has64BitSupport()) {
514 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
515 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
518 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
519 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
520 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
521 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
523 setBooleanContents(ZeroOrOneBooleanContent);
524 // Altivec instructions set fields to all zeros or all ones.
525 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
528 setStackPointerRegisterToSaveRestore(PPC::X1);
529 setExceptionPointerRegister(PPC::X3);
530 setExceptionSelectorRegister(PPC::X4);
532 setStackPointerRegisterToSaveRestore(PPC::R1);
533 setExceptionPointerRegister(PPC::R3);
534 setExceptionSelectorRegister(PPC::R4);
537 // We have target-specific dag combine patterns for the following nodes:
538 setTargetDAGCombine(ISD::SINT_TO_FP);
539 setTargetDAGCombine(ISD::STORE);
540 setTargetDAGCombine(ISD::BR_CC);
541 setTargetDAGCombine(ISD::BSWAP);
543 // Use reciprocal estimates.
544 if (TM.Options.UnsafeFPMath) {
545 setTargetDAGCombine(ISD::FDIV);
546 setTargetDAGCombine(ISD::FSQRT);
549 // Darwin long double math library functions have $LDBL128 appended.
550 if (Subtarget->isDarwin()) {
551 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
552 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
553 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
554 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
555 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
556 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
557 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
558 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
559 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
560 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
563 setMinFunctionAlignment(2);
564 if (PPCSubTarget.isDarwin())
565 setPrefFunctionAlignment(4);
567 if (isPPC64 && Subtarget->isJITCodeModel())
568 // Temporary workaround for the inability of PPC64 JIT to handle jump
570 setSupportJumpTables(false);
572 setInsertFencesForAtomic(true);
574 setSchedulingPreference(Sched::Hybrid);
576 computeRegisterProperties();
578 // The Freescale cores does better with aggressive inlining of memcpy and
579 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
580 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
581 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
582 MaxStoresPerMemset = 32;
583 MaxStoresPerMemsetOptSize = 16;
584 MaxStoresPerMemcpy = 32;
585 MaxStoresPerMemcpyOptSize = 8;
586 MaxStoresPerMemmove = 32;
587 MaxStoresPerMemmoveOptSize = 8;
589 setPrefFunctionAlignment(4);
593 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
594 /// function arguments in the caller parameter area.
595 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
596 const TargetMachine &TM = getTargetMachine();
597 // Darwin passes everything on 4 byte boundary.
598 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
601 // 16byte and wider vectors are passed on 16byte boundary.
602 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
603 if (VTy->getBitWidth() >= 128)
606 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
607 if (PPCSubTarget.isPPC64())
613 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
616 case PPCISD::FSEL: return "PPCISD::FSEL";
617 case PPCISD::FCFID: return "PPCISD::FCFID";
618 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
619 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
620 case PPCISD::FRE: return "PPCISD::FRE";
621 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
622 case PPCISD::STFIWX: return "PPCISD::STFIWX";
623 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
624 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
625 case PPCISD::VPERM: return "PPCISD::VPERM";
626 case PPCISD::Hi: return "PPCISD::Hi";
627 case PPCISD::Lo: return "PPCISD::Lo";
628 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
629 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
630 case PPCISD::LOAD: return "PPCISD::LOAD";
631 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
632 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
633 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
634 case PPCISD::SRL: return "PPCISD::SRL";
635 case PPCISD::SRA: return "PPCISD::SRA";
636 case PPCISD::SHL: return "PPCISD::SHL";
637 case PPCISD::CALL: return "PPCISD::CALL";
638 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
639 case PPCISD::MTCTR: return "PPCISD::MTCTR";
640 case PPCISD::BCTRL: return "PPCISD::BCTRL";
641 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
642 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
643 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
644 case PPCISD::MFCR: return "PPCISD::MFCR";
645 case PPCISD::VCMP: return "PPCISD::VCMP";
646 case PPCISD::VCMPo: return "PPCISD::VCMPo";
647 case PPCISD::LBRX: return "PPCISD::LBRX";
648 case PPCISD::STBRX: return "PPCISD::STBRX";
649 case PPCISD::LARX: return "PPCISD::LARX";
650 case PPCISD::STCX: return "PPCISD::STCX";
651 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
652 case PPCISD::BDNZ: return "PPCISD::BDNZ";
653 case PPCISD::BDZ: return "PPCISD::BDZ";
654 case PPCISD::MFFS: return "PPCISD::MFFS";
655 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
656 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
657 case PPCISD::CR6SET: return "PPCISD::CR6SET";
658 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
659 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
660 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
661 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
662 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
663 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
664 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
665 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
666 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
667 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
668 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
669 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
670 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
671 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
672 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
673 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
674 case PPCISD::SC: return "PPCISD::SC";
678 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
681 return VT.changeVectorElementTypeToInteger();
684 //===----------------------------------------------------------------------===//
685 // Node matching predicates, for use by the tblgen matching code.
686 //===----------------------------------------------------------------------===//
688 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
689 static bool isFloatingPointZero(SDValue Op) {
690 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
691 return CFP->getValueAPF().isZero();
692 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
693 // Maybe this has already been legalized into the constant pool?
694 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
695 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
696 return CFP->getValueAPF().isZero();
701 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
702 /// true if Op is undef or if it matches the specified value.
703 static bool isConstantOrUndef(int Op, int Val) {
704 return Op < 0 || Op == Val;
707 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
708 /// VPKUHUM instruction.
709 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
711 for (unsigned i = 0; i != 16; ++i)
712 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
715 for (unsigned i = 0; i != 8; ++i)
716 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
717 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
723 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
724 /// VPKUWUM instruction.
725 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
727 for (unsigned i = 0; i != 16; i += 2)
728 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
729 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
732 for (unsigned i = 0; i != 8; i += 2)
733 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
734 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
735 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
736 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
742 /// isVMerge - Common function, used to match vmrg* shuffles.
744 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
745 unsigned LHSStart, unsigned RHSStart) {
746 assert(N->getValueType(0) == MVT::v16i8 &&
747 "PPC only supports shuffles by bytes!");
748 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
749 "Unsupported merge size!");
751 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
752 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
753 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
754 LHSStart+j+i*UnitSize) ||
755 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
756 RHSStart+j+i*UnitSize))
762 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
763 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
764 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
767 return isVMerge(N, UnitSize, 8, 24);
768 return isVMerge(N, UnitSize, 8, 8);
771 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
772 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
773 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
776 return isVMerge(N, UnitSize, 0, 16);
777 return isVMerge(N, UnitSize, 0, 0);
781 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
782 /// amount, otherwise return -1.
783 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
784 assert(N->getValueType(0) == MVT::v16i8 &&
785 "PPC only supports shuffles by bytes!");
787 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
789 // Find the first non-undef value in the shuffle mask.
791 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
794 if (i == 16) return -1; // all undef.
796 // Otherwise, check to see if the rest of the elements are consecutively
797 // numbered from this value.
798 unsigned ShiftAmt = SVOp->getMaskElt(i);
799 if (ShiftAmt < i) return -1;
803 // Check the rest of the elements to see if they are consecutive.
804 for (++i; i != 16; ++i)
805 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
808 // Check the rest of the elements to see if they are consecutive.
809 for (++i; i != 16; ++i)
810 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
816 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
817 /// specifies a splat of a single element that is suitable for input to
818 /// VSPLTB/VSPLTH/VSPLTW.
819 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
820 assert(N->getValueType(0) == MVT::v16i8 &&
821 (EltSize == 1 || EltSize == 2 || EltSize == 4));
823 // This is a splat operation if each element of the permute is the same, and
824 // if the value doesn't reference the second vector.
825 unsigned ElementBase = N->getMaskElt(0);
827 // FIXME: Handle UNDEF elements too!
828 if (ElementBase >= 16)
831 // Check that the indices are consecutive, in the case of a multi-byte element
832 // splatted with a v16i8 mask.
833 for (unsigned i = 1; i != EltSize; ++i)
834 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
837 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
838 if (N->getMaskElt(i) < 0) continue;
839 for (unsigned j = 0; j != EltSize; ++j)
840 if (N->getMaskElt(i+j) != N->getMaskElt(j))
846 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
848 bool PPC::isAllNegativeZeroVector(SDNode *N) {
849 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
851 APInt APVal, APUndef;
855 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
856 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
857 return CFP->getValueAPF().isNegZero();
862 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
863 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
864 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
865 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
866 assert(isSplatShuffleMask(SVOp, EltSize));
867 return SVOp->getMaskElt(0) / EltSize;
870 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
871 /// by using a vspltis[bhw] instruction of the specified element size, return
872 /// the constant being splatted. The ByteSize field indicates the number of
873 /// bytes of each element [124] -> [bhw].
874 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
877 // If ByteSize of the splat is bigger than the element size of the
878 // build_vector, then we have a case where we are checking for a splat where
879 // multiple elements of the buildvector are folded together into a single
880 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
881 unsigned EltSize = 16/N->getNumOperands();
882 if (EltSize < ByteSize) {
883 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
884 SDValue UniquedVals[4];
885 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
887 // See if all of the elements in the buildvector agree across.
888 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
889 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
890 // If the element isn't a constant, bail fully out.
891 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
894 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
895 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
896 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
897 return SDValue(); // no match.
900 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
901 // either constant or undef values that are identical for each chunk. See
902 // if these chunks can form into a larger vspltis*.
904 // Check to see if all of the leading entries are either 0 or -1. If
905 // neither, then this won't fit into the immediate field.
906 bool LeadingZero = true;
907 bool LeadingOnes = true;
908 for (unsigned i = 0; i != Multiple-1; ++i) {
909 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
911 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
912 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
914 // Finally, check the least significant entry.
916 if (UniquedVals[Multiple-1].getNode() == 0)
917 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
918 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
920 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
923 if (UniquedVals[Multiple-1].getNode() == 0)
924 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
925 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
926 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
927 return DAG.getTargetConstant(Val, MVT::i32);
933 // Check to see if this buildvec has a single non-undef value in its elements.
934 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
935 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
936 if (OpVal.getNode() == 0)
937 OpVal = N->getOperand(i);
938 else if (OpVal != N->getOperand(i))
942 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
944 unsigned ValSizeInBytes = EltSize;
946 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
947 Value = CN->getZExtValue();
948 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
949 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
950 Value = FloatToBits(CN->getValueAPF().convertToFloat());
953 // If the splat value is larger than the element value, then we can never do
954 // this splat. The only case that we could fit the replicated bits into our
955 // immediate field for would be zero, and we prefer to use vxor for it.
956 if (ValSizeInBytes < ByteSize) return SDValue();
958 // If the element value is larger than the splat value, cut it in half and
959 // check to see if the two halves are equal. Continue doing this until we
960 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
961 while (ValSizeInBytes > ByteSize) {
962 ValSizeInBytes >>= 1;
964 // If the top half equals the bottom half, we're still ok.
965 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
966 (Value & ((1 << (8*ValSizeInBytes))-1)))
970 // Properly sign extend the value.
971 int MaskVal = SignExtend32(Value, ByteSize * 8);
973 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
974 if (MaskVal == 0) return SDValue();
976 // Finally, if this value fits in a 5 bit sext field, return it
977 if (SignExtend32<5>(MaskVal) == MaskVal)
978 return DAG.getTargetConstant(MaskVal, MVT::i32);
982 //===----------------------------------------------------------------------===//
983 // Addressing Mode Selection
984 //===----------------------------------------------------------------------===//
986 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
987 /// or 64-bit immediate, and if the value can be accurately represented as a
988 /// sign extension from a 16-bit value. If so, this returns true and the
990 static bool isIntS16Immediate(SDNode *N, short &Imm) {
991 if (N->getOpcode() != ISD::Constant)
994 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
995 if (N->getValueType(0) == MVT::i32)
996 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
998 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1000 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1001 return isIntS16Immediate(Op.getNode(), Imm);
1005 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1006 /// can be represented as an indexed [r+r] operation. Returns false if it
1007 /// can be more efficiently represented with [r+imm].
1008 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1010 SelectionDAG &DAG) const {
1012 if (N.getOpcode() == ISD::ADD) {
1013 if (isIntS16Immediate(N.getOperand(1), imm))
1014 return false; // r+i
1015 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1016 return false; // r+i
1018 Base = N.getOperand(0);
1019 Index = N.getOperand(1);
1021 } else if (N.getOpcode() == ISD::OR) {
1022 if (isIntS16Immediate(N.getOperand(1), imm))
1023 return false; // r+i can fold it if we can.
1025 // If this is an or of disjoint bitfields, we can codegen this as an add
1026 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1028 APInt LHSKnownZero, LHSKnownOne;
1029 APInt RHSKnownZero, RHSKnownOne;
1030 DAG.ComputeMaskedBits(N.getOperand(0),
1031 LHSKnownZero, LHSKnownOne);
1033 if (LHSKnownZero.getBoolValue()) {
1034 DAG.ComputeMaskedBits(N.getOperand(1),
1035 RHSKnownZero, RHSKnownOne);
1036 // If all of the bits are known zero on the LHS or RHS, the add won't
1038 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1039 Base = N.getOperand(0);
1040 Index = N.getOperand(1);
1049 /// Returns true if the address N can be represented by a base register plus
1050 /// a signed 16-bit displacement [r+imm], and if it is not better
1051 /// represented as reg+reg.
1052 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1054 SelectionDAG &DAG) const {
1055 // FIXME dl should come from parent load or store, not from address
1056 DebugLoc dl = N.getDebugLoc();
1057 // If this can be more profitably realized as r+r, fail.
1058 if (SelectAddressRegReg(N, Disp, Base, DAG))
1061 if (N.getOpcode() == ISD::ADD) {
1063 if (isIntS16Immediate(N.getOperand(1), imm)) {
1064 Disp = DAG.getTargetConstant(imm, N.getValueType());
1065 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1066 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1068 Base = N.getOperand(0);
1070 return true; // [r+i]
1071 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1072 // Match LOAD (ADD (X, Lo(G))).
1073 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1074 && "Cannot handle constant offsets yet!");
1075 Disp = N.getOperand(1).getOperand(0); // The global address.
1076 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1077 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1078 Disp.getOpcode() == ISD::TargetConstantPool ||
1079 Disp.getOpcode() == ISD::TargetJumpTable);
1080 Base = N.getOperand(0);
1081 return true; // [&g+r]
1083 } else if (N.getOpcode() == ISD::OR) {
1085 if (isIntS16Immediate(N.getOperand(1), imm)) {
1086 // If this is an or of disjoint bitfields, we can codegen this as an add
1087 // (for better address arithmetic) if the LHS and RHS of the OR are
1088 // provably disjoint.
1089 APInt LHSKnownZero, LHSKnownOne;
1090 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1092 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1093 // If all of the bits are known zero on the LHS or RHS, the add won't
1095 Base = N.getOperand(0);
1096 Disp = DAG.getTargetConstant(imm, N.getValueType());
1100 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1101 // Loading from a constant address.
1103 // If this address fits entirely in a 16-bit sext immediate field, codegen
1106 if (isIntS16Immediate(CN, Imm)) {
1107 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1108 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1109 CN->getValueType(0));
1113 // Handle 32-bit sext immediates with LIS + addr mode.
1114 if (CN->getValueType(0) == MVT::i32 ||
1115 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1116 int Addr = (int)CN->getZExtValue();
1118 // Otherwise, break this down into an LIS + disp.
1119 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1121 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1122 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1123 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1128 Disp = DAG.getTargetConstant(0, getPointerTy());
1129 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1130 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1133 return true; // [r+0]
1136 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1137 /// represented as an indexed [r+r] operation.
1138 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1140 SelectionDAG &DAG) const {
1141 // Check to see if we can easily represent this as an [r+r] address. This
1142 // will fail if it thinks that the address is more profitably represented as
1143 // reg+imm, e.g. where imm = 0.
1144 if (SelectAddressRegReg(N, Base, Index, DAG))
1147 // If the operand is an addition, always emit this as [r+r], since this is
1148 // better (for code size, and execution, as the memop does the add for free)
1149 // than emitting an explicit add.
1150 if (N.getOpcode() == ISD::ADD) {
1151 Base = N.getOperand(0);
1152 Index = N.getOperand(1);
1156 // Otherwise, do it the hard way, using R0 as the base register.
1157 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1163 /// SelectAddressRegImmShift - Returns true if the address N can be
1164 /// represented by a base register plus a signed 14-bit displacement
1165 /// [r+imm*4]. Suitable for use by STD and friends.
1166 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1168 SelectionDAG &DAG) const {
1169 // FIXME dl should come from the parent load or store, not the address
1170 DebugLoc dl = N.getDebugLoc();
1171 // If this can be more profitably realized as r+r, fail.
1172 if (SelectAddressRegReg(N, Disp, Base, DAG))
1175 if (N.getOpcode() == ISD::ADD) {
1177 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1178 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1179 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1180 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1182 Base = N.getOperand(0);
1184 return true; // [r+i]
1185 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1186 // Match LOAD (ADD (X, Lo(G))).
1187 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1188 && "Cannot handle constant offsets yet!");
1189 Disp = N.getOperand(1).getOperand(0); // The global address.
1190 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1191 Disp.getOpcode() == ISD::TargetConstantPool ||
1192 Disp.getOpcode() == ISD::TargetJumpTable);
1193 Base = N.getOperand(0);
1194 return true; // [&g+r]
1196 } else if (N.getOpcode() == ISD::OR) {
1198 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1199 // If this is an or of disjoint bitfields, we can codegen this as an add
1200 // (for better address arithmetic) if the LHS and RHS of the OR are
1201 // provably disjoint.
1202 APInt LHSKnownZero, LHSKnownOne;
1203 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1204 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1205 // If all of the bits are known zero on the LHS or RHS, the add won't
1207 Base = N.getOperand(0);
1208 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1212 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1213 // Loading from a constant address. Verify low two bits are clear.
1214 if ((CN->getZExtValue() & 3) == 0) {
1215 // If this address fits entirely in a 14-bit sext immediate field, codegen
1218 if (isIntS16Immediate(CN, Imm)) {
1219 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1220 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1221 CN->getValueType(0));
1225 // Fold the low-part of 32-bit absolute addresses into addr mode.
1226 if (CN->getValueType(0) == MVT::i32 ||
1227 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1228 int Addr = (int)CN->getZExtValue();
1230 // Otherwise, break this down into an LIS + disp.
1231 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1232 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1233 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1234 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1240 Disp = DAG.getTargetConstant(0, getPointerTy());
1241 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1242 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1245 return true; // [r+0]
1249 /// getPreIndexedAddressParts - returns true by value, base pointer and
1250 /// offset pointer and addressing mode by reference if the node's address
1251 /// can be legally represented as pre-indexed load / store address.
1252 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1254 ISD::MemIndexedMode &AM,
1255 SelectionDAG &DAG) const {
1256 if (DisablePPCPreinc) return false;
1262 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1263 Ptr = LD->getBasePtr();
1264 VT = LD->getMemoryVT();
1265 Alignment = LD->getAlignment();
1266 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1267 Ptr = ST->getBasePtr();
1268 VT = ST->getMemoryVT();
1269 Alignment = ST->getAlignment();
1274 // PowerPC doesn't have preinc load/store instructions for vectors.
1278 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1280 // Common code will reject creating a pre-inc form if the base pointer
1281 // is a frame index, or if N is a store and the base pointer is either
1282 // the same as or a predecessor of the value being stored. Check for
1283 // those situations here, and try with swapped Base/Offset instead.
1286 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1289 SDValue Val = cast<StoreSDNode>(N)->getValue();
1290 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1295 std::swap(Base, Offset);
1301 // LDU/STU use reg+imm*4, others use reg+imm.
1302 if (VT != MVT::i64) {
1304 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1307 // LDU/STU need an address with at least 4-byte alignment.
1312 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1316 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1317 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1318 // sext i32 to i64 when addr mode is r+i.
1319 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1320 LD->getExtensionType() == ISD::SEXTLOAD &&
1321 isa<ConstantSDNode>(Offset))
1329 //===----------------------------------------------------------------------===//
1330 // LowerOperation implementation
1331 //===----------------------------------------------------------------------===//
1333 /// GetLabelAccessInfo - Return true if we should reference labels using a
1334 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1335 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1336 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1337 HiOpFlags = PPCII::MO_HA16;
1338 LoOpFlags = PPCII::MO_LO16;
1340 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1341 // non-darwin platform. We don't support PIC on other platforms yet.
1342 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1343 TM.getSubtarget<PPCSubtarget>().isDarwin();
1345 HiOpFlags |= PPCII::MO_PIC_FLAG;
1346 LoOpFlags |= PPCII::MO_PIC_FLAG;
1349 // If this is a reference to a global value that requires a non-lazy-ptr, make
1350 // sure that instruction lowering adds it.
1351 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1352 HiOpFlags |= PPCII::MO_NLP_FLAG;
1353 LoOpFlags |= PPCII::MO_NLP_FLAG;
1355 if (GV->hasHiddenVisibility()) {
1356 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1357 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1364 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1365 SelectionDAG &DAG) {
1366 EVT PtrVT = HiPart.getValueType();
1367 SDValue Zero = DAG.getConstant(0, PtrVT);
1368 DebugLoc DL = HiPart.getDebugLoc();
1370 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1371 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1373 // With PIC, the first instruction is actually "GR+hi(&G)".
1375 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1376 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1378 // Generate non-pic code that has direct accesses to the constant pool.
1379 // The address of the global is just (hi(&g)+lo(&g)).
1380 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1383 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1384 SelectionDAG &DAG) const {
1385 EVT PtrVT = Op.getValueType();
1386 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1387 const Constant *C = CP->getConstVal();
1389 // 64-bit SVR4 ABI code is always position-independent.
1390 // The actual address of the GlobalValue is stored in the TOC.
1391 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1392 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1393 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1394 DAG.getRegister(PPC::X2, MVT::i64));
1397 unsigned MOHiFlag, MOLoFlag;
1398 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1400 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1402 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1403 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1406 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1407 EVT PtrVT = Op.getValueType();
1408 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1410 // 64-bit SVR4 ABI code is always position-independent.
1411 // The actual address of the GlobalValue is stored in the TOC.
1412 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1413 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1414 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1415 DAG.getRegister(PPC::X2, MVT::i64));
1418 unsigned MOHiFlag, MOLoFlag;
1419 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1420 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1421 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1422 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1425 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1426 SelectionDAG &DAG) const {
1427 EVT PtrVT = Op.getValueType();
1429 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1431 unsigned MOHiFlag, MOLoFlag;
1432 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1433 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1434 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1435 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1438 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1439 SelectionDAG &DAG) const {
1441 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1442 DebugLoc dl = GA->getDebugLoc();
1443 const GlobalValue *GV = GA->getGlobal();
1444 EVT PtrVT = getPointerTy();
1445 bool is64bit = PPCSubTarget.isPPC64();
1447 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1449 if (Model == TLSModel::LocalExec) {
1450 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1451 PPCII::MO_TPREL16_HA);
1452 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1453 PPCII::MO_TPREL16_LO);
1454 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1455 is64bit ? MVT::i64 : MVT::i32);
1456 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1457 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1461 llvm_unreachable("only local-exec is currently supported for ppc32");
1463 if (Model == TLSModel::InitialExec) {
1464 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1465 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1466 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1467 PtrVT, GOTReg, TGA);
1468 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1469 PtrVT, TGA, TPOffsetHi);
1470 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1473 if (Model == TLSModel::GeneralDynamic) {
1474 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1475 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1476 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1478 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1481 // We need a chain node, and don't have one handy. The underlying
1482 // call has no side effects, so using the function entry node
1484 SDValue Chain = DAG.getEntryNode();
1485 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1486 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1487 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1488 PtrVT, ParmReg, TGA);
1489 // The return value from GET_TLS_ADDR really is in X3 already, but
1490 // some hacks are needed here to tie everything together. The extra
1491 // copies dissolve during subsequent transforms.
1492 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1493 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1496 if (Model == TLSModel::LocalDynamic) {
1497 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1498 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1499 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1501 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1504 // We need a chain node, and don't have one handy. The underlying
1505 // call has no side effects, so using the function entry node
1507 SDValue Chain = DAG.getEntryNode();
1508 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1509 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1510 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1511 PtrVT, ParmReg, TGA);
1512 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1513 // some hacks are needed here to tie everything together. The extra
1514 // copies dissolve during subsequent transforms.
1515 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1516 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1517 Chain, ParmReg, TGA);
1518 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1521 llvm_unreachable("Unknown TLS model!");
1524 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1525 SelectionDAG &DAG) const {
1526 EVT PtrVT = Op.getValueType();
1527 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1528 DebugLoc DL = GSDN->getDebugLoc();
1529 const GlobalValue *GV = GSDN->getGlobal();
1531 // 64-bit SVR4 ABI code is always position-independent.
1532 // The actual address of the GlobalValue is stored in the TOC.
1533 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1534 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1535 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1536 DAG.getRegister(PPC::X2, MVT::i64));
1539 unsigned MOHiFlag, MOLoFlag;
1540 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1543 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1545 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1547 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1549 // If the global reference is actually to a non-lazy-pointer, we have to do an
1550 // extra load to get the address of the global.
1551 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1552 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1553 false, false, false, 0);
1557 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1558 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1559 DebugLoc dl = Op.getDebugLoc();
1561 // If we're comparing for equality to zero, expose the fact that this is
1562 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1563 // fold the new nodes.
1564 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1565 if (C->isNullValue() && CC == ISD::SETEQ) {
1566 EVT VT = Op.getOperand(0).getValueType();
1567 SDValue Zext = Op.getOperand(0);
1568 if (VT.bitsLT(MVT::i32)) {
1570 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1572 unsigned Log2b = Log2_32(VT.getSizeInBits());
1573 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1574 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1575 DAG.getConstant(Log2b, MVT::i32));
1576 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1578 // Leave comparisons against 0 and -1 alone for now, since they're usually
1579 // optimized. FIXME: revisit this when we can custom lower all setcc
1581 if (C->isAllOnesValue() || C->isNullValue())
1585 // If we have an integer seteq/setne, turn it into a compare against zero
1586 // by xor'ing the rhs with the lhs, which is faster than setting a
1587 // condition register, reading it back out, and masking the correct bit. The
1588 // normal approach here uses sub to do this instead of xor. Using xor exposes
1589 // the result to other bit-twiddling opportunities.
1590 EVT LHSVT = Op.getOperand(0).getValueType();
1591 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1592 EVT VT = Op.getValueType();
1593 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1595 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1600 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1601 const PPCSubtarget &Subtarget) const {
1602 SDNode *Node = Op.getNode();
1603 EVT VT = Node->getValueType(0);
1604 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1605 SDValue InChain = Node->getOperand(0);
1606 SDValue VAListPtr = Node->getOperand(1);
1607 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1608 DebugLoc dl = Node->getDebugLoc();
1610 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1613 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1614 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1616 InChain = GprIndex.getValue(1);
1618 if (VT == MVT::i64) {
1619 // Check if GprIndex is even
1620 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1621 DAG.getConstant(1, MVT::i32));
1622 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1623 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1624 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1625 DAG.getConstant(1, MVT::i32));
1626 // Align GprIndex to be even if it isn't
1627 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1631 // fpr index is 1 byte after gpr
1632 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1633 DAG.getConstant(1, MVT::i32));
1636 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1637 FprPtr, MachinePointerInfo(SV), MVT::i8,
1639 InChain = FprIndex.getValue(1);
1641 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1642 DAG.getConstant(8, MVT::i32));
1644 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1645 DAG.getConstant(4, MVT::i32));
1648 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1649 MachinePointerInfo(), false, false,
1651 InChain = OverflowArea.getValue(1);
1653 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1654 MachinePointerInfo(), false, false,
1656 InChain = RegSaveArea.getValue(1);
1658 // select overflow_area if index > 8
1659 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1660 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1662 // adjustment constant gpr_index * 4/8
1663 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1664 VT.isInteger() ? GprIndex : FprIndex,
1665 DAG.getConstant(VT.isInteger() ? 4 : 8,
1668 // OurReg = RegSaveArea + RegConstant
1669 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1672 // Floating types are 32 bytes into RegSaveArea
1673 if (VT.isFloatingPoint())
1674 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1675 DAG.getConstant(32, MVT::i32));
1677 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1678 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1679 VT.isInteger() ? GprIndex : FprIndex,
1680 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1683 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1684 VT.isInteger() ? VAListPtr : FprPtr,
1685 MachinePointerInfo(SV),
1686 MVT::i8, false, false, 0);
1688 // determine if we should load from reg_save_area or overflow_area
1689 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1691 // increase overflow_area by 4/8 if gpr/fpr > 8
1692 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1693 DAG.getConstant(VT.isInteger() ? 4 : 8,
1696 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1699 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1701 MachinePointerInfo(),
1702 MVT::i32, false, false, 0);
1704 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1705 false, false, false, 0);
1708 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1709 SelectionDAG &DAG) const {
1710 return Op.getOperand(0);
1713 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1714 SelectionDAG &DAG) const {
1715 SDValue Chain = Op.getOperand(0);
1716 SDValue Trmp = Op.getOperand(1); // trampoline
1717 SDValue FPtr = Op.getOperand(2); // nested function
1718 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1719 DebugLoc dl = Op.getDebugLoc();
1721 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1722 bool isPPC64 = (PtrVT == MVT::i64);
1724 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1727 TargetLowering::ArgListTy Args;
1728 TargetLowering::ArgListEntry Entry;
1730 Entry.Ty = IntPtrTy;
1731 Entry.Node = Trmp; Args.push_back(Entry);
1733 // TrampSize == (isPPC64 ? 48 : 40);
1734 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1735 isPPC64 ? MVT::i64 : MVT::i32);
1736 Args.push_back(Entry);
1738 Entry.Node = FPtr; Args.push_back(Entry);
1739 Entry.Node = Nest; Args.push_back(Entry);
1741 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1742 TargetLowering::CallLoweringInfo CLI(Chain,
1743 Type::getVoidTy(*DAG.getContext()),
1744 false, false, false, false, 0,
1746 /*isTailCall=*/false,
1747 /*doesNotRet=*/false,
1748 /*isReturnValueUsed=*/true,
1749 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1751 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1753 return CallResult.second;
1756 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1757 const PPCSubtarget &Subtarget) const {
1758 MachineFunction &MF = DAG.getMachineFunction();
1759 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1761 DebugLoc dl = Op.getDebugLoc();
1763 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1764 // vastart just stores the address of the VarArgsFrameIndex slot into the
1765 // memory location argument.
1766 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1767 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1768 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1769 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1770 MachinePointerInfo(SV),
1774 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1775 // We suppose the given va_list is already allocated.
1778 // char gpr; /* index into the array of 8 GPRs
1779 // * stored in the register save area
1780 // * gpr=0 corresponds to r3,
1781 // * gpr=1 to r4, etc.
1783 // char fpr; /* index into the array of 8 FPRs
1784 // * stored in the register save area
1785 // * fpr=0 corresponds to f1,
1786 // * fpr=1 to f2, etc.
1788 // char *overflow_arg_area;
1789 // /* location on stack that holds
1790 // * the next overflow argument
1792 // char *reg_save_area;
1793 // /* where r3:r10 and f1:f8 (if saved)
1799 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1800 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1803 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1805 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1807 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1810 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1811 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1813 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1814 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1816 uint64_t FPROffset = 1;
1817 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1819 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1821 // Store first byte : number of int regs
1822 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1824 MachinePointerInfo(SV),
1825 MVT::i8, false, false, 0);
1826 uint64_t nextOffset = FPROffset;
1827 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1830 // Store second byte : number of float regs
1831 SDValue secondStore =
1832 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1833 MachinePointerInfo(SV, nextOffset), MVT::i8,
1835 nextOffset += StackOffset;
1836 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1838 // Store second word : arguments given on stack
1839 SDValue thirdStore =
1840 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1841 MachinePointerInfo(SV, nextOffset),
1843 nextOffset += FrameOffset;
1844 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1846 // Store third word : arguments given in registers
1847 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1848 MachinePointerInfo(SV, nextOffset),
1853 #include "PPCGenCallingConv.inc"
1855 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1856 CCValAssign::LocInfo &LocInfo,
1857 ISD::ArgFlagsTy &ArgFlags,
1862 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1864 CCValAssign::LocInfo &LocInfo,
1865 ISD::ArgFlagsTy &ArgFlags,
1867 static const uint16_t ArgRegs[] = {
1868 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1869 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1871 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1873 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1875 // Skip one register if the first unallocated register has an even register
1876 // number and there are still argument registers available which have not been
1877 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1878 // need to skip a register if RegNum is odd.
1879 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1880 State.AllocateReg(ArgRegs[RegNum]);
1883 // Always return false here, as this function only makes sure that the first
1884 // unallocated register has an odd register number and does not actually
1885 // allocate a register for the current argument.
1889 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1891 CCValAssign::LocInfo &LocInfo,
1892 ISD::ArgFlagsTy &ArgFlags,
1894 static const uint16_t ArgRegs[] = {
1895 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1899 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1901 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1903 // If there is only one Floating-point register left we need to put both f64
1904 // values of a split ppc_fp128 value on the stack.
1905 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1906 State.AllocateReg(ArgRegs[RegNum]);
1909 // Always return false here, as this function only makes sure that the two f64
1910 // values a ppc_fp128 value is split into are both passed in registers or both
1911 // passed on the stack and does not actually allocate a register for the
1912 // current argument.
1916 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1918 static const uint16_t *GetFPR() {
1919 static const uint16_t FPR[] = {
1920 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1921 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1927 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1929 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1930 unsigned PtrByteSize) {
1931 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1932 if (Flags.isByVal())
1933 ArgSize = Flags.getByValSize();
1934 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1940 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1941 CallingConv::ID CallConv, bool isVarArg,
1942 const SmallVectorImpl<ISD::InputArg>
1944 DebugLoc dl, SelectionDAG &DAG,
1945 SmallVectorImpl<SDValue> &InVals)
1947 if (PPCSubTarget.isSVR4ABI()) {
1948 if (PPCSubTarget.isPPC64())
1949 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1952 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1955 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1961 PPCTargetLowering::LowerFormalArguments_32SVR4(
1963 CallingConv::ID CallConv, bool isVarArg,
1964 const SmallVectorImpl<ISD::InputArg>
1966 DebugLoc dl, SelectionDAG &DAG,
1967 SmallVectorImpl<SDValue> &InVals) const {
1969 // 32-bit SVR4 ABI Stack Frame Layout:
1970 // +-----------------------------------+
1971 // +--> | Back chain |
1972 // | +-----------------------------------+
1973 // | | Floating-point register save area |
1974 // | +-----------------------------------+
1975 // | | General register save area |
1976 // | +-----------------------------------+
1977 // | | CR save word |
1978 // | +-----------------------------------+
1979 // | | VRSAVE save word |
1980 // | +-----------------------------------+
1981 // | | Alignment padding |
1982 // | +-----------------------------------+
1983 // | | Vector register save area |
1984 // | +-----------------------------------+
1985 // | | Local variable space |
1986 // | +-----------------------------------+
1987 // | | Parameter list area |
1988 // | +-----------------------------------+
1989 // | | LR save word |
1990 // | +-----------------------------------+
1991 // SP--> +--- | Back chain |
1992 // +-----------------------------------+
1995 // System V Application Binary Interface PowerPC Processor Supplement
1996 // AltiVec Technology Programming Interface Manual
1998 MachineFunction &MF = DAG.getMachineFunction();
1999 MachineFrameInfo *MFI = MF.getFrameInfo();
2000 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2002 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2003 // Potential tail calls could cause overwriting of argument stack slots.
2004 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2005 (CallConv == CallingConv::Fast));
2006 unsigned PtrByteSize = 4;
2008 // Assign locations to all of the incoming arguments.
2009 SmallVector<CCValAssign, 16> ArgLocs;
2010 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2011 getTargetMachine(), ArgLocs, *DAG.getContext());
2013 // Reserve space for the linkage area on the stack.
2014 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2016 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2018 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2019 CCValAssign &VA = ArgLocs[i];
2021 // Arguments stored in registers.
2022 if (VA.isRegLoc()) {
2023 const TargetRegisterClass *RC;
2024 EVT ValVT = VA.getValVT();
2026 switch (ValVT.getSimpleVT().SimpleTy) {
2028 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2030 RC = &PPC::GPRCRegClass;
2033 RC = &PPC::F4RCRegClass;
2036 RC = &PPC::F8RCRegClass;
2042 RC = &PPC::VRRCRegClass;
2046 // Transform the arguments stored in physical registers into virtual ones.
2047 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2048 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
2050 InVals.push_back(ArgValue);
2052 // Argument stored in memory.
2053 assert(VA.isMemLoc());
2055 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
2056 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2059 // Create load nodes to retrieve arguments from the stack.
2060 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2061 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2062 MachinePointerInfo(),
2063 false, false, false, 0));
2067 // Assign locations to all of the incoming aggregate by value arguments.
2068 // Aggregates passed by value are stored in the local variable space of the
2069 // caller's stack frame, right above the parameter list area.
2070 SmallVector<CCValAssign, 16> ByValArgLocs;
2071 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2072 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2074 // Reserve stack space for the allocations in CCInfo.
2075 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2077 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2079 // Area that is at least reserved in the caller of this function.
2080 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2082 // Set the size that is at least reserved in caller of this function. Tail
2083 // call optimized function's reserved stack space needs to be aligned so that
2084 // taking the difference between two stack areas will result in an aligned
2086 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2089 std::max(MinReservedArea,
2090 PPCFrameLowering::getMinCallFrameSize(false, false));
2092 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2093 getStackAlignment();
2094 unsigned AlignMask = TargetAlign-1;
2095 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2097 FI->setMinReservedArea(MinReservedArea);
2099 SmallVector<SDValue, 8> MemOps;
2101 // If the function takes variable number of arguments, make a frame index for
2102 // the start of the first vararg value... for expansion of llvm.va_start.
2104 static const uint16_t GPArgRegs[] = {
2105 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2106 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2108 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2110 static const uint16_t FPArgRegs[] = {
2111 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2114 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2116 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2118 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2121 // Make room for NumGPArgRegs and NumFPArgRegs.
2122 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2123 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2125 FuncInfo->setVarArgsStackOffset(
2126 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2127 CCInfo.getNextStackOffset(), true));
2129 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2130 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2132 // The fixed integer arguments of a variadic function are stored to the
2133 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2134 // the result of va_next.
2135 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2136 // Get an existing live-in vreg, or add a new one.
2137 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2139 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2141 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2142 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2143 MachinePointerInfo(), false, false, 0);
2144 MemOps.push_back(Store);
2145 // Increment the address by four for the next argument to store
2146 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2147 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2150 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2152 // The double arguments are stored to the VarArgsFrameIndex
2154 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2155 // Get an existing live-in vreg, or add a new one.
2156 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2158 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2160 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2161 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2162 MachinePointerInfo(), false, false, 0);
2163 MemOps.push_back(Store);
2164 // Increment the address by eight for the next argument to store
2165 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2167 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2171 if (!MemOps.empty())
2172 Chain = DAG.getNode(ISD::TokenFactor, dl,
2173 MVT::Other, &MemOps[0], MemOps.size());
2178 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2179 // value to MVT::i64 and then truncate to the correct register size.
2181 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2182 SelectionDAG &DAG, SDValue ArgVal,
2183 DebugLoc dl) const {
2185 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2186 DAG.getValueType(ObjectVT));
2187 else if (Flags.isZExt())
2188 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2189 DAG.getValueType(ObjectVT));
2191 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2194 // Set the size that is at least reserved in caller of this function. Tail
2195 // call optimized functions' reserved stack space needs to be aligned so that
2196 // taking the difference between two stack areas will result in an aligned
2199 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2200 unsigned nAltivecParamsAtEnd,
2201 unsigned MinReservedArea,
2202 bool isPPC64) const {
2203 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2204 // Add the Altivec parameters at the end, if needed.
2205 if (nAltivecParamsAtEnd) {
2206 MinReservedArea = ((MinReservedArea+15)/16)*16;
2207 MinReservedArea += 16*nAltivecParamsAtEnd;
2210 std::max(MinReservedArea,
2211 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2212 unsigned TargetAlign
2213 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2214 getStackAlignment();
2215 unsigned AlignMask = TargetAlign-1;
2216 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2217 FI->setMinReservedArea(MinReservedArea);
2221 PPCTargetLowering::LowerFormalArguments_64SVR4(
2223 CallingConv::ID CallConv, bool isVarArg,
2224 const SmallVectorImpl<ISD::InputArg>
2226 DebugLoc dl, SelectionDAG &DAG,
2227 SmallVectorImpl<SDValue> &InVals) const {
2228 // TODO: add description of PPC stack frame format, or at least some docs.
2230 MachineFunction &MF = DAG.getMachineFunction();
2231 MachineFrameInfo *MFI = MF.getFrameInfo();
2232 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2234 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2235 // Potential tail calls could cause overwriting of argument stack slots.
2236 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2237 (CallConv == CallingConv::Fast));
2238 unsigned PtrByteSize = 8;
2240 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2241 // Area that is at least reserved in caller of this function.
2242 unsigned MinReservedArea = ArgOffset;
2244 static const uint16_t GPR[] = {
2245 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2246 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2249 static const uint16_t *FPR = GetFPR();
2251 static const uint16_t VR[] = {
2252 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2253 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2256 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2257 const unsigned Num_FPR_Regs = 13;
2258 const unsigned Num_VR_Regs = array_lengthof(VR);
2260 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2262 // Add DAG nodes to load the arguments or copy them out of registers. On
2263 // entry to a function on PPC, the arguments start after the linkage area,
2264 // although the first ones are often in registers.
2266 SmallVector<SDValue, 8> MemOps;
2267 unsigned nAltivecParamsAtEnd = 0;
2268 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2269 unsigned CurArgIdx = 0;
2270 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2272 bool needsLoad = false;
2273 EVT ObjectVT = Ins[ArgNo].VT;
2274 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2275 unsigned ArgSize = ObjSize;
2276 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2277 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2278 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2280 unsigned CurArgOffset = ArgOffset;
2282 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2283 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2284 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2286 MinReservedArea = ((MinReservedArea+15)/16)*16;
2287 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2291 nAltivecParamsAtEnd++;
2293 // Calculate min reserved area.
2294 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2298 // FIXME the codegen can be much improved in some cases.
2299 // We do not have to keep everything in memory.
2300 if (Flags.isByVal()) {
2301 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2302 ObjSize = Flags.getByValSize();
2303 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2304 // Empty aggregate parameters do not take up registers. Examples:
2308 // etc. However, we have to provide a place-holder in InVals, so
2309 // pretend we have an 8-byte item at the current address for that
2312 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2313 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2314 InVals.push_back(FIN);
2317 // All aggregates smaller than 8 bytes must be passed right-justified.
2318 if (ObjSize < PtrByteSize)
2319 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2320 // The value of the object is its address.
2321 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2322 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2323 InVals.push_back(FIN);
2326 if (GPR_idx != Num_GPR_Regs) {
2327 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2328 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2331 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2332 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2333 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2334 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2335 MachinePointerInfo(FuncArg, CurArgOffset),
2336 ObjType, false, false, 0);
2338 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2339 // store the whole register as-is to the parameter save area
2340 // slot. The address of the parameter was already calculated
2341 // above (InVals.push_back(FIN)) to be the right-justified
2342 // offset within the slot. For this store, we need a new
2343 // frame index that points at the beginning of the slot.
2344 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2345 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2346 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2347 MachinePointerInfo(FuncArg, ArgOffset),
2351 MemOps.push_back(Store);
2354 // Whether we copied from a register or not, advance the offset
2355 // into the parameter save area by a full doubleword.
2356 ArgOffset += PtrByteSize;
2360 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2361 // Store whatever pieces of the object are in registers
2362 // to memory. ArgOffset will be the address of the beginning
2364 if (GPR_idx != Num_GPR_Regs) {
2366 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2367 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2368 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2369 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2370 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2371 MachinePointerInfo(FuncArg, ArgOffset),
2373 MemOps.push_back(Store);
2375 ArgOffset += PtrByteSize;
2377 ArgOffset += ArgSize - j;
2384 switch (ObjectVT.getSimpleVT().SimpleTy) {
2385 default: llvm_unreachable("Unhandled argument type!");
2388 if (GPR_idx != Num_GPR_Regs) {
2389 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2390 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2392 if (ObjectVT == MVT::i32)
2393 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2394 // value to MVT::i64 and then truncate to the correct register size.
2395 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2400 ArgSize = PtrByteSize;
2407 // Every 8 bytes of argument space consumes one of the GPRs available for
2408 // argument passing.
2409 if (GPR_idx != Num_GPR_Regs) {
2412 if (FPR_idx != Num_FPR_Regs) {
2415 if (ObjectVT == MVT::f32)
2416 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2418 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2420 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2424 ArgSize = PtrByteSize;
2433 // Note that vector arguments in registers don't reserve stack space,
2434 // except in varargs functions.
2435 if (VR_idx != Num_VR_Regs) {
2436 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2437 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2439 while ((ArgOffset % 16) != 0) {
2440 ArgOffset += PtrByteSize;
2441 if (GPR_idx != Num_GPR_Regs)
2445 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2449 // Vectors are aligned.
2450 ArgOffset = ((ArgOffset+15)/16)*16;
2451 CurArgOffset = ArgOffset;
2458 // We need to load the argument to a virtual register if we determined
2459 // above that we ran out of physical registers of the appropriate type.
2461 int FI = MFI->CreateFixedObject(ObjSize,
2462 CurArgOffset + (ArgSize - ObjSize),
2464 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2465 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2466 false, false, false, 0);
2469 InVals.push_back(ArgVal);
2472 // Set the size that is at least reserved in caller of this function. Tail
2473 // call optimized functions' reserved stack space needs to be aligned so that
2474 // taking the difference between two stack areas will result in an aligned
2476 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2478 // If the function takes variable number of arguments, make a frame index for
2479 // the start of the first vararg value... for expansion of llvm.va_start.
2481 int Depth = ArgOffset;
2483 FuncInfo->setVarArgsFrameIndex(
2484 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2485 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2487 // If this function is vararg, store any remaining integer argument regs
2488 // to their spots on the stack so that they may be loaded by deferencing the
2489 // result of va_next.
2490 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2491 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2492 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2493 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2494 MachinePointerInfo(), false, false, 0);
2495 MemOps.push_back(Store);
2496 // Increment the address by four for the next argument to store
2497 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2498 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2502 if (!MemOps.empty())
2503 Chain = DAG.getNode(ISD::TokenFactor, dl,
2504 MVT::Other, &MemOps[0], MemOps.size());
2510 PPCTargetLowering::LowerFormalArguments_Darwin(
2512 CallingConv::ID CallConv, bool isVarArg,
2513 const SmallVectorImpl<ISD::InputArg>
2515 DebugLoc dl, SelectionDAG &DAG,
2516 SmallVectorImpl<SDValue> &InVals) const {
2517 // TODO: add description of PPC stack frame format, or at least some docs.
2519 MachineFunction &MF = DAG.getMachineFunction();
2520 MachineFrameInfo *MFI = MF.getFrameInfo();
2521 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2523 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2524 bool isPPC64 = PtrVT == MVT::i64;
2525 // Potential tail calls could cause overwriting of argument stack slots.
2526 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2527 (CallConv == CallingConv::Fast));
2528 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2530 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2531 // Area that is at least reserved in caller of this function.
2532 unsigned MinReservedArea = ArgOffset;
2534 static const uint16_t GPR_32[] = { // 32-bit registers.
2535 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2536 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2538 static const uint16_t GPR_64[] = { // 64-bit registers.
2539 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2540 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2543 static const uint16_t *FPR = GetFPR();
2545 static const uint16_t VR[] = {
2546 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2547 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2550 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2551 const unsigned Num_FPR_Regs = 13;
2552 const unsigned Num_VR_Regs = array_lengthof( VR);
2554 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2556 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2558 // In 32-bit non-varargs functions, the stack space for vectors is after the
2559 // stack space for non-vectors. We do not use this space unless we have
2560 // too many vectors to fit in registers, something that only occurs in
2561 // constructed examples:), but we have to walk the arglist to figure
2562 // that out...for the pathological case, compute VecArgOffset as the
2563 // start of the vector parameter area. Computing VecArgOffset is the
2564 // entire point of the following loop.
2565 unsigned VecArgOffset = ArgOffset;
2566 if (!isVarArg && !isPPC64) {
2567 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2569 EVT ObjectVT = Ins[ArgNo].VT;
2570 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2572 if (Flags.isByVal()) {
2573 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2574 unsigned ObjSize = Flags.getByValSize();
2576 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2577 VecArgOffset += ArgSize;
2581 switch(ObjectVT.getSimpleVT().SimpleTy) {
2582 default: llvm_unreachable("Unhandled argument type!");
2587 case MVT::i64: // PPC64
2589 // FIXME: We are guaranteed to be !isPPC64 at this point.
2590 // Does MVT::i64 apply?
2597 // Nothing to do, we're only looking at Nonvector args here.
2602 // We've found where the vector parameter area in memory is. Skip the
2603 // first 12 parameters; these don't use that memory.
2604 VecArgOffset = ((VecArgOffset+15)/16)*16;
2605 VecArgOffset += 12*16;
2607 // Add DAG nodes to load the arguments or copy them out of registers. On
2608 // entry to a function on PPC, the arguments start after the linkage area,
2609 // although the first ones are often in registers.
2611 SmallVector<SDValue, 8> MemOps;
2612 unsigned nAltivecParamsAtEnd = 0;
2613 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2614 unsigned CurArgIdx = 0;
2615 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2617 bool needsLoad = false;
2618 EVT ObjectVT = Ins[ArgNo].VT;
2619 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2620 unsigned ArgSize = ObjSize;
2621 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2622 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2623 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2625 unsigned CurArgOffset = ArgOffset;
2627 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2628 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2629 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2630 if (isVarArg || isPPC64) {
2631 MinReservedArea = ((MinReservedArea+15)/16)*16;
2632 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2635 } else nAltivecParamsAtEnd++;
2637 // Calculate min reserved area.
2638 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2642 // FIXME the codegen can be much improved in some cases.
2643 // We do not have to keep everything in memory.
2644 if (Flags.isByVal()) {
2645 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2646 ObjSize = Flags.getByValSize();
2647 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2648 // Objects of size 1 and 2 are right justified, everything else is
2649 // left justified. This means the memory address is adjusted forwards.
2650 if (ObjSize==1 || ObjSize==2) {
2651 CurArgOffset = CurArgOffset + (4 - ObjSize);
2653 // The value of the object is its address.
2654 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2655 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2656 InVals.push_back(FIN);
2657 if (ObjSize==1 || ObjSize==2) {
2658 if (GPR_idx != Num_GPR_Regs) {
2661 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2663 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2664 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2665 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2666 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2667 MachinePointerInfo(FuncArg,
2669 ObjType, false, false, 0);
2670 MemOps.push_back(Store);
2674 ArgOffset += PtrByteSize;
2678 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2679 // Store whatever pieces of the object are in registers
2680 // to memory. ArgOffset will be the address of the beginning
2682 if (GPR_idx != Num_GPR_Regs) {
2685 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2687 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2688 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2689 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2690 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2691 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2692 MachinePointerInfo(FuncArg, ArgOffset),
2694 MemOps.push_back(Store);
2696 ArgOffset += PtrByteSize;
2698 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2705 switch (ObjectVT.getSimpleVT().SimpleTy) {
2706 default: llvm_unreachable("Unhandled argument type!");
2709 if (GPR_idx != Num_GPR_Regs) {
2710 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2711 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2715 ArgSize = PtrByteSize;
2717 // All int arguments reserve stack space in the Darwin ABI.
2718 ArgOffset += PtrByteSize;
2722 case MVT::i64: // PPC64
2723 if (GPR_idx != Num_GPR_Regs) {
2724 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2725 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2727 if (ObjectVT == MVT::i32)
2728 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2729 // value to MVT::i64 and then truncate to the correct register size.
2730 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2735 ArgSize = PtrByteSize;
2737 // All int arguments reserve stack space in the Darwin ABI.
2743 // Every 4 bytes of argument space consumes one of the GPRs available for
2744 // argument passing.
2745 if (GPR_idx != Num_GPR_Regs) {
2747 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2750 if (FPR_idx != Num_FPR_Regs) {
2753 if (ObjectVT == MVT::f32)
2754 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2756 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2758 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2764 // All FP arguments reserve stack space in the Darwin ABI.
2765 ArgOffset += isPPC64 ? 8 : ObjSize;
2771 // Note that vector arguments in registers don't reserve stack space,
2772 // except in varargs functions.
2773 if (VR_idx != Num_VR_Regs) {
2774 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2775 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2777 while ((ArgOffset % 16) != 0) {
2778 ArgOffset += PtrByteSize;
2779 if (GPR_idx != Num_GPR_Regs)
2783 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2787 if (!isVarArg && !isPPC64) {
2788 // Vectors go after all the nonvectors.
2789 CurArgOffset = VecArgOffset;
2792 // Vectors are aligned.
2793 ArgOffset = ((ArgOffset+15)/16)*16;
2794 CurArgOffset = ArgOffset;
2802 // We need to load the argument to a virtual register if we determined above
2803 // that we ran out of physical registers of the appropriate type.
2805 int FI = MFI->CreateFixedObject(ObjSize,
2806 CurArgOffset + (ArgSize - ObjSize),
2808 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2809 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2810 false, false, false, 0);
2813 InVals.push_back(ArgVal);
2816 // Set the size that is at least reserved in caller of this function. Tail
2817 // call optimized functions' reserved stack space needs to be aligned so that
2818 // taking the difference between two stack areas will result in an aligned
2820 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2822 // If the function takes variable number of arguments, make a frame index for
2823 // the start of the first vararg value... for expansion of llvm.va_start.
2825 int Depth = ArgOffset;
2827 FuncInfo->setVarArgsFrameIndex(
2828 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2830 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2832 // If this function is vararg, store any remaining integer argument regs
2833 // to their spots on the stack so that they may be loaded by deferencing the
2834 // result of va_next.
2835 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2839 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2841 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2843 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2844 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2845 MachinePointerInfo(), false, false, 0);
2846 MemOps.push_back(Store);
2847 // Increment the address by four for the next argument to store
2848 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2849 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2853 if (!MemOps.empty())
2854 Chain = DAG.getNode(ISD::TokenFactor, dl,
2855 MVT::Other, &MemOps[0], MemOps.size());
2860 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2861 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2863 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2867 const SmallVectorImpl<ISD::OutputArg>
2869 const SmallVectorImpl<SDValue> &OutVals,
2870 unsigned &nAltivecParamsAtEnd) {
2871 // Count how many bytes are to be pushed on the stack, including the linkage
2872 // area, and parameter passing area. We start with 24/48 bytes, which is
2873 // prereserved space for [SP][CR][LR][3 x unused].
2874 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2875 unsigned NumOps = Outs.size();
2876 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2878 // Add up all the space actually used.
2879 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2880 // they all go in registers, but we must reserve stack space for them for
2881 // possible use by the caller. In varargs or 64-bit calls, parameters are
2882 // assigned stack space in order, with padding so Altivec parameters are
2884 nAltivecParamsAtEnd = 0;
2885 for (unsigned i = 0; i != NumOps; ++i) {
2886 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2887 EVT ArgVT = Outs[i].VT;
2888 // Varargs Altivec parameters are padded to a 16 byte boundary.
2889 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2890 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2891 if (!isVarArg && !isPPC64) {
2892 // Non-varargs Altivec parameters go after all the non-Altivec
2893 // parameters; handle those later so we know how much padding we need.
2894 nAltivecParamsAtEnd++;
2897 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2898 NumBytes = ((NumBytes+15)/16)*16;
2900 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2903 // Allow for Altivec parameters at the end, if needed.
2904 if (nAltivecParamsAtEnd) {
2905 NumBytes = ((NumBytes+15)/16)*16;
2906 NumBytes += 16*nAltivecParamsAtEnd;
2909 // The prolog code of the callee may store up to 8 GPR argument registers to
2910 // the stack, allowing va_start to index over them in memory if its varargs.
2911 // Because we cannot tell if this is needed on the caller side, we have to
2912 // conservatively assume that it is needed. As such, make sure we have at
2913 // least enough stack space for the caller to store the 8 GPRs.
2914 NumBytes = std::max(NumBytes,
2915 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2917 // Tail call needs the stack to be aligned.
2918 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2919 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2920 getFrameLowering()->getStackAlignment();
2921 unsigned AlignMask = TargetAlign-1;
2922 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2928 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2929 /// adjusted to accommodate the arguments for the tailcall.
2930 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2931 unsigned ParamSize) {
2933 if (!isTailCall) return 0;
2935 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2936 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2937 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2938 // Remember only if the new adjustement is bigger.
2939 if (SPDiff < FI->getTailCallSPDelta())
2940 FI->setTailCallSPDelta(SPDiff);
2945 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2946 /// for tail call optimization. Targets which want to do tail call
2947 /// optimization should implement this function.
2949 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2950 CallingConv::ID CalleeCC,
2952 const SmallVectorImpl<ISD::InputArg> &Ins,
2953 SelectionDAG& DAG) const {
2954 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2957 // Variable argument functions are not supported.
2961 MachineFunction &MF = DAG.getMachineFunction();
2962 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2963 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2964 // Functions containing by val parameters are not supported.
2965 for (unsigned i = 0; i != Ins.size(); i++) {
2966 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2967 if (Flags.isByVal()) return false;
2970 // Non PIC/GOT tail calls are supported.
2971 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2974 // At the moment we can only do local tail calls (in same module, hidden
2975 // or protected) if we are generating PIC.
2976 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2977 return G->getGlobal()->hasHiddenVisibility()
2978 || G->getGlobal()->hasProtectedVisibility();
2984 /// isCallCompatibleAddress - Return the immediate to use if the specified
2985 /// 32-bit value is representable in the immediate field of a BxA instruction.
2986 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2987 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2990 int Addr = C->getZExtValue();
2991 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2992 SignExtend32<26>(Addr) != Addr)
2993 return 0; // Top 6 bits have to be sext of immediate.
2995 return DAG.getConstant((int)C->getZExtValue() >> 2,
2996 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3001 struct TailCallArgumentInfo {
3006 TailCallArgumentInfo() : FrameIdx(0) {}
3011 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3013 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3015 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
3016 SmallVector<SDValue, 8> &MemOpChains,
3018 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3019 SDValue Arg = TailCallArgs[i].Arg;
3020 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3021 int FI = TailCallArgs[i].FrameIdx;
3022 // Store relative to framepointer.
3023 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3024 MachinePointerInfo::getFixedStack(FI),
3029 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3030 /// the appropriate stack slot for the tail call optimized function call.
3031 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3032 MachineFunction &MF,
3041 // Calculate the new stack slot for the return address.
3042 int SlotSize = isPPC64 ? 8 : 4;
3043 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3045 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3046 NewRetAddrLoc, true);
3047 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3048 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3049 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3050 MachinePointerInfo::getFixedStack(NewRetAddr),
3053 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3054 // slot as the FP is never overwritten.
3057 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3058 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3060 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3061 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3062 MachinePointerInfo::getFixedStack(NewFPIdx),
3069 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3070 /// the position of the argument.
3072 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3073 SDValue Arg, int SPDiff, unsigned ArgOffset,
3074 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
3075 int Offset = ArgOffset + SPDiff;
3076 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3077 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3078 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3079 SDValue FIN = DAG.getFrameIndex(FI, VT);
3080 TailCallArgumentInfo Info;
3082 Info.FrameIdxOp = FIN;
3084 TailCallArguments.push_back(Info);
3087 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3088 /// stack slot. Returns the chain as result and the loaded frame pointers in
3089 /// LROpOut/FPOpout. Used when tail calling.
3090 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3096 DebugLoc dl) const {
3098 // Load the LR and FP stack slot for later adjusting.
3099 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3100 LROpOut = getReturnAddrFrameIndex(DAG);
3101 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3102 false, false, false, 0);
3103 Chain = SDValue(LROpOut.getNode(), 1);
3105 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3106 // slot as the FP is never overwritten.
3108 FPOpOut = getFramePointerFrameIndex(DAG);
3109 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3110 false, false, false, 0);
3111 Chain = SDValue(FPOpOut.getNode(), 1);
3117 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3118 /// by "Src" to address "Dst" of size "Size". Alignment information is
3119 /// specified by the specific parameter attribute. The copy will be passed as
3120 /// a byval function parameter.
3121 /// Sometimes what we are copying is the end of a larger object, the part that
3122 /// does not fit in registers.
3124 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3125 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3127 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3128 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3129 false, false, MachinePointerInfo(0),
3130 MachinePointerInfo(0));
3133 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3136 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3137 SDValue Arg, SDValue PtrOff, int SPDiff,
3138 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3139 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3140 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3142 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3147 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3149 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3150 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3151 DAG.getConstant(ArgOffset, PtrVT));
3153 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3154 MachinePointerInfo(), false, false, 0));
3155 // Calculate and remember argument location.
3156 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3161 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3162 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3163 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3164 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3165 MachineFunction &MF = DAG.getMachineFunction();
3167 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3168 // might overwrite each other in case of tail call optimization.
3169 SmallVector<SDValue, 8> MemOpChains2;
3170 // Do not flag preceding copytoreg stuff together with the following stuff.
3172 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3174 if (!MemOpChains2.empty())
3175 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3176 &MemOpChains2[0], MemOpChains2.size());
3178 // Store the return address to the appropriate stack slot.
3179 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3180 isPPC64, isDarwinABI, dl);
3182 // Emit callseq_end just before tailcall node.
3183 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3184 DAG.getIntPtrConstant(0, true), InFlag);
3185 InFlag = Chain.getValue(1);
3189 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3190 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3191 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3192 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3193 const PPCSubtarget &PPCSubTarget) {
3195 bool isPPC64 = PPCSubTarget.isPPC64();
3196 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3198 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3199 NodeTys.push_back(MVT::Other); // Returns a chain
3200 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3202 unsigned CallOpc = PPCISD::CALL;
3204 bool needIndirectCall = true;
3205 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3206 // If this is an absolute destination address, use the munged value.
3207 Callee = SDValue(Dest, 0);
3208 needIndirectCall = false;
3211 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3212 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3213 // Use indirect calls for ALL functions calls in JIT mode, since the
3214 // far-call stubs may be outside relocation limits for a BL instruction.
3215 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3216 unsigned OpFlags = 0;
3217 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3218 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3219 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3220 (G->getGlobal()->isDeclaration() ||
3221 G->getGlobal()->isWeakForLinker())) {
3222 // PC-relative references to external symbols should go through $stub,
3223 // unless we're building with the leopard linker or later, which
3224 // automatically synthesizes these stubs.
3225 OpFlags = PPCII::MO_DARWIN_STUB;
3228 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3229 // every direct call is) turn it into a TargetGlobalAddress /
3230 // TargetExternalSymbol node so that legalize doesn't hack it.
3231 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3232 Callee.getValueType(),
3234 needIndirectCall = false;
3238 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3239 unsigned char OpFlags = 0;
3241 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3242 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3243 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3244 // PC-relative references to external symbols should go through $stub,
3245 // unless we're building with the leopard linker or later, which
3246 // automatically synthesizes these stubs.
3247 OpFlags = PPCII::MO_DARWIN_STUB;
3250 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3252 needIndirectCall = false;
3255 if (needIndirectCall) {
3256 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3257 // to do the call, we can't use PPCISD::CALL.
3258 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3260 if (isSVR4ABI && isPPC64) {
3261 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3262 // entry point, but to the function descriptor (the function entry point
3263 // address is part of the function descriptor though).
3264 // The function descriptor is a three doubleword structure with the
3265 // following fields: function entry point, TOC base address and
3266 // environment pointer.
3267 // Thus for a call through a function pointer, the following actions need
3269 // 1. Save the TOC of the caller in the TOC save area of its stack
3270 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3271 // 2. Load the address of the function entry point from the function
3273 // 3. Load the TOC of the callee from the function descriptor into r2.
3274 // 4. Load the environment pointer from the function descriptor into
3276 // 5. Branch to the function entry point address.
3277 // 6. On return of the callee, the TOC of the caller needs to be
3278 // restored (this is done in FinishCall()).
3280 // All those operations are flagged together to ensure that no other
3281 // operations can be scheduled in between. E.g. without flagging the
3282 // operations together, a TOC access in the caller could be scheduled
3283 // between the load of the callee TOC and the branch to the callee, which
3284 // results in the TOC access going through the TOC of the callee instead
3285 // of going through the TOC of the caller, which leads to incorrect code.
3287 // Load the address of the function entry point from the function
3289 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3290 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3291 InFlag.getNode() ? 3 : 2);
3292 Chain = LoadFuncPtr.getValue(1);
3293 InFlag = LoadFuncPtr.getValue(2);
3295 // Load environment pointer into r11.
3296 // Offset of the environment pointer within the function descriptor.
3297 SDValue PtrOff = DAG.getIntPtrConstant(16);
3299 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3300 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3302 Chain = LoadEnvPtr.getValue(1);
3303 InFlag = LoadEnvPtr.getValue(2);
3305 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3307 Chain = EnvVal.getValue(0);
3308 InFlag = EnvVal.getValue(1);
3310 // Load TOC of the callee into r2. We are using a target-specific load
3311 // with r2 hard coded, because the result of a target-independent load
3312 // would never go directly into r2, since r2 is a reserved register (which
3313 // prevents the register allocator from allocating it), resulting in an
3314 // additional register being allocated and an unnecessary move instruction
3316 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3317 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3319 Chain = LoadTOCPtr.getValue(0);
3320 InFlag = LoadTOCPtr.getValue(1);
3322 MTCTROps[0] = Chain;
3323 MTCTROps[1] = LoadFuncPtr;
3324 MTCTROps[2] = InFlag;
3327 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3328 2 + (InFlag.getNode() != 0));
3329 InFlag = Chain.getValue(1);
3332 NodeTys.push_back(MVT::Other);
3333 NodeTys.push_back(MVT::Glue);
3334 Ops.push_back(Chain);
3335 CallOpc = PPCISD::BCTRL;
3337 // Add use of X11 (holding environment pointer)
3338 if (isSVR4ABI && isPPC64)
3339 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3340 // Add CTR register as callee so a bctr can be emitted later.
3342 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3345 // If this is a direct call, pass the chain and the callee.
3346 if (Callee.getNode()) {
3347 Ops.push_back(Chain);
3348 Ops.push_back(Callee);
3350 // If this is a tail call add stack pointer delta.
3352 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3354 // Add argument registers to the end of the list so that they are known live
3356 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3357 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3358 RegsToPass[i].second.getValueType()));
3364 bool isLocalCall(const SDValue &Callee)
3366 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3367 return !G->getGlobal()->isDeclaration() &&
3368 !G->getGlobal()->isWeakForLinker();
3373 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3374 CallingConv::ID CallConv, bool isVarArg,
3375 const SmallVectorImpl<ISD::InputArg> &Ins,
3376 DebugLoc dl, SelectionDAG &DAG,
3377 SmallVectorImpl<SDValue> &InVals) const {
3379 SmallVector<CCValAssign, 16> RVLocs;
3380 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3381 getTargetMachine(), RVLocs, *DAG.getContext());
3382 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3384 // Copy all of the result registers out of their specified physreg.
3385 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3386 CCValAssign &VA = RVLocs[i];
3387 assert(VA.isRegLoc() && "Can only return in registers!");
3389 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3390 VA.getLocReg(), VA.getLocVT(), InFlag);
3391 Chain = Val.getValue(1);
3392 InFlag = Val.getValue(2);
3394 switch (VA.getLocInfo()) {
3395 default: llvm_unreachable("Unknown loc info!");
3396 case CCValAssign::Full: break;
3397 case CCValAssign::AExt:
3398 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3400 case CCValAssign::ZExt:
3401 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3402 DAG.getValueType(VA.getValVT()));
3403 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3405 case CCValAssign::SExt:
3406 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3407 DAG.getValueType(VA.getValVT()));
3408 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3412 InVals.push_back(Val);
3419 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3420 bool isTailCall, bool isVarArg,
3422 SmallVector<std::pair<unsigned, SDValue>, 8>
3424 SDValue InFlag, SDValue Chain,
3426 int SPDiff, unsigned NumBytes,
3427 const SmallVectorImpl<ISD::InputArg> &Ins,
3428 SmallVectorImpl<SDValue> &InVals) const {
3429 std::vector<EVT> NodeTys;
3430 SmallVector<SDValue, 8> Ops;
3431 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3432 isTailCall, RegsToPass, Ops, NodeTys,
3435 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3436 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3437 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3439 // When performing tail call optimization the callee pops its arguments off
3440 // the stack. Account for this here so these bytes can be pushed back on in
3441 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3442 int BytesCalleePops =
3443 (CallConv == CallingConv::Fast &&
3444 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3446 // Add a register mask operand representing the call-preserved registers.
3447 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3448 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3449 assert(Mask && "Missing call preserved mask for calling convention");
3450 Ops.push_back(DAG.getRegisterMask(Mask));
3452 if (InFlag.getNode())
3453 Ops.push_back(InFlag);
3457 assert(((Callee.getOpcode() == ISD::Register &&
3458 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3459 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3460 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3461 isa<ConstantSDNode>(Callee)) &&
3462 "Expecting an global address, external symbol, absolute value or register");
3464 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3467 // Add a NOP immediately after the branch instruction when using the 64-bit
3468 // SVR4 ABI. At link time, if caller and callee are in a different module and
3469 // thus have a different TOC, the call will be replaced with a call to a stub
3470 // function which saves the current TOC, loads the TOC of the callee and
3471 // branches to the callee. The NOP will be replaced with a load instruction
3472 // which restores the TOC of the caller from the TOC save slot of the current
3473 // stack frame. If caller and callee belong to the same module (and have the
3474 // same TOC), the NOP will remain unchanged.
3476 bool needsTOCRestore = false;
3477 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3478 if (CallOpc == PPCISD::BCTRL) {
3479 // This is a call through a function pointer.
3480 // Restore the caller TOC from the save area into R2.
3481 // See PrepareCall() for more information about calls through function
3482 // pointers in the 64-bit SVR4 ABI.
3483 // We are using a target-specific load with r2 hard coded, because the
3484 // result of a target-independent load would never go directly into r2,
3485 // since r2 is a reserved register (which prevents the register allocator
3486 // from allocating it), resulting in an additional register being
3487 // allocated and an unnecessary move instruction being generated.
3488 needsTOCRestore = true;
3489 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3490 // Otherwise insert NOP for non-local calls.
3491 CallOpc = PPCISD::CALL_NOP;
3495 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3496 InFlag = Chain.getValue(1);
3498 if (needsTOCRestore) {
3499 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3500 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3501 InFlag = Chain.getValue(1);
3504 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3505 DAG.getIntPtrConstant(BytesCalleePops, true),
3508 InFlag = Chain.getValue(1);
3510 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3511 Ins, dl, DAG, InVals);
3515 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3516 SmallVectorImpl<SDValue> &InVals) const {
3517 SelectionDAG &DAG = CLI.DAG;
3518 DebugLoc &dl = CLI.DL;
3519 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3520 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3521 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3522 SDValue Chain = CLI.Chain;
3523 SDValue Callee = CLI.Callee;
3524 bool &isTailCall = CLI.IsTailCall;
3525 CallingConv::ID CallConv = CLI.CallConv;
3526 bool isVarArg = CLI.IsVarArg;
3529 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3532 if (PPCSubTarget.isSVR4ABI()) {
3533 if (PPCSubTarget.isPPC64())
3534 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3535 isTailCall, Outs, OutVals, Ins,
3538 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3539 isTailCall, Outs, OutVals, Ins,
3543 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3544 isTailCall, Outs, OutVals, Ins,
3549 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3550 CallingConv::ID CallConv, bool isVarArg,
3552 const SmallVectorImpl<ISD::OutputArg> &Outs,
3553 const SmallVectorImpl<SDValue> &OutVals,
3554 const SmallVectorImpl<ISD::InputArg> &Ins,
3555 DebugLoc dl, SelectionDAG &DAG,
3556 SmallVectorImpl<SDValue> &InVals) const {
3557 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3558 // of the 32-bit SVR4 ABI stack frame layout.
3560 assert((CallConv == CallingConv::C ||
3561 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3563 unsigned PtrByteSize = 4;
3565 MachineFunction &MF = DAG.getMachineFunction();
3567 // Mark this function as potentially containing a function that contains a
3568 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3569 // and restoring the callers stack pointer in this functions epilog. This is
3570 // done because by tail calling the called function might overwrite the value
3571 // in this function's (MF) stack pointer stack slot 0(SP).
3572 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3573 CallConv == CallingConv::Fast)
3574 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3576 // Count how many bytes are to be pushed on the stack, including the linkage
3577 // area, parameter list area and the part of the local variable space which
3578 // contains copies of aggregates which are passed by value.
3580 // Assign locations to all of the outgoing arguments.
3581 SmallVector<CCValAssign, 16> ArgLocs;
3582 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3583 getTargetMachine(), ArgLocs, *DAG.getContext());
3585 // Reserve space for the linkage area on the stack.
3586 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3589 // Handle fixed and variable vector arguments differently.
3590 // Fixed vector arguments go into registers as long as registers are
3591 // available. Variable vector arguments always go into memory.
3592 unsigned NumArgs = Outs.size();
3594 for (unsigned i = 0; i != NumArgs; ++i) {
3595 MVT ArgVT = Outs[i].VT;
3596 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3599 if (Outs[i].IsFixed) {
3600 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3603 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3609 errs() << "Call operand #" << i << " has unhandled type "
3610 << EVT(ArgVT).getEVTString() << "\n";
3612 llvm_unreachable(0);
3616 // All arguments are treated the same.
3617 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3620 // Assign locations to all of the outgoing aggregate by value arguments.
3621 SmallVector<CCValAssign, 16> ByValArgLocs;
3622 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3623 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3625 // Reserve stack space for the allocations in CCInfo.
3626 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3628 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3630 // Size of the linkage area, parameter list area and the part of the local
3631 // space variable where copies of aggregates which are passed by value are
3633 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3635 // Calculate by how many bytes the stack has to be adjusted in case of tail
3636 // call optimization.
3637 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3639 // Adjust the stack pointer for the new arguments...
3640 // These operations are automatically eliminated by the prolog/epilog pass
3641 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3642 SDValue CallSeqStart = Chain;
3644 // Load the return address and frame pointer so it can be moved somewhere else
3647 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3650 // Set up a copy of the stack pointer for use loading and storing any
3651 // arguments that may not fit in the registers available for argument
3653 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3655 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3656 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3657 SmallVector<SDValue, 8> MemOpChains;
3659 bool seenFloatArg = false;
3660 // Walk the register/memloc assignments, inserting copies/loads.
3661 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3664 CCValAssign &VA = ArgLocs[i];
3665 SDValue Arg = OutVals[i];
3666 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3668 if (Flags.isByVal()) {
3669 // Argument is an aggregate which is passed by value, thus we need to
3670 // create a copy of it in the local variable space of the current stack
3671 // frame (which is the stack frame of the caller) and pass the address of
3672 // this copy to the callee.
3673 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3674 CCValAssign &ByValVA = ByValArgLocs[j++];
3675 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3677 // Memory reserved in the local variable space of the callers stack frame.
3678 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3680 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3681 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3683 // Create a copy of the argument in the local area of the current
3685 SDValue MemcpyCall =
3686 CreateCopyOfByValArgument(Arg, PtrOff,
3687 CallSeqStart.getNode()->getOperand(0),
3690 // This must go outside the CALLSEQ_START..END.
3691 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3692 CallSeqStart.getNode()->getOperand(1));
3693 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3694 NewCallSeqStart.getNode());
3695 Chain = CallSeqStart = NewCallSeqStart;
3697 // Pass the address of the aggregate copy on the stack either in a
3698 // physical register or in the parameter list area of the current stack
3699 // frame to the callee.
3703 if (VA.isRegLoc()) {
3704 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3705 // Put argument in a physical register.
3706 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3708 // Put argument in the parameter list area of the current stack frame.
3709 assert(VA.isMemLoc());
3710 unsigned LocMemOffset = VA.getLocMemOffset();
3713 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3714 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3716 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3717 MachinePointerInfo(),
3720 // Calculate and remember argument location.
3721 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3727 if (!MemOpChains.empty())
3728 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3729 &MemOpChains[0], MemOpChains.size());
3731 // Build a sequence of copy-to-reg nodes chained together with token chain
3732 // and flag operands which copy the outgoing args into the appropriate regs.
3734 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3735 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3736 RegsToPass[i].second, InFlag);
3737 InFlag = Chain.getValue(1);
3740 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3743 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3744 SDValue Ops[] = { Chain, InFlag };
3746 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3747 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3749 InFlag = Chain.getValue(1);
3753 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3754 false, TailCallArguments);
3756 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3757 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3761 // Copy an argument into memory, being careful to do this outside the
3762 // call sequence for the call to which the argument belongs.
3764 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3765 SDValue CallSeqStart,
3766 ISD::ArgFlagsTy Flags,
3768 DebugLoc dl) const {
3769 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3770 CallSeqStart.getNode()->getOperand(0),
3772 // The MEMCPY must go outside the CALLSEQ_START..END.
3773 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3774 CallSeqStart.getNode()->getOperand(1));
3775 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3776 NewCallSeqStart.getNode());
3777 return NewCallSeqStart;
3781 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3782 CallingConv::ID CallConv, bool isVarArg,
3784 const SmallVectorImpl<ISD::OutputArg> &Outs,
3785 const SmallVectorImpl<SDValue> &OutVals,
3786 const SmallVectorImpl<ISD::InputArg> &Ins,
3787 DebugLoc dl, SelectionDAG &DAG,
3788 SmallVectorImpl<SDValue> &InVals) const {
3790 unsigned NumOps = Outs.size();
3792 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3793 unsigned PtrByteSize = 8;
3795 MachineFunction &MF = DAG.getMachineFunction();
3797 // Mark this function as potentially containing a function that contains a
3798 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3799 // and restoring the callers stack pointer in this functions epilog. This is
3800 // done because by tail calling the called function might overwrite the value
3801 // in this function's (MF) stack pointer stack slot 0(SP).
3802 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3803 CallConv == CallingConv::Fast)
3804 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3806 unsigned nAltivecParamsAtEnd = 0;
3808 // Count how many bytes are to be pushed on the stack, including the linkage
3809 // area, and parameter passing area. We start with at least 48 bytes, which
3810 // is reserved space for [SP][CR][LR][3 x unused].
3811 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3814 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3815 Outs, OutVals, nAltivecParamsAtEnd);
3817 // Calculate by how many bytes the stack has to be adjusted in case of tail
3818 // call optimization.
3819 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3821 // To protect arguments on the stack from being clobbered in a tail call,
3822 // force all the loads to happen before doing any other lowering.
3824 Chain = DAG.getStackArgumentTokenFactor(Chain);
3826 // Adjust the stack pointer for the new arguments...
3827 // These operations are automatically eliminated by the prolog/epilog pass
3828 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3829 SDValue CallSeqStart = Chain;
3831 // Load the return address and frame pointer so it can be move somewhere else
3834 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3837 // Set up a copy of the stack pointer for use loading and storing any
3838 // arguments that may not fit in the registers available for argument
3840 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3842 // Figure out which arguments are going to go in registers, and which in
3843 // memory. Also, if this is a vararg function, floating point operations
3844 // must be stored to our stack, and loaded into integer regs as well, if
3845 // any integer regs are available for argument passing.
3846 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3847 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3849 static const uint16_t GPR[] = {
3850 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3851 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3853 static const uint16_t *FPR = GetFPR();
3855 static const uint16_t VR[] = {
3856 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3857 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3859 const unsigned NumGPRs = array_lengthof(GPR);
3860 const unsigned NumFPRs = 13;
3861 const unsigned NumVRs = array_lengthof(VR);
3863 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3864 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3866 SmallVector<SDValue, 8> MemOpChains;
3867 for (unsigned i = 0; i != NumOps; ++i) {
3868 SDValue Arg = OutVals[i];
3869 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3871 // PtrOff will be used to store the current argument to the stack if a
3872 // register cannot be found for it.
3875 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3877 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3879 // Promote integers to 64-bit values.
3880 if (Arg.getValueType() == MVT::i32) {
3881 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3882 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3883 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3886 // FIXME memcpy is used way more than necessary. Correctness first.
3887 // Note: "by value" is code for passing a structure by value, not
3889 if (Flags.isByVal()) {
3890 // Note: Size includes alignment padding, so
3891 // struct x { short a; char b; }
3892 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3893 // These are the proper values we need for right-justifying the
3894 // aggregate in a parameter register.
3895 unsigned Size = Flags.getByValSize();
3897 // An empty aggregate parameter takes up no storage and no
3902 // All aggregates smaller than 8 bytes must be passed right-justified.
3903 if (Size==1 || Size==2 || Size==4) {
3904 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3905 if (GPR_idx != NumGPRs) {
3906 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3907 MachinePointerInfo(), VT,
3909 MemOpChains.push_back(Load.getValue(1));
3910 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3912 ArgOffset += PtrByteSize;
3917 if (GPR_idx == NumGPRs && Size < 8) {
3918 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3919 PtrOff.getValueType());
3920 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3921 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3924 ArgOffset += PtrByteSize;
3927 // Copy entire object into memory. There are cases where gcc-generated
3928 // code assumes it is there, even if it could be put entirely into
3929 // registers. (This is not what the doc says.)
3931 // FIXME: The above statement is likely due to a misunderstanding of the
3932 // documents. All arguments must be copied into the parameter area BY
3933 // THE CALLEE in the event that the callee takes the address of any
3934 // formal argument. That has not yet been implemented. However, it is
3935 // reasonable to use the stack area as a staging area for the register
3938 // Skip this for small aggregates, as we will use the same slot for a
3939 // right-justified copy, below.
3941 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3945 // When a register is available, pass a small aggregate right-justified.
3946 if (Size < 8 && GPR_idx != NumGPRs) {
3947 // The easiest way to get this right-justified in a register
3948 // is to copy the structure into the rightmost portion of a
3949 // local variable slot, then load the whole slot into the
3951 // FIXME: The memcpy seems to produce pretty awful code for
3952 // small aggregates, particularly for packed ones.
3953 // FIXME: It would be preferable to use the slot in the
3954 // parameter save area instead of a new local variable.
3955 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3956 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3957 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3961 // Load the slot into the register.
3962 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3963 MachinePointerInfo(),
3964 false, false, false, 0);
3965 MemOpChains.push_back(Load.getValue(1));
3966 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3968 // Done with this argument.
3969 ArgOffset += PtrByteSize;
3973 // For aggregates larger than PtrByteSize, copy the pieces of the
3974 // object that fit into registers from the parameter save area.
3975 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3976 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3977 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3978 if (GPR_idx != NumGPRs) {
3979 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3980 MachinePointerInfo(),
3981 false, false, false, 0);
3982 MemOpChains.push_back(Load.getValue(1));
3983 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3984 ArgOffset += PtrByteSize;
3986 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3993 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3994 default: llvm_unreachable("Unexpected ValueType for argument!");
3997 if (GPR_idx != NumGPRs) {
3998 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4000 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4001 true, isTailCall, false, MemOpChains,
4002 TailCallArguments, dl);
4004 ArgOffset += PtrByteSize;
4008 if (FPR_idx != NumFPRs) {
4009 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4012 // A single float or an aggregate containing only a single float
4013 // must be passed right-justified in the stack doubleword, and
4014 // in the GPR, if one is available.
4016 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
4017 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4018 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4022 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
4023 MachinePointerInfo(), false, false, 0);
4024 MemOpChains.push_back(Store);
4026 // Float varargs are always shadowed in available integer registers
4027 if (GPR_idx != NumGPRs) {
4028 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4029 MachinePointerInfo(), false, false,
4031 MemOpChains.push_back(Load.getValue(1));
4032 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4034 } else if (GPR_idx != NumGPRs)
4035 // If we have any FPRs remaining, we may also have GPRs remaining.
4038 // Single-precision floating-point values are mapped to the
4039 // second (rightmost) word of the stack doubleword.
4040 if (Arg.getValueType() == MVT::f32) {
4041 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4042 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4045 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4046 true, isTailCall, false, MemOpChains,
4047 TailCallArguments, dl);
4056 // These go aligned on the stack, or in the corresponding R registers
4057 // when within range. The Darwin PPC ABI doc claims they also go in
4058 // V registers; in fact gcc does this only for arguments that are
4059 // prototyped, not for those that match the ... We do it for all
4060 // arguments, seems to work.
4061 while (ArgOffset % 16 !=0) {
4062 ArgOffset += PtrByteSize;
4063 if (GPR_idx != NumGPRs)
4066 // We could elide this store in the case where the object fits
4067 // entirely in R registers. Maybe later.
4068 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4069 DAG.getConstant(ArgOffset, PtrVT));
4070 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4071 MachinePointerInfo(), false, false, 0);
4072 MemOpChains.push_back(Store);
4073 if (VR_idx != NumVRs) {
4074 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4075 MachinePointerInfo(),
4076 false, false, false, 0);
4077 MemOpChains.push_back(Load.getValue(1));
4078 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4081 for (unsigned i=0; i<16; i+=PtrByteSize) {
4082 if (GPR_idx == NumGPRs)
4084 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4085 DAG.getConstant(i, PtrVT));
4086 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4087 false, false, false, 0);
4088 MemOpChains.push_back(Load.getValue(1));
4089 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4094 // Non-varargs Altivec params generally go in registers, but have
4095 // stack space allocated at the end.
4096 if (VR_idx != NumVRs) {
4097 // Doesn't have GPR space allocated.
4098 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4100 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4101 true, isTailCall, true, MemOpChains,
4102 TailCallArguments, dl);
4109 if (!MemOpChains.empty())
4110 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4111 &MemOpChains[0], MemOpChains.size());
4113 // Check if this is an indirect call (MTCTR/BCTRL).
4114 // See PrepareCall() for more information about calls through function
4115 // pointers in the 64-bit SVR4 ABI.
4117 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4118 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4119 !isBLACompatibleAddress(Callee, DAG)) {
4120 // Load r2 into a virtual register and store it to the TOC save area.
4121 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4122 // TOC save area offset.
4123 SDValue PtrOff = DAG.getIntPtrConstant(40);
4124 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4125 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4127 // R12 must contain the address of an indirect callee. This does not
4128 // mean the MTCTR instruction must use R12; it's easier to model this
4129 // as an extra parameter, so do that.
4130 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4133 // Build a sequence of copy-to-reg nodes chained together with token chain
4134 // and flag operands which copy the outgoing args into the appropriate regs.
4136 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4137 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4138 RegsToPass[i].second, InFlag);
4139 InFlag = Chain.getValue(1);
4143 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4144 FPOp, true, TailCallArguments);
4146 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4147 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4152 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4153 CallingConv::ID CallConv, bool isVarArg,
4155 const SmallVectorImpl<ISD::OutputArg> &Outs,
4156 const SmallVectorImpl<SDValue> &OutVals,
4157 const SmallVectorImpl<ISD::InputArg> &Ins,
4158 DebugLoc dl, SelectionDAG &DAG,
4159 SmallVectorImpl<SDValue> &InVals) const {
4161 unsigned NumOps = Outs.size();
4163 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4164 bool isPPC64 = PtrVT == MVT::i64;
4165 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4167 MachineFunction &MF = DAG.getMachineFunction();
4169 // Mark this function as potentially containing a function that contains a
4170 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4171 // and restoring the callers stack pointer in this functions epilog. This is
4172 // done because by tail calling the called function might overwrite the value
4173 // in this function's (MF) stack pointer stack slot 0(SP).
4174 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4175 CallConv == CallingConv::Fast)
4176 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4178 unsigned nAltivecParamsAtEnd = 0;
4180 // Count how many bytes are to be pushed on the stack, including the linkage
4181 // area, and parameter passing area. We start with 24/48 bytes, which is
4182 // prereserved space for [SP][CR][LR][3 x unused].
4184 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4186 nAltivecParamsAtEnd);
4188 // Calculate by how many bytes the stack has to be adjusted in case of tail
4189 // call optimization.
4190 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4192 // To protect arguments on the stack from being clobbered in a tail call,
4193 // force all the loads to happen before doing any other lowering.
4195 Chain = DAG.getStackArgumentTokenFactor(Chain);
4197 // Adjust the stack pointer for the new arguments...
4198 // These operations are automatically eliminated by the prolog/epilog pass
4199 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4200 SDValue CallSeqStart = Chain;
4202 // Load the return address and frame pointer so it can be move somewhere else
4205 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4208 // Set up a copy of the stack pointer for use loading and storing any
4209 // arguments that may not fit in the registers available for argument
4213 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4215 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4217 // Figure out which arguments are going to go in registers, and which in
4218 // memory. Also, if this is a vararg function, floating point operations
4219 // must be stored to our stack, and loaded into integer regs as well, if
4220 // any integer regs are available for argument passing.
4221 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4222 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4224 static const uint16_t GPR_32[] = { // 32-bit registers.
4225 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4226 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4228 static const uint16_t GPR_64[] = { // 64-bit registers.
4229 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4230 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4232 static const uint16_t *FPR = GetFPR();
4234 static const uint16_t VR[] = {
4235 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4236 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4238 const unsigned NumGPRs = array_lengthof(GPR_32);
4239 const unsigned NumFPRs = 13;
4240 const unsigned NumVRs = array_lengthof(VR);
4242 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4244 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4245 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4247 SmallVector<SDValue, 8> MemOpChains;
4248 for (unsigned i = 0; i != NumOps; ++i) {
4249 SDValue Arg = OutVals[i];
4250 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4252 // PtrOff will be used to store the current argument to the stack if a
4253 // register cannot be found for it.
4256 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4258 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4260 // On PPC64, promote integers to 64-bit values.
4261 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4262 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4263 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4264 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4267 // FIXME memcpy is used way more than necessary. Correctness first.
4268 // Note: "by value" is code for passing a structure by value, not
4270 if (Flags.isByVal()) {
4271 unsigned Size = Flags.getByValSize();
4272 // Very small objects are passed right-justified. Everything else is
4273 // passed left-justified.
4274 if (Size==1 || Size==2) {
4275 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4276 if (GPR_idx != NumGPRs) {
4277 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4278 MachinePointerInfo(), VT,
4280 MemOpChains.push_back(Load.getValue(1));
4281 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4283 ArgOffset += PtrByteSize;
4285 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4286 PtrOff.getValueType());
4287 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4288 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4291 ArgOffset += PtrByteSize;
4295 // Copy entire object into memory. There are cases where gcc-generated
4296 // code assumes it is there, even if it could be put entirely into
4297 // registers. (This is not what the doc says.)
4298 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4302 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4303 // copy the pieces of the object that fit into registers from the
4304 // parameter save area.
4305 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4306 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4307 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4308 if (GPR_idx != NumGPRs) {
4309 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4310 MachinePointerInfo(),
4311 false, false, false, 0);
4312 MemOpChains.push_back(Load.getValue(1));
4313 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4314 ArgOffset += PtrByteSize;
4316 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4323 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4324 default: llvm_unreachable("Unexpected ValueType for argument!");
4327 if (GPR_idx != NumGPRs) {
4328 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4330 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4331 isPPC64, isTailCall, false, MemOpChains,
4332 TailCallArguments, dl);
4334 ArgOffset += PtrByteSize;
4338 if (FPR_idx != NumFPRs) {
4339 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4342 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4343 MachinePointerInfo(), false, false, 0);
4344 MemOpChains.push_back(Store);
4346 // Float varargs are always shadowed in available integer registers
4347 if (GPR_idx != NumGPRs) {
4348 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4349 MachinePointerInfo(), false, false,
4351 MemOpChains.push_back(Load.getValue(1));
4352 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4354 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4355 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4356 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4357 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4358 MachinePointerInfo(),
4359 false, false, false, 0);
4360 MemOpChains.push_back(Load.getValue(1));
4361 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4364 // If we have any FPRs remaining, we may also have GPRs remaining.
4365 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4367 if (GPR_idx != NumGPRs)
4369 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4370 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4374 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4375 isPPC64, isTailCall, false, MemOpChains,
4376 TailCallArguments, dl);
4380 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4387 // These go aligned on the stack, or in the corresponding R registers
4388 // when within range. The Darwin PPC ABI doc claims they also go in
4389 // V registers; in fact gcc does this only for arguments that are
4390 // prototyped, not for those that match the ... We do it for all
4391 // arguments, seems to work.
4392 while (ArgOffset % 16 !=0) {
4393 ArgOffset += PtrByteSize;
4394 if (GPR_idx != NumGPRs)
4397 // We could elide this store in the case where the object fits
4398 // entirely in R registers. Maybe later.
4399 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4400 DAG.getConstant(ArgOffset, PtrVT));
4401 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4402 MachinePointerInfo(), false, false, 0);
4403 MemOpChains.push_back(Store);
4404 if (VR_idx != NumVRs) {
4405 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4406 MachinePointerInfo(),
4407 false, false, false, 0);
4408 MemOpChains.push_back(Load.getValue(1));
4409 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4412 for (unsigned i=0; i<16; i+=PtrByteSize) {
4413 if (GPR_idx == NumGPRs)
4415 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4416 DAG.getConstant(i, PtrVT));
4417 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4418 false, false, false, 0);
4419 MemOpChains.push_back(Load.getValue(1));
4420 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4425 // Non-varargs Altivec params generally go in registers, but have
4426 // stack space allocated at the end.
4427 if (VR_idx != NumVRs) {
4428 // Doesn't have GPR space allocated.
4429 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4430 } else if (nAltivecParamsAtEnd==0) {
4431 // We are emitting Altivec params in order.
4432 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4433 isPPC64, isTailCall, true, MemOpChains,
4434 TailCallArguments, dl);
4440 // If all Altivec parameters fit in registers, as they usually do,
4441 // they get stack space following the non-Altivec parameters. We
4442 // don't track this here because nobody below needs it.
4443 // If there are more Altivec parameters than fit in registers emit
4445 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4447 // Offset is aligned; skip 1st 12 params which go in V registers.
4448 ArgOffset = ((ArgOffset+15)/16)*16;
4450 for (unsigned i = 0; i != NumOps; ++i) {
4451 SDValue Arg = OutVals[i];
4452 EVT ArgType = Outs[i].VT;
4453 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4454 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4457 // We are emitting Altivec params in order.
4458 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4459 isPPC64, isTailCall, true, MemOpChains,
4460 TailCallArguments, dl);
4467 if (!MemOpChains.empty())
4468 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4469 &MemOpChains[0], MemOpChains.size());
4471 // On Darwin, R12 must contain the address of an indirect callee. This does
4472 // not mean the MTCTR instruction must use R12; it's easier to model this as
4473 // an extra parameter, so do that.
4475 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4476 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4477 !isBLACompatibleAddress(Callee, DAG))
4478 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4479 PPC::R12), Callee));
4481 // Build a sequence of copy-to-reg nodes chained together with token chain
4482 // and flag operands which copy the outgoing args into the appropriate regs.
4484 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4485 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4486 RegsToPass[i].second, InFlag);
4487 InFlag = Chain.getValue(1);
4491 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4492 FPOp, true, TailCallArguments);
4494 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4495 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4500 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4501 MachineFunction &MF, bool isVarArg,
4502 const SmallVectorImpl<ISD::OutputArg> &Outs,
4503 LLVMContext &Context) const {
4504 SmallVector<CCValAssign, 16> RVLocs;
4505 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4507 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4511 PPCTargetLowering::LowerReturn(SDValue Chain,
4512 CallingConv::ID CallConv, bool isVarArg,
4513 const SmallVectorImpl<ISD::OutputArg> &Outs,
4514 const SmallVectorImpl<SDValue> &OutVals,
4515 DebugLoc dl, SelectionDAG &DAG) const {
4517 SmallVector<CCValAssign, 16> RVLocs;
4518 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4519 getTargetMachine(), RVLocs, *DAG.getContext());
4520 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4523 SmallVector<SDValue, 4> RetOps(1, Chain);
4525 // Copy the result values into the output registers.
4526 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4527 CCValAssign &VA = RVLocs[i];
4528 assert(VA.isRegLoc() && "Can only return in registers!");
4530 SDValue Arg = OutVals[i];
4532 switch (VA.getLocInfo()) {
4533 default: llvm_unreachable("Unknown loc info!");
4534 case CCValAssign::Full: break;
4535 case CCValAssign::AExt:
4536 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4538 case CCValAssign::ZExt:
4539 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4541 case CCValAssign::SExt:
4542 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4546 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4547 Flag = Chain.getValue(1);
4548 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4551 RetOps[0] = Chain; // Update chain.
4553 // Add the flag if we have it.
4555 RetOps.push_back(Flag);
4557 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4558 &RetOps[0], RetOps.size());
4561 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4562 const PPCSubtarget &Subtarget) const {
4563 // When we pop the dynamic allocation we need to restore the SP link.
4564 DebugLoc dl = Op.getDebugLoc();
4566 // Get the corect type for pointers.
4567 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4569 // Construct the stack pointer operand.
4570 bool isPPC64 = Subtarget.isPPC64();
4571 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4572 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4574 // Get the operands for the STACKRESTORE.
4575 SDValue Chain = Op.getOperand(0);
4576 SDValue SaveSP = Op.getOperand(1);
4578 // Load the old link SP.
4579 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4580 MachinePointerInfo(),
4581 false, false, false, 0);
4583 // Restore the stack pointer.
4584 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4586 // Store the old link SP.
4587 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4594 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4595 MachineFunction &MF = DAG.getMachineFunction();
4596 bool isPPC64 = PPCSubTarget.isPPC64();
4597 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4598 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4600 // Get current frame pointer save index. The users of this index will be
4601 // primarily DYNALLOC instructions.
4602 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4603 int RASI = FI->getReturnAddrSaveIndex();
4605 // If the frame pointer save index hasn't been defined yet.
4607 // Find out what the fix offset of the frame pointer save area.
4608 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4609 // Allocate the frame index for frame pointer save area.
4610 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4612 FI->setReturnAddrSaveIndex(RASI);
4614 return DAG.getFrameIndex(RASI, PtrVT);
4618 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4619 MachineFunction &MF = DAG.getMachineFunction();
4620 bool isPPC64 = PPCSubTarget.isPPC64();
4621 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4622 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4624 // Get current frame pointer save index. The users of this index will be
4625 // primarily DYNALLOC instructions.
4626 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4627 int FPSI = FI->getFramePointerSaveIndex();
4629 // If the frame pointer save index hasn't been defined yet.
4631 // Find out what the fix offset of the frame pointer save area.
4632 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4635 // Allocate the frame index for frame pointer save area.
4636 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4638 FI->setFramePointerSaveIndex(FPSI);
4640 return DAG.getFrameIndex(FPSI, PtrVT);
4643 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4645 const PPCSubtarget &Subtarget) const {
4647 SDValue Chain = Op.getOperand(0);
4648 SDValue Size = Op.getOperand(1);
4649 DebugLoc dl = Op.getDebugLoc();
4651 // Get the corect type for pointers.
4652 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4654 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4655 DAG.getConstant(0, PtrVT), Size);
4656 // Construct a node for the frame pointer save index.
4657 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4658 // Build a DYNALLOC node.
4659 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4660 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4661 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4664 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4665 SelectionDAG &DAG) const {
4666 DebugLoc DL = Op.getDebugLoc();
4667 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4668 DAG.getVTList(MVT::i32, MVT::Other),
4669 Op.getOperand(0), Op.getOperand(1));
4672 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4673 SelectionDAG &DAG) const {
4674 DebugLoc DL = Op.getDebugLoc();
4675 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4676 Op.getOperand(0), Op.getOperand(1));
4679 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4681 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4682 // Not FP? Not a fsel.
4683 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4684 !Op.getOperand(2).getValueType().isFloatingPoint())
4687 // We might be able to do better than this under some circumstances, but in
4688 // general, fsel-based lowering of select is a finite-math-only optimization.
4689 // For more information, see section F.3 of the 2.06 ISA specification.
4690 if (!DAG.getTarget().Options.NoInfsFPMath ||
4691 !DAG.getTarget().Options.NoNaNsFPMath)
4694 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4696 EVT ResVT = Op.getValueType();
4697 EVT CmpVT = Op.getOperand(0).getValueType();
4698 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4699 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4700 DebugLoc dl = Op.getDebugLoc();
4702 // If the RHS of the comparison is a 0.0, we don't need to do the
4703 // subtraction at all.
4705 if (isFloatingPointZero(RHS))
4707 default: break; // SETUO etc aren't handled by fsel.
4711 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4712 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4713 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4714 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4715 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4716 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4717 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4720 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4723 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4724 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4725 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4728 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4731 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4732 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4733 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4734 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4739 default: break; // SETUO etc aren't handled by fsel.
4743 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4744 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4745 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4746 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4747 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4748 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4749 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4750 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
4753 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4754 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4755 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4756 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4759 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4760 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4761 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4762 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4765 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4766 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4767 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4768 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4771 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4772 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4773 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4774 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4779 // FIXME: Split this code up when LegalizeDAGTypes lands.
4780 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4781 DebugLoc dl) const {
4782 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4783 SDValue Src = Op.getOperand(0);
4784 if (Src.getValueType() == MVT::f32)
4785 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4788 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4789 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4791 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4792 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4797 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4798 "i64 FP_TO_UINT is supported only with FPCVT");
4799 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4805 // Convert the FP value to an int value through memory.
4806 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4807 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4808 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4809 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4810 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4812 // Emit a store to the stack slot.
4815 MachineFunction &MF = DAG.getMachineFunction();
4816 MachineMemOperand *MMO =
4817 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4818 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4819 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4820 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4823 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4824 MPI, false, false, 0);
4826 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4828 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4829 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4830 DAG.getConstant(4, FIPtr.getValueType()));
4831 MPI = MachinePointerInfo();
4834 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4835 false, false, false, 0);
4838 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4839 SelectionDAG &DAG) const {
4840 DebugLoc dl = Op.getDebugLoc();
4841 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4842 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4845 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4846 "UINT_TO_FP is supported only with FPCVT");
4848 // If we have FCFIDS, then use it when converting to single-precision.
4849 // Otherwise, convert to double-precision and then round.
4850 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4851 (Op.getOpcode() == ISD::UINT_TO_FP ?
4852 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4853 (Op.getOpcode() == ISD::UINT_TO_FP ?
4854 PPCISD::FCFIDU : PPCISD::FCFID);
4855 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4856 MVT::f32 : MVT::f64;
4858 if (Op.getOperand(0).getValueType() == MVT::i64) {
4859 SDValue SINT = Op.getOperand(0);
4860 // When converting to single-precision, we actually need to convert
4861 // to double-precision first and then round to single-precision.
4862 // To avoid double-rounding effects during that operation, we have
4863 // to prepare the input operand. Bits that might be truncated when
4864 // converting to double-precision are replaced by a bit that won't
4865 // be lost at this stage, but is below the single-precision rounding
4868 // However, if -enable-unsafe-fp-math is in effect, accept double
4869 // rounding to avoid the extra overhead.
4870 if (Op.getValueType() == MVT::f32 &&
4871 !PPCSubTarget.hasFPCVT() &&
4872 !DAG.getTarget().Options.UnsafeFPMath) {
4874 // Twiddle input to make sure the low 11 bits are zero. (If this
4875 // is the case, we are guaranteed the value will fit into the 53 bit
4876 // mantissa of an IEEE double-precision value without rounding.)
4877 // If any of those low 11 bits were not zero originally, make sure
4878 // bit 12 (value 2048) is set instead, so that the final rounding
4879 // to single-precision gets the correct result.
4880 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4881 SINT, DAG.getConstant(2047, MVT::i64));
4882 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4883 Round, DAG.getConstant(2047, MVT::i64));
4884 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4885 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4886 Round, DAG.getConstant(-2048, MVT::i64));
4888 // However, we cannot use that value unconditionally: if the magnitude
4889 // of the input value is small, the bit-twiddling we did above might
4890 // end up visibly changing the output. Fortunately, in that case, we
4891 // don't need to twiddle bits since the original input will convert
4892 // exactly to double-precision floating-point already. Therefore,
4893 // construct a conditional to use the original value if the top 11
4894 // bits are all sign-bit copies, and use the rounded value computed
4896 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4897 SINT, DAG.getConstant(53, MVT::i32));
4898 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4899 Cond, DAG.getConstant(1, MVT::i64));
4900 Cond = DAG.getSetCC(dl, MVT::i32,
4901 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4903 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4906 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4907 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
4909 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4910 FP = DAG.getNode(ISD::FP_ROUND, dl,
4911 MVT::f32, FP, DAG.getIntPtrConstant(0));
4915 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4916 "Unhandled INT_TO_FP type in custom expander!");
4917 // Since we only generate this in 64-bit mode, we can take advantage of
4918 // 64-bit registers. In particular, sign extend the input value into the
4919 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4920 // then lfd it and fcfid it.
4921 MachineFunction &MF = DAG.getMachineFunction();
4922 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4923 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4926 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
4927 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
4928 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4930 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
4931 MachinePointerInfo::getFixedStack(FrameIdx),
4934 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
4935 "Expected an i32 store");
4936 MachineMemOperand *MMO =
4937 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4938 MachineMemOperand::MOLoad, 4, 4);
4939 SDValue Ops[] = { Store, FIdx };
4940 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
4941 PPCISD::LFIWZX : PPCISD::LFIWAX,
4942 dl, DAG.getVTList(MVT::f64, MVT::Other),
4943 Ops, 2, MVT::i32, MMO);
4945 assert(PPCSubTarget.isPPC64() &&
4946 "i32->FP without LFIWAX supported only on PPC64");
4948 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4949 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4951 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
4954 // STD the extended value into the stack slot.
4955 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
4956 MachinePointerInfo::getFixedStack(FrameIdx),
4959 // Load the value as a double.
4960 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
4961 MachinePointerInfo::getFixedStack(FrameIdx),
4962 false, false, false, 0);
4965 // FCFID it and return it.
4966 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
4967 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4968 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4972 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4973 SelectionDAG &DAG) const {
4974 DebugLoc dl = Op.getDebugLoc();
4976 The rounding mode is in bits 30:31 of FPSR, and has the following
4983 FLT_ROUNDS, on the other hand, expects the following:
4990 To perform the conversion, we do:
4991 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4994 MachineFunction &MF = DAG.getMachineFunction();
4995 EVT VT = Op.getValueType();
4996 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4997 SDValue MFFSreg, InFlag;
4999 // Save FP Control Word to register
5001 MVT::f64, // return register
5002 MVT::Glue // unused in this context
5004 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5006 // Save FP register to stack slot
5007 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5008 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5009 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5010 StackSlot, MachinePointerInfo(), false, false,0);
5012 // Load FP Control Word from low 32 bits of stack slot.
5013 SDValue Four = DAG.getConstant(4, PtrVT);
5014 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5015 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5016 false, false, false, 0);
5018 // Transform as necessary
5020 DAG.getNode(ISD::AND, dl, MVT::i32,
5021 CWD, DAG.getConstant(3, MVT::i32));
5023 DAG.getNode(ISD::SRL, dl, MVT::i32,
5024 DAG.getNode(ISD::AND, dl, MVT::i32,
5025 DAG.getNode(ISD::XOR, dl, MVT::i32,
5026 CWD, DAG.getConstant(3, MVT::i32)),
5027 DAG.getConstant(3, MVT::i32)),
5028 DAG.getConstant(1, MVT::i32));
5031 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5033 return DAG.getNode((VT.getSizeInBits() < 16 ?
5034 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5037 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5038 EVT VT = Op.getValueType();
5039 unsigned BitWidth = VT.getSizeInBits();
5040 DebugLoc dl = Op.getDebugLoc();
5041 assert(Op.getNumOperands() == 3 &&
5042 VT == Op.getOperand(1).getValueType() &&
5045 // Expand into a bunch of logical ops. Note that these ops
5046 // depend on the PPC behavior for oversized shift amounts.
5047 SDValue Lo = Op.getOperand(0);
5048 SDValue Hi = Op.getOperand(1);
5049 SDValue Amt = Op.getOperand(2);
5050 EVT AmtVT = Amt.getValueType();
5052 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5053 DAG.getConstant(BitWidth, AmtVT), Amt);
5054 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5055 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5056 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5057 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5058 DAG.getConstant(-BitWidth, AmtVT));
5059 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5060 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5061 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5062 SDValue OutOps[] = { OutLo, OutHi };
5063 return DAG.getMergeValues(OutOps, 2, dl);
5066 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5067 EVT VT = Op.getValueType();
5068 DebugLoc dl = Op.getDebugLoc();
5069 unsigned BitWidth = VT.getSizeInBits();
5070 assert(Op.getNumOperands() == 3 &&
5071 VT == Op.getOperand(1).getValueType() &&
5074 // Expand into a bunch of logical ops. Note that these ops
5075 // depend on the PPC behavior for oversized shift amounts.
5076 SDValue Lo = Op.getOperand(0);
5077 SDValue Hi = Op.getOperand(1);
5078 SDValue Amt = Op.getOperand(2);
5079 EVT AmtVT = Amt.getValueType();
5081 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5082 DAG.getConstant(BitWidth, AmtVT), Amt);
5083 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5084 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5085 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5086 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5087 DAG.getConstant(-BitWidth, AmtVT));
5088 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5089 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5090 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5091 SDValue OutOps[] = { OutLo, OutHi };
5092 return DAG.getMergeValues(OutOps, 2, dl);
5095 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5096 DebugLoc dl = Op.getDebugLoc();
5097 EVT VT = Op.getValueType();
5098 unsigned BitWidth = VT.getSizeInBits();
5099 assert(Op.getNumOperands() == 3 &&
5100 VT == Op.getOperand(1).getValueType() &&
5103 // Expand into a bunch of logical ops, followed by a select_cc.
5104 SDValue Lo = Op.getOperand(0);
5105 SDValue Hi = Op.getOperand(1);
5106 SDValue Amt = Op.getOperand(2);
5107 EVT AmtVT = Amt.getValueType();
5109 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5110 DAG.getConstant(BitWidth, AmtVT), Amt);
5111 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5112 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5113 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5114 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5115 DAG.getConstant(-BitWidth, AmtVT));
5116 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5117 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5118 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5119 Tmp4, Tmp6, ISD::SETLE);
5120 SDValue OutOps[] = { OutLo, OutHi };
5121 return DAG.getMergeValues(OutOps, 2, dl);
5124 //===----------------------------------------------------------------------===//
5125 // Vector related lowering.
5128 /// BuildSplatI - Build a canonical splati of Val with an element size of
5129 /// SplatSize. Cast the result to VT.
5130 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5131 SelectionDAG &DAG, DebugLoc dl) {
5132 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5134 static const EVT VTys[] = { // canonical VT to use for each size.
5135 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5138 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5140 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5144 EVT CanonicalVT = VTys[SplatSize-1];
5146 // Build a canonical splat for this value.
5147 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5148 SmallVector<SDValue, 8> Ops;
5149 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5150 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5151 &Ops[0], Ops.size());
5152 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5155 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5156 /// specified intrinsic ID.
5157 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5158 SelectionDAG &DAG, DebugLoc dl,
5159 EVT DestVT = MVT::Other) {
5160 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5161 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5162 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5165 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5166 /// specified intrinsic ID.
5167 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5168 SDValue Op2, SelectionDAG &DAG,
5169 DebugLoc dl, EVT DestVT = MVT::Other) {
5170 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5171 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5172 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5176 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5177 /// amount. The result has the specified value type.
5178 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5179 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
5180 // Force LHS/RHS to be the right type.
5181 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5182 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5185 for (unsigned i = 0; i != 16; ++i)
5187 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5188 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5191 // If this is a case we can't handle, return null and let the default
5192 // expansion code take care of it. If we CAN select this case, and if it
5193 // selects to a single instruction, return Op. Otherwise, if we can codegen
5194 // this case more efficiently than a constant pool load, lower it to the
5195 // sequence of ops that should be used.
5196 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5197 SelectionDAG &DAG) const {
5198 DebugLoc dl = Op.getDebugLoc();
5199 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5200 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5202 // Check if this is a splat of a constant value.
5203 APInt APSplatBits, APSplatUndef;
5204 unsigned SplatBitSize;
5206 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5207 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5210 unsigned SplatBits = APSplatBits.getZExtValue();
5211 unsigned SplatUndef = APSplatUndef.getZExtValue();
5212 unsigned SplatSize = SplatBitSize / 8;
5214 // First, handle single instruction cases.
5217 if (SplatBits == 0) {
5218 // Canonicalize all zero vectors to be v4i32.
5219 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5220 SDValue Z = DAG.getConstant(0, MVT::i32);
5221 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5222 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5227 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5228 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5230 if (SextVal >= -16 && SextVal <= 15)
5231 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5234 // Two instruction sequences.
5236 // If this value is in the range [-32,30] and is even, use:
5237 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5238 // If this value is in the range [17,31] and is odd, use:
5239 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5240 // If this value is in the range [-31,-17] and is odd, use:
5241 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5242 // Note the last two are three-instruction sequences.
5243 if (SextVal >= -32 && SextVal <= 31) {
5244 // To avoid having these optimizations undone by constant folding,
5245 // we convert to a pseudo that will be expanded later into one of
5247 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5248 EVT VT = Op.getValueType();
5249 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5250 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5251 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5254 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5255 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5257 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5258 // Make -1 and vspltisw -1:
5259 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5261 // Make the VSLW intrinsic, computing 0x8000_0000.
5262 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5265 // xor by OnesV to invert it.
5266 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5267 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5270 // Check to see if this is a wide variety of vsplti*, binop self cases.
5271 static const signed char SplatCsts[] = {
5272 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5273 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5276 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5277 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5278 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5279 int i = SplatCsts[idx];
5281 // Figure out what shift amount will be used by altivec if shifted by i in
5283 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5285 // vsplti + shl self.
5286 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5287 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5288 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5289 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5290 Intrinsic::ppc_altivec_vslw
5292 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5293 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5296 // vsplti + srl self.
5297 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5298 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5299 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5300 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5301 Intrinsic::ppc_altivec_vsrw
5303 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5304 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5307 // vsplti + sra self.
5308 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5309 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5310 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5311 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5312 Intrinsic::ppc_altivec_vsraw
5314 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5315 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5318 // vsplti + rol self.
5319 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5320 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5321 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5322 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5323 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5324 Intrinsic::ppc_altivec_vrlw
5326 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5327 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5330 // t = vsplti c, result = vsldoi t, t, 1
5331 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5332 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5333 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5335 // t = vsplti c, result = vsldoi t, t, 2
5336 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5337 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5338 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5340 // t = vsplti c, result = vsldoi t, t, 3
5341 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5342 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5343 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5350 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5351 /// the specified operations to build the shuffle.
5352 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5353 SDValue RHS, SelectionDAG &DAG,
5355 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5356 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5357 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5360 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5372 if (OpNum == OP_COPY) {
5373 if (LHSID == (1*9+2)*9+3) return LHS;
5374 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5378 SDValue OpLHS, OpRHS;
5379 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5380 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5384 default: llvm_unreachable("Unknown i32 permute!");
5386 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5387 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5388 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5389 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5392 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5393 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5394 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5395 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5398 for (unsigned i = 0; i != 16; ++i)
5399 ShufIdxs[i] = (i&3)+0;
5402 for (unsigned i = 0; i != 16; ++i)
5403 ShufIdxs[i] = (i&3)+4;
5406 for (unsigned i = 0; i != 16; ++i)
5407 ShufIdxs[i] = (i&3)+8;
5410 for (unsigned i = 0; i != 16; ++i)
5411 ShufIdxs[i] = (i&3)+12;
5414 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5416 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5418 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5420 EVT VT = OpLHS.getValueType();
5421 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5422 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5423 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5424 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5427 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5428 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5429 /// return the code it can be lowered into. Worst case, it can always be
5430 /// lowered into a vperm.
5431 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5432 SelectionDAG &DAG) const {
5433 DebugLoc dl = Op.getDebugLoc();
5434 SDValue V1 = Op.getOperand(0);
5435 SDValue V2 = Op.getOperand(1);
5436 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5437 EVT VT = Op.getValueType();
5439 // Cases that are handled by instructions that take permute immediates
5440 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5441 // selected by the instruction selector.
5442 if (V2.getOpcode() == ISD::UNDEF) {
5443 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5444 PPC::isSplatShuffleMask(SVOp, 2) ||
5445 PPC::isSplatShuffleMask(SVOp, 4) ||
5446 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5447 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5448 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5449 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5450 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5451 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5452 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5453 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5454 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5459 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5460 // and produce a fixed permutation. If any of these match, do not lower to
5462 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5463 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5464 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5465 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5466 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5467 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5468 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5469 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5470 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5473 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5474 // perfect shuffle table to emit an optimal matching sequence.
5475 ArrayRef<int> PermMask = SVOp->getMask();
5477 unsigned PFIndexes[4];
5478 bool isFourElementShuffle = true;
5479 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5480 unsigned EltNo = 8; // Start out undef.
5481 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5482 if (PermMask[i*4+j] < 0)
5483 continue; // Undef, ignore it.
5485 unsigned ByteSource = PermMask[i*4+j];
5486 if ((ByteSource & 3) != j) {
5487 isFourElementShuffle = false;
5492 EltNo = ByteSource/4;
5493 } else if (EltNo != ByteSource/4) {
5494 isFourElementShuffle = false;
5498 PFIndexes[i] = EltNo;
5501 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5502 // perfect shuffle vector to determine if it is cost effective to do this as
5503 // discrete instructions, or whether we should use a vperm.
5504 if (isFourElementShuffle) {
5505 // Compute the index in the perfect shuffle table.
5506 unsigned PFTableIndex =
5507 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5509 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5510 unsigned Cost = (PFEntry >> 30);
5512 // Determining when to avoid vperm is tricky. Many things affect the cost
5513 // of vperm, particularly how many times the perm mask needs to be computed.
5514 // For example, if the perm mask can be hoisted out of a loop or is already
5515 // used (perhaps because there are multiple permutes with the same shuffle
5516 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5517 // the loop requires an extra register.
5519 // As a compromise, we only emit discrete instructions if the shuffle can be
5520 // generated in 3 or fewer operations. When we have loop information
5521 // available, if this block is within a loop, we should avoid using vperm
5522 // for 3-operation perms and use a constant pool load instead.
5524 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5527 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5528 // vector that will get spilled to the constant pool.
5529 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5531 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5532 // that it is in input element units, not in bytes. Convert now.
5533 EVT EltVT = V1.getValueType().getVectorElementType();
5534 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5536 SmallVector<SDValue, 16> ResultMask;
5537 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5538 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5540 for (unsigned j = 0; j != BytesPerElement; ++j)
5541 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5545 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5546 &ResultMask[0], ResultMask.size());
5547 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5550 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5551 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5552 /// information about the intrinsic.
5553 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5555 unsigned IntrinsicID =
5556 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5559 switch (IntrinsicID) {
5560 default: return false;
5561 // Comparison predicates.
5562 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5563 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5564 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5565 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5566 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5567 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5568 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5569 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5570 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5571 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5572 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5573 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5574 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5576 // Normal Comparisons.
5577 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5578 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5579 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5580 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5581 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5582 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5583 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5584 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5585 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5586 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5587 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5588 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5589 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5594 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5595 /// lower, do it, otherwise return null.
5596 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5597 SelectionDAG &DAG) const {
5598 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5599 // opcode number of the comparison.
5600 DebugLoc dl = Op.getDebugLoc();
5603 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5604 return SDValue(); // Don't custom lower most intrinsics.
5606 // If this is a non-dot comparison, make the VCMP node and we are done.
5608 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5609 Op.getOperand(1), Op.getOperand(2),
5610 DAG.getConstant(CompareOpc, MVT::i32));
5611 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5614 // Create the PPCISD altivec 'dot' comparison node.
5616 Op.getOperand(2), // LHS
5617 Op.getOperand(3), // RHS
5618 DAG.getConstant(CompareOpc, MVT::i32)
5620 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5621 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5623 // Now that we have the comparison, emit a copy from the CR to a GPR.
5624 // This is flagged to the above dot comparison.
5625 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5626 DAG.getRegister(PPC::CR6, MVT::i32),
5627 CompNode.getValue(1));
5629 // Unpack the result based on how the target uses it.
5630 unsigned BitNo; // Bit # of CR6.
5631 bool InvertBit; // Invert result?
5632 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5633 default: // Can't happen, don't crash on invalid number though.
5634 case 0: // Return the value of the EQ bit of CR6.
5635 BitNo = 0; InvertBit = false;
5637 case 1: // Return the inverted value of the EQ bit of CR6.
5638 BitNo = 0; InvertBit = true;
5640 case 2: // Return the value of the LT bit of CR6.
5641 BitNo = 2; InvertBit = false;
5643 case 3: // Return the inverted value of the LT bit of CR6.
5644 BitNo = 2; InvertBit = true;
5648 // Shift the bit into the low position.
5649 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5650 DAG.getConstant(8-(3-BitNo), MVT::i32));
5652 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5653 DAG.getConstant(1, MVT::i32));
5655 // If we are supposed to, toggle the bit.
5657 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5658 DAG.getConstant(1, MVT::i32));
5662 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5663 SelectionDAG &DAG) const {
5664 DebugLoc dl = Op.getDebugLoc();
5665 // Create a stack slot that is 16-byte aligned.
5666 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5667 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5668 EVT PtrVT = getPointerTy();
5669 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5671 // Store the input value into Value#0 of the stack slot.
5672 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5673 Op.getOperand(0), FIdx, MachinePointerInfo(),
5676 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5677 false, false, false, 0);
5680 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5681 DebugLoc dl = Op.getDebugLoc();
5682 if (Op.getValueType() == MVT::v4i32) {
5683 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5685 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5686 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5688 SDValue RHSSwap = // = vrlw RHS, 16
5689 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5691 // Shrinkify inputs to v8i16.
5692 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5693 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5694 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5696 // Low parts multiplied together, generating 32-bit results (we ignore the
5698 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5699 LHS, RHS, DAG, dl, MVT::v4i32);
5701 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5702 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5703 // Shift the high parts up 16 bits.
5704 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5706 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5707 } else if (Op.getValueType() == MVT::v8i16) {
5708 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5710 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5712 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5713 LHS, RHS, Zero, DAG, dl);
5714 } else if (Op.getValueType() == MVT::v16i8) {
5715 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5717 // Multiply the even 8-bit parts, producing 16-bit sums.
5718 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5719 LHS, RHS, DAG, dl, MVT::v8i16);
5720 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5722 // Multiply the odd 8-bit parts, producing 16-bit sums.
5723 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5724 LHS, RHS, DAG, dl, MVT::v8i16);
5725 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5727 // Merge the results together.
5729 for (unsigned i = 0; i != 8; ++i) {
5731 Ops[i*2+1] = 2*i+1+16;
5733 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5735 llvm_unreachable("Unknown mul to lower!");
5739 /// LowerOperation - Provide custom lowering hooks for some operations.
5741 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5742 switch (Op.getOpcode()) {
5743 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5744 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5745 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5746 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5747 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5748 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5749 case ISD::SETCC: return LowerSETCC(Op, DAG);
5750 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5751 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5753 return LowerVASTART(Op, DAG, PPCSubTarget);
5756 return LowerVAARG(Op, DAG, PPCSubTarget);
5758 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5759 case ISD::DYNAMIC_STACKALLOC:
5760 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5762 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5763 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5765 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5766 case ISD::FP_TO_UINT:
5767 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5769 case ISD::UINT_TO_FP:
5770 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5771 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5773 // Lower 64-bit shifts.
5774 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5775 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5776 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5778 // Vector-related lowering.
5779 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5780 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5781 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5782 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5783 case ISD::MUL: return LowerMUL(Op, DAG);
5785 // For counter-based loop handling.
5786 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5788 // Frame & Return address.
5789 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5790 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5794 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5795 SmallVectorImpl<SDValue>&Results,
5796 SelectionDAG &DAG) const {
5797 const TargetMachine &TM = getTargetMachine();
5798 DebugLoc dl = N->getDebugLoc();
5799 switch (N->getOpcode()) {
5801 llvm_unreachable("Do not know how to custom type legalize this operation!");
5802 case ISD::INTRINSIC_W_CHAIN: {
5803 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5804 Intrinsic::ppc_is_decremented_ctr_nonzero)
5807 assert(N->getValueType(0) == MVT::i1 &&
5808 "Unexpected result type for CTR decrement intrinsic");
5809 EVT SVT = getSetCCResultType(N->getValueType(0));
5810 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5811 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5814 Results.push_back(NewInt);
5815 Results.push_back(NewInt.getValue(1));
5819 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5820 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5823 EVT VT = N->getValueType(0);
5825 if (VT == MVT::i64) {
5826 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5828 Results.push_back(NewNode);
5829 Results.push_back(NewNode.getValue(1));
5833 case ISD::FP_ROUND_INREG: {
5834 assert(N->getValueType(0) == MVT::ppcf128);
5835 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5836 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5837 MVT::f64, N->getOperand(0),
5838 DAG.getIntPtrConstant(0));
5839 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5840 MVT::f64, N->getOperand(0),
5841 DAG.getIntPtrConstant(1));
5843 // Add the two halves of the long double in round-to-zero mode.
5844 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5846 // We know the low half is about to be thrown away, so just use something
5848 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5852 case ISD::FP_TO_SINT:
5853 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5859 //===----------------------------------------------------------------------===//
5860 // Other Lowering Code
5861 //===----------------------------------------------------------------------===//
5864 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5865 bool is64bit, unsigned BinOpcode) const {
5866 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5869 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5870 MachineFunction *F = BB->getParent();
5871 MachineFunction::iterator It = BB;
5874 unsigned dest = MI->getOperand(0).getReg();
5875 unsigned ptrA = MI->getOperand(1).getReg();
5876 unsigned ptrB = MI->getOperand(2).getReg();
5877 unsigned incr = MI->getOperand(3).getReg();
5878 DebugLoc dl = MI->getDebugLoc();
5880 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5881 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5882 F->insert(It, loopMBB);
5883 F->insert(It, exitMBB);
5884 exitMBB->splice(exitMBB->begin(), BB,
5885 llvm::next(MachineBasicBlock::iterator(MI)),
5887 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5889 MachineRegisterInfo &RegInfo = F->getRegInfo();
5890 unsigned TmpReg = (!BinOpcode) ? incr :
5891 RegInfo.createVirtualRegister(
5892 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5893 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5897 // fallthrough --> loopMBB
5898 BB->addSuccessor(loopMBB);
5901 // l[wd]arx dest, ptr
5902 // add r0, dest, incr
5903 // st[wd]cx. r0, ptr
5905 // fallthrough --> exitMBB
5907 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5908 .addReg(ptrA).addReg(ptrB);
5910 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5911 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5912 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5913 BuildMI(BB, dl, TII->get(PPC::BCC))
5914 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5915 BB->addSuccessor(loopMBB);
5916 BB->addSuccessor(exitMBB);
5925 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5926 MachineBasicBlock *BB,
5927 bool is8bit, // operation
5928 unsigned BinOpcode) const {
5929 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5930 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5931 // In 64 bit mode we have to use 64 bits for addresses, even though the
5932 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5933 // registers without caring whether they're 32 or 64, but here we're
5934 // doing actual arithmetic on the addresses.
5935 bool is64bit = PPCSubTarget.isPPC64();
5936 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5938 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5939 MachineFunction *F = BB->getParent();
5940 MachineFunction::iterator It = BB;
5943 unsigned dest = MI->getOperand(0).getReg();
5944 unsigned ptrA = MI->getOperand(1).getReg();
5945 unsigned ptrB = MI->getOperand(2).getReg();
5946 unsigned incr = MI->getOperand(3).getReg();
5947 DebugLoc dl = MI->getDebugLoc();
5949 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5950 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5951 F->insert(It, loopMBB);
5952 F->insert(It, exitMBB);
5953 exitMBB->splice(exitMBB->begin(), BB,
5954 llvm::next(MachineBasicBlock::iterator(MI)),
5956 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5958 MachineRegisterInfo &RegInfo = F->getRegInfo();
5959 const TargetRegisterClass *RC =
5960 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5961 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5962 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5963 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5964 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5965 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5966 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5967 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5968 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5969 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5970 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5971 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5972 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5974 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5978 // fallthrough --> loopMBB
5979 BB->addSuccessor(loopMBB);
5981 // The 4-byte load must be aligned, while a char or short may be
5982 // anywhere in the word. Hence all this nasty bookkeeping code.
5983 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5984 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5985 // xori shift, shift1, 24 [16]
5986 // rlwinm ptr, ptr1, 0, 0, 29
5987 // slw incr2, incr, shift
5988 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5989 // slw mask, mask2, shift
5991 // lwarx tmpDest, ptr
5992 // add tmp, tmpDest, incr2
5993 // andc tmp2, tmpDest, mask
5994 // and tmp3, tmp, mask
5995 // or tmp4, tmp3, tmp2
5998 // fallthrough --> exitMBB
5999 // srw dest, tmpDest, shift
6000 if (ptrA != ZeroReg) {
6001 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6002 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6003 .addReg(ptrA).addReg(ptrB);
6007 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6008 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6009 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6010 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6012 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6013 .addReg(Ptr1Reg).addImm(0).addImm(61);
6015 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6016 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6017 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6018 .addReg(incr).addReg(ShiftReg);
6020 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6022 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6023 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6025 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6026 .addReg(Mask2Reg).addReg(ShiftReg);
6029 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6030 .addReg(ZeroReg).addReg(PtrReg);
6032 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6033 .addReg(Incr2Reg).addReg(TmpDestReg);
6034 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6035 .addReg(TmpDestReg).addReg(MaskReg);
6036 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6037 .addReg(TmpReg).addReg(MaskReg);
6038 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6039 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6040 BuildMI(BB, dl, TII->get(PPC::STWCX))
6041 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6042 BuildMI(BB, dl, TII->get(PPC::BCC))
6043 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6044 BB->addSuccessor(loopMBB);
6045 BB->addSuccessor(exitMBB);
6050 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6055 llvm::MachineBasicBlock*
6056 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6057 MachineBasicBlock *MBB) const {
6058 DebugLoc DL = MI->getDebugLoc();
6059 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6061 MachineFunction *MF = MBB->getParent();
6062 MachineRegisterInfo &MRI = MF->getRegInfo();
6064 const BasicBlock *BB = MBB->getBasicBlock();
6065 MachineFunction::iterator I = MBB;
6069 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6070 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6072 unsigned DstReg = MI->getOperand(0).getReg();
6073 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6074 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6075 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6076 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6078 MVT PVT = getPointerTy();
6079 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6080 "Invalid Pointer Size!");
6081 // For v = setjmp(buf), we generate
6084 // SjLjSetup mainMBB
6090 // buf[LabelOffset] = LR
6094 // v = phi(main, restore)
6097 MachineBasicBlock *thisMBB = MBB;
6098 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6099 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6100 MF->insert(I, mainMBB);
6101 MF->insert(I, sinkMBB);
6103 MachineInstrBuilder MIB;
6105 // Transfer the remainder of BB and its successor edges to sinkMBB.
6106 sinkMBB->splice(sinkMBB->begin(), MBB,
6107 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
6108 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6110 // Note that the structure of the jmp_buf used here is not compatible
6111 // with that used by libc, and is not designed to be. Specifically, it
6112 // stores only those 'reserved' registers that LLVM does not otherwise
6113 // understand how to spill. Also, by convention, by the time this
6114 // intrinsic is called, Clang has already stored the frame address in the
6115 // first slot of the buffer and stack address in the third. Following the
6116 // X86 target code, we'll store the jump address in the second slot. We also
6117 // need to save the TOC pointer (R2) to handle jumps between shared
6118 // libraries, and that will be stored in the fourth slot. The thread
6119 // identifier (R13) is not affected.
6122 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6123 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6125 // Prepare IP either in reg.
6126 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6127 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6128 unsigned BufReg = MI->getOperand(1).getReg();
6130 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6131 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6133 .addImm(TOCOffset / 4)
6136 MIB.setMemRefs(MMOBegin, MMOEnd);
6140 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6141 MIB.addRegMask(PPCRegInfo->getNoPreservedMask());
6143 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6145 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6147 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6149 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6150 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6154 MIB = BuildMI(mainMBB, DL,
6155 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6158 if (PPCSubTarget.isPPC64()) {
6159 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6161 .addImm(LabelOffset / 4)
6164 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6166 .addImm(LabelOffset)
6170 MIB.setMemRefs(MMOBegin, MMOEnd);
6172 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6173 mainMBB->addSuccessor(sinkMBB);
6176 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6177 TII->get(PPC::PHI), DstReg)
6178 .addReg(mainDstReg).addMBB(mainMBB)
6179 .addReg(restoreDstReg).addMBB(thisMBB);
6181 MI->eraseFromParent();
6186 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6187 MachineBasicBlock *MBB) const {
6188 DebugLoc DL = MI->getDebugLoc();
6189 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6191 MachineFunction *MF = MBB->getParent();
6192 MachineRegisterInfo &MRI = MF->getRegInfo();
6195 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6196 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6198 MVT PVT = getPointerTy();
6199 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6200 "Invalid Pointer Size!");
6202 const TargetRegisterClass *RC =
6203 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6204 unsigned Tmp = MRI.createVirtualRegister(RC);
6205 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6206 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6207 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6209 MachineInstrBuilder MIB;
6211 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6212 const int64_t SPOffset = 2 * PVT.getStoreSize();
6213 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6215 unsigned BufReg = MI->getOperand(0).getReg();
6217 // Reload FP (the jumped-to function may not have had a
6218 // frame pointer, and if so, then its r31 will be restored
6220 if (PVT == MVT::i64) {
6221 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6225 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6229 MIB.setMemRefs(MMOBegin, MMOEnd);
6232 if (PVT == MVT::i64) {
6233 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6234 .addImm(LabelOffset / 4)
6237 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6238 .addImm(LabelOffset)
6241 MIB.setMemRefs(MMOBegin, MMOEnd);
6244 if (PVT == MVT::i64) {
6245 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6246 .addImm(SPOffset / 4)
6249 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6253 MIB.setMemRefs(MMOBegin, MMOEnd);
6255 // FIXME: When we also support base pointers, that register must also be
6259 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6260 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6261 .addImm(TOCOffset / 4)
6264 MIB.setMemRefs(MMOBegin, MMOEnd);
6268 BuildMI(*MBB, MI, DL,
6269 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6270 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6272 MI->eraseFromParent();
6277 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6278 MachineBasicBlock *BB) const {
6279 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6280 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6281 return emitEHSjLjSetJmp(MI, BB);
6282 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6283 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6284 return emitEHSjLjLongJmp(MI, BB);
6287 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6289 // To "insert" these instructions we actually have to insert their
6290 // control-flow patterns.
6291 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6292 MachineFunction::iterator It = BB;
6295 MachineFunction *F = BB->getParent();
6297 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6298 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6299 SmallVector<MachineOperand, 2> Cond;
6300 Cond.push_back(MI->getOperand(4));
6301 Cond.push_back(MI->getOperand(1));
6303 DebugLoc dl = MI->getDebugLoc();
6304 PPCII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(), Cond,
6305 MI->getOperand(2).getReg(), MI->getOperand(3).getReg());
6306 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6307 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6308 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6309 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6310 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6313 // The incoming instruction knows the destination vreg to set, the
6314 // condition code register to branch on, the true/false values to
6315 // select between, and a branch opcode to use.
6320 // cmpTY ccX, r1, r2
6322 // fallthrough --> copy0MBB
6323 MachineBasicBlock *thisMBB = BB;
6324 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6325 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6326 unsigned SelectPred = MI->getOperand(4).getImm();
6327 DebugLoc dl = MI->getDebugLoc();
6328 F->insert(It, copy0MBB);
6329 F->insert(It, sinkMBB);
6331 // Transfer the remainder of BB and its successor edges to sinkMBB.
6332 sinkMBB->splice(sinkMBB->begin(), BB,
6333 llvm::next(MachineBasicBlock::iterator(MI)),
6335 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6337 // Next, add the true and fallthrough blocks as its successors.
6338 BB->addSuccessor(copy0MBB);
6339 BB->addSuccessor(sinkMBB);
6341 BuildMI(BB, dl, TII->get(PPC::BCC))
6342 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6345 // %FalseValue = ...
6346 // # fallthrough to sinkMBB
6349 // Update machine-CFG edges
6350 BB->addSuccessor(sinkMBB);
6353 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6356 BuildMI(*BB, BB->begin(), dl,
6357 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6358 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6359 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6361 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6362 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6363 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6364 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6365 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6366 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6367 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6368 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6370 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6371 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6372 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6373 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6374 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6375 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6376 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6377 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6379 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6380 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6381 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6382 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6383 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6384 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6385 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6386 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6388 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6389 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6390 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6391 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6392 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6393 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6394 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6395 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6397 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6398 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6399 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6400 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6401 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6402 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6403 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6404 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6406 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6407 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6408 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6409 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6410 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6411 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6412 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6413 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6415 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6416 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6417 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6418 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6419 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6420 BB = EmitAtomicBinary(MI, BB, false, 0);
6421 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6422 BB = EmitAtomicBinary(MI, BB, true, 0);
6424 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6425 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6426 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6428 unsigned dest = MI->getOperand(0).getReg();
6429 unsigned ptrA = MI->getOperand(1).getReg();
6430 unsigned ptrB = MI->getOperand(2).getReg();
6431 unsigned oldval = MI->getOperand(3).getReg();
6432 unsigned newval = MI->getOperand(4).getReg();
6433 DebugLoc dl = MI->getDebugLoc();
6435 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6436 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6437 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6438 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6439 F->insert(It, loop1MBB);
6440 F->insert(It, loop2MBB);
6441 F->insert(It, midMBB);
6442 F->insert(It, exitMBB);
6443 exitMBB->splice(exitMBB->begin(), BB,
6444 llvm::next(MachineBasicBlock::iterator(MI)),
6446 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6450 // fallthrough --> loopMBB
6451 BB->addSuccessor(loop1MBB);
6454 // l[wd]arx dest, ptr
6455 // cmp[wd] dest, oldval
6458 // st[wd]cx. newval, ptr
6462 // st[wd]cx. dest, ptr
6465 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6466 .addReg(ptrA).addReg(ptrB);
6467 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6468 .addReg(oldval).addReg(dest);
6469 BuildMI(BB, dl, TII->get(PPC::BCC))
6470 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6471 BB->addSuccessor(loop2MBB);
6472 BB->addSuccessor(midMBB);
6475 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6476 .addReg(newval).addReg(ptrA).addReg(ptrB);
6477 BuildMI(BB, dl, TII->get(PPC::BCC))
6478 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6479 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6480 BB->addSuccessor(loop1MBB);
6481 BB->addSuccessor(exitMBB);
6484 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6485 .addReg(dest).addReg(ptrA).addReg(ptrB);
6486 BB->addSuccessor(exitMBB);
6491 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6492 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6493 // We must use 64-bit registers for addresses when targeting 64-bit,
6494 // since we're actually doing arithmetic on them. Other registers
6496 bool is64bit = PPCSubTarget.isPPC64();
6497 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6499 unsigned dest = MI->getOperand(0).getReg();
6500 unsigned ptrA = MI->getOperand(1).getReg();
6501 unsigned ptrB = MI->getOperand(2).getReg();
6502 unsigned oldval = MI->getOperand(3).getReg();
6503 unsigned newval = MI->getOperand(4).getReg();
6504 DebugLoc dl = MI->getDebugLoc();
6506 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6507 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6508 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6509 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6510 F->insert(It, loop1MBB);
6511 F->insert(It, loop2MBB);
6512 F->insert(It, midMBB);
6513 F->insert(It, exitMBB);
6514 exitMBB->splice(exitMBB->begin(), BB,
6515 llvm::next(MachineBasicBlock::iterator(MI)),
6517 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6519 MachineRegisterInfo &RegInfo = F->getRegInfo();
6520 const TargetRegisterClass *RC =
6521 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6522 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6523 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6524 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6525 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6526 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6527 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6528 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6529 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6530 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6531 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6532 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6533 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6534 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6535 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6537 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6538 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6541 // fallthrough --> loopMBB
6542 BB->addSuccessor(loop1MBB);
6544 // The 4-byte load must be aligned, while a char or short may be
6545 // anywhere in the word. Hence all this nasty bookkeeping code.
6546 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6547 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6548 // xori shift, shift1, 24 [16]
6549 // rlwinm ptr, ptr1, 0, 0, 29
6550 // slw newval2, newval, shift
6551 // slw oldval2, oldval,shift
6552 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6553 // slw mask, mask2, shift
6554 // and newval3, newval2, mask
6555 // and oldval3, oldval2, mask
6557 // lwarx tmpDest, ptr
6558 // and tmp, tmpDest, mask
6559 // cmpw tmp, oldval3
6562 // andc tmp2, tmpDest, mask
6563 // or tmp4, tmp2, newval3
6568 // stwcx. tmpDest, ptr
6570 // srw dest, tmpDest, shift
6571 if (ptrA != ZeroReg) {
6572 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6573 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6574 .addReg(ptrA).addReg(ptrB);
6578 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6579 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6580 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6581 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6583 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6584 .addReg(Ptr1Reg).addImm(0).addImm(61);
6586 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6587 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6588 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6589 .addReg(newval).addReg(ShiftReg);
6590 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6591 .addReg(oldval).addReg(ShiftReg);
6593 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6595 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6596 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6597 .addReg(Mask3Reg).addImm(65535);
6599 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6600 .addReg(Mask2Reg).addReg(ShiftReg);
6601 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6602 .addReg(NewVal2Reg).addReg(MaskReg);
6603 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6604 .addReg(OldVal2Reg).addReg(MaskReg);
6607 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6608 .addReg(ZeroReg).addReg(PtrReg);
6609 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6610 .addReg(TmpDestReg).addReg(MaskReg);
6611 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6612 .addReg(TmpReg).addReg(OldVal3Reg);
6613 BuildMI(BB, dl, TII->get(PPC::BCC))
6614 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6615 BB->addSuccessor(loop2MBB);
6616 BB->addSuccessor(midMBB);
6619 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6620 .addReg(TmpDestReg).addReg(MaskReg);
6621 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6622 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6623 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6624 .addReg(ZeroReg).addReg(PtrReg);
6625 BuildMI(BB, dl, TII->get(PPC::BCC))
6626 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6627 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6628 BB->addSuccessor(loop1MBB);
6629 BB->addSuccessor(exitMBB);
6632 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6633 .addReg(ZeroReg).addReg(PtrReg);
6634 BB->addSuccessor(exitMBB);
6639 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6641 } else if (MI->getOpcode() == PPC::FADDrtz) {
6642 // This pseudo performs an FADD with rounding mode temporarily forced
6643 // to round-to-zero. We emit this via custom inserter since the FPSCR
6644 // is not modeled at the SelectionDAG level.
6645 unsigned Dest = MI->getOperand(0).getReg();
6646 unsigned Src1 = MI->getOperand(1).getReg();
6647 unsigned Src2 = MI->getOperand(2).getReg();
6648 DebugLoc dl = MI->getDebugLoc();
6650 MachineRegisterInfo &RegInfo = F->getRegInfo();
6651 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6653 // Save FPSCR value.
6654 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6656 // Set rounding mode to round-to-zero.
6657 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6658 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6660 // Perform addition.
6661 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6663 // Restore FPSCR value.
6664 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6665 } else if (MI->getOpcode() == PPC::FRINDrint ||
6666 MI->getOpcode() == PPC::FRINSrint) {
6667 bool isf32 = MI->getOpcode() == PPC::FRINSrint;
6668 unsigned Dest = MI->getOperand(0).getReg();
6669 unsigned Src = MI->getOperand(1).getReg();
6670 DebugLoc dl = MI->getDebugLoc();
6672 MachineRegisterInfo &RegInfo = F->getRegInfo();
6673 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
6675 // Perform the rounding.
6676 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FRINS : PPC::FRIND), Dest)
6679 // Compare the results.
6680 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FCMPUS : PPC::FCMPUD), CRReg)
6681 .addReg(Dest).addReg(Src);
6683 // If the results were not equal, then set the FPSCR XX bit.
6684 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6685 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6686 F->insert(It, midMBB);
6687 F->insert(It, exitMBB);
6688 exitMBB->splice(exitMBB->begin(), BB,
6689 llvm::next(MachineBasicBlock::iterator(MI)),
6691 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6693 BuildMI(*BB, MI, dl, TII->get(PPC::BCC))
6694 .addImm(PPC::PRED_EQ).addReg(CRReg).addMBB(exitMBB);
6696 BB->addSuccessor(midMBB);
6697 BB->addSuccessor(exitMBB);
6701 // Set the FPSCR XX bit (FE_INEXACT). Note that we cannot just set
6702 // the FI bit here because that will not automatically set XX also,
6703 // and XX is what libm interprets as the FE_INEXACT flag.
6704 BuildMI(BB, dl, TII->get(PPC::MTFSB1)).addImm(/* 38 - 32 = */ 6);
6705 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6707 BB->addSuccessor(exitMBB);
6711 llvm_unreachable("Unexpected instr type to insert");
6714 MI->eraseFromParent(); // The pseudo instruction is gone now.
6718 //===----------------------------------------------------------------------===//
6719 // Target Optimization Hooks
6720 //===----------------------------------------------------------------------===//
6722 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6723 DAGCombinerInfo &DCI) const {
6724 if (DCI.isAfterLegalizeVectorOps())
6727 EVT VT = Op.getValueType();
6729 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6730 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6731 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6733 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6734 // For the reciprocal, we need to find the zero of the function:
6735 // F(X) = A X - 1 [which has a zero at X = 1/A]
6737 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6738 // does not require additional intermediate precision]
6740 // Convergence is quadratic, so we essentially double the number of digits
6741 // correct after every iteration. The minimum architected relative
6742 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6743 // 23 digits and double has 52 digits.
6744 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6745 if (VT.getScalarType() == MVT::f64)
6748 SelectionDAG &DAG = DCI.DAG;
6749 DebugLoc dl = Op.getDebugLoc();
6752 DAG.getConstantFP(1.0, VT.getScalarType());
6753 if (VT.isVector()) {
6754 assert(VT.getVectorNumElements() == 4 &&
6755 "Unknown vector type");
6756 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6757 FPOne, FPOne, FPOne, FPOne);
6760 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6761 DCI.AddToWorklist(Est.getNode());
6763 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6764 for (int i = 0; i < Iterations; ++i) {
6765 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6766 DCI.AddToWorklist(NewEst.getNode());
6768 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6769 DCI.AddToWorklist(NewEst.getNode());
6771 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6772 DCI.AddToWorklist(NewEst.getNode());
6774 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6775 DCI.AddToWorklist(Est.getNode());
6784 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6785 DAGCombinerInfo &DCI) const {
6786 if (DCI.isAfterLegalizeVectorOps())
6789 EVT VT = Op.getValueType();
6791 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6792 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6793 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6795 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6796 // For the reciprocal sqrt, we need to find the zero of the function:
6797 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6799 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6800 // As a result, we precompute A/2 prior to the iteration loop.
6802 // Convergence is quadratic, so we essentially double the number of digits
6803 // correct after every iteration. The minimum architected relative
6804 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6805 // 23 digits and double has 52 digits.
6806 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6807 if (VT.getScalarType() == MVT::f64)
6810 SelectionDAG &DAG = DCI.DAG;
6811 DebugLoc dl = Op.getDebugLoc();
6813 SDValue FPThreeHalves =
6814 DAG.getConstantFP(1.5, VT.getScalarType());
6815 if (VT.isVector()) {
6816 assert(VT.getVectorNumElements() == 4 &&
6817 "Unknown vector type");
6818 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6819 FPThreeHalves, FPThreeHalves,
6820 FPThreeHalves, FPThreeHalves);
6823 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6824 DCI.AddToWorklist(Est.getNode());
6826 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
6827 // this entire sequence requires only one FP constant.
6828 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
6829 DCI.AddToWorklist(HalfArg.getNode());
6831 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
6832 DCI.AddToWorklist(HalfArg.getNode());
6834 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
6835 for (int i = 0; i < Iterations; ++i) {
6836 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
6837 DCI.AddToWorklist(NewEst.getNode());
6839 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
6840 DCI.AddToWorklist(NewEst.getNode());
6842 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
6843 DCI.AddToWorklist(NewEst.getNode());
6845 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6846 DCI.AddToWorklist(Est.getNode());
6855 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6856 DAGCombinerInfo &DCI) const {
6857 const TargetMachine &TM = getTargetMachine();
6858 SelectionDAG &DAG = DCI.DAG;
6859 DebugLoc dl = N->getDebugLoc();
6860 switch (N->getOpcode()) {
6863 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6864 if (C->isNullValue()) // 0 << V -> 0.
6865 return N->getOperand(0);
6869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6870 if (C->isNullValue()) // 0 >>u V -> 0.
6871 return N->getOperand(0);
6875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6876 if (C->isNullValue() || // 0 >>s V -> 0.
6877 C->isAllOnesValue()) // -1 >>s V -> -1.
6878 return N->getOperand(0);
6882 assert(TM.Options.UnsafeFPMath &&
6883 "Reciprocal estimates require UnsafeFPMath");
6885 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
6887 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
6888 if (RV.getNode() != 0) {
6889 DCI.AddToWorklist(RV.getNode());
6890 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6891 N->getOperand(0), RV);
6893 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
6894 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6896 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6898 if (RV.getNode() != 0) {
6899 DCI.AddToWorklist(RV.getNode());
6900 RV = DAG.getNode(ISD::FP_EXTEND, N->getOperand(1).getDebugLoc(),
6901 N->getValueType(0), RV);
6902 DCI.AddToWorklist(RV.getNode());
6903 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6904 N->getOperand(0), RV);
6906 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
6907 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6909 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6911 if (RV.getNode() != 0) {
6912 DCI.AddToWorklist(RV.getNode());
6913 RV = DAG.getNode(ISD::FP_ROUND, N->getOperand(1).getDebugLoc(),
6914 N->getValueType(0), RV,
6915 N->getOperand(1).getOperand(1));
6916 DCI.AddToWorklist(RV.getNode());
6917 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6918 N->getOperand(0), RV);
6922 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
6923 if (RV.getNode() != 0) {
6924 DCI.AddToWorklist(RV.getNode());
6925 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6926 N->getOperand(0), RV);
6932 assert(TM.Options.UnsafeFPMath &&
6933 "Reciprocal estimates require UnsafeFPMath");
6935 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
6937 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
6938 if (RV.getNode() != 0) {
6939 DCI.AddToWorklist(RV.getNode());
6940 RV = DAGCombineFastRecip(RV, DCI);
6941 if (RV.getNode() != 0)
6947 case ISD::SINT_TO_FP:
6948 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6949 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6950 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6951 // We allow the src/dst to be either f32/f64, but the intermediate
6952 // type must be i64.
6953 if (N->getOperand(0).getValueType() == MVT::i64 &&
6954 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6955 SDValue Val = N->getOperand(0).getOperand(0);
6956 if (Val.getValueType() == MVT::f32) {
6957 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6958 DCI.AddToWorklist(Val.getNode());
6961 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6962 DCI.AddToWorklist(Val.getNode());
6963 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6964 DCI.AddToWorklist(Val.getNode());
6965 if (N->getValueType(0) == MVT::f32) {
6966 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6967 DAG.getIntPtrConstant(0));
6968 DCI.AddToWorklist(Val.getNode());
6971 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6972 // If the intermediate type is i32, we can avoid the load/store here
6979 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6980 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6981 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6982 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6983 N->getOperand(1).getValueType() == MVT::i32 &&
6984 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6985 SDValue Val = N->getOperand(1).getOperand(0);
6986 if (Val.getValueType() == MVT::f32) {
6987 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6988 DCI.AddToWorklist(Val.getNode());
6990 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6991 DCI.AddToWorklist(Val.getNode());
6994 N->getOperand(0), Val, N->getOperand(2),
6995 DAG.getValueType(N->getOperand(1).getValueType())
6998 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
6999 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7000 cast<StoreSDNode>(N)->getMemoryVT(),
7001 cast<StoreSDNode>(N)->getMemOperand());
7002 DCI.AddToWorklist(Val.getNode());
7006 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7007 if (cast<StoreSDNode>(N)->isUnindexed() &&
7008 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7009 N->getOperand(1).getNode()->hasOneUse() &&
7010 (N->getOperand(1).getValueType() == MVT::i32 ||
7011 N->getOperand(1).getValueType() == MVT::i16 ||
7012 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7013 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7014 N->getOperand(1).getValueType() == MVT::i64))) {
7015 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7016 // Do an any-extend to 32-bits if this is a half-word input.
7017 if (BSwapOp.getValueType() == MVT::i16)
7018 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7021 N->getOperand(0), BSwapOp, N->getOperand(2),
7022 DAG.getValueType(N->getOperand(1).getValueType())
7025 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7026 Ops, array_lengthof(Ops),
7027 cast<StoreSDNode>(N)->getMemoryVT(),
7028 cast<StoreSDNode>(N)->getMemOperand());
7032 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
7033 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
7034 N->getOperand(0).hasOneUse() &&
7035 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
7036 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7037 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7038 N->getValueType(0) == MVT::i64))) {
7039 SDValue Load = N->getOperand(0);
7040 LoadSDNode *LD = cast<LoadSDNode>(Load);
7041 // Create the byte-swapping load.
7043 LD->getChain(), // Chain
7044 LD->getBasePtr(), // Ptr
7045 DAG.getValueType(N->getValueType(0)) // VT
7048 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
7049 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
7050 MVT::i64 : MVT::i32, MVT::Other),
7051 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
7053 // If this is an i16 load, insert the truncate.
7054 SDValue ResVal = BSLoad;
7055 if (N->getValueType(0) == MVT::i16)
7056 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
7058 // First, combine the bswap away. This makes the value produced by the
7060 DCI.CombineTo(N, ResVal);
7062 // Next, combine the load away, we give it a bogus result value but a real
7063 // chain result. The result value is dead because the bswap is dead.
7064 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
7066 // Return N so it doesn't get rechecked!
7067 return SDValue(N, 0);
7071 case PPCISD::VCMP: {
7072 // If a VCMPo node already exists with exactly the same operands as this
7073 // node, use its result instead of this node (VCMPo computes both a CR6 and
7074 // a normal output).
7076 if (!N->getOperand(0).hasOneUse() &&
7077 !N->getOperand(1).hasOneUse() &&
7078 !N->getOperand(2).hasOneUse()) {
7080 // Scan all of the users of the LHS, looking for VCMPo's that match.
7081 SDNode *VCMPoNode = 0;
7083 SDNode *LHSN = N->getOperand(0).getNode();
7084 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
7086 if (UI->getOpcode() == PPCISD::VCMPo &&
7087 UI->getOperand(1) == N->getOperand(1) &&
7088 UI->getOperand(2) == N->getOperand(2) &&
7089 UI->getOperand(0) == N->getOperand(0)) {
7094 // If there is no VCMPo node, or if the flag value has a single use, don't
7096 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
7099 // Look at the (necessarily single) use of the flag value. If it has a
7100 // chain, this transformation is more complex. Note that multiple things
7101 // could use the value result, which we should ignore.
7102 SDNode *FlagUser = 0;
7103 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
7104 FlagUser == 0; ++UI) {
7105 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
7107 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
7108 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
7115 // If the user is a MFCR instruction, we know this is safe. Otherwise we
7116 // give up for right now.
7117 if (FlagUser->getOpcode() == PPCISD::MFCR)
7118 return SDValue(VCMPoNode, 0);
7123 // If this is a branch on an altivec predicate comparison, lower this so
7124 // that we don't have to do a MFCR: instead, branch directly on CR6. This
7125 // lowering is done pre-legalize, because the legalizer lowers the predicate
7126 // compare down to code that is difficult to reassemble.
7127 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
7128 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
7130 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
7131 // value. If so, pass-through the AND to get to the intrinsic.
7132 if (LHS.getOpcode() == ISD::AND &&
7133 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7134 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
7135 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7136 isa<ConstantSDNode>(LHS.getOperand(1)) &&
7137 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
7139 LHS = LHS.getOperand(0);
7141 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7142 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
7143 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7144 isa<ConstantSDNode>(RHS)) {
7145 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7146 "Counter decrement comparison is not EQ or NE");
7148 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7149 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
7150 (CC == ISD::SETNE && !Val);
7152 // We now need to make the intrinsic dead (it cannot be instruction
7154 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
7155 assert(LHS.getNode()->hasOneUse() &&
7156 "Counter decrement has more than one use");
7158 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
7159 N->getOperand(0), N->getOperand(4));
7165 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7166 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
7167 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
7168 assert(isDot && "Can't compare against a vector result!");
7170 // If this is a comparison against something other than 0/1, then we know
7171 // that the condition is never/always true.
7172 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7173 if (Val != 0 && Val != 1) {
7174 if (CC == ISD::SETEQ) // Cond never true, remove branch.
7175 return N->getOperand(0);
7176 // Always !=, turn it into an unconditional branch.
7177 return DAG.getNode(ISD::BR, dl, MVT::Other,
7178 N->getOperand(0), N->getOperand(4));
7181 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
7183 // Create the PPCISD altivec 'dot' comparison node.
7185 LHS.getOperand(2), // LHS of compare
7186 LHS.getOperand(3), // RHS of compare
7187 DAG.getConstant(CompareOpc, MVT::i32)
7189 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
7190 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
7192 // Unpack the result based on how the target uses it.
7193 PPC::Predicate CompOpc;
7194 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
7195 default: // Can't happen, don't crash on invalid number though.
7196 case 0: // Branch on the value of the EQ bit of CR6.
7197 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
7199 case 1: // Branch on the inverted value of the EQ bit of CR6.
7200 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
7202 case 2: // Branch on the value of the LT bit of CR6.
7203 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
7205 case 3: // Branch on the inverted value of the LT bit of CR6.
7206 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
7210 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
7211 DAG.getConstant(CompOpc, MVT::i32),
7212 DAG.getRegister(PPC::CR6, MVT::i32),
7213 N->getOperand(4), CompNode.getValue(1));
7222 //===----------------------------------------------------------------------===//
7223 // Inline Assembly Support
7224 //===----------------------------------------------------------------------===//
7226 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7229 const SelectionDAG &DAG,
7230 unsigned Depth) const {
7231 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
7232 switch (Op.getOpcode()) {
7234 case PPCISD::LBRX: {
7235 // lhbrx is known to have the top bits cleared out.
7236 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
7237 KnownZero = 0xFFFF0000;
7240 case ISD::INTRINSIC_WO_CHAIN: {
7241 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
7243 case Intrinsic::ppc_altivec_vcmpbfp_p:
7244 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7245 case Intrinsic::ppc_altivec_vcmpequb_p:
7246 case Intrinsic::ppc_altivec_vcmpequh_p:
7247 case Intrinsic::ppc_altivec_vcmpequw_p:
7248 case Intrinsic::ppc_altivec_vcmpgefp_p:
7249 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7250 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7251 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7252 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7253 case Intrinsic::ppc_altivec_vcmpgtub_p:
7254 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7255 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7256 KnownZero = ~1U; // All bits but the low one are known to be zero.
7264 /// getConstraintType - Given a constraint, return the type of
7265 /// constraint it is for this target.
7266 PPCTargetLowering::ConstraintType
7267 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
7268 if (Constraint.size() == 1) {
7269 switch (Constraint[0]) {
7276 return C_RegisterClass;
7278 // FIXME: While Z does indicate a memory constraint, it specifically
7279 // indicates an r+r address (used in conjunction with the 'y' modifier
7280 // in the replacement string). Currently, we're forcing the base
7281 // register to be r0 in the asm printer (which is interpreted as zero)
7282 // and forming the complete address in the second register. This is
7287 return TargetLowering::getConstraintType(Constraint);
7290 /// Examine constraint type and operand type and determine a weight value.
7291 /// This object must already have been set up with the operand type
7292 /// and the current alternative constraint selected.
7293 TargetLowering::ConstraintWeight
7294 PPCTargetLowering::getSingleConstraintMatchWeight(
7295 AsmOperandInfo &info, const char *constraint) const {
7296 ConstraintWeight weight = CW_Invalid;
7297 Value *CallOperandVal = info.CallOperandVal;
7298 // If we don't have a value, we can't do a match,
7299 // but allow it at the lowest weight.
7300 if (CallOperandVal == NULL)
7302 Type *type = CallOperandVal->getType();
7303 // Look at the constraint type.
7304 switch (*constraint) {
7306 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7309 if (type->isIntegerTy())
7310 weight = CW_Register;
7313 if (type->isFloatTy())
7314 weight = CW_Register;
7317 if (type->isDoubleTy())
7318 weight = CW_Register;
7321 if (type->isVectorTy())
7322 weight = CW_Register;
7325 weight = CW_Register;
7334 std::pair<unsigned, const TargetRegisterClass*>
7335 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7337 if (Constraint.size() == 1) {
7338 // GCC RS6000 Constraint Letters
7339 switch (Constraint[0]) {
7341 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7342 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
7343 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
7345 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7346 return std::make_pair(0U, &PPC::G8RCRegClass);
7347 return std::make_pair(0U, &PPC::GPRCRegClass);
7349 if (VT == MVT::f32 || VT == MVT::i32)
7350 return std::make_pair(0U, &PPC::F4RCRegClass);
7351 if (VT == MVT::f64 || VT == MVT::i64)
7352 return std::make_pair(0U, &PPC::F8RCRegClass);
7355 return std::make_pair(0U, &PPC::VRRCRegClass);
7357 return std::make_pair(0U, &PPC::CRRCRegClass);
7361 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7365 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7366 /// vector. If it is invalid, don't add anything to Ops.
7367 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7368 std::string &Constraint,
7369 std::vector<SDValue>&Ops,
7370 SelectionDAG &DAG) const {
7371 SDValue Result(0,0);
7373 // Only support length 1 constraints.
7374 if (Constraint.length() > 1) return;
7376 char Letter = Constraint[0];
7387 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
7388 if (!CST) return; // Must be an immediate to match.
7389 unsigned Value = CST->getZExtValue();
7391 default: llvm_unreachable("Unknown constraint letter!");
7392 case 'I': // "I" is a signed 16-bit constant.
7393 if ((short)Value == (int)Value)
7394 Result = DAG.getTargetConstant(Value, Op.getValueType());
7396 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
7397 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
7398 if ((short)Value == 0)
7399 Result = DAG.getTargetConstant(Value, Op.getValueType());
7401 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
7402 if ((Value >> 16) == 0)
7403 Result = DAG.getTargetConstant(Value, Op.getValueType());
7405 case 'M': // "M" is a constant that is greater than 31.
7407 Result = DAG.getTargetConstant(Value, Op.getValueType());
7409 case 'N': // "N" is a positive constant that is an exact power of two.
7410 if ((int)Value > 0 && isPowerOf2_32(Value))
7411 Result = DAG.getTargetConstant(Value, Op.getValueType());
7413 case 'O': // "O" is the constant zero.
7415 Result = DAG.getTargetConstant(Value, Op.getValueType());
7417 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
7418 if ((short)-Value == (int)-Value)
7419 Result = DAG.getTargetConstant(Value, Op.getValueType());
7426 if (Result.getNode()) {
7427 Ops.push_back(Result);
7431 // Handle standard constraint letters.
7432 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7435 // isLegalAddressingMode - Return true if the addressing mode represented
7436 // by AM is legal for this target, for a load/store of the specified type.
7437 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7439 // FIXME: PPC does not allow r+i addressing modes for vectors!
7441 // PPC allows a sign-extended 16-bit immediate field.
7442 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
7445 // No global is ever allowed as a base.
7449 // PPC only support r+r,
7451 case 0: // "r+i" or just "i", depending on HasBaseReg.
7454 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7456 // Otherwise we have r+r or r+i.
7459 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7461 // Allow 2*r as r+r.
7464 // No other scales are supported.
7471 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7472 SelectionDAG &DAG) const {
7473 MachineFunction &MF = DAG.getMachineFunction();
7474 MachineFrameInfo *MFI = MF.getFrameInfo();
7475 MFI->setReturnAddressIsTaken(true);
7477 DebugLoc dl = Op.getDebugLoc();
7478 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7480 // Make sure the function does not optimize away the store of the RA to
7482 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7483 FuncInfo->setLRStoreRequired();
7484 bool isPPC64 = PPCSubTarget.isPPC64();
7485 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7488 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7491 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7492 isPPC64? MVT::i64 : MVT::i32);
7493 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7494 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7496 MachinePointerInfo(), false, false, false, 0);
7499 // Just load the return address off the stack.
7500 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7501 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7502 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7505 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7506 SelectionDAG &DAG) const {
7507 DebugLoc dl = Op.getDebugLoc();
7508 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7510 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7511 bool isPPC64 = PtrVT == MVT::i64;
7513 MachineFunction &MF = DAG.getMachineFunction();
7514 MachineFrameInfo *MFI = MF.getFrameInfo();
7515 MFI->setFrameAddressIsTaken(true);
7517 // Naked functions never have a frame pointer, and so we use r1. For all
7518 // other functions, this decision must be delayed until during PEI.
7520 if (MF.getFunction()->getAttributes().hasAttribute(
7521 AttributeSet::FunctionIndex, Attribute::Naked))
7522 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7524 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7526 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7529 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7530 FrameAddr, MachinePointerInfo(), false, false,
7536 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7537 // The PowerPC target isn't yet aware of offsets.
7541 /// getOptimalMemOpType - Returns the target specific optimal type for load
7542 /// and store operations as a result of memset, memcpy, and memmove
7543 /// lowering. If DstAlign is zero that means it's safe to destination
7544 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7545 /// means there isn't a need to check it against alignment requirement,
7546 /// probably because the source does not need to be loaded. If 'IsMemset' is
7547 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7548 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7549 /// source is constant so it does not need to be loaded.
7550 /// It returns EVT::Other if the type should be determined using generic
7551 /// target-independent logic.
7552 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7553 unsigned DstAlign, unsigned SrcAlign,
7554 bool IsMemset, bool ZeroMemset,
7556 MachineFunction &MF) const {
7557 if (this->PPCSubTarget.isPPC64()) {
7564 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7566 if (DisablePPCUnaligned)
7569 // PowerPC supports unaligned memory access for simple non-vector types.
7570 // Although accessing unaligned addresses is not as efficient as accessing
7571 // aligned addresses, it is generally more efficient than manual expansion,
7572 // and generally only traps for software emulation when crossing page
7578 if (VT.getSimpleVT().isVector())
7581 if (VT == MVT::ppcf128)
7590 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7591 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7592 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7593 /// is expanded to mul + add.
7594 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7598 switch (VT.getSimpleVT().SimpleTy) {
7610 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7612 return TargetLowering::getSchedulingPreference(N);