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 "PPCMachineFunctionInfo.h"
16 #include "PPCPerfectShuffle.h"
17 #include "PPCTargetMachine.h"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40 CCValAssign::LocInfo &LocInfo,
41 ISD::ArgFlagsTy &ArgFlags,
43 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
45 CCValAssign::LocInfo &LocInfo,
46 ISD::ArgFlagsTy &ArgFlags,
48 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
50 CCValAssign::LocInfo &LocInfo,
51 ISD::ArgFlagsTy &ArgFlags,
54 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
55 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
57 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
58 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
60 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
61 if (TM.getSubtargetImpl()->isDarwin())
62 return new TargetLoweringObjectFileMachO();
64 return new TargetLoweringObjectFileELF();
67 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
68 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72 // Use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
76 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
77 // arguments are at least 4/8 bytes aligned.
78 setMinStackArgumentAlignment(TM.getSubtarget<PPCSubtarget>().isPPC64() ? 8:4);
80 // Set up the register classes.
81 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
82 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
83 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
85 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
86 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
89 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
91 // PowerPC has pre-inc load and store's.
92 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
93 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
94 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
95 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
96 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
97 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
98 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
101 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
103 // This is used in the ppcf128->int sequence. Note it has different semantics
104 // from FP_ROUND: that rounds to nearest, this rounds to zero.
105 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
107 // We do not currently implment this libm ops for PowerPC.
108 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
109 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
110 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
111 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
112 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
114 // PowerPC has no SREM/UREM instructions
115 setOperationAction(ISD::SREM, MVT::i32, Expand);
116 setOperationAction(ISD::UREM, MVT::i32, Expand);
117 setOperationAction(ISD::SREM, MVT::i64, Expand);
118 setOperationAction(ISD::UREM, MVT::i64, Expand);
120 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
121 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
122 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
123 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
124 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
125 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
126 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
127 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
128 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
130 // We don't support sin/cos/sqrt/fmod/pow
131 setOperationAction(ISD::FSIN , MVT::f64, Expand);
132 setOperationAction(ISD::FCOS , MVT::f64, Expand);
133 setOperationAction(ISD::FREM , MVT::f64, Expand);
134 setOperationAction(ISD::FPOW , MVT::f64, Expand);
135 setOperationAction(ISD::FMA , MVT::f64, Legal);
136 setOperationAction(ISD::FSIN , MVT::f32, Expand);
137 setOperationAction(ISD::FCOS , MVT::f32, Expand);
138 setOperationAction(ISD::FREM , MVT::f32, Expand);
139 setOperationAction(ISD::FPOW , MVT::f32, Expand);
140 setOperationAction(ISD::FMA , MVT::f32, Legal);
142 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
144 // If we're enabling GP optimizations, use hardware square root
145 if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
146 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
147 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
150 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
153 // PowerPC does not have BSWAP, CTPOP or CTTZ
154 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
155 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
156 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
157 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
158 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
159 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
160 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
161 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
162 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
163 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
165 // PowerPC does not have ROTR
166 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
167 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
169 // PowerPC does not have Select
170 setOperationAction(ISD::SELECT, MVT::i32, Expand);
171 setOperationAction(ISD::SELECT, MVT::i64, Expand);
172 setOperationAction(ISD::SELECT, MVT::f32, Expand);
173 setOperationAction(ISD::SELECT, MVT::f64, Expand);
175 // PowerPC wants to turn select_cc of FP into fsel when possible.
176 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
177 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
179 // PowerPC wants to optimize integer setcc a bit
180 setOperationAction(ISD::SETCC, MVT::i32, Custom);
182 // PowerPC does not have BRCOND which requires SetCC
183 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
185 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
188 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
190 // PowerPC does not have [U|S]INT_TO_FP
191 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
194 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
195 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
196 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
197 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
199 // We cannot sextinreg(i1). Expand to shifts.
200 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
202 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
203 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
204 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
205 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
208 // We want to legalize GlobalAddress and ConstantPool nodes into the
209 // appropriate instructions to materialize the address.
210 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
211 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
212 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
213 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
214 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
215 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
216 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
217 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
218 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
219 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
222 setOperationAction(ISD::TRAP, MVT::Other, Legal);
224 // TRAMPOLINE is custom lowered.
225 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
226 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
228 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
229 setOperationAction(ISD::VASTART , MVT::Other, Custom);
231 if (TM.getSubtarget<PPCSubtarget>().isSVR4ABI()) {
232 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
233 // VAARG always uses double-word chunks, so promote anything smaller.
234 setOperationAction(ISD::VAARG, MVT::i1, Promote);
235 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
236 setOperationAction(ISD::VAARG, MVT::i8, Promote);
237 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
238 setOperationAction(ISD::VAARG, MVT::i16, Promote);
239 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
240 setOperationAction(ISD::VAARG, MVT::i32, Promote);
241 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
242 setOperationAction(ISD::VAARG, MVT::Other, Expand);
244 // VAARG is custom lowered with the 32-bit SVR4 ABI.
245 setOperationAction(ISD::VAARG, MVT::Other, Custom);
246 setOperationAction(ISD::VAARG, MVT::i64, Custom);
249 setOperationAction(ISD::VAARG, MVT::Other, Expand);
251 // Use the default implementation.
252 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
253 setOperationAction(ISD::VAEND , MVT::Other, Expand);
254 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
255 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
256 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
257 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
259 // We want to custom lower some of our intrinsics.
260 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
262 // Comparisons that require checking two conditions.
263 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
264 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
265 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
266 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
267 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
268 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
269 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
270 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
271 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
272 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
273 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
274 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
276 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
277 // They also have instructions for converting between i64 and fp.
278 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
279 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
280 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
281 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
282 // This is just the low 32 bits of a (signed) fp->i64 conversion.
283 // We cannot do this with Promote because i64 is not a legal type.
284 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
286 // FIXME: disable this lowered code. This generates 64-bit register values,
287 // and we don't model the fact that the top part is clobbered by calls. We
288 // need to flag these together so that the value isn't live across a call.
289 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
291 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
292 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
295 if (TM.getSubtarget<PPCSubtarget>().use64BitRegs()) {
296 // 64-bit PowerPC implementations can support i64 types directly
297 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
298 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
299 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
300 // 64-bit PowerPC wants to expand i128 shifts itself.
301 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
302 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
303 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
305 // 32-bit PowerPC wants to expand i64 shifts itself.
306 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
307 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
308 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
311 if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
312 // First set operation action for all vector types to expand. Then we
313 // will selectively turn on ones that can be effectively codegen'd.
314 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
315 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
316 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
318 // add/sub are legal for all supported vector VT's.
319 setOperationAction(ISD::ADD , VT, Legal);
320 setOperationAction(ISD::SUB , VT, Legal);
322 // We promote all shuffles to v16i8.
323 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
324 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
326 // We promote all non-typed operations to v4i32.
327 setOperationAction(ISD::AND , VT, Promote);
328 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
329 setOperationAction(ISD::OR , VT, Promote);
330 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
331 setOperationAction(ISD::XOR , VT, Promote);
332 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
333 setOperationAction(ISD::LOAD , VT, Promote);
334 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
335 setOperationAction(ISD::SELECT, VT, Promote);
336 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
337 setOperationAction(ISD::STORE, VT, Promote);
338 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
340 // No other operations are legal.
341 setOperationAction(ISD::MUL , VT, Expand);
342 setOperationAction(ISD::SDIV, VT, Expand);
343 setOperationAction(ISD::SREM, VT, Expand);
344 setOperationAction(ISD::UDIV, VT, Expand);
345 setOperationAction(ISD::UREM, VT, Expand);
346 setOperationAction(ISD::FDIV, VT, Expand);
347 setOperationAction(ISD::FNEG, VT, Expand);
348 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
349 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
350 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
351 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
352 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
353 setOperationAction(ISD::UDIVREM, VT, Expand);
354 setOperationAction(ISD::SDIVREM, VT, Expand);
355 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
356 setOperationAction(ISD::FPOW, VT, Expand);
357 setOperationAction(ISD::CTPOP, VT, Expand);
358 setOperationAction(ISD::CTLZ, VT, Expand);
359 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
360 setOperationAction(ISD::CTTZ, VT, Expand);
361 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
364 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
365 // with merges, splats, etc.
366 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
368 setOperationAction(ISD::AND , MVT::v4i32, Legal);
369 setOperationAction(ISD::OR , MVT::v4i32, Legal);
370 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
371 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
372 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
373 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
375 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
376 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
377 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
378 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
380 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
381 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
382 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
383 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
384 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
386 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
387 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
389 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
390 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
391 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
392 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
395 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport())
396 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
398 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
399 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
401 setBooleanContents(ZeroOrOneBooleanContent);
402 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
404 if (TM.getSubtarget<PPCSubtarget>().isPPC64()) {
405 setStackPointerRegisterToSaveRestore(PPC::X1);
406 setExceptionPointerRegister(PPC::X3);
407 setExceptionSelectorRegister(PPC::X4);
409 setStackPointerRegisterToSaveRestore(PPC::R1);
410 setExceptionPointerRegister(PPC::R3);
411 setExceptionSelectorRegister(PPC::R4);
414 // We have target-specific dag combine patterns for the following nodes:
415 setTargetDAGCombine(ISD::SINT_TO_FP);
416 setTargetDAGCombine(ISD::STORE);
417 setTargetDAGCombine(ISD::BR_CC);
418 setTargetDAGCombine(ISD::BSWAP);
420 // Darwin long double math library functions have $LDBL128 appended.
421 if (TM.getSubtarget<PPCSubtarget>().isDarwin()) {
422 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
423 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
424 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
425 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
426 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
427 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
428 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
429 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
430 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
431 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
434 setMinFunctionAlignment(2);
435 if (PPCSubTarget.isDarwin())
436 setPrefFunctionAlignment(4);
438 setInsertFencesForAtomic(true);
440 setSchedulingPreference(Sched::Hybrid);
442 computeRegisterProperties();
445 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
446 /// function arguments in the caller parameter area.
447 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
448 const TargetMachine &TM = getTargetMachine();
449 // Darwin passes everything on 4 byte boundary.
450 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
453 // 16byte and wider vectors are passed on 16byte boundary.
454 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
455 if (VTy->getBitWidth() >= 128)
458 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
459 if (PPCSubTarget.isPPC64())
465 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
468 case PPCISD::FSEL: return "PPCISD::FSEL";
469 case PPCISD::FCFID: return "PPCISD::FCFID";
470 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
471 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
472 case PPCISD::STFIWX: return "PPCISD::STFIWX";
473 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
474 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
475 case PPCISD::VPERM: return "PPCISD::VPERM";
476 case PPCISD::Hi: return "PPCISD::Hi";
477 case PPCISD::Lo: return "PPCISD::Lo";
478 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
479 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
480 case PPCISD::LOAD: return "PPCISD::LOAD";
481 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
482 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
483 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
484 case PPCISD::SRL: return "PPCISD::SRL";
485 case PPCISD::SRA: return "PPCISD::SRA";
486 case PPCISD::SHL: return "PPCISD::SHL";
487 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
488 case PPCISD::STD_32: return "PPCISD::STD_32";
489 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
490 case PPCISD::CALL_NOP_SVR4: return "PPCISD::CALL_NOP_SVR4";
491 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
492 case PPCISD::NOP: return "PPCISD::NOP";
493 case PPCISD::MTCTR: return "PPCISD::MTCTR";
494 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
495 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
496 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
497 case PPCISD::MFCR: return "PPCISD::MFCR";
498 case PPCISD::VCMP: return "PPCISD::VCMP";
499 case PPCISD::VCMPo: return "PPCISD::VCMPo";
500 case PPCISD::LBRX: return "PPCISD::LBRX";
501 case PPCISD::STBRX: return "PPCISD::STBRX";
502 case PPCISD::LARX: return "PPCISD::LARX";
503 case PPCISD::STCX: return "PPCISD::STCX";
504 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
505 case PPCISD::MFFS: return "PPCISD::MFFS";
506 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
507 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
508 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
509 case PPCISD::MTFSF: return "PPCISD::MTFSF";
510 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
514 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
518 //===----------------------------------------------------------------------===//
519 // Node matching predicates, for use by the tblgen matching code.
520 //===----------------------------------------------------------------------===//
522 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
523 static bool isFloatingPointZero(SDValue Op) {
524 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
525 return CFP->getValueAPF().isZero();
526 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
527 // Maybe this has already been legalized into the constant pool?
528 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
529 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
530 return CFP->getValueAPF().isZero();
535 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
536 /// true if Op is undef or if it matches the specified value.
537 static bool isConstantOrUndef(int Op, int Val) {
538 return Op < 0 || Op == Val;
541 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
542 /// VPKUHUM instruction.
543 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
545 for (unsigned i = 0; i != 16; ++i)
546 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
549 for (unsigned i = 0; i != 8; ++i)
550 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
551 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
557 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
558 /// VPKUWUM instruction.
559 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
561 for (unsigned i = 0; i != 16; i += 2)
562 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
563 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
566 for (unsigned i = 0; i != 8; i += 2)
567 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
568 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
569 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
570 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
576 /// isVMerge - Common function, used to match vmrg* shuffles.
578 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
579 unsigned LHSStart, unsigned RHSStart) {
580 assert(N->getValueType(0) == MVT::v16i8 &&
581 "PPC only supports shuffles by bytes!");
582 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
583 "Unsupported merge size!");
585 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
586 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
587 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
588 LHSStart+j+i*UnitSize) ||
589 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
590 RHSStart+j+i*UnitSize))
596 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
597 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
598 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
601 return isVMerge(N, UnitSize, 8, 24);
602 return isVMerge(N, UnitSize, 8, 8);
605 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
606 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
607 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
610 return isVMerge(N, UnitSize, 0, 16);
611 return isVMerge(N, UnitSize, 0, 0);
615 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
616 /// amount, otherwise return -1.
617 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
618 assert(N->getValueType(0) == MVT::v16i8 &&
619 "PPC only supports shuffles by bytes!");
621 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
623 // Find the first non-undef value in the shuffle mask.
625 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
628 if (i == 16) return -1; // all undef.
630 // Otherwise, check to see if the rest of the elements are consecutively
631 // numbered from this value.
632 unsigned ShiftAmt = SVOp->getMaskElt(i);
633 if (ShiftAmt < i) return -1;
637 // Check the rest of the elements to see if they are consecutive.
638 for (++i; i != 16; ++i)
639 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
642 // Check the rest of the elements to see if they are consecutive.
643 for (++i; i != 16; ++i)
644 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
650 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
651 /// specifies a splat of a single element that is suitable for input to
652 /// VSPLTB/VSPLTH/VSPLTW.
653 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
654 assert(N->getValueType(0) == MVT::v16i8 &&
655 (EltSize == 1 || EltSize == 2 || EltSize == 4));
657 // This is a splat operation if each element of the permute is the same, and
658 // if the value doesn't reference the second vector.
659 unsigned ElementBase = N->getMaskElt(0);
661 // FIXME: Handle UNDEF elements too!
662 if (ElementBase >= 16)
665 // Check that the indices are consecutive, in the case of a multi-byte element
666 // splatted with a v16i8 mask.
667 for (unsigned i = 1; i != EltSize; ++i)
668 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
671 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
672 if (N->getMaskElt(i) < 0) continue;
673 for (unsigned j = 0; j != EltSize; ++j)
674 if (N->getMaskElt(i+j) != N->getMaskElt(j))
680 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
682 bool PPC::isAllNegativeZeroVector(SDNode *N) {
683 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
685 APInt APVal, APUndef;
689 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
690 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
691 return CFP->getValueAPF().isNegZero();
696 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
697 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
698 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
699 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
700 assert(isSplatShuffleMask(SVOp, EltSize));
701 return SVOp->getMaskElt(0) / EltSize;
704 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
705 /// by using a vspltis[bhw] instruction of the specified element size, return
706 /// the constant being splatted. The ByteSize field indicates the number of
707 /// bytes of each element [124] -> [bhw].
708 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
711 // If ByteSize of the splat is bigger than the element size of the
712 // build_vector, then we have a case where we are checking for a splat where
713 // multiple elements of the buildvector are folded together into a single
714 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
715 unsigned EltSize = 16/N->getNumOperands();
716 if (EltSize < ByteSize) {
717 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
718 SDValue UniquedVals[4];
719 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
721 // See if all of the elements in the buildvector agree across.
722 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
723 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
724 // If the element isn't a constant, bail fully out.
725 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
728 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
729 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
730 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
731 return SDValue(); // no match.
734 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
735 // either constant or undef values that are identical for each chunk. See
736 // if these chunks can form into a larger vspltis*.
738 // Check to see if all of the leading entries are either 0 or -1. If
739 // neither, then this won't fit into the immediate field.
740 bool LeadingZero = true;
741 bool LeadingOnes = true;
742 for (unsigned i = 0; i != Multiple-1; ++i) {
743 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
745 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
746 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
748 // Finally, check the least significant entry.
750 if (UniquedVals[Multiple-1].getNode() == 0)
751 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
752 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
754 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
757 if (UniquedVals[Multiple-1].getNode() == 0)
758 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
759 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
760 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
761 return DAG.getTargetConstant(Val, MVT::i32);
767 // Check to see if this buildvec has a single non-undef value in its elements.
768 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
769 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
770 if (OpVal.getNode() == 0)
771 OpVal = N->getOperand(i);
772 else if (OpVal != N->getOperand(i))
776 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
778 unsigned ValSizeInBytes = EltSize;
780 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
781 Value = CN->getZExtValue();
782 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
783 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
784 Value = FloatToBits(CN->getValueAPF().convertToFloat());
787 // If the splat value is larger than the element value, then we can never do
788 // this splat. The only case that we could fit the replicated bits into our
789 // immediate field for would be zero, and we prefer to use vxor for it.
790 if (ValSizeInBytes < ByteSize) return SDValue();
792 // If the element value is larger than the splat value, cut it in half and
793 // check to see if the two halves are equal. Continue doing this until we
794 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
795 while (ValSizeInBytes > ByteSize) {
796 ValSizeInBytes >>= 1;
798 // If the top half equals the bottom half, we're still ok.
799 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
800 (Value & ((1 << (8*ValSizeInBytes))-1)))
804 // Properly sign extend the value.
805 int ShAmt = (4-ByteSize)*8;
806 int MaskVal = ((int)Value << ShAmt) >> ShAmt;
808 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
809 if (MaskVal == 0) return SDValue();
811 // Finally, if this value fits in a 5 bit sext field, return it
812 if (((MaskVal << (32-5)) >> (32-5)) == MaskVal)
813 return DAG.getTargetConstant(MaskVal, MVT::i32);
817 //===----------------------------------------------------------------------===//
818 // Addressing Mode Selection
819 //===----------------------------------------------------------------------===//
821 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
822 /// or 64-bit immediate, and if the value can be accurately represented as a
823 /// sign extension from a 16-bit value. If so, this returns true and the
825 static bool isIntS16Immediate(SDNode *N, short &Imm) {
826 if (N->getOpcode() != ISD::Constant)
829 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
830 if (N->getValueType(0) == MVT::i32)
831 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
833 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
835 static bool isIntS16Immediate(SDValue Op, short &Imm) {
836 return isIntS16Immediate(Op.getNode(), Imm);
840 /// SelectAddressRegReg - Given the specified addressed, check to see if it
841 /// can be represented as an indexed [r+r] operation. Returns false if it
842 /// can be more efficiently represented with [r+imm].
843 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
845 SelectionDAG &DAG) const {
847 if (N.getOpcode() == ISD::ADD) {
848 if (isIntS16Immediate(N.getOperand(1), imm))
850 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
853 Base = N.getOperand(0);
854 Index = N.getOperand(1);
856 } else if (N.getOpcode() == ISD::OR) {
857 if (isIntS16Immediate(N.getOperand(1), imm))
858 return false; // r+i can fold it if we can.
860 // If this is an or of disjoint bitfields, we can codegen this as an add
861 // (for better address arithmetic) if the LHS and RHS of the OR are provably
863 APInt LHSKnownZero, LHSKnownOne;
864 APInt RHSKnownZero, RHSKnownOne;
865 DAG.ComputeMaskedBits(N.getOperand(0),
866 LHSKnownZero, LHSKnownOne);
868 if (LHSKnownZero.getBoolValue()) {
869 DAG.ComputeMaskedBits(N.getOperand(1),
870 RHSKnownZero, RHSKnownOne);
871 // If all of the bits are known zero on the LHS or RHS, the add won't
873 if (~(LHSKnownZero | RHSKnownZero) == 0) {
874 Base = N.getOperand(0);
875 Index = N.getOperand(1);
884 /// Returns true if the address N can be represented by a base register plus
885 /// a signed 16-bit displacement [r+imm], and if it is not better
886 /// represented as reg+reg.
887 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
889 SelectionDAG &DAG) const {
890 // FIXME dl should come from parent load or store, not from address
891 DebugLoc dl = N.getDebugLoc();
892 // If this can be more profitably realized as r+r, fail.
893 if (SelectAddressRegReg(N, Disp, Base, DAG))
896 if (N.getOpcode() == ISD::ADD) {
898 if (isIntS16Immediate(N.getOperand(1), imm)) {
899 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
900 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
901 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
903 Base = N.getOperand(0);
905 return true; // [r+i]
906 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
907 // Match LOAD (ADD (X, Lo(G))).
908 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
909 && "Cannot handle constant offsets yet!");
910 Disp = N.getOperand(1).getOperand(0); // The global address.
911 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
912 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
913 Disp.getOpcode() == ISD::TargetConstantPool ||
914 Disp.getOpcode() == ISD::TargetJumpTable);
915 Base = N.getOperand(0);
916 return true; // [&g+r]
918 } else if (N.getOpcode() == ISD::OR) {
920 if (isIntS16Immediate(N.getOperand(1), imm)) {
921 // If this is an or of disjoint bitfields, we can codegen this as an add
922 // (for better address arithmetic) if the LHS and RHS of the OR are
923 // provably disjoint.
924 APInt LHSKnownZero, LHSKnownOne;
925 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
927 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
928 // If all of the bits are known zero on the LHS or RHS, the add won't
930 Base = N.getOperand(0);
931 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
935 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
936 // Loading from a constant address.
938 // If this address fits entirely in a 16-bit sext immediate field, codegen
941 if (isIntS16Immediate(CN, Imm)) {
942 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
943 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
944 CN->getValueType(0));
948 // Handle 32-bit sext immediates with LIS + addr mode.
949 if (CN->getValueType(0) == MVT::i32 ||
950 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
951 int Addr = (int)CN->getZExtValue();
953 // Otherwise, break this down into an LIS + disp.
954 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
956 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
957 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
958 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
963 Disp = DAG.getTargetConstant(0, getPointerTy());
964 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
965 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
968 return true; // [r+0]
971 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
972 /// represented as an indexed [r+r] operation.
973 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
975 SelectionDAG &DAG) const {
976 // Check to see if we can easily represent this as an [r+r] address. This
977 // will fail if it thinks that the address is more profitably represented as
978 // reg+imm, e.g. where imm = 0.
979 if (SelectAddressRegReg(N, Base, Index, DAG))
982 // If the operand is an addition, always emit this as [r+r], since this is
983 // better (for code size, and execution, as the memop does the add for free)
984 // than emitting an explicit add.
985 if (N.getOpcode() == ISD::ADD) {
986 Base = N.getOperand(0);
987 Index = N.getOperand(1);
991 // Otherwise, do it the hard way, using R0 as the base register.
992 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
998 /// SelectAddressRegImmShift - Returns true if the address N can be
999 /// represented by a base register plus a signed 14-bit displacement
1000 /// [r+imm*4]. Suitable for use by STD and friends.
1001 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1003 SelectionDAG &DAG) const {
1004 // FIXME dl should come from the parent load or store, not the address
1005 DebugLoc dl = N.getDebugLoc();
1006 // If this can be more profitably realized as r+r, fail.
1007 if (SelectAddressRegReg(N, Disp, Base, DAG))
1010 if (N.getOpcode() == ISD::ADD) {
1012 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1013 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1014 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1015 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1017 Base = N.getOperand(0);
1019 return true; // [r+i]
1020 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1021 // Match LOAD (ADD (X, Lo(G))).
1022 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1023 && "Cannot handle constant offsets yet!");
1024 Disp = N.getOperand(1).getOperand(0); // The global address.
1025 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1026 Disp.getOpcode() == ISD::TargetConstantPool ||
1027 Disp.getOpcode() == ISD::TargetJumpTable);
1028 Base = N.getOperand(0);
1029 return true; // [&g+r]
1031 } else if (N.getOpcode() == ISD::OR) {
1033 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1034 // If this is an or of disjoint bitfields, we can codegen this as an add
1035 // (for better address arithmetic) if the LHS and RHS of the OR are
1036 // provably disjoint.
1037 APInt LHSKnownZero, LHSKnownOne;
1038 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1039 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1040 // If all of the bits are known zero on the LHS or RHS, the add won't
1042 Base = N.getOperand(0);
1043 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1047 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1048 // Loading from a constant address. Verify low two bits are clear.
1049 if ((CN->getZExtValue() & 3) == 0) {
1050 // If this address fits entirely in a 14-bit sext immediate field, codegen
1053 if (isIntS16Immediate(CN, Imm)) {
1054 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1055 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1056 CN->getValueType(0));
1060 // Fold the low-part of 32-bit absolute addresses into addr mode.
1061 if (CN->getValueType(0) == MVT::i32 ||
1062 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1063 int Addr = (int)CN->getZExtValue();
1065 // Otherwise, break this down into an LIS + disp.
1066 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1067 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1068 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1069 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1075 Disp = DAG.getTargetConstant(0, getPointerTy());
1076 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1077 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1080 return true; // [r+0]
1084 /// getPreIndexedAddressParts - returns true by value, base pointer and
1085 /// offset pointer and addressing mode by reference if the node's address
1086 /// can be legally represented as pre-indexed load / store address.
1087 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1089 ISD::MemIndexedMode &AM,
1090 SelectionDAG &DAG) const {
1091 if (DisablePPCPreinc) return false;
1095 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1096 Ptr = LD->getBasePtr();
1097 VT = LD->getMemoryVT();
1099 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1100 Ptr = ST->getBasePtr();
1101 VT = ST->getMemoryVT();
1105 // PowerPC doesn't have preinc load/store instructions for vectors.
1109 if (SelectAddressRegReg(Ptr, Offset, Base, DAG)) {
1114 // LDU/STU use reg+imm*4, others use reg+imm.
1115 if (VT != MVT::i64) {
1117 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1121 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1125 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1126 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1127 // sext i32 to i64 when addr mode is r+i.
1128 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1129 LD->getExtensionType() == ISD::SEXTLOAD &&
1130 isa<ConstantSDNode>(Offset))
1138 //===----------------------------------------------------------------------===//
1139 // LowerOperation implementation
1140 //===----------------------------------------------------------------------===//
1142 /// GetLabelAccessInfo - Return true if we should reference labels using a
1143 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1144 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1145 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1146 HiOpFlags = PPCII::MO_HA16;
1147 LoOpFlags = PPCII::MO_LO16;
1149 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1150 // non-darwin platform. We don't support PIC on other platforms yet.
1151 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1152 TM.getSubtarget<PPCSubtarget>().isDarwin();
1154 HiOpFlags |= PPCII::MO_PIC_FLAG;
1155 LoOpFlags |= PPCII::MO_PIC_FLAG;
1158 // If this is a reference to a global value that requires a non-lazy-ptr, make
1159 // sure that instruction lowering adds it.
1160 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1161 HiOpFlags |= PPCII::MO_NLP_FLAG;
1162 LoOpFlags |= PPCII::MO_NLP_FLAG;
1164 if (GV->hasHiddenVisibility()) {
1165 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1166 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1173 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1174 SelectionDAG &DAG) {
1175 EVT PtrVT = HiPart.getValueType();
1176 SDValue Zero = DAG.getConstant(0, PtrVT);
1177 DebugLoc DL = HiPart.getDebugLoc();
1179 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1180 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1182 // With PIC, the first instruction is actually "GR+hi(&G)".
1184 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1185 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1187 // Generate non-pic code that has direct accesses to the constant pool.
1188 // The address of the global is just (hi(&g)+lo(&g)).
1189 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1192 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1193 SelectionDAG &DAG) const {
1194 EVT PtrVT = Op.getValueType();
1195 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1196 const Constant *C = CP->getConstVal();
1198 unsigned MOHiFlag, MOLoFlag;
1199 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1201 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1203 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1204 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1207 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1208 EVT PtrVT = Op.getValueType();
1209 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1211 unsigned MOHiFlag, MOLoFlag;
1212 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1213 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1214 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1215 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1218 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1219 SelectionDAG &DAG) const {
1220 EVT PtrVT = Op.getValueType();
1222 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1224 unsigned MOHiFlag, MOLoFlag;
1225 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1226 SDValue TgtBAHi = DAG.getBlockAddress(BA, PtrVT, /*isTarget=*/true, MOHiFlag);
1227 SDValue TgtBALo = DAG.getBlockAddress(BA, PtrVT, /*isTarget=*/true, MOLoFlag);
1228 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1231 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1232 SelectionDAG &DAG) const {
1234 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1235 DebugLoc dl = GA->getDebugLoc();
1236 const GlobalValue *GV = GA->getGlobal();
1237 EVT PtrVT = getPointerTy();
1238 bool is64bit = PPCSubTarget.isPPC64();
1240 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1242 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1243 PPCII::MO_TPREL16_HA);
1244 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1245 PPCII::MO_TPREL16_LO);
1247 if (model != TLSModel::LocalExec)
1248 llvm_unreachable("only local-exec TLS mode supported");
1249 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1250 is64bit ? MVT::i64 : MVT::i32);
1251 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1252 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1255 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1256 SelectionDAG &DAG) const {
1257 EVT PtrVT = Op.getValueType();
1258 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1259 DebugLoc DL = GSDN->getDebugLoc();
1260 const GlobalValue *GV = GSDN->getGlobal();
1262 // 64-bit SVR4 ABI code is always position-independent.
1263 // The actual address of the GlobalValue is stored in the TOC.
1264 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1265 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1266 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1267 DAG.getRegister(PPC::X2, MVT::i64));
1270 unsigned MOHiFlag, MOLoFlag;
1271 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1274 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1276 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1278 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1280 // If the global reference is actually to a non-lazy-pointer, we have to do an
1281 // extra load to get the address of the global.
1282 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1283 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1284 false, false, false, 0);
1288 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1289 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1290 DebugLoc dl = Op.getDebugLoc();
1292 // If we're comparing for equality to zero, expose the fact that this is
1293 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1294 // fold the new nodes.
1295 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1296 if (C->isNullValue() && CC == ISD::SETEQ) {
1297 EVT VT = Op.getOperand(0).getValueType();
1298 SDValue Zext = Op.getOperand(0);
1299 if (VT.bitsLT(MVT::i32)) {
1301 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1303 unsigned Log2b = Log2_32(VT.getSizeInBits());
1304 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1305 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1306 DAG.getConstant(Log2b, MVT::i32));
1307 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1309 // Leave comparisons against 0 and -1 alone for now, since they're usually
1310 // optimized. FIXME: revisit this when we can custom lower all setcc
1312 if (C->isAllOnesValue() || C->isNullValue())
1316 // If we have an integer seteq/setne, turn it into a compare against zero
1317 // by xor'ing the rhs with the lhs, which is faster than setting a
1318 // condition register, reading it back out, and masking the correct bit. The
1319 // normal approach here uses sub to do this instead of xor. Using xor exposes
1320 // the result to other bit-twiddling opportunities.
1321 EVT LHSVT = Op.getOperand(0).getValueType();
1322 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1323 EVT VT = Op.getValueType();
1324 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1326 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1331 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1332 const PPCSubtarget &Subtarget) const {
1333 SDNode *Node = Op.getNode();
1334 EVT VT = Node->getValueType(0);
1335 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1336 SDValue InChain = Node->getOperand(0);
1337 SDValue VAListPtr = Node->getOperand(1);
1338 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1339 DebugLoc dl = Node->getDebugLoc();
1341 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1344 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1345 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1347 InChain = GprIndex.getValue(1);
1349 if (VT == MVT::i64) {
1350 // Check if GprIndex is even
1351 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1352 DAG.getConstant(1, MVT::i32));
1353 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1354 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1355 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1356 DAG.getConstant(1, MVT::i32));
1357 // Align GprIndex to be even if it isn't
1358 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1362 // fpr index is 1 byte after gpr
1363 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1364 DAG.getConstant(1, MVT::i32));
1367 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1368 FprPtr, MachinePointerInfo(SV), MVT::i8,
1370 InChain = FprIndex.getValue(1);
1372 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1373 DAG.getConstant(8, MVT::i32));
1375 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1376 DAG.getConstant(4, MVT::i32));
1379 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1380 MachinePointerInfo(), false, false,
1382 InChain = OverflowArea.getValue(1);
1384 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1385 MachinePointerInfo(), false, false,
1387 InChain = RegSaveArea.getValue(1);
1389 // select overflow_area if index > 8
1390 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1391 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1393 // adjustment constant gpr_index * 4/8
1394 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1395 VT.isInteger() ? GprIndex : FprIndex,
1396 DAG.getConstant(VT.isInteger() ? 4 : 8,
1399 // OurReg = RegSaveArea + RegConstant
1400 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1403 // Floating types are 32 bytes into RegSaveArea
1404 if (VT.isFloatingPoint())
1405 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1406 DAG.getConstant(32, MVT::i32));
1408 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1409 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1410 VT.isInteger() ? GprIndex : FprIndex,
1411 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1414 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1415 VT.isInteger() ? VAListPtr : FprPtr,
1416 MachinePointerInfo(SV),
1417 MVT::i8, false, false, 0);
1419 // determine if we should load from reg_save_area or overflow_area
1420 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1422 // increase overflow_area by 4/8 if gpr/fpr > 8
1423 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1424 DAG.getConstant(VT.isInteger() ? 4 : 8,
1427 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1430 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1432 MachinePointerInfo(),
1433 MVT::i32, false, false, 0);
1435 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1436 false, false, false, 0);
1439 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1440 SelectionDAG &DAG) const {
1441 return Op.getOperand(0);
1444 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1445 SelectionDAG &DAG) const {
1446 SDValue Chain = Op.getOperand(0);
1447 SDValue Trmp = Op.getOperand(1); // trampoline
1448 SDValue FPtr = Op.getOperand(2); // nested function
1449 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1450 DebugLoc dl = Op.getDebugLoc();
1452 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1453 bool isPPC64 = (PtrVT == MVT::i64);
1455 DAG.getTargetLoweringInfo().getTargetData()->getIntPtrType(
1458 TargetLowering::ArgListTy Args;
1459 TargetLowering::ArgListEntry Entry;
1461 Entry.Ty = IntPtrTy;
1462 Entry.Node = Trmp; Args.push_back(Entry);
1464 // TrampSize == (isPPC64 ? 48 : 40);
1465 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1466 isPPC64 ? MVT::i64 : MVT::i32);
1467 Args.push_back(Entry);
1469 Entry.Node = FPtr; Args.push_back(Entry);
1470 Entry.Node = Nest; Args.push_back(Entry);
1472 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1473 TargetLowering::CallLoweringInfo CLI(Chain,
1474 Type::getVoidTy(*DAG.getContext()),
1475 false, false, false, false, 0,
1477 /*isTailCall=*/false,
1478 /*doesNotRet=*/false,
1479 /*isReturnValueUsed=*/true,
1480 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1482 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1484 return CallResult.second;
1487 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1488 const PPCSubtarget &Subtarget) const {
1489 MachineFunction &MF = DAG.getMachineFunction();
1490 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1492 DebugLoc dl = Op.getDebugLoc();
1494 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1495 // vastart just stores the address of the VarArgsFrameIndex slot into the
1496 // memory location argument.
1497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1498 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1499 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1500 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1501 MachinePointerInfo(SV),
1505 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1506 // We suppose the given va_list is already allocated.
1509 // char gpr; /* index into the array of 8 GPRs
1510 // * stored in the register save area
1511 // * gpr=0 corresponds to r3,
1512 // * gpr=1 to r4, etc.
1514 // char fpr; /* index into the array of 8 FPRs
1515 // * stored in the register save area
1516 // * fpr=0 corresponds to f1,
1517 // * fpr=1 to f2, etc.
1519 // char *overflow_arg_area;
1520 // /* location on stack that holds
1521 // * the next overflow argument
1523 // char *reg_save_area;
1524 // /* where r3:r10 and f1:f8 (if saved)
1530 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1531 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1534 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1536 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1538 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1541 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1542 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1544 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1545 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1547 uint64_t FPROffset = 1;
1548 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1550 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1552 // Store first byte : number of int regs
1553 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1555 MachinePointerInfo(SV),
1556 MVT::i8, false, false, 0);
1557 uint64_t nextOffset = FPROffset;
1558 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1561 // Store second byte : number of float regs
1562 SDValue secondStore =
1563 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1564 MachinePointerInfo(SV, nextOffset), MVT::i8,
1566 nextOffset += StackOffset;
1567 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1569 // Store second word : arguments given on stack
1570 SDValue thirdStore =
1571 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1572 MachinePointerInfo(SV, nextOffset),
1574 nextOffset += FrameOffset;
1575 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1577 // Store third word : arguments given in registers
1578 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1579 MachinePointerInfo(SV, nextOffset),
1584 #include "PPCGenCallingConv.inc"
1586 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1587 CCValAssign::LocInfo &LocInfo,
1588 ISD::ArgFlagsTy &ArgFlags,
1593 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1595 CCValAssign::LocInfo &LocInfo,
1596 ISD::ArgFlagsTy &ArgFlags,
1598 static const uint16_t ArgRegs[] = {
1599 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1600 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1602 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1604 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1606 // Skip one register if the first unallocated register has an even register
1607 // number and there are still argument registers available which have not been
1608 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1609 // need to skip a register if RegNum is odd.
1610 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1611 State.AllocateReg(ArgRegs[RegNum]);
1614 // Always return false here, as this function only makes sure that the first
1615 // unallocated register has an odd register number and does not actually
1616 // allocate a register for the current argument.
1620 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1622 CCValAssign::LocInfo &LocInfo,
1623 ISD::ArgFlagsTy &ArgFlags,
1625 static const uint16_t ArgRegs[] = {
1626 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1630 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1632 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1634 // If there is only one Floating-point register left we need to put both f64
1635 // values of a split ppc_fp128 value on the stack.
1636 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1637 State.AllocateReg(ArgRegs[RegNum]);
1640 // Always return false here, as this function only makes sure that the two f64
1641 // values a ppc_fp128 value is split into are both passed in registers or both
1642 // passed on the stack and does not actually allocate a register for the
1643 // current argument.
1647 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1649 static const uint16_t *GetFPR() {
1650 static const uint16_t FPR[] = {
1651 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1652 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1658 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1660 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1661 unsigned PtrByteSize) {
1662 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1663 if (Flags.isByVal())
1664 ArgSize = Flags.getByValSize();
1665 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1671 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1672 CallingConv::ID CallConv, bool isVarArg,
1673 const SmallVectorImpl<ISD::InputArg>
1675 DebugLoc dl, SelectionDAG &DAG,
1676 SmallVectorImpl<SDValue> &InVals)
1678 if (PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64()) {
1679 return LowerFormalArguments_SVR4(Chain, CallConv, isVarArg, Ins,
1682 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1688 PPCTargetLowering::LowerFormalArguments_SVR4(
1690 CallingConv::ID CallConv, bool isVarArg,
1691 const SmallVectorImpl<ISD::InputArg>
1693 DebugLoc dl, SelectionDAG &DAG,
1694 SmallVectorImpl<SDValue> &InVals) const {
1696 // 32-bit SVR4 ABI Stack Frame Layout:
1697 // +-----------------------------------+
1698 // +--> | Back chain |
1699 // | +-----------------------------------+
1700 // | | Floating-point register save area |
1701 // | +-----------------------------------+
1702 // | | General register save area |
1703 // | +-----------------------------------+
1704 // | | CR save word |
1705 // | +-----------------------------------+
1706 // | | VRSAVE save word |
1707 // | +-----------------------------------+
1708 // | | Alignment padding |
1709 // | +-----------------------------------+
1710 // | | Vector register save area |
1711 // | +-----------------------------------+
1712 // | | Local variable space |
1713 // | +-----------------------------------+
1714 // | | Parameter list area |
1715 // | +-----------------------------------+
1716 // | | LR save word |
1717 // | +-----------------------------------+
1718 // SP--> +--- | Back chain |
1719 // +-----------------------------------+
1722 // System V Application Binary Interface PowerPC Processor Supplement
1723 // AltiVec Technology Programming Interface Manual
1725 MachineFunction &MF = DAG.getMachineFunction();
1726 MachineFrameInfo *MFI = MF.getFrameInfo();
1727 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1729 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1730 // Potential tail calls could cause overwriting of argument stack slots.
1731 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1732 (CallConv == CallingConv::Fast));
1733 unsigned PtrByteSize = 4;
1735 // Assign locations to all of the incoming arguments.
1736 SmallVector<CCValAssign, 16> ArgLocs;
1737 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1738 getTargetMachine(), ArgLocs, *DAG.getContext());
1740 // Reserve space for the linkage area on the stack.
1741 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1743 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4);
1745 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1746 CCValAssign &VA = ArgLocs[i];
1748 // Arguments stored in registers.
1749 if (VA.isRegLoc()) {
1750 const TargetRegisterClass *RC;
1751 EVT ValVT = VA.getValVT();
1753 switch (ValVT.getSimpleVT().SimpleTy) {
1755 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1757 RC = &PPC::GPRCRegClass;
1760 RC = &PPC::F4RCRegClass;
1763 RC = &PPC::F8RCRegClass;
1769 RC = &PPC::VRRCRegClass;
1773 // Transform the arguments stored in physical registers into virtual ones.
1774 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1775 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1777 InVals.push_back(ArgValue);
1779 // Argument stored in memory.
1780 assert(VA.isMemLoc());
1782 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1783 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1786 // Create load nodes to retrieve arguments from the stack.
1787 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1788 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1789 MachinePointerInfo(),
1790 false, false, false, 0));
1794 // Assign locations to all of the incoming aggregate by value arguments.
1795 // Aggregates passed by value are stored in the local variable space of the
1796 // caller's stack frame, right above the parameter list area.
1797 SmallVector<CCValAssign, 16> ByValArgLocs;
1798 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1799 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1801 // Reserve stack space for the allocations in CCInfo.
1802 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1804 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal);
1806 // Area that is at least reserved in the caller of this function.
1807 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1809 // Set the size that is at least reserved in caller of this function. Tail
1810 // call optimized function's reserved stack space needs to be aligned so that
1811 // taking the difference between two stack areas will result in an aligned
1813 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1816 std::max(MinReservedArea,
1817 PPCFrameLowering::getMinCallFrameSize(false, false));
1819 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1820 getStackAlignment();
1821 unsigned AlignMask = TargetAlign-1;
1822 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1824 FI->setMinReservedArea(MinReservedArea);
1826 SmallVector<SDValue, 8> MemOps;
1828 // If the function takes variable number of arguments, make a frame index for
1829 // the start of the first vararg value... for expansion of llvm.va_start.
1831 static const uint16_t GPArgRegs[] = {
1832 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1833 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1835 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
1837 static const uint16_t FPArgRegs[] = {
1838 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1841 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
1843 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
1845 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
1848 // Make room for NumGPArgRegs and NumFPArgRegs.
1849 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
1850 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
1852 FuncInfo->setVarArgsStackOffset(
1853 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1854 CCInfo.getNextStackOffset(), true));
1856 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
1857 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1859 // The fixed integer arguments of a variadic function are stored to the
1860 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
1861 // the result of va_next.
1862 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
1863 // Get an existing live-in vreg, or add a new one.
1864 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
1866 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
1868 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
1869 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1870 MachinePointerInfo(), false, false, 0);
1871 MemOps.push_back(Store);
1872 // Increment the address by four for the next argument to store
1873 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1874 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1877 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
1879 // The double arguments are stored to the VarArgsFrameIndex
1881 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
1882 // Get an existing live-in vreg, or add a new one.
1883 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
1885 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
1887 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
1888 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1889 MachinePointerInfo(), false, false, 0);
1890 MemOps.push_back(Store);
1891 // Increment the address by eight for the next argument to store
1892 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
1894 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1898 if (!MemOps.empty())
1899 Chain = DAG.getNode(ISD::TokenFactor, dl,
1900 MVT::Other, &MemOps[0], MemOps.size());
1906 PPCTargetLowering::LowerFormalArguments_Darwin(
1908 CallingConv::ID CallConv, bool isVarArg,
1909 const SmallVectorImpl<ISD::InputArg>
1911 DebugLoc dl, SelectionDAG &DAG,
1912 SmallVectorImpl<SDValue> &InVals) const {
1913 // TODO: add description of PPC stack frame format, or at least some docs.
1915 MachineFunction &MF = DAG.getMachineFunction();
1916 MachineFrameInfo *MFI = MF.getFrameInfo();
1917 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1919 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1920 bool isPPC64 = PtrVT == MVT::i64;
1921 // Potential tail calls could cause overwriting of argument stack slots.
1922 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1923 (CallConv == CallingConv::Fast));
1924 unsigned PtrByteSize = isPPC64 ? 8 : 4;
1926 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
1927 // Area that is at least reserved in caller of this function.
1928 unsigned MinReservedArea = ArgOffset;
1930 static const uint16_t GPR_32[] = { // 32-bit registers.
1931 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1932 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1934 static const uint16_t GPR_64[] = { // 64-bit registers.
1935 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
1936 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
1939 static const uint16_t *FPR = GetFPR();
1941 static const uint16_t VR[] = {
1942 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
1943 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
1946 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
1947 const unsigned Num_FPR_Regs = 13;
1948 const unsigned Num_VR_Regs = array_lengthof( VR);
1950 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
1952 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
1954 // In 32-bit non-varargs functions, the stack space for vectors is after the
1955 // stack space for non-vectors. We do not use this space unless we have
1956 // too many vectors to fit in registers, something that only occurs in
1957 // constructed examples:), but we have to walk the arglist to figure
1958 // that out...for the pathological case, compute VecArgOffset as the
1959 // start of the vector parameter area. Computing VecArgOffset is the
1960 // entire point of the following loop.
1961 unsigned VecArgOffset = ArgOffset;
1962 if (!isVarArg && !isPPC64) {
1963 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
1965 EVT ObjectVT = Ins[ArgNo].VT;
1966 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
1968 if (Flags.isByVal()) {
1969 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
1970 unsigned ObjSize = Flags.getByValSize();
1972 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1973 VecArgOffset += ArgSize;
1977 switch(ObjectVT.getSimpleVT().SimpleTy) {
1978 default: llvm_unreachable("Unhandled argument type!");
1981 VecArgOffset += isPPC64 ? 8 : 4;
1983 case MVT::i64: // PPC64
1991 // Nothing to do, we're only looking at Nonvector args here.
1996 // We've found where the vector parameter area in memory is. Skip the
1997 // first 12 parameters; these don't use that memory.
1998 VecArgOffset = ((VecArgOffset+15)/16)*16;
1999 VecArgOffset += 12*16;
2001 // Add DAG nodes to load the arguments or copy them out of registers. On
2002 // entry to a function on PPC, the arguments start after the linkage area,
2003 // although the first ones are often in registers.
2005 SmallVector<SDValue, 8> MemOps;
2006 unsigned nAltivecParamsAtEnd = 0;
2007 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2009 bool needsLoad = false;
2010 EVT ObjectVT = Ins[ArgNo].VT;
2011 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2012 unsigned ArgSize = ObjSize;
2013 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2015 unsigned CurArgOffset = ArgOffset;
2017 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2018 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2019 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2020 if (isVarArg || isPPC64) {
2021 MinReservedArea = ((MinReservedArea+15)/16)*16;
2022 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2025 } else nAltivecParamsAtEnd++;
2027 // Calculate min reserved area.
2028 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2032 // FIXME the codegen can be much improved in some cases.
2033 // We do not have to keep everything in memory.
2034 if (Flags.isByVal()) {
2035 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2036 ObjSize = Flags.getByValSize();
2037 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2038 // Objects of size 1 and 2 are right justified, everything else is
2039 // left justified. This means the memory address is adjusted forwards.
2040 if (ObjSize==1 || ObjSize==2) {
2041 CurArgOffset = CurArgOffset + (4 - ObjSize);
2043 // The value of the object is its address.
2044 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2045 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2046 InVals.push_back(FIN);
2047 if (ObjSize==1 || ObjSize==2) {
2048 if (GPR_idx != Num_GPR_Regs) {
2051 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2053 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2054 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2055 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2056 MachinePointerInfo(),
2057 ObjSize==1 ? MVT::i8 : MVT::i16,
2059 MemOps.push_back(Store);
2063 ArgOffset += PtrByteSize;
2067 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2068 // Store whatever pieces of the object are in registers
2069 // to memory. ArgVal will be address of the beginning of
2071 if (GPR_idx != Num_GPR_Regs) {
2074 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2076 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2077 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2078 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2079 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2080 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2081 MachinePointerInfo(),
2083 MemOps.push_back(Store);
2085 ArgOffset += PtrByteSize;
2087 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2094 switch (ObjectVT.getSimpleVT().SimpleTy) {
2095 default: llvm_unreachable("Unhandled argument type!");
2098 if (GPR_idx != Num_GPR_Regs) {
2099 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2100 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2104 ArgSize = PtrByteSize;
2106 // All int arguments reserve stack space in the Darwin ABI.
2107 ArgOffset += PtrByteSize;
2111 case MVT::i64: // PPC64
2112 if (GPR_idx != Num_GPR_Regs) {
2113 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2114 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2116 if (ObjectVT == MVT::i32) {
2117 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2118 // value to MVT::i64 and then truncate to the correct register size.
2120 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2121 DAG.getValueType(ObjectVT));
2122 else if (Flags.isZExt())
2123 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2124 DAG.getValueType(ObjectVT));
2126 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2132 ArgSize = PtrByteSize;
2134 // All int arguments reserve stack space in the Darwin ABI.
2140 // Every 4 bytes of argument space consumes one of the GPRs available for
2141 // argument passing.
2142 if (GPR_idx != Num_GPR_Regs) {
2144 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2147 if (FPR_idx != Num_FPR_Regs) {
2150 if (ObjectVT == MVT::f32)
2151 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2153 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2155 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2161 // All FP arguments reserve stack space in the Darwin ABI.
2162 ArgOffset += isPPC64 ? 8 : ObjSize;
2168 // Note that vector arguments in registers don't reserve stack space,
2169 // except in varargs functions.
2170 if (VR_idx != Num_VR_Regs) {
2171 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2172 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2174 while ((ArgOffset % 16) != 0) {
2175 ArgOffset += PtrByteSize;
2176 if (GPR_idx != Num_GPR_Regs)
2180 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2184 if (!isVarArg && !isPPC64) {
2185 // Vectors go after all the nonvectors.
2186 CurArgOffset = VecArgOffset;
2189 // Vectors are aligned.
2190 ArgOffset = ((ArgOffset+15)/16)*16;
2191 CurArgOffset = ArgOffset;
2199 // We need to load the argument to a virtual register if we determined above
2200 // that we ran out of physical registers of the appropriate type.
2202 int FI = MFI->CreateFixedObject(ObjSize,
2203 CurArgOffset + (ArgSize - ObjSize),
2205 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2206 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2207 false, false, false, 0);
2210 InVals.push_back(ArgVal);
2213 // Set the size that is at least reserved in caller of this function. Tail
2214 // call optimized function's reserved stack space needs to be aligned so that
2215 // taking the difference between two stack areas will result in an aligned
2217 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2218 // Add the Altivec parameters at the end, if needed.
2219 if (nAltivecParamsAtEnd) {
2220 MinReservedArea = ((MinReservedArea+15)/16)*16;
2221 MinReservedArea += 16*nAltivecParamsAtEnd;
2224 std::max(MinReservedArea,
2225 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2226 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2227 getStackAlignment();
2228 unsigned AlignMask = TargetAlign-1;
2229 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2230 FI->setMinReservedArea(MinReservedArea);
2232 // If the function takes variable number of arguments, make a frame index for
2233 // the start of the first vararg value... for expansion of llvm.va_start.
2235 int Depth = ArgOffset;
2237 FuncInfo->setVarArgsFrameIndex(
2238 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2240 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2242 // If this function is vararg, store any remaining integer argument regs
2243 // to their spots on the stack so that they may be loaded by deferencing the
2244 // result of va_next.
2245 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2249 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2251 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2253 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2254 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2255 MachinePointerInfo(), false, false, 0);
2256 MemOps.push_back(Store);
2257 // Increment the address by four for the next argument to store
2258 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2259 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2263 if (!MemOps.empty())
2264 Chain = DAG.getNode(ISD::TokenFactor, dl,
2265 MVT::Other, &MemOps[0], MemOps.size());
2270 /// CalculateParameterAndLinkageAreaSize - Get the size of the paramter plus
2271 /// linkage area for the Darwin ABI.
2273 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2277 const SmallVectorImpl<ISD::OutputArg>
2279 const SmallVectorImpl<SDValue> &OutVals,
2280 unsigned &nAltivecParamsAtEnd) {
2281 // Count how many bytes are to be pushed on the stack, including the linkage
2282 // area, and parameter passing area. We start with 24/48 bytes, which is
2283 // prereserved space for [SP][CR][LR][3 x unused].
2284 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2285 unsigned NumOps = Outs.size();
2286 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2288 // Add up all the space actually used.
2289 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2290 // they all go in registers, but we must reserve stack space for them for
2291 // possible use by the caller. In varargs or 64-bit calls, parameters are
2292 // assigned stack space in order, with padding so Altivec parameters are
2294 nAltivecParamsAtEnd = 0;
2295 for (unsigned i = 0; i != NumOps; ++i) {
2296 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2297 EVT ArgVT = Outs[i].VT;
2298 // Varargs Altivec parameters are padded to a 16 byte boundary.
2299 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2300 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2301 if (!isVarArg && !isPPC64) {
2302 // Non-varargs Altivec parameters go after all the non-Altivec
2303 // parameters; handle those later so we know how much padding we need.
2304 nAltivecParamsAtEnd++;
2307 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2308 NumBytes = ((NumBytes+15)/16)*16;
2310 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2313 // Allow for Altivec parameters at the end, if needed.
2314 if (nAltivecParamsAtEnd) {
2315 NumBytes = ((NumBytes+15)/16)*16;
2316 NumBytes += 16*nAltivecParamsAtEnd;
2319 // The prolog code of the callee may store up to 8 GPR argument registers to
2320 // the stack, allowing va_start to index over them in memory if its varargs.
2321 // Because we cannot tell if this is needed on the caller side, we have to
2322 // conservatively assume that it is needed. As such, make sure we have at
2323 // least enough stack space for the caller to store the 8 GPRs.
2324 NumBytes = std::max(NumBytes,
2325 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2327 // Tail call needs the stack to be aligned.
2328 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2329 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2330 getFrameLowering()->getStackAlignment();
2331 unsigned AlignMask = TargetAlign-1;
2332 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2338 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2339 /// adjusted to accommodate the arguments for the tailcall.
2340 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2341 unsigned ParamSize) {
2343 if (!isTailCall) return 0;
2345 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2346 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2347 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2348 // Remember only if the new adjustement is bigger.
2349 if (SPDiff < FI->getTailCallSPDelta())
2350 FI->setTailCallSPDelta(SPDiff);
2355 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2356 /// for tail call optimization. Targets which want to do tail call
2357 /// optimization should implement this function.
2359 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2360 CallingConv::ID CalleeCC,
2362 const SmallVectorImpl<ISD::InputArg> &Ins,
2363 SelectionDAG& DAG) const {
2364 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2367 // Variable argument functions are not supported.
2371 MachineFunction &MF = DAG.getMachineFunction();
2372 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2373 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2374 // Functions containing by val parameters are not supported.
2375 for (unsigned i = 0; i != Ins.size(); i++) {
2376 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2377 if (Flags.isByVal()) return false;
2380 // Non PIC/GOT tail calls are supported.
2381 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2384 // At the moment we can only do local tail calls (in same module, hidden
2385 // or protected) if we are generating PIC.
2386 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2387 return G->getGlobal()->hasHiddenVisibility()
2388 || G->getGlobal()->hasProtectedVisibility();
2394 /// isCallCompatibleAddress - Return the immediate to use if the specified
2395 /// 32-bit value is representable in the immediate field of a BxA instruction.
2396 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2397 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2400 int Addr = C->getZExtValue();
2401 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2402 (Addr << 6 >> 6) != Addr)
2403 return 0; // Top 6 bits have to be sext of immediate.
2405 return DAG.getConstant((int)C->getZExtValue() >> 2,
2406 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2411 struct TailCallArgumentInfo {
2416 TailCallArgumentInfo() : FrameIdx(0) {}
2421 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2423 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2425 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2426 SmallVector<SDValue, 8> &MemOpChains,
2428 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2429 SDValue Arg = TailCallArgs[i].Arg;
2430 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2431 int FI = TailCallArgs[i].FrameIdx;
2432 // Store relative to framepointer.
2433 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2434 MachinePointerInfo::getFixedStack(FI),
2439 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2440 /// the appropriate stack slot for the tail call optimized function call.
2441 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2442 MachineFunction &MF,
2451 // Calculate the new stack slot for the return address.
2452 int SlotSize = isPPC64 ? 8 : 4;
2453 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2455 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2456 NewRetAddrLoc, true);
2457 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2458 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2459 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2460 MachinePointerInfo::getFixedStack(NewRetAddr),
2463 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2464 // slot as the FP is never overwritten.
2467 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2468 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2470 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2471 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2472 MachinePointerInfo::getFixedStack(NewFPIdx),
2479 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2480 /// the position of the argument.
2482 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2483 SDValue Arg, int SPDiff, unsigned ArgOffset,
2484 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2485 int Offset = ArgOffset + SPDiff;
2486 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2487 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2488 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2489 SDValue FIN = DAG.getFrameIndex(FI, VT);
2490 TailCallArgumentInfo Info;
2492 Info.FrameIdxOp = FIN;
2494 TailCallArguments.push_back(Info);
2497 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2498 /// stack slot. Returns the chain as result and the loaded frame pointers in
2499 /// LROpOut/FPOpout. Used when tail calling.
2500 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2506 DebugLoc dl) const {
2508 // Load the LR and FP stack slot for later adjusting.
2509 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2510 LROpOut = getReturnAddrFrameIndex(DAG);
2511 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
2512 false, false, false, 0);
2513 Chain = SDValue(LROpOut.getNode(), 1);
2515 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
2516 // slot as the FP is never overwritten.
2518 FPOpOut = getFramePointerFrameIndex(DAG);
2519 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
2520 false, false, false, 0);
2521 Chain = SDValue(FPOpOut.getNode(), 1);
2527 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2528 /// by "Src" to address "Dst" of size "Size". Alignment information is
2529 /// specified by the specific parameter attribute. The copy will be passed as
2530 /// a byval function parameter.
2531 /// Sometimes what we are copying is the end of a larger object, the part that
2532 /// does not fit in registers.
2534 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2535 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2537 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2538 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2539 false, false, MachinePointerInfo(0),
2540 MachinePointerInfo(0));
2543 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2546 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2547 SDValue Arg, SDValue PtrOff, int SPDiff,
2548 unsigned ArgOffset, bool isPPC64, bool isTailCall,
2549 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2550 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
2552 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2557 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2559 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2560 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2561 DAG.getConstant(ArgOffset, PtrVT));
2563 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2564 MachinePointerInfo(), false, false, 0));
2565 // Calculate and remember argument location.
2566 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2571 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
2572 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
2573 SDValue LROp, SDValue FPOp, bool isDarwinABI,
2574 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
2575 MachineFunction &MF = DAG.getMachineFunction();
2577 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2578 // might overwrite each other in case of tail call optimization.
2579 SmallVector<SDValue, 8> MemOpChains2;
2580 // Do not flag preceding copytoreg stuff together with the following stuff.
2582 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2584 if (!MemOpChains2.empty())
2585 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2586 &MemOpChains2[0], MemOpChains2.size());
2588 // Store the return address to the appropriate stack slot.
2589 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2590 isPPC64, isDarwinABI, dl);
2592 // Emit callseq_end just before tailcall node.
2593 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2594 DAG.getIntPtrConstant(0, true), InFlag);
2595 InFlag = Chain.getValue(1);
2599 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
2600 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
2601 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
2602 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
2603 const PPCSubtarget &PPCSubTarget) {
2605 bool isPPC64 = PPCSubTarget.isPPC64();
2606 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
2608 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2609 NodeTys.push_back(MVT::Other); // Returns a chain
2610 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
2612 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
2614 bool needIndirectCall = true;
2615 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
2616 // If this is an absolute destination address, use the munged value.
2617 Callee = SDValue(Dest, 0);
2618 needIndirectCall = false;
2621 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2622 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
2623 // Use indirect calls for ALL functions calls in JIT mode, since the
2624 // far-call stubs may be outside relocation limits for a BL instruction.
2625 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
2626 unsigned OpFlags = 0;
2627 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
2628 (PPCSubTarget.getTargetTriple().isMacOSX() &&
2629 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
2630 (G->getGlobal()->isDeclaration() ||
2631 G->getGlobal()->isWeakForLinker())) {
2632 // PC-relative references to external symbols should go through $stub,
2633 // unless we're building with the leopard linker or later, which
2634 // automatically synthesizes these stubs.
2635 OpFlags = PPCII::MO_DARWIN_STUB;
2638 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
2639 // every direct call is) turn it into a TargetGlobalAddress /
2640 // TargetExternalSymbol node so that legalize doesn't hack it.
2641 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2642 Callee.getValueType(),
2644 needIndirectCall = false;
2648 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2649 unsigned char OpFlags = 0;
2651 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
2652 (PPCSubTarget.getTargetTriple().isMacOSX() &&
2653 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
2654 // PC-relative references to external symbols should go through $stub,
2655 // unless we're building with the leopard linker or later, which
2656 // automatically synthesizes these stubs.
2657 OpFlags = PPCII::MO_DARWIN_STUB;
2660 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
2662 needIndirectCall = false;
2665 if (needIndirectCall) {
2666 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
2667 // to do the call, we can't use PPCISD::CALL.
2668 SDValue MTCTROps[] = {Chain, Callee, InFlag};
2670 if (isSVR4ABI && isPPC64) {
2671 // Function pointers in the 64-bit SVR4 ABI do not point to the function
2672 // entry point, but to the function descriptor (the function entry point
2673 // address is part of the function descriptor though).
2674 // The function descriptor is a three doubleword structure with the
2675 // following fields: function entry point, TOC base address and
2676 // environment pointer.
2677 // Thus for a call through a function pointer, the following actions need
2679 // 1. Save the TOC of the caller in the TOC save area of its stack
2680 // frame (this is done in LowerCall_Darwin()).
2681 // 2. Load the address of the function entry point from the function
2683 // 3. Load the TOC of the callee from the function descriptor into r2.
2684 // 4. Load the environment pointer from the function descriptor into
2686 // 5. Branch to the function entry point address.
2687 // 6. On return of the callee, the TOC of the caller needs to be
2688 // restored (this is done in FinishCall()).
2690 // All those operations are flagged together to ensure that no other
2691 // operations can be scheduled in between. E.g. without flagging the
2692 // operations together, a TOC access in the caller could be scheduled
2693 // between the load of the callee TOC and the branch to the callee, which
2694 // results in the TOC access going through the TOC of the callee instead
2695 // of going through the TOC of the caller, which leads to incorrect code.
2697 // Load the address of the function entry point from the function
2699 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
2700 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
2701 InFlag.getNode() ? 3 : 2);
2702 Chain = LoadFuncPtr.getValue(1);
2703 InFlag = LoadFuncPtr.getValue(2);
2705 // Load environment pointer into r11.
2706 // Offset of the environment pointer within the function descriptor.
2707 SDValue PtrOff = DAG.getIntPtrConstant(16);
2709 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
2710 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
2712 Chain = LoadEnvPtr.getValue(1);
2713 InFlag = LoadEnvPtr.getValue(2);
2715 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
2717 Chain = EnvVal.getValue(0);
2718 InFlag = EnvVal.getValue(1);
2720 // Load TOC of the callee into r2. We are using a target-specific load
2721 // with r2 hard coded, because the result of a target-independent load
2722 // would never go directly into r2, since r2 is a reserved register (which
2723 // prevents the register allocator from allocating it), resulting in an
2724 // additional register being allocated and an unnecessary move instruction
2726 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2727 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
2729 Chain = LoadTOCPtr.getValue(0);
2730 InFlag = LoadTOCPtr.getValue(1);
2732 MTCTROps[0] = Chain;
2733 MTCTROps[1] = LoadFuncPtr;
2734 MTCTROps[2] = InFlag;
2737 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
2738 2 + (InFlag.getNode() != 0));
2739 InFlag = Chain.getValue(1);
2742 NodeTys.push_back(MVT::Other);
2743 NodeTys.push_back(MVT::Glue);
2744 Ops.push_back(Chain);
2745 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
2747 // Add CTR register as callee so a bctr can be emitted later.
2749 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
2752 // If this is a direct call, pass the chain and the callee.
2753 if (Callee.getNode()) {
2754 Ops.push_back(Chain);
2755 Ops.push_back(Callee);
2757 // If this is a tail call add stack pointer delta.
2759 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
2761 // Add argument registers to the end of the list so that they are known live
2763 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2764 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2765 RegsToPass[i].second.getValueType()));
2771 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2772 CallingConv::ID CallConv, bool isVarArg,
2773 const SmallVectorImpl<ISD::InputArg> &Ins,
2774 DebugLoc dl, SelectionDAG &DAG,
2775 SmallVectorImpl<SDValue> &InVals) const {
2777 SmallVector<CCValAssign, 16> RVLocs;
2778 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2779 getTargetMachine(), RVLocs, *DAG.getContext());
2780 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
2782 // Copy all of the result registers out of their specified physreg.
2783 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2784 CCValAssign &VA = RVLocs[i];
2785 EVT VT = VA.getValVT();
2786 assert(VA.isRegLoc() && "Can only return in registers!");
2787 Chain = DAG.getCopyFromReg(Chain, dl,
2788 VA.getLocReg(), VT, InFlag).getValue(1);
2789 InVals.push_back(Chain.getValue(0));
2790 InFlag = Chain.getValue(2);
2797 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
2798 bool isTailCall, bool isVarArg,
2800 SmallVector<std::pair<unsigned, SDValue>, 8>
2802 SDValue InFlag, SDValue Chain,
2804 int SPDiff, unsigned NumBytes,
2805 const SmallVectorImpl<ISD::InputArg> &Ins,
2806 SmallVectorImpl<SDValue> &InVals) const {
2807 std::vector<EVT> NodeTys;
2808 SmallVector<SDValue, 8> Ops;
2809 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
2810 isTailCall, RegsToPass, Ops, NodeTys,
2813 // When performing tail call optimization the callee pops its arguments off
2814 // the stack. Account for this here so these bytes can be pushed back on in
2815 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
2816 int BytesCalleePops =
2817 (CallConv == CallingConv::Fast &&
2818 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
2820 // Add a register mask operand representing the call-preserved registers.
2821 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2822 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2823 assert(Mask && "Missing call preserved mask for calling convention");
2824 Ops.push_back(DAG.getRegisterMask(Mask));
2826 if (InFlag.getNode())
2827 Ops.push_back(InFlag);
2831 // If this is the first return lowered for this function, add the regs
2832 // to the liveout set for the function.
2833 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2834 SmallVector<CCValAssign, 16> RVLocs;
2835 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2836 getTargetMachine(), RVLocs, *DAG.getContext());
2837 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC);
2838 for (unsigned i = 0; i != RVLocs.size(); ++i)
2839 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2842 assert(((Callee.getOpcode() == ISD::Register &&
2843 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
2844 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2845 Callee.getOpcode() == ISD::TargetGlobalAddress ||
2846 isa<ConstantSDNode>(Callee)) &&
2847 "Expecting an global address, external symbol, absolute value or register");
2849 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
2852 // Add a NOP immediately after the branch instruction when using the 64-bit
2853 // SVR4 ABI. At link time, if caller and callee are in a different module and
2854 // thus have a different TOC, the call will be replaced with a call to a stub
2855 // function which saves the current TOC, loads the TOC of the callee and
2856 // branches to the callee. The NOP will be replaced with a load instruction
2857 // which restores the TOC of the caller from the TOC save slot of the current
2858 // stack frame. If caller and callee belong to the same module (and have the
2859 // same TOC), the NOP will remain unchanged.
2861 bool needsTOCRestore = false;
2862 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
2863 if (CallOpc == PPCISD::BCTRL_SVR4) {
2864 // This is a call through a function pointer.
2865 // Restore the caller TOC from the save area into R2.
2866 // See PrepareCall() for more information about calls through function
2867 // pointers in the 64-bit SVR4 ABI.
2868 // We are using a target-specific load with r2 hard coded, because the
2869 // result of a target-independent load would never go directly into r2,
2870 // since r2 is a reserved register (which prevents the register allocator
2871 // from allocating it), resulting in an additional register being
2872 // allocated and an unnecessary move instruction being generated.
2873 needsTOCRestore = true;
2874 } else if (CallOpc == PPCISD::CALL_SVR4) {
2875 // Otherwise insert NOP.
2876 CallOpc = PPCISD::CALL_NOP_SVR4;
2880 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
2881 InFlag = Chain.getValue(1);
2883 if (needsTOCRestore) {
2884 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
2885 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
2886 InFlag = Chain.getValue(1);
2889 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2890 DAG.getIntPtrConstant(BytesCalleePops, true),
2893 InFlag = Chain.getValue(1);
2895 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2896 Ins, dl, DAG, InVals);
2900 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2901 SmallVectorImpl<SDValue> &InVals) const {
2902 SelectionDAG &DAG = CLI.DAG;
2903 DebugLoc &dl = CLI.DL;
2904 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2905 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2906 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2907 SDValue Chain = CLI.Chain;
2908 SDValue Callee = CLI.Callee;
2909 bool &isTailCall = CLI.IsTailCall;
2910 CallingConv::ID CallConv = CLI.CallConv;
2911 bool isVarArg = CLI.IsVarArg;
2914 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
2917 if (PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
2918 return LowerCall_SVR4(Chain, Callee, CallConv, isVarArg,
2919 isTailCall, Outs, OutVals, Ins,
2922 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
2923 isTailCall, Outs, OutVals, Ins,
2928 PPCTargetLowering::LowerCall_SVR4(SDValue Chain, SDValue Callee,
2929 CallingConv::ID CallConv, bool isVarArg,
2931 const SmallVectorImpl<ISD::OutputArg> &Outs,
2932 const SmallVectorImpl<SDValue> &OutVals,
2933 const SmallVectorImpl<ISD::InputArg> &Ins,
2934 DebugLoc dl, SelectionDAG &DAG,
2935 SmallVectorImpl<SDValue> &InVals) const {
2936 // See PPCTargetLowering::LowerFormalArguments_SVR4() for a description
2937 // of the 32-bit SVR4 ABI stack frame layout.
2939 assert((CallConv == CallingConv::C ||
2940 CallConv == CallingConv::Fast) && "Unknown calling convention!");
2942 unsigned PtrByteSize = 4;
2944 MachineFunction &MF = DAG.getMachineFunction();
2946 // Mark this function as potentially containing a function that contains a
2947 // tail call. As a consequence the frame pointer will be used for dynamicalloc
2948 // and restoring the callers stack pointer in this functions epilog. This is
2949 // done because by tail calling the called function might overwrite the value
2950 // in this function's (MF) stack pointer stack slot 0(SP).
2951 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2952 CallConv == CallingConv::Fast)
2953 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
2955 // Count how many bytes are to be pushed on the stack, including the linkage
2956 // area, parameter list area and the part of the local variable space which
2957 // contains copies of aggregates which are passed by value.
2959 // Assign locations to all of the outgoing arguments.
2960 SmallVector<CCValAssign, 16> ArgLocs;
2961 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2962 getTargetMachine(), ArgLocs, *DAG.getContext());
2964 // Reserve space for the linkage area on the stack.
2965 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
2968 // Handle fixed and variable vector arguments differently.
2969 // Fixed vector arguments go into registers as long as registers are
2970 // available. Variable vector arguments always go into memory.
2971 unsigned NumArgs = Outs.size();
2973 for (unsigned i = 0; i != NumArgs; ++i) {
2974 MVT ArgVT = Outs[i].VT;
2975 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2978 if (Outs[i].IsFixed) {
2979 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
2982 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
2988 errs() << "Call operand #" << i << " has unhandled type "
2989 << EVT(ArgVT).getEVTString() << "\n";
2991 llvm_unreachable(0);
2995 // All arguments are treated the same.
2996 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4);
2999 // Assign locations to all of the outgoing aggregate by value arguments.
3000 SmallVector<CCValAssign, 16> ByValArgLocs;
3001 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3002 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3004 // Reserve stack space for the allocations in CCInfo.
3005 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3007 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal);
3009 // Size of the linkage area, parameter list area and the part of the local
3010 // space variable where copies of aggregates which are passed by value are
3012 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3014 // Calculate by how many bytes the stack has to be adjusted in case of tail
3015 // call optimization.
3016 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3018 // Adjust the stack pointer for the new arguments...
3019 // These operations are automatically eliminated by the prolog/epilog pass
3020 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3021 SDValue CallSeqStart = Chain;
3023 // Load the return address and frame pointer so it can be moved somewhere else
3026 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3029 // Set up a copy of the stack pointer for use loading and storing any
3030 // arguments that may not fit in the registers available for argument
3032 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3034 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3035 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3036 SmallVector<SDValue, 8> MemOpChains;
3038 bool seenFloatArg = false;
3039 // Walk the register/memloc assignments, inserting copies/loads.
3040 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3043 CCValAssign &VA = ArgLocs[i];
3044 SDValue Arg = OutVals[i];
3045 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3047 if (Flags.isByVal()) {
3048 // Argument is an aggregate which is passed by value, thus we need to
3049 // create a copy of it in the local variable space of the current stack
3050 // frame (which is the stack frame of the caller) and pass the address of
3051 // this copy to the callee.
3052 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3053 CCValAssign &ByValVA = ByValArgLocs[j++];
3054 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3056 // Memory reserved in the local variable space of the callers stack frame.
3057 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3059 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3060 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3062 // Create a copy of the argument in the local area of the current
3064 SDValue MemcpyCall =
3065 CreateCopyOfByValArgument(Arg, PtrOff,
3066 CallSeqStart.getNode()->getOperand(0),
3069 // This must go outside the CALLSEQ_START..END.
3070 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3071 CallSeqStart.getNode()->getOperand(1));
3072 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3073 NewCallSeqStart.getNode());
3074 Chain = CallSeqStart = NewCallSeqStart;
3076 // Pass the address of the aggregate copy on the stack either in a
3077 // physical register or in the parameter list area of the current stack
3078 // frame to the callee.
3082 if (VA.isRegLoc()) {
3083 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3084 // Put argument in a physical register.
3085 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3087 // Put argument in the parameter list area of the current stack frame.
3088 assert(VA.isMemLoc());
3089 unsigned LocMemOffset = VA.getLocMemOffset();
3092 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3093 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3095 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3096 MachinePointerInfo(),
3099 // Calculate and remember argument location.
3100 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3106 if (!MemOpChains.empty())
3107 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3108 &MemOpChains[0], MemOpChains.size());
3110 // Set CR6 to true if this is a vararg call with floating args passed in
3113 SDValue SetCR(DAG.getMachineNode(seenFloatArg ? PPC::CRSET : PPC::CRUNSET,
3115 RegsToPass.push_back(std::make_pair(unsigned(PPC::CR1EQ), SetCR));
3118 // Build a sequence of copy-to-reg nodes chained together with token chain
3119 // and flag operands which copy the outgoing args into the appropriate regs.
3121 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3122 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3123 RegsToPass[i].second, InFlag);
3124 InFlag = Chain.getValue(1);
3128 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3129 false, TailCallArguments);
3131 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3132 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3137 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
3138 CallingConv::ID CallConv, bool isVarArg,
3140 const SmallVectorImpl<ISD::OutputArg> &Outs,
3141 const SmallVectorImpl<SDValue> &OutVals,
3142 const SmallVectorImpl<ISD::InputArg> &Ins,
3143 DebugLoc dl, SelectionDAG &DAG,
3144 SmallVectorImpl<SDValue> &InVals) const {
3146 unsigned NumOps = Outs.size();
3148 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3149 bool isPPC64 = PtrVT == MVT::i64;
3150 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3152 MachineFunction &MF = DAG.getMachineFunction();
3154 // Mark this function as potentially containing a function that contains a
3155 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3156 // and restoring the callers stack pointer in this functions epilog. This is
3157 // done because by tail calling the called function might overwrite the value
3158 // in this function's (MF) stack pointer stack slot 0(SP).
3159 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3160 CallConv == CallingConv::Fast)
3161 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3163 unsigned nAltivecParamsAtEnd = 0;
3165 // Count how many bytes are to be pushed on the stack, including the linkage
3166 // area, and parameter passing area. We start with 24/48 bytes, which is
3167 // prereserved space for [SP][CR][LR][3 x unused].
3169 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
3171 nAltivecParamsAtEnd);
3173 // Calculate by how many bytes the stack has to be adjusted in case of tail
3174 // call optimization.
3175 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3177 // To protect arguments on the stack from being clobbered in a tail call,
3178 // force all the loads to happen before doing any other lowering.
3180 Chain = DAG.getStackArgumentTokenFactor(Chain);
3182 // Adjust the stack pointer for the new arguments...
3183 // These operations are automatically eliminated by the prolog/epilog pass
3184 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3185 SDValue CallSeqStart = Chain;
3187 // Load the return address and frame pointer so it can be move somewhere else
3190 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3193 // Set up a copy of the stack pointer for use loading and storing any
3194 // arguments that may not fit in the registers available for argument
3198 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3200 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3202 // Figure out which arguments are going to go in registers, and which in
3203 // memory. Also, if this is a vararg function, floating point operations
3204 // must be stored to our stack, and loaded into integer regs as well, if
3205 // any integer regs are available for argument passing.
3206 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
3207 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3209 static const uint16_t GPR_32[] = { // 32-bit registers.
3210 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
3211 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
3213 static const uint16_t GPR_64[] = { // 64-bit registers.
3214 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3215 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3217 static const uint16_t *FPR = GetFPR();
3219 static const uint16_t VR[] = {
3220 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3221 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3223 const unsigned NumGPRs = array_lengthof(GPR_32);
3224 const unsigned NumFPRs = 13;
3225 const unsigned NumVRs = array_lengthof(VR);
3227 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
3229 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3230 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3232 SmallVector<SDValue, 8> MemOpChains;
3233 for (unsigned i = 0; i != NumOps; ++i) {
3234 SDValue Arg = OutVals[i];
3235 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3237 // PtrOff will be used to store the current argument to the stack if a
3238 // register cannot be found for it.
3241 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3243 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3245 // On PPC64, promote integers to 64-bit values.
3246 if (isPPC64 && Arg.getValueType() == MVT::i32) {
3247 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3248 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3249 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3252 // FIXME memcpy is used way more than necessary. Correctness first.
3253 if (Flags.isByVal()) {
3254 unsigned Size = Flags.getByValSize();
3255 if (Size==1 || Size==2) {
3256 // Very small objects are passed right-justified.
3257 // Everything else is passed left-justified.
3258 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
3259 if (GPR_idx != NumGPRs) {
3260 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3261 MachinePointerInfo(), VT,
3263 MemOpChains.push_back(Load.getValue(1));
3264 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3266 ArgOffset += PtrByteSize;
3268 SDValue Const = DAG.getConstant(4 - Size, PtrOff.getValueType());
3269 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3270 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, AddPtr,
3271 CallSeqStart.getNode()->getOperand(0),
3273 // This must go outside the CALLSEQ_START..END.
3274 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3275 CallSeqStart.getNode()->getOperand(1));
3276 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3277 NewCallSeqStart.getNode());
3278 Chain = CallSeqStart = NewCallSeqStart;
3279 ArgOffset += PtrByteSize;
3283 // Copy entire object into memory. There are cases where gcc-generated
3284 // code assumes it is there, even if it could be put entirely into
3285 // registers. (This is not what the doc says.)
3286 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3287 CallSeqStart.getNode()->getOperand(0),
3289 // This must go outside the CALLSEQ_START..END.
3290 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3291 CallSeqStart.getNode()->getOperand(1));
3292 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(), NewCallSeqStart.getNode());
3293 Chain = CallSeqStart = NewCallSeqStart;
3294 // And copy the pieces of it that fit into registers.
3295 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3296 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3297 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3298 if (GPR_idx != NumGPRs) {
3299 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3300 MachinePointerInfo(),
3301 false, false, false, 0);
3302 MemOpChains.push_back(Load.getValue(1));
3303 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3304 ArgOffset += PtrByteSize;
3306 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3313 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3314 default: llvm_unreachable("Unexpected ValueType for argument!");
3317 if (GPR_idx != NumGPRs) {
3318 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3320 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3321 isPPC64, isTailCall, false, MemOpChains,
3322 TailCallArguments, dl);
3324 ArgOffset += PtrByteSize;
3328 if (FPR_idx != NumFPRs) {
3329 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3332 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3333 MachinePointerInfo(), false, false, 0);
3334 MemOpChains.push_back(Store);
3336 // Float varargs are always shadowed in available integer registers
3337 if (GPR_idx != NumGPRs) {
3338 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3339 MachinePointerInfo(), false, false,
3341 MemOpChains.push_back(Load.getValue(1));
3342 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3344 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
3345 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3346 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3347 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3348 MachinePointerInfo(),
3349 false, false, false, 0);
3350 MemOpChains.push_back(Load.getValue(1));
3351 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3354 // If we have any FPRs remaining, we may also have GPRs remaining.
3355 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
3357 if (GPR_idx != NumGPRs)
3359 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
3360 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
3364 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3365 isPPC64, isTailCall, false, MemOpChains,
3366 TailCallArguments, dl);
3371 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
3378 // These go aligned on the stack, or in the corresponding R registers
3379 // when within range. The Darwin PPC ABI doc claims they also go in
3380 // V registers; in fact gcc does this only for arguments that are
3381 // prototyped, not for those that match the ... We do it for all
3382 // arguments, seems to work.
3383 while (ArgOffset % 16 !=0) {
3384 ArgOffset += PtrByteSize;
3385 if (GPR_idx != NumGPRs)
3388 // We could elide this store in the case where the object fits
3389 // entirely in R registers. Maybe later.
3390 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3391 DAG.getConstant(ArgOffset, PtrVT));
3392 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3393 MachinePointerInfo(), false, false, 0);
3394 MemOpChains.push_back(Store);
3395 if (VR_idx != NumVRs) {
3396 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3397 MachinePointerInfo(),
3398 false, false, false, 0);
3399 MemOpChains.push_back(Load.getValue(1));
3400 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3403 for (unsigned i=0; i<16; i+=PtrByteSize) {
3404 if (GPR_idx == NumGPRs)
3406 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3407 DAG.getConstant(i, PtrVT));
3408 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3409 false, false, false, 0);
3410 MemOpChains.push_back(Load.getValue(1));
3411 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3416 // Non-varargs Altivec params generally go in registers, but have
3417 // stack space allocated at the end.
3418 if (VR_idx != NumVRs) {
3419 // Doesn't have GPR space allocated.
3420 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3421 } else if (nAltivecParamsAtEnd==0) {
3422 // We are emitting Altivec params in order.
3423 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3424 isPPC64, isTailCall, true, MemOpChains,
3425 TailCallArguments, dl);
3431 // If all Altivec parameters fit in registers, as they usually do,
3432 // they get stack space following the non-Altivec parameters. We
3433 // don't track this here because nobody below needs it.
3434 // If there are more Altivec parameters than fit in registers emit
3436 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
3438 // Offset is aligned; skip 1st 12 params which go in V registers.
3439 ArgOffset = ((ArgOffset+15)/16)*16;
3441 for (unsigned i = 0; i != NumOps; ++i) {
3442 SDValue Arg = OutVals[i];
3443 EVT ArgType = Outs[i].VT;
3444 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
3445 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
3448 // We are emitting Altivec params in order.
3449 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3450 isPPC64, isTailCall, true, MemOpChains,
3451 TailCallArguments, dl);
3458 if (!MemOpChains.empty())
3459 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3460 &MemOpChains[0], MemOpChains.size());
3462 // Check if this is an indirect call (MTCTR/BCTRL).
3463 // See PrepareCall() for more information about calls through function
3464 // pointers in the 64-bit SVR4 ABI.
3465 if (!isTailCall && isPPC64 && PPCSubTarget.isSVR4ABI() &&
3466 !dyn_cast<GlobalAddressSDNode>(Callee) &&
3467 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
3468 !isBLACompatibleAddress(Callee, DAG)) {
3469 // Load r2 into a virtual register and store it to the TOC save area.
3470 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
3471 // TOC save area offset.
3472 SDValue PtrOff = DAG.getIntPtrConstant(40);
3473 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3474 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
3478 // On Darwin, R12 must contain the address of an indirect callee. This does
3479 // not mean the MTCTR instruction must use R12; it's easier to model this as
3480 // an extra parameter, so do that.
3482 !dyn_cast<GlobalAddressSDNode>(Callee) &&
3483 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
3484 !isBLACompatibleAddress(Callee, DAG))
3485 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
3486 PPC::R12), Callee));
3488 // Build a sequence of copy-to-reg nodes chained together with token chain
3489 // and flag operands which copy the outgoing args into the appropriate regs.
3491 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3492 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3493 RegsToPass[i].second, InFlag);
3494 InFlag = Chain.getValue(1);
3498 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
3499 FPOp, true, TailCallArguments);
3501 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3502 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3507 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3508 MachineFunction &MF, bool isVarArg,
3509 const SmallVectorImpl<ISD::OutputArg> &Outs,
3510 LLVMContext &Context) const {
3511 SmallVector<CCValAssign, 16> RVLocs;
3512 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3514 return CCInfo.CheckReturn(Outs, RetCC_PPC);
3518 PPCTargetLowering::LowerReturn(SDValue Chain,
3519 CallingConv::ID CallConv, bool isVarArg,
3520 const SmallVectorImpl<ISD::OutputArg> &Outs,
3521 const SmallVectorImpl<SDValue> &OutVals,
3522 DebugLoc dl, SelectionDAG &DAG) const {
3524 SmallVector<CCValAssign, 16> RVLocs;
3525 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3526 getTargetMachine(), RVLocs, *DAG.getContext());
3527 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
3529 // If this is the first return lowered for this function, add the regs to the
3530 // liveout set for the function.
3531 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3532 for (unsigned i = 0; i != RVLocs.size(); ++i)
3533 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3538 // Copy the result values into the output registers.
3539 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3540 CCValAssign &VA = RVLocs[i];
3541 assert(VA.isRegLoc() && "Can only return in registers!");
3542 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
3544 Flag = Chain.getValue(1);
3548 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
3550 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
3553 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
3554 const PPCSubtarget &Subtarget) const {
3555 // When we pop the dynamic allocation we need to restore the SP link.
3556 DebugLoc dl = Op.getDebugLoc();
3558 // Get the corect type for pointers.
3559 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3561 // Construct the stack pointer operand.
3562 bool isPPC64 = Subtarget.isPPC64();
3563 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
3564 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
3566 // Get the operands for the STACKRESTORE.
3567 SDValue Chain = Op.getOperand(0);
3568 SDValue SaveSP = Op.getOperand(1);
3570 // Load the old link SP.
3571 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
3572 MachinePointerInfo(),
3573 false, false, false, 0);
3575 // Restore the stack pointer.
3576 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
3578 // Store the old link SP.
3579 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
3586 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
3587 MachineFunction &MF = DAG.getMachineFunction();
3588 bool isPPC64 = PPCSubTarget.isPPC64();
3589 bool isDarwinABI = PPCSubTarget.isDarwinABI();
3590 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3592 // Get current frame pointer save index. The users of this index will be
3593 // primarily DYNALLOC instructions.
3594 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
3595 int RASI = FI->getReturnAddrSaveIndex();
3597 // If the frame pointer save index hasn't been defined yet.
3599 // Find out what the fix offset of the frame pointer save area.
3600 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
3601 // Allocate the frame index for frame pointer save area.
3602 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
3604 FI->setReturnAddrSaveIndex(RASI);
3606 return DAG.getFrameIndex(RASI, PtrVT);
3610 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
3611 MachineFunction &MF = DAG.getMachineFunction();
3612 bool isPPC64 = PPCSubTarget.isPPC64();
3613 bool isDarwinABI = PPCSubTarget.isDarwinABI();
3614 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3616 // Get current frame pointer save index. The users of this index will be
3617 // primarily DYNALLOC instructions.
3618 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
3619 int FPSI = FI->getFramePointerSaveIndex();
3621 // If the frame pointer save index hasn't been defined yet.
3623 // Find out what the fix offset of the frame pointer save area.
3624 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
3627 // Allocate the frame index for frame pointer save area.
3628 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
3630 FI->setFramePointerSaveIndex(FPSI);
3632 return DAG.getFrameIndex(FPSI, PtrVT);
3635 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3637 const PPCSubtarget &Subtarget) const {
3639 SDValue Chain = Op.getOperand(0);
3640 SDValue Size = Op.getOperand(1);
3641 DebugLoc dl = Op.getDebugLoc();
3643 // Get the corect type for pointers.
3644 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3646 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
3647 DAG.getConstant(0, PtrVT), Size);
3648 // Construct a node for the frame pointer save index.
3649 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
3650 // Build a DYNALLOC node.
3651 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
3652 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
3653 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
3656 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
3658 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
3659 // Not FP? Not a fsel.
3660 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
3661 !Op.getOperand(2).getValueType().isFloatingPoint())
3664 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3666 // Cannot handle SETEQ/SETNE.
3667 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
3669 EVT ResVT = Op.getValueType();
3670 EVT CmpVT = Op.getOperand(0).getValueType();
3671 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
3672 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
3673 DebugLoc dl = Op.getDebugLoc();
3675 // If the RHS of the comparison is a 0.0, we don't need to do the
3676 // subtraction at all.
3677 if (isFloatingPointZero(RHS))
3679 default: break; // SETUO etc aren't handled by fsel.
3682 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
3685 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
3686 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
3687 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
3690 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
3693 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
3694 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
3695 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
3696 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
3701 default: break; // SETUO etc aren't handled by fsel.
3704 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
3705 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3706 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3707 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
3710 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
3711 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3712 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3713 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
3716 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
3717 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3718 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3719 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
3722 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
3723 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
3724 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
3725 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
3730 // FIXME: Split this code up when LegalizeDAGTypes lands.
3731 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
3732 DebugLoc dl) const {
3733 assert(Op.getOperand(0).getValueType().isFloatingPoint());
3734 SDValue Src = Op.getOperand(0);
3735 if (Src.getValueType() == MVT::f32)
3736 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
3739 switch (Op.getValueType().getSimpleVT().SimpleTy) {
3740 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
3742 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
3747 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
3751 // Convert the FP value to an int value through memory.
3752 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
3754 // Emit a store to the stack slot.
3755 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
3756 MachinePointerInfo(), false, false, 0);
3758 // Result is a load from the stack slot. If loading 4 bytes, make sure to
3760 if (Op.getValueType() == MVT::i32)
3761 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
3762 DAG.getConstant(4, FIPtr.getValueType()));
3763 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
3764 false, false, false, 0);
3767 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
3768 SelectionDAG &DAG) const {
3769 DebugLoc dl = Op.getDebugLoc();
3770 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
3771 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
3774 if (Op.getOperand(0).getValueType() == MVT::i64) {
3775 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op.getOperand(0));
3776 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
3777 if (Op.getValueType() == MVT::f32)
3778 FP = DAG.getNode(ISD::FP_ROUND, dl,
3779 MVT::f32, FP, DAG.getIntPtrConstant(0));
3783 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
3784 "Unhandled SINT_TO_FP type in custom expander!");
3785 // Since we only generate this in 64-bit mode, we can take advantage of
3786 // 64-bit registers. In particular, sign extend the input value into the
3787 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
3788 // then lfd it and fcfid it.
3789 MachineFunction &MF = DAG.getMachineFunction();
3790 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
3791 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
3792 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3793 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
3795 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
3798 // STD the extended value into the stack slot.
3799 MachineMemOperand *MMO =
3800 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
3801 MachineMemOperand::MOStore, 8, 8);
3802 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
3804 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
3805 Ops, 4, MVT::i64, MMO);
3806 // Load the value as a double.
3807 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
3808 false, false, false, 0);
3810 // FCFID it and return it.
3811 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
3812 if (Op.getValueType() == MVT::f32)
3813 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
3817 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
3818 SelectionDAG &DAG) const {
3819 DebugLoc dl = Op.getDebugLoc();
3821 The rounding mode is in bits 30:31 of FPSR, and has the following
3828 FLT_ROUNDS, on the other hand, expects the following:
3835 To perform the conversion, we do:
3836 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
3839 MachineFunction &MF = DAG.getMachineFunction();
3840 EVT VT = Op.getValueType();
3841 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3842 std::vector<EVT> NodeTys;
3843 SDValue MFFSreg, InFlag;
3845 // Save FP Control Word to register
3846 NodeTys.push_back(MVT::f64); // return register
3847 NodeTys.push_back(MVT::Glue); // unused in this context
3848 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
3850 // Save FP register to stack slot
3851 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
3852 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
3853 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
3854 StackSlot, MachinePointerInfo(), false, false,0);
3856 // Load FP Control Word from low 32 bits of stack slot.
3857 SDValue Four = DAG.getConstant(4, PtrVT);
3858 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
3859 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
3860 false, false, false, 0);
3862 // Transform as necessary
3864 DAG.getNode(ISD::AND, dl, MVT::i32,
3865 CWD, DAG.getConstant(3, MVT::i32));
3867 DAG.getNode(ISD::SRL, dl, MVT::i32,
3868 DAG.getNode(ISD::AND, dl, MVT::i32,
3869 DAG.getNode(ISD::XOR, dl, MVT::i32,
3870 CWD, DAG.getConstant(3, MVT::i32)),
3871 DAG.getConstant(3, MVT::i32)),
3872 DAG.getConstant(1, MVT::i32));
3875 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
3877 return DAG.getNode((VT.getSizeInBits() < 16 ?
3878 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
3881 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
3882 EVT VT = Op.getValueType();
3883 unsigned BitWidth = VT.getSizeInBits();
3884 DebugLoc dl = Op.getDebugLoc();
3885 assert(Op.getNumOperands() == 3 &&
3886 VT == Op.getOperand(1).getValueType() &&
3889 // Expand into a bunch of logical ops. Note that these ops
3890 // depend on the PPC behavior for oversized shift amounts.
3891 SDValue Lo = Op.getOperand(0);
3892 SDValue Hi = Op.getOperand(1);
3893 SDValue Amt = Op.getOperand(2);
3894 EVT AmtVT = Amt.getValueType();
3896 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3897 DAG.getConstant(BitWidth, AmtVT), Amt);
3898 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
3899 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
3900 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
3901 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3902 DAG.getConstant(-BitWidth, AmtVT));
3903 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
3904 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3905 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
3906 SDValue OutOps[] = { OutLo, OutHi };
3907 return DAG.getMergeValues(OutOps, 2, dl);
3910 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
3911 EVT VT = Op.getValueType();
3912 DebugLoc dl = Op.getDebugLoc();
3913 unsigned BitWidth = VT.getSizeInBits();
3914 assert(Op.getNumOperands() == 3 &&
3915 VT == Op.getOperand(1).getValueType() &&
3918 // Expand into a bunch of logical ops. Note that these ops
3919 // depend on the PPC behavior for oversized shift amounts.
3920 SDValue Lo = Op.getOperand(0);
3921 SDValue Hi = Op.getOperand(1);
3922 SDValue Amt = Op.getOperand(2);
3923 EVT AmtVT = Amt.getValueType();
3925 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3926 DAG.getConstant(BitWidth, AmtVT), Amt);
3927 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3928 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3929 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3930 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3931 DAG.getConstant(-BitWidth, AmtVT));
3932 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
3933 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
3934 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
3935 SDValue OutOps[] = { OutLo, OutHi };
3936 return DAG.getMergeValues(OutOps, 2, dl);
3939 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
3940 DebugLoc dl = Op.getDebugLoc();
3941 EVT VT = Op.getValueType();
3942 unsigned BitWidth = VT.getSizeInBits();
3943 assert(Op.getNumOperands() == 3 &&
3944 VT == Op.getOperand(1).getValueType() &&
3947 // Expand into a bunch of logical ops, followed by a select_cc.
3948 SDValue Lo = Op.getOperand(0);
3949 SDValue Hi = Op.getOperand(1);
3950 SDValue Amt = Op.getOperand(2);
3951 EVT AmtVT = Amt.getValueType();
3953 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
3954 DAG.getConstant(BitWidth, AmtVT), Amt);
3955 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
3956 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
3957 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
3958 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
3959 DAG.getConstant(-BitWidth, AmtVT));
3960 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
3961 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
3962 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
3963 Tmp4, Tmp6, ISD::SETLE);
3964 SDValue OutOps[] = { OutLo, OutHi };
3965 return DAG.getMergeValues(OutOps, 2, dl);
3968 //===----------------------------------------------------------------------===//
3969 // Vector related lowering.
3972 /// BuildSplatI - Build a canonical splati of Val with an element size of
3973 /// SplatSize. Cast the result to VT.
3974 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
3975 SelectionDAG &DAG, DebugLoc dl) {
3976 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
3978 static const EVT VTys[] = { // canonical VT to use for each size.
3979 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
3982 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
3984 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
3988 EVT CanonicalVT = VTys[SplatSize-1];
3990 // Build a canonical splat for this value.
3991 SDValue Elt = DAG.getConstant(Val, MVT::i32);
3992 SmallVector<SDValue, 8> Ops;
3993 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
3994 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
3995 &Ops[0], Ops.size());
3996 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
3999 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
4000 /// specified intrinsic ID.
4001 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
4002 SelectionDAG &DAG, DebugLoc dl,
4003 EVT DestVT = MVT::Other) {
4004 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
4005 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4006 DAG.getConstant(IID, MVT::i32), LHS, RHS);
4009 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
4010 /// specified intrinsic ID.
4011 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
4012 SDValue Op2, SelectionDAG &DAG,
4013 DebugLoc dl, EVT DestVT = MVT::Other) {
4014 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
4015 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4016 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
4020 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
4021 /// amount. The result has the specified value type.
4022 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
4023 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4024 // Force LHS/RHS to be the right type.
4025 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
4026 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
4029 for (unsigned i = 0; i != 16; ++i)
4031 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
4032 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4035 // If this is a case we can't handle, return null and let the default
4036 // expansion code take care of it. If we CAN select this case, and if it
4037 // selects to a single instruction, return Op. Otherwise, if we can codegen
4038 // this case more efficiently than a constant pool load, lower it to the
4039 // sequence of ops that should be used.
4040 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
4041 SelectionDAG &DAG) const {
4042 DebugLoc dl = Op.getDebugLoc();
4043 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4044 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
4046 // Check if this is a splat of a constant value.
4047 APInt APSplatBits, APSplatUndef;
4048 unsigned SplatBitSize;
4050 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
4051 HasAnyUndefs, 0, true) || SplatBitSize > 32)
4054 unsigned SplatBits = APSplatBits.getZExtValue();
4055 unsigned SplatUndef = APSplatUndef.getZExtValue();
4056 unsigned SplatSize = SplatBitSize / 8;
4058 // First, handle single instruction cases.
4061 if (SplatBits == 0) {
4062 // Canonicalize all zero vectors to be v4i32.
4063 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
4064 SDValue Z = DAG.getConstant(0, MVT::i32);
4065 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
4066 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
4071 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
4072 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
4074 if (SextVal >= -16 && SextVal <= 15)
4075 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
4078 // Two instruction sequences.
4080 // If this value is in the range [-32,30] and is even, use:
4081 // tmp = VSPLTI[bhw], result = add tmp, tmp
4082 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
4083 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
4084 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
4085 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4088 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
4089 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
4091 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
4092 // Make -1 and vspltisw -1:
4093 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
4095 // Make the VSLW intrinsic, computing 0x8000_0000.
4096 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
4099 // xor by OnesV to invert it.
4100 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
4101 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4104 // Check to see if this is a wide variety of vsplti*, binop self cases.
4105 static const signed char SplatCsts[] = {
4106 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
4107 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
4110 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
4111 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
4112 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
4113 int i = SplatCsts[idx];
4115 // Figure out what shift amount will be used by altivec if shifted by i in
4117 unsigned TypeShiftAmt = i & (SplatBitSize-1);
4119 // vsplti + shl self.
4120 if (SextVal == (i << (int)TypeShiftAmt)) {
4121 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4122 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4123 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
4124 Intrinsic::ppc_altivec_vslw
4126 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4127 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4130 // vsplti + srl self.
4131 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
4132 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4133 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4134 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
4135 Intrinsic::ppc_altivec_vsrw
4137 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4138 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4141 // vsplti + sra self.
4142 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
4143 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4144 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4145 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
4146 Intrinsic::ppc_altivec_vsraw
4148 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4149 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4152 // vsplti + rol self.
4153 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
4154 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
4155 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4156 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4157 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
4158 Intrinsic::ppc_altivec_vrlw
4160 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4161 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4164 // t = vsplti c, result = vsldoi t, t, 1
4165 if (SextVal == ((i << 8) | (i < 0 ? 0xFF : 0))) {
4166 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4167 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
4169 // t = vsplti c, result = vsldoi t, t, 2
4170 if (SextVal == ((i << 16) | (i < 0 ? 0xFFFF : 0))) {
4171 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4172 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
4174 // t = vsplti c, result = vsldoi t, t, 3
4175 if (SextVal == ((i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
4176 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4177 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
4181 // Three instruction sequences.
4183 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
4184 if (SextVal >= 0 && SextVal <= 31) {
4185 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
4186 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
4187 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
4188 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
4190 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
4191 if (SextVal >= -31 && SextVal <= 0) {
4192 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
4193 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
4194 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
4195 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
4201 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4202 /// the specified operations to build the shuffle.
4203 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4204 SDValue RHS, SelectionDAG &DAG,
4206 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4207 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
4208 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
4211 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4223 if (OpNum == OP_COPY) {
4224 if (LHSID == (1*9+2)*9+3) return LHS;
4225 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
4229 SDValue OpLHS, OpRHS;
4230 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4231 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4235 default: llvm_unreachable("Unknown i32 permute!");
4237 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
4238 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
4239 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
4240 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
4243 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
4244 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
4245 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
4246 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
4249 for (unsigned i = 0; i != 16; ++i)
4250 ShufIdxs[i] = (i&3)+0;
4253 for (unsigned i = 0; i != 16; ++i)
4254 ShufIdxs[i] = (i&3)+4;
4257 for (unsigned i = 0; i != 16; ++i)
4258 ShufIdxs[i] = (i&3)+8;
4261 for (unsigned i = 0; i != 16; ++i)
4262 ShufIdxs[i] = (i&3)+12;
4265 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
4267 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
4269 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
4271 EVT VT = OpLHS.getValueType();
4272 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
4273 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
4274 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
4275 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4278 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
4279 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
4280 /// return the code it can be lowered into. Worst case, it can always be
4281 /// lowered into a vperm.
4282 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4283 SelectionDAG &DAG) const {
4284 DebugLoc dl = Op.getDebugLoc();
4285 SDValue V1 = Op.getOperand(0);
4286 SDValue V2 = Op.getOperand(1);
4287 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4288 EVT VT = Op.getValueType();
4290 // Cases that are handled by instructions that take permute immediates
4291 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
4292 // selected by the instruction selector.
4293 if (V2.getOpcode() == ISD::UNDEF) {
4294 if (PPC::isSplatShuffleMask(SVOp, 1) ||
4295 PPC::isSplatShuffleMask(SVOp, 2) ||
4296 PPC::isSplatShuffleMask(SVOp, 4) ||
4297 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
4298 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
4299 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
4300 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
4301 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
4302 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
4303 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
4304 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
4305 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
4310 // Altivec has a variety of "shuffle immediates" that take two vector inputs
4311 // and produce a fixed permutation. If any of these match, do not lower to
4313 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
4314 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
4315 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
4316 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
4317 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
4318 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
4319 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
4320 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
4321 PPC::isVMRGHShuffleMask(SVOp, 4, false))
4324 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
4325 // perfect shuffle table to emit an optimal matching sequence.
4326 ArrayRef<int> PermMask = SVOp->getMask();
4328 unsigned PFIndexes[4];
4329 bool isFourElementShuffle = true;
4330 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
4331 unsigned EltNo = 8; // Start out undef.
4332 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
4333 if (PermMask[i*4+j] < 0)
4334 continue; // Undef, ignore it.
4336 unsigned ByteSource = PermMask[i*4+j];
4337 if ((ByteSource & 3) != j) {
4338 isFourElementShuffle = false;
4343 EltNo = ByteSource/4;
4344 } else if (EltNo != ByteSource/4) {
4345 isFourElementShuffle = false;
4349 PFIndexes[i] = EltNo;
4352 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
4353 // perfect shuffle vector to determine if it is cost effective to do this as
4354 // discrete instructions, or whether we should use a vperm.
4355 if (isFourElementShuffle) {
4356 // Compute the index in the perfect shuffle table.
4357 unsigned PFTableIndex =
4358 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
4360 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4361 unsigned Cost = (PFEntry >> 30);
4363 // Determining when to avoid vperm is tricky. Many things affect the cost
4364 // of vperm, particularly how many times the perm mask needs to be computed.
4365 // For example, if the perm mask can be hoisted out of a loop or is already
4366 // used (perhaps because there are multiple permutes with the same shuffle
4367 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
4368 // the loop requires an extra register.
4370 // As a compromise, we only emit discrete instructions if the shuffle can be
4371 // generated in 3 or fewer operations. When we have loop information
4372 // available, if this block is within a loop, we should avoid using vperm
4373 // for 3-operation perms and use a constant pool load instead.
4375 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4378 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
4379 // vector that will get spilled to the constant pool.
4380 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
4382 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
4383 // that it is in input element units, not in bytes. Convert now.
4384 EVT EltVT = V1.getValueType().getVectorElementType();
4385 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
4387 SmallVector<SDValue, 16> ResultMask;
4388 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4389 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
4391 for (unsigned j = 0; j != BytesPerElement; ++j)
4392 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
4396 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
4397 &ResultMask[0], ResultMask.size());
4398 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
4401 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
4402 /// altivec comparison. If it is, return true and fill in Opc/isDot with
4403 /// information about the intrinsic.
4404 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
4406 unsigned IntrinsicID =
4407 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
4410 switch (IntrinsicID) {
4411 default: return false;
4412 // Comparison predicates.
4413 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
4414 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
4415 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
4416 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
4417 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
4418 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
4419 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
4420 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
4421 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
4422 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
4423 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
4424 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
4425 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
4427 // Normal Comparisons.
4428 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
4429 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
4430 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
4431 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
4432 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
4433 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
4434 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
4435 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
4436 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
4437 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
4438 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
4439 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
4440 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
4445 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
4446 /// lower, do it, otherwise return null.
4447 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4448 SelectionDAG &DAG) const {
4449 // If this is a lowered altivec predicate compare, CompareOpc is set to the
4450 // opcode number of the comparison.
4451 DebugLoc dl = Op.getDebugLoc();
4454 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
4455 return SDValue(); // Don't custom lower most intrinsics.
4457 // If this is a non-dot comparison, make the VCMP node and we are done.
4459 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
4460 Op.getOperand(1), Op.getOperand(2),
4461 DAG.getConstant(CompareOpc, MVT::i32));
4462 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
4465 // Create the PPCISD altivec 'dot' comparison node.
4467 Op.getOperand(2), // LHS
4468 Op.getOperand(3), // RHS
4469 DAG.getConstant(CompareOpc, MVT::i32)
4471 std::vector<EVT> VTs;
4472 VTs.push_back(Op.getOperand(2).getValueType());
4473 VTs.push_back(MVT::Glue);
4474 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
4476 // Now that we have the comparison, emit a copy from the CR to a GPR.
4477 // This is flagged to the above dot comparison.
4478 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
4479 DAG.getRegister(PPC::CR6, MVT::i32),
4480 CompNode.getValue(1));
4482 // Unpack the result based on how the target uses it.
4483 unsigned BitNo; // Bit # of CR6.
4484 bool InvertBit; // Invert result?
4485 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
4486 default: // Can't happen, don't crash on invalid number though.
4487 case 0: // Return the value of the EQ bit of CR6.
4488 BitNo = 0; InvertBit = false;
4490 case 1: // Return the inverted value of the EQ bit of CR6.
4491 BitNo = 0; InvertBit = true;
4493 case 2: // Return the value of the LT bit of CR6.
4494 BitNo = 2; InvertBit = false;
4496 case 3: // Return the inverted value of the LT bit of CR6.
4497 BitNo = 2; InvertBit = true;
4501 // Shift the bit into the low position.
4502 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
4503 DAG.getConstant(8-(3-BitNo), MVT::i32));
4505 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
4506 DAG.getConstant(1, MVT::i32));
4508 // If we are supposed to, toggle the bit.
4510 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
4511 DAG.getConstant(1, MVT::i32));
4515 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
4516 SelectionDAG &DAG) const {
4517 DebugLoc dl = Op.getDebugLoc();
4518 // Create a stack slot that is 16-byte aligned.
4519 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
4520 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
4521 EVT PtrVT = getPointerTy();
4522 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4524 // Store the input value into Value#0 of the stack slot.
4525 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
4526 Op.getOperand(0), FIdx, MachinePointerInfo(),
4529 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
4530 false, false, false, 0);
4533 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
4534 DebugLoc dl = Op.getDebugLoc();
4535 if (Op.getValueType() == MVT::v4i32) {
4536 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4538 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
4539 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
4541 SDValue RHSSwap = // = vrlw RHS, 16
4542 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
4544 // Shrinkify inputs to v8i16.
4545 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
4546 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
4547 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
4549 // Low parts multiplied together, generating 32-bit results (we ignore the
4551 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
4552 LHS, RHS, DAG, dl, MVT::v4i32);
4554 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
4555 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
4556 // Shift the high parts up 16 bits.
4557 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
4559 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
4560 } else if (Op.getValueType() == MVT::v8i16) {
4561 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4563 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
4565 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
4566 LHS, RHS, Zero, DAG, dl);
4567 } else if (Op.getValueType() == MVT::v16i8) {
4568 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4570 // Multiply the even 8-bit parts, producing 16-bit sums.
4571 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
4572 LHS, RHS, DAG, dl, MVT::v8i16);
4573 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
4575 // Multiply the odd 8-bit parts, producing 16-bit sums.
4576 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
4577 LHS, RHS, DAG, dl, MVT::v8i16);
4578 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
4580 // Merge the results together.
4582 for (unsigned i = 0; i != 8; ++i) {
4584 Ops[i*2+1] = 2*i+1+16;
4586 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
4588 llvm_unreachable("Unknown mul to lower!");
4592 /// LowerOperation - Provide custom lowering hooks for some operations.
4594 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4595 switch (Op.getOpcode()) {
4596 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
4597 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
4598 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
4599 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
4600 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
4601 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
4602 case ISD::SETCC: return LowerSETCC(Op, DAG);
4603 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
4604 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
4606 return LowerVASTART(Op, DAG, PPCSubTarget);
4609 return LowerVAARG(Op, DAG, PPCSubTarget);
4611 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
4612 case ISD::DYNAMIC_STACKALLOC:
4613 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
4615 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
4616 case ISD::FP_TO_UINT:
4617 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
4619 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
4620 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
4622 // Lower 64-bit shifts.
4623 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
4624 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
4625 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
4627 // Vector-related lowering.
4628 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
4629 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
4630 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4631 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
4632 case ISD::MUL: return LowerMUL(Op, DAG);
4634 // Frame & Return address.
4635 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4636 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
4640 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
4641 SmallVectorImpl<SDValue>&Results,
4642 SelectionDAG &DAG) const {
4643 const TargetMachine &TM = getTargetMachine();
4644 DebugLoc dl = N->getDebugLoc();
4645 switch (N->getOpcode()) {
4647 llvm_unreachable("Do not know how to custom type legalize this operation!");
4649 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
4650 || TM.getSubtarget<PPCSubtarget>().isPPC64())
4653 EVT VT = N->getValueType(0);
4655 if (VT == MVT::i64) {
4656 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
4658 Results.push_back(NewNode);
4659 Results.push_back(NewNode.getValue(1));
4663 case ISD::FP_ROUND_INREG: {
4664 assert(N->getValueType(0) == MVT::ppcf128);
4665 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
4666 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
4667 MVT::f64, N->getOperand(0),
4668 DAG.getIntPtrConstant(0));
4669 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
4670 MVT::f64, N->getOperand(0),
4671 DAG.getIntPtrConstant(1));
4673 // This sequence changes FPSCR to do round-to-zero, adds the two halves
4674 // of the long double, and puts FPSCR back the way it was. We do not
4675 // actually model FPSCR.
4676 std::vector<EVT> NodeTys;
4677 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
4679 NodeTys.push_back(MVT::f64); // Return register
4680 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
4681 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4682 MFFSreg = Result.getValue(0);
4683 InFlag = Result.getValue(1);
4686 NodeTys.push_back(MVT::Glue); // Returns a flag
4687 Ops[0] = DAG.getConstant(31, MVT::i32);
4689 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
4690 InFlag = Result.getValue(0);
4693 NodeTys.push_back(MVT::Glue); // Returns a flag
4694 Ops[0] = DAG.getConstant(30, MVT::i32);
4696 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
4697 InFlag = Result.getValue(0);
4700 NodeTys.push_back(MVT::f64); // result of add
4701 NodeTys.push_back(MVT::Glue); // Returns a flag
4705 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
4706 FPreg = Result.getValue(0);
4707 InFlag = Result.getValue(1);
4710 NodeTys.push_back(MVT::f64);
4711 Ops[0] = DAG.getConstant(1, MVT::i32);
4715 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
4716 FPreg = Result.getValue(0);
4718 // We know the low half is about to be thrown away, so just use something
4720 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
4724 case ISD::FP_TO_SINT:
4725 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
4731 //===----------------------------------------------------------------------===//
4732 // Other Lowering Code
4733 //===----------------------------------------------------------------------===//
4736 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
4737 bool is64bit, unsigned BinOpcode) const {
4738 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4739 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4741 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4742 MachineFunction *F = BB->getParent();
4743 MachineFunction::iterator It = BB;
4746 unsigned dest = MI->getOperand(0).getReg();
4747 unsigned ptrA = MI->getOperand(1).getReg();
4748 unsigned ptrB = MI->getOperand(2).getReg();
4749 unsigned incr = MI->getOperand(3).getReg();
4750 DebugLoc dl = MI->getDebugLoc();
4752 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
4753 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4754 F->insert(It, loopMBB);
4755 F->insert(It, exitMBB);
4756 exitMBB->splice(exitMBB->begin(), BB,
4757 llvm::next(MachineBasicBlock::iterator(MI)),
4759 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
4761 MachineRegisterInfo &RegInfo = F->getRegInfo();
4762 unsigned TmpReg = (!BinOpcode) ? incr :
4763 RegInfo.createVirtualRegister(
4764 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4765 (const TargetRegisterClass *) &PPC::GPRCRegClass);
4769 // fallthrough --> loopMBB
4770 BB->addSuccessor(loopMBB);
4773 // l[wd]arx dest, ptr
4774 // add r0, dest, incr
4775 // st[wd]cx. r0, ptr
4777 // fallthrough --> exitMBB
4779 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
4780 .addReg(ptrA).addReg(ptrB);
4782 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
4783 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4784 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
4785 BuildMI(BB, dl, TII->get(PPC::BCC))
4786 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4787 BB->addSuccessor(loopMBB);
4788 BB->addSuccessor(exitMBB);
4797 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
4798 MachineBasicBlock *BB,
4799 bool is8bit, // operation
4800 unsigned BinOpcode) const {
4801 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
4802 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4803 // In 64 bit mode we have to use 64 bits for addresses, even though the
4804 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
4805 // registers without caring whether they're 32 or 64, but here we're
4806 // doing actual arithmetic on the addresses.
4807 bool is64bit = PPCSubTarget.isPPC64();
4808 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
4810 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4811 MachineFunction *F = BB->getParent();
4812 MachineFunction::iterator It = BB;
4815 unsigned dest = MI->getOperand(0).getReg();
4816 unsigned ptrA = MI->getOperand(1).getReg();
4817 unsigned ptrB = MI->getOperand(2).getReg();
4818 unsigned incr = MI->getOperand(3).getReg();
4819 DebugLoc dl = MI->getDebugLoc();
4821 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
4822 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
4823 F->insert(It, loopMBB);
4824 F->insert(It, exitMBB);
4825 exitMBB->splice(exitMBB->begin(), BB,
4826 llvm::next(MachineBasicBlock::iterator(MI)),
4828 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
4830 MachineRegisterInfo &RegInfo = F->getRegInfo();
4831 const TargetRegisterClass *RC =
4832 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
4833 (const TargetRegisterClass *) &PPC::GPRCRegClass;
4834 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
4835 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
4836 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
4837 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
4838 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
4839 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
4840 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
4841 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
4842 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
4843 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
4844 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
4846 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
4850 // fallthrough --> loopMBB
4851 BB->addSuccessor(loopMBB);
4853 // The 4-byte load must be aligned, while a char or short may be
4854 // anywhere in the word. Hence all this nasty bookkeeping code.
4855 // add ptr1, ptrA, ptrB [copy if ptrA==0]
4856 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
4857 // xori shift, shift1, 24 [16]
4858 // rlwinm ptr, ptr1, 0, 0, 29
4859 // slw incr2, incr, shift
4860 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
4861 // slw mask, mask2, shift
4863 // lwarx tmpDest, ptr
4864 // add tmp, tmpDest, incr2
4865 // andc tmp2, tmpDest, mask
4866 // and tmp3, tmp, mask
4867 // or tmp4, tmp3, tmp2
4870 // fallthrough --> exitMBB
4871 // srw dest, tmpDest, shift
4872 if (ptrA != ZeroReg) {
4873 Ptr1Reg = RegInfo.createVirtualRegister(RC);
4874 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
4875 .addReg(ptrA).addReg(ptrB);
4879 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
4880 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
4881 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
4882 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
4884 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
4885 .addReg(Ptr1Reg).addImm(0).addImm(61);
4887 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
4888 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
4889 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
4890 .addReg(incr).addReg(ShiftReg);
4892 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
4894 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
4895 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
4897 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
4898 .addReg(Mask2Reg).addReg(ShiftReg);
4901 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
4902 .addReg(ZeroReg).addReg(PtrReg);
4904 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
4905 .addReg(Incr2Reg).addReg(TmpDestReg);
4906 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
4907 .addReg(TmpDestReg).addReg(MaskReg);
4908 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
4909 .addReg(TmpReg).addReg(MaskReg);
4910 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
4911 .addReg(Tmp3Reg).addReg(Tmp2Reg);
4912 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
4913 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
4914 BuildMI(BB, dl, TII->get(PPC::BCC))
4915 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
4916 BB->addSuccessor(loopMBB);
4917 BB->addSuccessor(exitMBB);
4922 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
4928 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4929 MachineBasicBlock *BB) const {
4930 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
4932 // To "insert" these instructions we actually have to insert their
4933 // control-flow patterns.
4934 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4935 MachineFunction::iterator It = BB;
4938 MachineFunction *F = BB->getParent();
4940 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
4941 MI->getOpcode() == PPC::SELECT_CC_I8)) {
4942 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
4943 PPC::ISEL8 : PPC::ISEL;
4944 unsigned SelectPred = MI->getOperand(4).getImm();
4945 DebugLoc dl = MI->getDebugLoc();
4947 // The SelectPred is ((BI << 5) | BO) for a BCC
4948 unsigned BO = SelectPred & 0xF;
4949 assert((BO == 12 || BO == 4) && "invalid predicate BO field for isel");
4951 unsigned TrueOpNo, FalseOpNo;
4958 SelectPred = PPC::InvertPredicate((PPC::Predicate)SelectPred);
4961 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
4962 .addReg(MI->getOperand(TrueOpNo).getReg())
4963 .addReg(MI->getOperand(FalseOpNo).getReg())
4964 .addImm(SelectPred).addReg(MI->getOperand(1).getReg());
4965 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
4966 MI->getOpcode() == PPC::SELECT_CC_I8 ||
4967 MI->getOpcode() == PPC::SELECT_CC_F4 ||
4968 MI->getOpcode() == PPC::SELECT_CC_F8 ||
4969 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
4972 // The incoming instruction knows the destination vreg to set, the
4973 // condition code register to branch on, the true/false values to
4974 // select between, and a branch opcode to use.
4979 // cmpTY ccX, r1, r2
4981 // fallthrough --> copy0MBB
4982 MachineBasicBlock *thisMBB = BB;
4983 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4984 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4985 unsigned SelectPred = MI->getOperand(4).getImm();
4986 DebugLoc dl = MI->getDebugLoc();
4987 F->insert(It, copy0MBB);
4988 F->insert(It, sinkMBB);
4990 // Transfer the remainder of BB and its successor edges to sinkMBB.
4991 sinkMBB->splice(sinkMBB->begin(), BB,
4992 llvm::next(MachineBasicBlock::iterator(MI)),
4994 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4996 // Next, add the true and fallthrough blocks as its successors.
4997 BB->addSuccessor(copy0MBB);
4998 BB->addSuccessor(sinkMBB);
5000 BuildMI(BB, dl, TII->get(PPC::BCC))
5001 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
5004 // %FalseValue = ...
5005 // # fallthrough to sinkMBB
5008 // Update machine-CFG edges
5009 BB->addSuccessor(sinkMBB);
5012 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5015 BuildMI(*BB, BB->begin(), dl,
5016 TII->get(PPC::PHI), MI->getOperand(0).getReg())
5017 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
5018 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5020 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
5021 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
5022 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
5023 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
5024 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
5025 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
5026 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
5027 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
5029 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
5030 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
5031 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
5032 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
5033 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
5034 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
5035 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
5036 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
5038 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
5039 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
5040 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
5041 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
5042 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
5043 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
5044 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
5045 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
5047 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
5048 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
5049 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
5050 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
5051 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
5052 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
5053 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
5054 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
5056 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
5057 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
5058 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
5059 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
5060 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
5061 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
5062 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
5063 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
5065 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
5066 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
5067 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
5068 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
5069 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
5070 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
5071 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
5072 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
5074 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
5075 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
5076 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
5077 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
5078 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
5079 BB = EmitAtomicBinary(MI, BB, false, 0);
5080 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
5081 BB = EmitAtomicBinary(MI, BB, true, 0);
5083 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
5084 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
5085 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
5087 unsigned dest = MI->getOperand(0).getReg();
5088 unsigned ptrA = MI->getOperand(1).getReg();
5089 unsigned ptrB = MI->getOperand(2).getReg();
5090 unsigned oldval = MI->getOperand(3).getReg();
5091 unsigned newval = MI->getOperand(4).getReg();
5092 DebugLoc dl = MI->getDebugLoc();
5094 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
5095 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
5096 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
5097 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5098 F->insert(It, loop1MBB);
5099 F->insert(It, loop2MBB);
5100 F->insert(It, midMBB);
5101 F->insert(It, exitMBB);
5102 exitMBB->splice(exitMBB->begin(), BB,
5103 llvm::next(MachineBasicBlock::iterator(MI)),
5105 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5109 // fallthrough --> loopMBB
5110 BB->addSuccessor(loop1MBB);
5113 // l[wd]arx dest, ptr
5114 // cmp[wd] dest, oldval
5117 // st[wd]cx. newval, ptr
5121 // st[wd]cx. dest, ptr
5124 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5125 .addReg(ptrA).addReg(ptrB);
5126 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
5127 .addReg(oldval).addReg(dest);
5128 BuildMI(BB, dl, TII->get(PPC::BCC))
5129 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
5130 BB->addSuccessor(loop2MBB);
5131 BB->addSuccessor(midMBB);
5134 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5135 .addReg(newval).addReg(ptrA).addReg(ptrB);
5136 BuildMI(BB, dl, TII->get(PPC::BCC))
5137 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
5138 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
5139 BB->addSuccessor(loop1MBB);
5140 BB->addSuccessor(exitMBB);
5143 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5144 .addReg(dest).addReg(ptrA).addReg(ptrB);
5145 BB->addSuccessor(exitMBB);
5150 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
5151 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
5152 // We must use 64-bit registers for addresses when targeting 64-bit,
5153 // since we're actually doing arithmetic on them. Other registers
5155 bool is64bit = PPCSubTarget.isPPC64();
5156 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
5158 unsigned dest = MI->getOperand(0).getReg();
5159 unsigned ptrA = MI->getOperand(1).getReg();
5160 unsigned ptrB = MI->getOperand(2).getReg();
5161 unsigned oldval = MI->getOperand(3).getReg();
5162 unsigned newval = MI->getOperand(4).getReg();
5163 DebugLoc dl = MI->getDebugLoc();
5165 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
5166 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
5167 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
5168 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5169 F->insert(It, loop1MBB);
5170 F->insert(It, loop2MBB);
5171 F->insert(It, midMBB);
5172 F->insert(It, exitMBB);
5173 exitMBB->splice(exitMBB->begin(), BB,
5174 llvm::next(MachineBasicBlock::iterator(MI)),
5176 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5178 MachineRegisterInfo &RegInfo = F->getRegInfo();
5179 const TargetRegisterClass *RC =
5180 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5181 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5182 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5183 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5184 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5185 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
5186 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
5187 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
5188 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
5189 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5190 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5191 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5192 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5193 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5194 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5196 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
5197 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
5200 // fallthrough --> loopMBB
5201 BB->addSuccessor(loop1MBB);
5203 // The 4-byte load must be aligned, while a char or short may be
5204 // anywhere in the word. Hence all this nasty bookkeeping code.
5205 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5206 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5207 // xori shift, shift1, 24 [16]
5208 // rlwinm ptr, ptr1, 0, 0, 29
5209 // slw newval2, newval, shift
5210 // slw oldval2, oldval,shift
5211 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5212 // slw mask, mask2, shift
5213 // and newval3, newval2, mask
5214 // and oldval3, oldval2, mask
5216 // lwarx tmpDest, ptr
5217 // and tmp, tmpDest, mask
5218 // cmpw tmp, oldval3
5221 // andc tmp2, tmpDest, mask
5222 // or tmp4, tmp2, newval3
5227 // stwcx. tmpDest, ptr
5229 // srw dest, tmpDest, shift
5230 if (ptrA != ZeroReg) {
5231 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5232 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5233 .addReg(ptrA).addReg(ptrB);
5237 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5238 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5239 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5240 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5242 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5243 .addReg(Ptr1Reg).addImm(0).addImm(61);
5245 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5246 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5247 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
5248 .addReg(newval).addReg(ShiftReg);
5249 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
5250 .addReg(oldval).addReg(ShiftReg);
5252 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5254 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5255 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
5256 .addReg(Mask3Reg).addImm(65535);
5258 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5259 .addReg(Mask2Reg).addReg(ShiftReg);
5260 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
5261 .addReg(NewVal2Reg).addReg(MaskReg);
5262 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
5263 .addReg(OldVal2Reg).addReg(MaskReg);
5266 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5267 .addReg(ZeroReg).addReg(PtrReg);
5268 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
5269 .addReg(TmpDestReg).addReg(MaskReg);
5270 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
5271 .addReg(TmpReg).addReg(OldVal3Reg);
5272 BuildMI(BB, dl, TII->get(PPC::BCC))
5273 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
5274 BB->addSuccessor(loop2MBB);
5275 BB->addSuccessor(midMBB);
5278 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
5279 .addReg(TmpDestReg).addReg(MaskReg);
5280 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
5281 .addReg(Tmp2Reg).addReg(NewVal3Reg);
5282 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
5283 .addReg(ZeroReg).addReg(PtrReg);
5284 BuildMI(BB, dl, TII->get(PPC::BCC))
5285 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
5286 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
5287 BB->addSuccessor(loop1MBB);
5288 BB->addSuccessor(exitMBB);
5291 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
5292 .addReg(ZeroReg).addReg(PtrReg);
5293 BB->addSuccessor(exitMBB);
5298 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
5301 llvm_unreachable("Unexpected instr type to insert");
5304 MI->eraseFromParent(); // The pseudo instruction is gone now.
5308 //===----------------------------------------------------------------------===//
5309 // Target Optimization Hooks
5310 //===----------------------------------------------------------------------===//
5312 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
5313 DAGCombinerInfo &DCI) const {
5314 const TargetMachine &TM = getTargetMachine();
5315 SelectionDAG &DAG = DCI.DAG;
5316 DebugLoc dl = N->getDebugLoc();
5317 switch (N->getOpcode()) {
5320 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
5321 if (C->isNullValue()) // 0 << V -> 0.
5322 return N->getOperand(0);
5326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
5327 if (C->isNullValue()) // 0 >>u V -> 0.
5328 return N->getOperand(0);
5332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
5333 if (C->isNullValue() || // 0 >>s V -> 0.
5334 C->isAllOnesValue()) // -1 >>s V -> -1.
5335 return N->getOperand(0);
5339 case ISD::SINT_TO_FP:
5340 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
5341 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
5342 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
5343 // We allow the src/dst to be either f32/f64, but the intermediate
5344 // type must be i64.
5345 if (N->getOperand(0).getValueType() == MVT::i64 &&
5346 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
5347 SDValue Val = N->getOperand(0).getOperand(0);
5348 if (Val.getValueType() == MVT::f32) {
5349 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
5350 DCI.AddToWorklist(Val.getNode());
5353 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
5354 DCI.AddToWorklist(Val.getNode());
5355 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
5356 DCI.AddToWorklist(Val.getNode());
5357 if (N->getValueType(0) == MVT::f32) {
5358 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
5359 DAG.getIntPtrConstant(0));
5360 DCI.AddToWorklist(Val.getNode());
5363 } else if (N->getOperand(0).getValueType() == MVT::i32) {
5364 // If the intermediate type is i32, we can avoid the load/store here
5371 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
5372 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
5373 !cast<StoreSDNode>(N)->isTruncatingStore() &&
5374 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
5375 N->getOperand(1).getValueType() == MVT::i32 &&
5376 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
5377 SDValue Val = N->getOperand(1).getOperand(0);
5378 if (Val.getValueType() == MVT::f32) {
5379 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
5380 DCI.AddToWorklist(Val.getNode());
5382 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
5383 DCI.AddToWorklist(Val.getNode());
5385 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
5386 N->getOperand(2), N->getOperand(3));
5387 DCI.AddToWorklist(Val.getNode());
5391 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
5392 if (cast<StoreSDNode>(N)->isUnindexed() &&
5393 N->getOperand(1).getOpcode() == ISD::BSWAP &&
5394 N->getOperand(1).getNode()->hasOneUse() &&
5395 (N->getOperand(1).getValueType() == MVT::i32 ||
5396 N->getOperand(1).getValueType() == MVT::i16)) {
5397 SDValue BSwapOp = N->getOperand(1).getOperand(0);
5398 // Do an any-extend to 32-bits if this is a half-word input.
5399 if (BSwapOp.getValueType() == MVT::i16)
5400 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
5403 N->getOperand(0), BSwapOp, N->getOperand(2),
5404 DAG.getValueType(N->getOperand(1).getValueType())
5407 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
5408 Ops, array_lengthof(Ops),
5409 cast<StoreSDNode>(N)->getMemoryVT(),
5410 cast<StoreSDNode>(N)->getMemOperand());
5414 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
5415 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
5416 N->getOperand(0).hasOneUse() &&
5417 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
5418 SDValue Load = N->getOperand(0);
5419 LoadSDNode *LD = cast<LoadSDNode>(Load);
5420 // Create the byte-swapping load.
5422 LD->getChain(), // Chain
5423 LD->getBasePtr(), // Ptr
5424 DAG.getValueType(N->getValueType(0)) // VT
5427 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
5428 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
5429 LD->getMemoryVT(), LD->getMemOperand());
5431 // If this is an i16 load, insert the truncate.
5432 SDValue ResVal = BSLoad;
5433 if (N->getValueType(0) == MVT::i16)
5434 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
5436 // First, combine the bswap away. This makes the value produced by the
5438 DCI.CombineTo(N, ResVal);
5440 // Next, combine the load away, we give it a bogus result value but a real
5441 // chain result. The result value is dead because the bswap is dead.
5442 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
5444 // Return N so it doesn't get rechecked!
5445 return SDValue(N, 0);
5449 case PPCISD::VCMP: {
5450 // If a VCMPo node already exists with exactly the same operands as this
5451 // node, use its result instead of this node (VCMPo computes both a CR6 and
5452 // a normal output).
5454 if (!N->getOperand(0).hasOneUse() &&
5455 !N->getOperand(1).hasOneUse() &&
5456 !N->getOperand(2).hasOneUse()) {
5458 // Scan all of the users of the LHS, looking for VCMPo's that match.
5459 SDNode *VCMPoNode = 0;
5461 SDNode *LHSN = N->getOperand(0).getNode();
5462 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
5464 if (UI->getOpcode() == PPCISD::VCMPo &&
5465 UI->getOperand(1) == N->getOperand(1) &&
5466 UI->getOperand(2) == N->getOperand(2) &&
5467 UI->getOperand(0) == N->getOperand(0)) {
5472 // If there is no VCMPo node, or if the flag value has a single use, don't
5474 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
5477 // Look at the (necessarily single) use of the flag value. If it has a
5478 // chain, this transformation is more complex. Note that multiple things
5479 // could use the value result, which we should ignore.
5480 SDNode *FlagUser = 0;
5481 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
5482 FlagUser == 0; ++UI) {
5483 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
5485 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
5486 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
5493 // If the user is a MFCR instruction, we know this is safe. Otherwise we
5494 // give up for right now.
5495 if (FlagUser->getOpcode() == PPCISD::MFCR)
5496 return SDValue(VCMPoNode, 0);
5501 // If this is a branch on an altivec predicate comparison, lower this so
5502 // that we don't have to do a MFCR: instead, branch directly on CR6. This
5503 // lowering is done pre-legalize, because the legalizer lowers the predicate
5504 // compare down to code that is difficult to reassemble.
5505 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
5506 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
5510 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
5511 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
5512 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
5513 assert(isDot && "Can't compare against a vector result!");
5515 // If this is a comparison against something other than 0/1, then we know
5516 // that the condition is never/always true.
5517 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
5518 if (Val != 0 && Val != 1) {
5519 if (CC == ISD::SETEQ) // Cond never true, remove branch.
5520 return N->getOperand(0);
5521 // Always !=, turn it into an unconditional branch.
5522 return DAG.getNode(ISD::BR, dl, MVT::Other,
5523 N->getOperand(0), N->getOperand(4));
5526 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
5528 // Create the PPCISD altivec 'dot' comparison node.
5529 std::vector<EVT> VTs;
5531 LHS.getOperand(2), // LHS of compare
5532 LHS.getOperand(3), // RHS of compare
5533 DAG.getConstant(CompareOpc, MVT::i32)
5535 VTs.push_back(LHS.getOperand(2).getValueType());
5536 VTs.push_back(MVT::Glue);
5537 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5539 // Unpack the result based on how the target uses it.
5540 PPC::Predicate CompOpc;
5541 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
5542 default: // Can't happen, don't crash on invalid number though.
5543 case 0: // Branch on the value of the EQ bit of CR6.
5544 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
5546 case 1: // Branch on the inverted value of the EQ bit of CR6.
5547 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
5549 case 2: // Branch on the value of the LT bit of CR6.
5550 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
5552 case 3: // Branch on the inverted value of the LT bit of CR6.
5553 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
5557 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
5558 DAG.getConstant(CompOpc, MVT::i32),
5559 DAG.getRegister(PPC::CR6, MVT::i32),
5560 N->getOperand(4), CompNode.getValue(1));
5569 //===----------------------------------------------------------------------===//
5570 // Inline Assembly Support
5571 //===----------------------------------------------------------------------===//
5573 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
5576 const SelectionDAG &DAG,
5577 unsigned Depth) const {
5578 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
5579 switch (Op.getOpcode()) {
5581 case PPCISD::LBRX: {
5582 // lhbrx is known to have the top bits cleared out.
5583 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
5584 KnownZero = 0xFFFF0000;
5587 case ISD::INTRINSIC_WO_CHAIN: {
5588 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
5590 case Intrinsic::ppc_altivec_vcmpbfp_p:
5591 case Intrinsic::ppc_altivec_vcmpeqfp_p:
5592 case Intrinsic::ppc_altivec_vcmpequb_p:
5593 case Intrinsic::ppc_altivec_vcmpequh_p:
5594 case Intrinsic::ppc_altivec_vcmpequw_p:
5595 case Intrinsic::ppc_altivec_vcmpgefp_p:
5596 case Intrinsic::ppc_altivec_vcmpgtfp_p:
5597 case Intrinsic::ppc_altivec_vcmpgtsb_p:
5598 case Intrinsic::ppc_altivec_vcmpgtsh_p:
5599 case Intrinsic::ppc_altivec_vcmpgtsw_p:
5600 case Intrinsic::ppc_altivec_vcmpgtub_p:
5601 case Intrinsic::ppc_altivec_vcmpgtuh_p:
5602 case Intrinsic::ppc_altivec_vcmpgtuw_p:
5603 KnownZero = ~1U; // All bits but the low one are known to be zero.
5611 /// getConstraintType - Given a constraint, return the type of
5612 /// constraint it is for this target.
5613 PPCTargetLowering::ConstraintType
5614 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
5615 if (Constraint.size() == 1) {
5616 switch (Constraint[0]) {
5623 return C_RegisterClass;
5626 return TargetLowering::getConstraintType(Constraint);
5629 /// Examine constraint type and operand type and determine a weight value.
5630 /// This object must already have been set up with the operand type
5631 /// and the current alternative constraint selected.
5632 TargetLowering::ConstraintWeight
5633 PPCTargetLowering::getSingleConstraintMatchWeight(
5634 AsmOperandInfo &info, const char *constraint) const {
5635 ConstraintWeight weight = CW_Invalid;
5636 Value *CallOperandVal = info.CallOperandVal;
5637 // If we don't have a value, we can't do a match,
5638 // but allow it at the lowest weight.
5639 if (CallOperandVal == NULL)
5641 Type *type = CallOperandVal->getType();
5642 // Look at the constraint type.
5643 switch (*constraint) {
5645 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5648 if (type->isIntegerTy())
5649 weight = CW_Register;
5652 if (type->isFloatTy())
5653 weight = CW_Register;
5656 if (type->isDoubleTy())
5657 weight = CW_Register;
5660 if (type->isVectorTy())
5661 weight = CW_Register;
5664 weight = CW_Register;
5670 std::pair<unsigned, const TargetRegisterClass*>
5671 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
5673 if (Constraint.size() == 1) {
5674 // GCC RS6000 Constraint Letters
5675 switch (Constraint[0]) {
5678 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
5679 return std::make_pair(0U, &PPC::G8RCRegClass);
5680 return std::make_pair(0U, &PPC::GPRCRegClass);
5683 return std::make_pair(0U, &PPC::F4RCRegClass);
5685 return std::make_pair(0U, &PPC::F8RCRegClass);
5688 return std::make_pair(0U, &PPC::VRRCRegClass);
5690 return std::make_pair(0U, &PPC::CRRCRegClass);
5694 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
5698 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5699 /// vector. If it is invalid, don't add anything to Ops.
5700 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5701 std::string &Constraint,
5702 std::vector<SDValue>&Ops,
5703 SelectionDAG &DAG) const {
5704 SDValue Result(0,0);
5706 // Only support length 1 constraints.
5707 if (Constraint.length() > 1) return;
5709 char Letter = Constraint[0];
5720 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
5721 if (!CST) return; // Must be an immediate to match.
5722 unsigned Value = CST->getZExtValue();
5724 default: llvm_unreachable("Unknown constraint letter!");
5725 case 'I': // "I" is a signed 16-bit constant.
5726 if ((short)Value == (int)Value)
5727 Result = DAG.getTargetConstant(Value, Op.getValueType());
5729 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
5730 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
5731 if ((short)Value == 0)
5732 Result = DAG.getTargetConstant(Value, Op.getValueType());
5734 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
5735 if ((Value >> 16) == 0)
5736 Result = DAG.getTargetConstant(Value, Op.getValueType());
5738 case 'M': // "M" is a constant that is greater than 31.
5740 Result = DAG.getTargetConstant(Value, Op.getValueType());
5742 case 'N': // "N" is a positive constant that is an exact power of two.
5743 if ((int)Value > 0 && isPowerOf2_32(Value))
5744 Result = DAG.getTargetConstant(Value, Op.getValueType());
5746 case 'O': // "O" is the constant zero.
5748 Result = DAG.getTargetConstant(Value, Op.getValueType());
5750 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
5751 if ((short)-Value == (int)-Value)
5752 Result = DAG.getTargetConstant(Value, Op.getValueType());
5759 if (Result.getNode()) {
5760 Ops.push_back(Result);
5764 // Handle standard constraint letters.
5765 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5768 // isLegalAddressingMode - Return true if the addressing mode represented
5769 // by AM is legal for this target, for a load/store of the specified type.
5770 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
5772 // FIXME: PPC does not allow r+i addressing modes for vectors!
5774 // PPC allows a sign-extended 16-bit immediate field.
5775 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
5778 // No global is ever allowed as a base.
5782 // PPC only support r+r,
5784 case 0: // "r+i" or just "i", depending on HasBaseReg.
5787 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
5789 // Otherwise we have r+r or r+i.
5792 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
5794 // Allow 2*r as r+r.
5797 // No other scales are supported.
5804 /// isLegalAddressImmediate - Return true if the integer value can be used
5805 /// as the offset of the target addressing mode for load / store of the
5807 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
5808 // PPC allows a sign-extended 16-bit immediate field.
5809 return (V > -(1 << 16) && V < (1 << 16)-1);
5812 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
5816 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
5817 SelectionDAG &DAG) const {
5818 MachineFunction &MF = DAG.getMachineFunction();
5819 MachineFrameInfo *MFI = MF.getFrameInfo();
5820 MFI->setReturnAddressIsTaken(true);
5822 DebugLoc dl = Op.getDebugLoc();
5823 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5825 // Make sure the function does not optimize away the store of the RA to
5827 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
5828 FuncInfo->setLRStoreRequired();
5829 bool isPPC64 = PPCSubTarget.isPPC64();
5830 bool isDarwinABI = PPCSubTarget.isDarwinABI();
5833 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5836 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
5837 isPPC64? MVT::i64 : MVT::i32);
5838 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
5839 DAG.getNode(ISD::ADD, dl, getPointerTy(),
5841 MachinePointerInfo(), false, false, false, 0);
5844 // Just load the return address off the stack.
5845 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
5846 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
5847 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
5850 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
5851 SelectionDAG &DAG) const {
5852 DebugLoc dl = Op.getDebugLoc();
5853 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5855 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5856 bool isPPC64 = PtrVT == MVT::i64;
5858 MachineFunction &MF = DAG.getMachineFunction();
5859 MachineFrameInfo *MFI = MF.getFrameInfo();
5860 MFI->setFrameAddressIsTaken(true);
5861 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) ||
5862 MFI->hasVarSizedObjects()) &&
5863 MFI->getStackSize() &&
5864 !MF.getFunction()->hasFnAttr(Attribute::Naked);
5865 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
5866 (is31 ? PPC::R31 : PPC::R1);
5867 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
5870 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
5871 FrameAddr, MachinePointerInfo(), false, false,
5877 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5878 // The PowerPC target isn't yet aware of offsets.
5882 /// getOptimalMemOpType - Returns the target specific optimal type for load
5883 /// and store operations as a result of memset, memcpy, and memmove
5884 /// lowering. If DstAlign is zero that means it's safe to destination
5885 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
5886 /// means there isn't a need to check it against alignment requirement,
5887 /// probably because the source does not need to be loaded. If
5888 /// 'IsZeroVal' is true, that means it's safe to return a
5889 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
5890 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
5891 /// constant so it does not need to be loaded.
5892 /// It returns EVT::Other if the type should be determined using generic
5893 /// target-independent logic.
5894 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
5895 unsigned DstAlign, unsigned SrcAlign,
5898 MachineFunction &MF) const {
5899 if (this->PPCSubTarget.isPPC64()) {
5906 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
5907 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
5908 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
5909 /// is expanded to mul + add.
5910 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
5914 switch (VT.getSimpleVT().SimpleTy) {
5926 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
5928 return TargetLowering::getSchedulingPreference(N);