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()) {
69 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73 // Use _setjmp/_longjmp instead of setjmp/longjmp.
74 setUseUnderscoreSetJmp(true);
75 setUseUnderscoreLongJmp(true);
77 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
78 // arguments are at least 4/8 bytes aligned.
79 bool isPPC64 = Subtarget->isPPC64();
80 setMinStackArgumentAlignment(isPPC64 ? 8:4);
82 // Set up the register classes.
83 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
84 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
85 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
87 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
88 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
91 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
93 // PowerPC has pre-inc load and store's.
94 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
95 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
96 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
97 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
98 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
99 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
100 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
101 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
102 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
103 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
105 // This is used in the ppcf128->int sequence. Note it has different semantics
106 // from FP_ROUND: that rounds to nearest, this rounds to zero.
107 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
109 // We do not currently implement these libm ops for PowerPC.
110 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
111 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
112 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
113 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
114 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
116 // PowerPC has no SREM/UREM instructions
117 setOperationAction(ISD::SREM, MVT::i32, Expand);
118 setOperationAction(ISD::UREM, MVT::i32, Expand);
119 setOperationAction(ISD::SREM, MVT::i64, Expand);
120 setOperationAction(ISD::UREM, MVT::i64, Expand);
122 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
123 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
124 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
125 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
126 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
127 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
128 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
129 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
130 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
132 // We don't support sin/cos/sqrt/fmod/pow
133 setOperationAction(ISD::FSIN , MVT::f64, Expand);
134 setOperationAction(ISD::FCOS , MVT::f64, Expand);
135 setOperationAction(ISD::FREM , MVT::f64, Expand);
136 setOperationAction(ISD::FPOW , MVT::f64, Expand);
137 setOperationAction(ISD::FMA , MVT::f64, Legal);
138 setOperationAction(ISD::FSIN , MVT::f32, Expand);
139 setOperationAction(ISD::FCOS , MVT::f32, Expand);
140 setOperationAction(ISD::FREM , MVT::f32, Expand);
141 setOperationAction(ISD::FPOW , MVT::f32, Expand);
142 setOperationAction(ISD::FMA , MVT::f32, Legal);
144 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
146 // If we're enabling GP optimizations, use hardware square root
147 if (!Subtarget->hasFSQRT()) {
148 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
149 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
152 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
153 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
155 // PowerPC does not have BSWAP, CTPOP or CTTZ
156 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
157 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
158 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
159 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
160 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
161 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
162 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
163 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
164 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
165 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
167 // PowerPC does not have ROTR
168 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
169 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
171 // PowerPC does not have Select
172 setOperationAction(ISD::SELECT, MVT::i32, Expand);
173 setOperationAction(ISD::SELECT, MVT::i64, Expand);
174 setOperationAction(ISD::SELECT, MVT::f32, Expand);
175 setOperationAction(ISD::SELECT, MVT::f64, Expand);
177 // PowerPC wants to turn select_cc of FP into fsel when possible.
178 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
179 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
181 // PowerPC wants to optimize integer setcc a bit
182 setOperationAction(ISD::SETCC, MVT::i32, Custom);
184 // PowerPC does not have BRCOND which requires SetCC
185 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
187 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
189 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
190 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
192 // PowerPC does not have [U|S]INT_TO_FP
193 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
196 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
197 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
198 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
199 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
201 // We cannot sextinreg(i1). Expand to shifts.
202 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
204 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
205 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
206 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
207 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
210 // We want to legalize GlobalAddress and ConstantPool nodes into the
211 // appropriate instructions to materialize the address.
212 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
213 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
214 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
215 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
216 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
217 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
218 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
219 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
220 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
221 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
224 setOperationAction(ISD::TRAP, MVT::Other, Legal);
226 // TRAMPOLINE is custom lowered.
227 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
228 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
230 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
231 setOperationAction(ISD::VASTART , MVT::Other, Custom);
233 if (Subtarget->isSVR4ABI()) {
235 // VAARG always uses double-word chunks, so promote anything smaller.
236 setOperationAction(ISD::VAARG, MVT::i1, Promote);
237 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
238 setOperationAction(ISD::VAARG, MVT::i8, Promote);
239 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
240 setOperationAction(ISD::VAARG, MVT::i16, Promote);
241 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
242 setOperationAction(ISD::VAARG, MVT::i32, Promote);
243 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
244 setOperationAction(ISD::VAARG, MVT::Other, Expand);
246 // VAARG is custom lowered with the 32-bit SVR4 ABI.
247 setOperationAction(ISD::VAARG, MVT::Other, Custom);
248 setOperationAction(ISD::VAARG, MVT::i64, Custom);
251 setOperationAction(ISD::VAARG, MVT::Other, Expand);
253 // Use the default implementation.
254 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
255 setOperationAction(ISD::VAEND , MVT::Other, Expand);
256 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
258 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
259 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
261 // We want to custom lower some of our intrinsics.
262 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
264 // Comparisons that require checking two conditions.
265 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
266 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
267 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
268 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
269 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
270 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
271 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
272 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
273 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
274 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
275 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
276 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
278 if (Subtarget->has64BitSupport()) {
279 // They also have instructions for converting between i64 and fp.
280 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
281 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
282 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
283 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
284 // This is just the low 32 bits of a (signed) fp->i64 conversion.
285 // We cannot do this with Promote because i64 is not a legal type.
286 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
288 // FIXME: disable this lowered code. This generates 64-bit register values,
289 // and we don't model the fact that the top part is clobbered by calls. We
290 // need to flag these together so that the value isn't live across a call.
291 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
293 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
297 if (Subtarget->use64BitRegs()) {
298 // 64-bit PowerPC implementations can support i64 types directly
299 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
300 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
301 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
302 // 64-bit PowerPC wants to expand i128 shifts itself.
303 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
304 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
305 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
307 // 32-bit PowerPC wants to expand i64 shifts itself.
308 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
310 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
313 if (Subtarget->hasAltivec()) {
314 // First set operation action for all vector types to expand. Then we
315 // will selectively turn on ones that can be effectively codegen'd.
316 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
317 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
318 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
320 // add/sub are legal for all supported vector VT's.
321 setOperationAction(ISD::ADD , VT, Legal);
322 setOperationAction(ISD::SUB , VT, Legal);
324 // We promote all shuffles to v16i8.
325 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
326 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
328 // We promote all non-typed operations to v4i32.
329 setOperationAction(ISD::AND , VT, Promote);
330 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
331 setOperationAction(ISD::OR , VT, Promote);
332 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
333 setOperationAction(ISD::XOR , VT, Promote);
334 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
335 setOperationAction(ISD::LOAD , VT, Promote);
336 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
337 setOperationAction(ISD::SELECT, VT, Promote);
338 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
339 setOperationAction(ISD::STORE, VT, Promote);
340 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
342 // No other operations are legal.
343 setOperationAction(ISD::MUL , VT, Expand);
344 setOperationAction(ISD::SDIV, VT, Expand);
345 setOperationAction(ISD::SREM, VT, Expand);
346 setOperationAction(ISD::UDIV, VT, Expand);
347 setOperationAction(ISD::UREM, VT, Expand);
348 setOperationAction(ISD::FDIV, VT, Expand);
349 setOperationAction(ISD::FNEG, VT, Expand);
350 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
351 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
352 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
353 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
354 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
355 setOperationAction(ISD::UDIVREM, VT, Expand);
356 setOperationAction(ISD::SDIVREM, VT, Expand);
357 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
358 setOperationAction(ISD::FPOW, VT, Expand);
359 setOperationAction(ISD::CTPOP, VT, Expand);
360 setOperationAction(ISD::CTLZ, VT, Expand);
361 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
362 setOperationAction(ISD::CTTZ, VT, Expand);
363 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
366 for (unsigned i = (unsigned)MVT::FIRST_FP_VECTOR_VALUETYPE;
367 i <= (unsigned)MVT::LAST_FP_VECTOR_VALUETYPE; ++i) {
368 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
369 setOperationAction(ISD::FSQRT, VT, Expand);
372 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
373 // with merges, splats, etc.
374 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
376 setOperationAction(ISD::AND , MVT::v4i32, Legal);
377 setOperationAction(ISD::OR , MVT::v4i32, Legal);
378 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
379 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
380 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
381 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
382 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
383 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
384 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
385 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
387 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
388 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
389 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
390 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
392 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
393 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
394 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
395 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
396 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
398 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
399 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
401 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
402 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
403 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
404 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
406 // Altivec does not contain unordered floating-point compare instructions
407 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
408 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
409 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
410 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
411 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
412 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
415 if (Subtarget->has64BitSupport()) {
416 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
417 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
420 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
421 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
423 setBooleanContents(ZeroOrOneBooleanContent);
424 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
427 setStackPointerRegisterToSaveRestore(PPC::X1);
428 setExceptionPointerRegister(PPC::X3);
429 setExceptionSelectorRegister(PPC::X4);
431 setStackPointerRegisterToSaveRestore(PPC::R1);
432 setExceptionPointerRegister(PPC::R3);
433 setExceptionSelectorRegister(PPC::R4);
436 // We have target-specific dag combine patterns for the following nodes:
437 setTargetDAGCombine(ISD::SINT_TO_FP);
438 setTargetDAGCombine(ISD::STORE);
439 setTargetDAGCombine(ISD::BR_CC);
440 setTargetDAGCombine(ISD::BSWAP);
442 // Darwin long double math library functions have $LDBL128 appended.
443 if (Subtarget->isDarwin()) {
444 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
445 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
446 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
447 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
448 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
449 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
450 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
451 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
452 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
453 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
456 setMinFunctionAlignment(2);
457 if (PPCSubTarget.isDarwin())
458 setPrefFunctionAlignment(4);
460 if (isPPC64 && Subtarget->isJITCodeModel())
461 // Temporary workaround for the inability of PPC64 JIT to handle jump
463 setSupportJumpTables(false);
465 setInsertFencesForAtomic(true);
467 setSchedulingPreference(Sched::Hybrid);
469 computeRegisterProperties();
471 // The Freescale cores does better with aggressive inlining of memcpy and
472 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
473 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
474 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
475 maxStoresPerMemset = 32;
476 maxStoresPerMemsetOptSize = 16;
477 maxStoresPerMemcpy = 32;
478 maxStoresPerMemcpyOptSize = 8;
479 maxStoresPerMemmove = 32;
480 maxStoresPerMemmoveOptSize = 8;
482 setPrefFunctionAlignment(4);
483 benefitFromCodePlacementOpt = true;
487 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
488 /// function arguments in the caller parameter area.
489 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
490 const TargetMachine &TM = getTargetMachine();
491 // Darwin passes everything on 4 byte boundary.
492 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
495 // 16byte and wider vectors are passed on 16byte boundary.
496 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
497 if (VTy->getBitWidth() >= 128)
500 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
501 if (PPCSubTarget.isPPC64())
507 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
510 case PPCISD::FSEL: return "PPCISD::FSEL";
511 case PPCISD::FCFID: return "PPCISD::FCFID";
512 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
513 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
514 case PPCISD::STFIWX: return "PPCISD::STFIWX";
515 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
516 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
517 case PPCISD::VPERM: return "PPCISD::VPERM";
518 case PPCISD::Hi: return "PPCISD::Hi";
519 case PPCISD::Lo: return "PPCISD::Lo";
520 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
521 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
522 case PPCISD::LOAD: return "PPCISD::LOAD";
523 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
524 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
525 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
526 case PPCISD::SRL: return "PPCISD::SRL";
527 case PPCISD::SRA: return "PPCISD::SRA";
528 case PPCISD::SHL: return "PPCISD::SHL";
529 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
530 case PPCISD::STD_32: return "PPCISD::STD_32";
531 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
532 case PPCISD::CALL_NOP_SVR4: return "PPCISD::CALL_NOP_SVR4";
533 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
534 case PPCISD::NOP: return "PPCISD::NOP";
535 case PPCISD::MTCTR: return "PPCISD::MTCTR";
536 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
537 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
538 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
539 case PPCISD::MFCR: return "PPCISD::MFCR";
540 case PPCISD::VCMP: return "PPCISD::VCMP";
541 case PPCISD::VCMPo: return "PPCISD::VCMPo";
542 case PPCISD::LBRX: return "PPCISD::LBRX";
543 case PPCISD::STBRX: return "PPCISD::STBRX";
544 case PPCISD::LARX: return "PPCISD::LARX";
545 case PPCISD::STCX: return "PPCISD::STCX";
546 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
547 case PPCISD::MFFS: return "PPCISD::MFFS";
548 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
549 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
550 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
551 case PPCISD::MTFSF: return "PPCISD::MTFSF";
552 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
553 case PPCISD::CR6SET: return "PPCISD::CR6SET";
554 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
558 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
561 return VT.changeVectorElementTypeToInteger();
564 //===----------------------------------------------------------------------===//
565 // Node matching predicates, for use by the tblgen matching code.
566 //===----------------------------------------------------------------------===//
568 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
569 static bool isFloatingPointZero(SDValue Op) {
570 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
571 return CFP->getValueAPF().isZero();
572 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
573 // Maybe this has already been legalized into the constant pool?
574 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
575 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
576 return CFP->getValueAPF().isZero();
581 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
582 /// true if Op is undef or if it matches the specified value.
583 static bool isConstantOrUndef(int Op, int Val) {
584 return Op < 0 || Op == Val;
587 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
588 /// VPKUHUM instruction.
589 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
591 for (unsigned i = 0; i != 16; ++i)
592 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
595 for (unsigned i = 0; i != 8; ++i)
596 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
597 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
603 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
604 /// VPKUWUM instruction.
605 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
607 for (unsigned i = 0; i != 16; i += 2)
608 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
609 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
612 for (unsigned i = 0; i != 8; i += 2)
613 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
614 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
615 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
616 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
622 /// isVMerge - Common function, used to match vmrg* shuffles.
624 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
625 unsigned LHSStart, unsigned RHSStart) {
626 assert(N->getValueType(0) == MVT::v16i8 &&
627 "PPC only supports shuffles by bytes!");
628 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
629 "Unsupported merge size!");
631 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
632 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
633 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
634 LHSStart+j+i*UnitSize) ||
635 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
636 RHSStart+j+i*UnitSize))
642 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
643 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
644 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
647 return isVMerge(N, UnitSize, 8, 24);
648 return isVMerge(N, UnitSize, 8, 8);
651 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
652 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
653 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
656 return isVMerge(N, UnitSize, 0, 16);
657 return isVMerge(N, UnitSize, 0, 0);
661 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
662 /// amount, otherwise return -1.
663 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
664 assert(N->getValueType(0) == MVT::v16i8 &&
665 "PPC only supports shuffles by bytes!");
667 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
669 // Find the first non-undef value in the shuffle mask.
671 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
674 if (i == 16) return -1; // all undef.
676 // Otherwise, check to see if the rest of the elements are consecutively
677 // numbered from this value.
678 unsigned ShiftAmt = SVOp->getMaskElt(i);
679 if (ShiftAmt < i) return -1;
683 // Check the rest of the elements to see if they are consecutive.
684 for (++i; i != 16; ++i)
685 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
688 // Check the rest of the elements to see if they are consecutive.
689 for (++i; i != 16; ++i)
690 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
696 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
697 /// specifies a splat of a single element that is suitable for input to
698 /// VSPLTB/VSPLTH/VSPLTW.
699 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
700 assert(N->getValueType(0) == MVT::v16i8 &&
701 (EltSize == 1 || EltSize == 2 || EltSize == 4));
703 // This is a splat operation if each element of the permute is the same, and
704 // if the value doesn't reference the second vector.
705 unsigned ElementBase = N->getMaskElt(0);
707 // FIXME: Handle UNDEF elements too!
708 if (ElementBase >= 16)
711 // Check that the indices are consecutive, in the case of a multi-byte element
712 // splatted with a v16i8 mask.
713 for (unsigned i = 1; i != EltSize; ++i)
714 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
717 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
718 if (N->getMaskElt(i) < 0) continue;
719 for (unsigned j = 0; j != EltSize; ++j)
720 if (N->getMaskElt(i+j) != N->getMaskElt(j))
726 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
728 bool PPC::isAllNegativeZeroVector(SDNode *N) {
729 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
731 APInt APVal, APUndef;
735 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
736 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
737 return CFP->getValueAPF().isNegZero();
742 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
743 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
744 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
745 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
746 assert(isSplatShuffleMask(SVOp, EltSize));
747 return SVOp->getMaskElt(0) / EltSize;
750 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
751 /// by using a vspltis[bhw] instruction of the specified element size, return
752 /// the constant being splatted. The ByteSize field indicates the number of
753 /// bytes of each element [124] -> [bhw].
754 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
757 // If ByteSize of the splat is bigger than the element size of the
758 // build_vector, then we have a case where we are checking for a splat where
759 // multiple elements of the buildvector are folded together into a single
760 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
761 unsigned EltSize = 16/N->getNumOperands();
762 if (EltSize < ByteSize) {
763 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
764 SDValue UniquedVals[4];
765 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
767 // See if all of the elements in the buildvector agree across.
768 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
769 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
770 // If the element isn't a constant, bail fully out.
771 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
774 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
775 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
776 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
777 return SDValue(); // no match.
780 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
781 // either constant or undef values that are identical for each chunk. See
782 // if these chunks can form into a larger vspltis*.
784 // Check to see if all of the leading entries are either 0 or -1. If
785 // neither, then this won't fit into the immediate field.
786 bool LeadingZero = true;
787 bool LeadingOnes = true;
788 for (unsigned i = 0; i != Multiple-1; ++i) {
789 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
791 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
792 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
794 // Finally, check the least significant entry.
796 if (UniquedVals[Multiple-1].getNode() == 0)
797 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
798 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
800 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
803 if (UniquedVals[Multiple-1].getNode() == 0)
804 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
805 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
806 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
807 return DAG.getTargetConstant(Val, MVT::i32);
813 // Check to see if this buildvec has a single non-undef value in its elements.
814 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
815 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
816 if (OpVal.getNode() == 0)
817 OpVal = N->getOperand(i);
818 else if (OpVal != N->getOperand(i))
822 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
824 unsigned ValSizeInBytes = EltSize;
826 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
827 Value = CN->getZExtValue();
828 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
829 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
830 Value = FloatToBits(CN->getValueAPF().convertToFloat());
833 // If the splat value is larger than the element value, then we can never do
834 // this splat. The only case that we could fit the replicated bits into our
835 // immediate field for would be zero, and we prefer to use vxor for it.
836 if (ValSizeInBytes < ByteSize) return SDValue();
838 // If the element value is larger than the splat value, cut it in half and
839 // check to see if the two halves are equal. Continue doing this until we
840 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
841 while (ValSizeInBytes > ByteSize) {
842 ValSizeInBytes >>= 1;
844 // If the top half equals the bottom half, we're still ok.
845 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
846 (Value & ((1 << (8*ValSizeInBytes))-1)))
850 // Properly sign extend the value.
851 int MaskVal = SignExtend32(Value, ByteSize * 8);
853 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
854 if (MaskVal == 0) return SDValue();
856 // Finally, if this value fits in a 5 bit sext field, return it
857 if (SignExtend32<5>(MaskVal) == MaskVal)
858 return DAG.getTargetConstant(MaskVal, MVT::i32);
862 //===----------------------------------------------------------------------===//
863 // Addressing Mode Selection
864 //===----------------------------------------------------------------------===//
866 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
867 /// or 64-bit immediate, and if the value can be accurately represented as a
868 /// sign extension from a 16-bit value. If so, this returns true and the
870 static bool isIntS16Immediate(SDNode *N, short &Imm) {
871 if (N->getOpcode() != ISD::Constant)
874 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
875 if (N->getValueType(0) == MVT::i32)
876 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
878 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
880 static bool isIntS16Immediate(SDValue Op, short &Imm) {
881 return isIntS16Immediate(Op.getNode(), Imm);
885 /// SelectAddressRegReg - Given the specified addressed, check to see if it
886 /// can be represented as an indexed [r+r] operation. Returns false if it
887 /// can be more efficiently represented with [r+imm].
888 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
890 SelectionDAG &DAG) const {
892 if (N.getOpcode() == ISD::ADD) {
893 if (isIntS16Immediate(N.getOperand(1), imm))
895 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
898 Base = N.getOperand(0);
899 Index = N.getOperand(1);
901 } else if (N.getOpcode() == ISD::OR) {
902 if (isIntS16Immediate(N.getOperand(1), imm))
903 return false; // r+i can fold it if we can.
905 // If this is an or of disjoint bitfields, we can codegen this as an add
906 // (for better address arithmetic) if the LHS and RHS of the OR are provably
908 APInt LHSKnownZero, LHSKnownOne;
909 APInt RHSKnownZero, RHSKnownOne;
910 DAG.ComputeMaskedBits(N.getOperand(0),
911 LHSKnownZero, LHSKnownOne);
913 if (LHSKnownZero.getBoolValue()) {
914 DAG.ComputeMaskedBits(N.getOperand(1),
915 RHSKnownZero, RHSKnownOne);
916 // If all of the bits are known zero on the LHS or RHS, the add won't
918 if (~(LHSKnownZero | RHSKnownZero) == 0) {
919 Base = N.getOperand(0);
920 Index = N.getOperand(1);
929 /// Returns true if the address N can be represented by a base register plus
930 /// a signed 16-bit displacement [r+imm], and if it is not better
931 /// represented as reg+reg.
932 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
934 SelectionDAG &DAG) const {
935 // FIXME dl should come from parent load or store, not from address
936 DebugLoc dl = N.getDebugLoc();
937 // If this can be more profitably realized as r+r, fail.
938 if (SelectAddressRegReg(N, Disp, Base, DAG))
941 if (N.getOpcode() == ISD::ADD) {
943 if (isIntS16Immediate(N.getOperand(1), imm)) {
944 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
945 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
946 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
948 Base = N.getOperand(0);
950 return true; // [r+i]
951 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
952 // Match LOAD (ADD (X, Lo(G))).
953 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
954 && "Cannot handle constant offsets yet!");
955 Disp = N.getOperand(1).getOperand(0); // The global address.
956 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
957 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
958 Disp.getOpcode() == ISD::TargetConstantPool ||
959 Disp.getOpcode() == ISD::TargetJumpTable);
960 Base = N.getOperand(0);
961 return true; // [&g+r]
963 } else if (N.getOpcode() == ISD::OR) {
965 if (isIntS16Immediate(N.getOperand(1), imm)) {
966 // If this is an or of disjoint bitfields, we can codegen this as an add
967 // (for better address arithmetic) if the LHS and RHS of the OR are
968 // provably disjoint.
969 APInt LHSKnownZero, LHSKnownOne;
970 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
972 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
973 // If all of the bits are known zero on the LHS or RHS, the add won't
975 Base = N.getOperand(0);
976 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
980 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
981 // Loading from a constant address.
983 // If this address fits entirely in a 16-bit sext immediate field, codegen
986 if (isIntS16Immediate(CN, Imm)) {
987 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
988 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
989 CN->getValueType(0));
993 // Handle 32-bit sext immediates with LIS + addr mode.
994 if (CN->getValueType(0) == MVT::i32 ||
995 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
996 int Addr = (int)CN->getZExtValue();
998 // Otherwise, break this down into an LIS + disp.
999 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1001 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1002 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1003 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1008 Disp = DAG.getTargetConstant(0, getPointerTy());
1009 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1010 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1013 return true; // [r+0]
1016 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1017 /// represented as an indexed [r+r] operation.
1018 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1020 SelectionDAG &DAG) const {
1021 // Check to see if we can easily represent this as an [r+r] address. This
1022 // will fail if it thinks that the address is more profitably represented as
1023 // reg+imm, e.g. where imm = 0.
1024 if (SelectAddressRegReg(N, Base, Index, DAG))
1027 // If the operand is an addition, always emit this as [r+r], since this is
1028 // better (for code size, and execution, as the memop does the add for free)
1029 // than emitting an explicit add.
1030 if (N.getOpcode() == ISD::ADD) {
1031 Base = N.getOperand(0);
1032 Index = N.getOperand(1);
1036 // Otherwise, do it the hard way, using R0 as the base register.
1037 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1043 /// SelectAddressRegImmShift - Returns true if the address N can be
1044 /// represented by a base register plus a signed 14-bit displacement
1045 /// [r+imm*4]. Suitable for use by STD and friends.
1046 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1048 SelectionDAG &DAG) const {
1049 // FIXME dl should come from the parent load or store, not the address
1050 DebugLoc dl = N.getDebugLoc();
1051 // If this can be more profitably realized as r+r, fail.
1052 if (SelectAddressRegReg(N, Disp, Base, DAG))
1055 if (N.getOpcode() == ISD::ADD) {
1057 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1058 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1059 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1060 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1062 Base = N.getOperand(0);
1064 return true; // [r+i]
1065 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1066 // Match LOAD (ADD (X, Lo(G))).
1067 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1068 && "Cannot handle constant offsets yet!");
1069 Disp = N.getOperand(1).getOperand(0); // The global address.
1070 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1071 Disp.getOpcode() == ISD::TargetConstantPool ||
1072 Disp.getOpcode() == ISD::TargetJumpTable);
1073 Base = N.getOperand(0);
1074 return true; // [&g+r]
1076 } else if (N.getOpcode() == ISD::OR) {
1078 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1079 // If this is an or of disjoint bitfields, we can codegen this as an add
1080 // (for better address arithmetic) if the LHS and RHS of the OR are
1081 // provably disjoint.
1082 APInt LHSKnownZero, LHSKnownOne;
1083 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1084 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1085 // If all of the bits are known zero on the LHS or RHS, the add won't
1087 Base = N.getOperand(0);
1088 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1092 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1093 // Loading from a constant address. Verify low two bits are clear.
1094 if ((CN->getZExtValue() & 3) == 0) {
1095 // If this address fits entirely in a 14-bit sext immediate field, codegen
1098 if (isIntS16Immediate(CN, Imm)) {
1099 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1100 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1101 CN->getValueType(0));
1105 // Fold the low-part of 32-bit absolute addresses into addr mode.
1106 if (CN->getValueType(0) == MVT::i32 ||
1107 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1108 int Addr = (int)CN->getZExtValue();
1110 // Otherwise, break this down into an LIS + disp.
1111 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1112 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1113 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1114 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1120 Disp = DAG.getTargetConstant(0, getPointerTy());
1121 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1122 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1125 return true; // [r+0]
1129 /// getPreIndexedAddressParts - returns true by value, base pointer and
1130 /// offset pointer and addressing mode by reference if the node's address
1131 /// can be legally represented as pre-indexed load / store address.
1132 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1134 ISD::MemIndexedMode &AM,
1135 SelectionDAG &DAG) const {
1136 if (DisablePPCPreinc) return false;
1140 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1141 Ptr = LD->getBasePtr();
1142 VT = LD->getMemoryVT();
1144 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1145 Ptr = ST->getBasePtr();
1146 VT = ST->getMemoryVT();
1150 // PowerPC doesn't have preinc load/store instructions for vectors.
1154 if (SelectAddressRegReg(Ptr, Offset, Base, DAG)) {
1159 // LDU/STU use reg+imm*4, others use reg+imm.
1160 if (VT != MVT::i64) {
1162 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1166 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1170 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1171 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1172 // sext i32 to i64 when addr mode is r+i.
1173 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1174 LD->getExtensionType() == ISD::SEXTLOAD &&
1175 isa<ConstantSDNode>(Offset))
1183 //===----------------------------------------------------------------------===//
1184 // LowerOperation implementation
1185 //===----------------------------------------------------------------------===//
1187 /// GetLabelAccessInfo - Return true if we should reference labels using a
1188 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1189 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1190 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1191 HiOpFlags = PPCII::MO_HA16;
1192 LoOpFlags = PPCII::MO_LO16;
1194 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1195 // non-darwin platform. We don't support PIC on other platforms yet.
1196 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1197 TM.getSubtarget<PPCSubtarget>().isDarwin();
1199 HiOpFlags |= PPCII::MO_PIC_FLAG;
1200 LoOpFlags |= PPCII::MO_PIC_FLAG;
1203 // If this is a reference to a global value that requires a non-lazy-ptr, make
1204 // sure that instruction lowering adds it.
1205 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1206 HiOpFlags |= PPCII::MO_NLP_FLAG;
1207 LoOpFlags |= PPCII::MO_NLP_FLAG;
1209 if (GV->hasHiddenVisibility()) {
1210 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1211 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1218 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1219 SelectionDAG &DAG) {
1220 EVT PtrVT = HiPart.getValueType();
1221 SDValue Zero = DAG.getConstant(0, PtrVT);
1222 DebugLoc DL = HiPart.getDebugLoc();
1224 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1225 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1227 // With PIC, the first instruction is actually "GR+hi(&G)".
1229 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1230 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1232 // Generate non-pic code that has direct accesses to the constant pool.
1233 // The address of the global is just (hi(&g)+lo(&g)).
1234 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1237 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1238 SelectionDAG &DAG) const {
1239 EVT PtrVT = Op.getValueType();
1240 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1241 const Constant *C = CP->getConstVal();
1243 // 64-bit SVR4 ABI code is always position-independent.
1244 // The actual address of the GlobalValue is stored in the TOC.
1245 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1246 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1247 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1248 DAG.getRegister(PPC::X2, MVT::i64));
1251 unsigned MOHiFlag, MOLoFlag;
1252 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1254 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1256 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1257 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1260 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1261 EVT PtrVT = Op.getValueType();
1262 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1264 // 64-bit SVR4 ABI code is always position-independent.
1265 // The actual address of the GlobalValue is stored in the TOC.
1266 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1267 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1268 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1269 DAG.getRegister(PPC::X2, MVT::i64));
1272 unsigned MOHiFlag, MOLoFlag;
1273 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1274 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1275 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1276 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1279 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1280 SelectionDAG &DAG) const {
1281 EVT PtrVT = Op.getValueType();
1283 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1285 unsigned MOHiFlag, MOLoFlag;
1286 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1287 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1288 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1289 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1292 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1293 SelectionDAG &DAG) const {
1295 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1296 DebugLoc dl = GA->getDebugLoc();
1297 const GlobalValue *GV = GA->getGlobal();
1298 EVT PtrVT = getPointerTy();
1299 bool is64bit = PPCSubTarget.isPPC64();
1301 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1303 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1304 PPCII::MO_TPREL16_HA);
1305 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1306 PPCII::MO_TPREL16_LO);
1308 if (model != TLSModel::LocalExec)
1309 llvm_unreachable("only local-exec TLS mode supported");
1310 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1311 is64bit ? MVT::i64 : MVT::i32);
1312 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1313 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1316 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1317 SelectionDAG &DAG) const {
1318 EVT PtrVT = Op.getValueType();
1319 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1320 DebugLoc DL = GSDN->getDebugLoc();
1321 const GlobalValue *GV = GSDN->getGlobal();
1323 // 64-bit SVR4 ABI code is always position-independent.
1324 // The actual address of the GlobalValue is stored in the TOC.
1325 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1326 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1327 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1328 DAG.getRegister(PPC::X2, MVT::i64));
1331 unsigned MOHiFlag, MOLoFlag;
1332 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1335 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1337 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1339 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1341 // If the global reference is actually to a non-lazy-pointer, we have to do an
1342 // extra load to get the address of the global.
1343 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1344 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1345 false, false, false, 0);
1349 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1350 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1351 DebugLoc dl = Op.getDebugLoc();
1353 // If we're comparing for equality to zero, expose the fact that this is
1354 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1355 // fold the new nodes.
1356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1357 if (C->isNullValue() && CC == ISD::SETEQ) {
1358 EVT VT = Op.getOperand(0).getValueType();
1359 SDValue Zext = Op.getOperand(0);
1360 if (VT.bitsLT(MVT::i32)) {
1362 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1364 unsigned Log2b = Log2_32(VT.getSizeInBits());
1365 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1366 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1367 DAG.getConstant(Log2b, MVT::i32));
1368 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1370 // Leave comparisons against 0 and -1 alone for now, since they're usually
1371 // optimized. FIXME: revisit this when we can custom lower all setcc
1373 if (C->isAllOnesValue() || C->isNullValue())
1377 // If we have an integer seteq/setne, turn it into a compare against zero
1378 // by xor'ing the rhs with the lhs, which is faster than setting a
1379 // condition register, reading it back out, and masking the correct bit. The
1380 // normal approach here uses sub to do this instead of xor. Using xor exposes
1381 // the result to other bit-twiddling opportunities.
1382 EVT LHSVT = Op.getOperand(0).getValueType();
1383 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1384 EVT VT = Op.getValueType();
1385 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1387 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1392 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1393 const PPCSubtarget &Subtarget) const {
1394 SDNode *Node = Op.getNode();
1395 EVT VT = Node->getValueType(0);
1396 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1397 SDValue InChain = Node->getOperand(0);
1398 SDValue VAListPtr = Node->getOperand(1);
1399 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1400 DebugLoc dl = Node->getDebugLoc();
1402 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1405 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1406 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1408 InChain = GprIndex.getValue(1);
1410 if (VT == MVT::i64) {
1411 // Check if GprIndex is even
1412 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1413 DAG.getConstant(1, MVT::i32));
1414 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1415 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1416 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1417 DAG.getConstant(1, MVT::i32));
1418 // Align GprIndex to be even if it isn't
1419 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1423 // fpr index is 1 byte after gpr
1424 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1425 DAG.getConstant(1, MVT::i32));
1428 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1429 FprPtr, MachinePointerInfo(SV), MVT::i8,
1431 InChain = FprIndex.getValue(1);
1433 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1434 DAG.getConstant(8, MVT::i32));
1436 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1437 DAG.getConstant(4, MVT::i32));
1440 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1441 MachinePointerInfo(), false, false,
1443 InChain = OverflowArea.getValue(1);
1445 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1446 MachinePointerInfo(), false, false,
1448 InChain = RegSaveArea.getValue(1);
1450 // select overflow_area if index > 8
1451 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1452 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1454 // adjustment constant gpr_index * 4/8
1455 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1456 VT.isInteger() ? GprIndex : FprIndex,
1457 DAG.getConstant(VT.isInteger() ? 4 : 8,
1460 // OurReg = RegSaveArea + RegConstant
1461 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1464 // Floating types are 32 bytes into RegSaveArea
1465 if (VT.isFloatingPoint())
1466 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1467 DAG.getConstant(32, MVT::i32));
1469 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1470 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1471 VT.isInteger() ? GprIndex : FprIndex,
1472 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1475 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1476 VT.isInteger() ? VAListPtr : FprPtr,
1477 MachinePointerInfo(SV),
1478 MVT::i8, false, false, 0);
1480 // determine if we should load from reg_save_area or overflow_area
1481 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1483 // increase overflow_area by 4/8 if gpr/fpr > 8
1484 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1485 DAG.getConstant(VT.isInteger() ? 4 : 8,
1488 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1491 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1493 MachinePointerInfo(),
1494 MVT::i32, false, false, 0);
1496 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1497 false, false, false, 0);
1500 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1501 SelectionDAG &DAG) const {
1502 return Op.getOperand(0);
1505 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1506 SelectionDAG &DAG) const {
1507 SDValue Chain = Op.getOperand(0);
1508 SDValue Trmp = Op.getOperand(1); // trampoline
1509 SDValue FPtr = Op.getOperand(2); // nested function
1510 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1511 DebugLoc dl = Op.getDebugLoc();
1513 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1514 bool isPPC64 = (PtrVT == MVT::i64);
1517 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1518 *DAG.getContext(), AS);
1520 TargetLowering::ArgListTy Args;
1521 TargetLowering::ArgListEntry Entry;
1523 Entry.Ty = IntPtrTy;
1524 Entry.Node = Trmp; Args.push_back(Entry);
1526 // TrampSize == (isPPC64 ? 48 : 40);
1527 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1528 isPPC64 ? MVT::i64 : MVT::i32);
1529 Args.push_back(Entry);
1531 Entry.Node = FPtr; Args.push_back(Entry);
1532 Entry.Node = Nest; Args.push_back(Entry);
1534 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1535 TargetLowering::CallLoweringInfo CLI(Chain,
1536 Type::getVoidTy(*DAG.getContext()),
1537 false, false, false, false, 0,
1539 /*isTailCall=*/false,
1540 /*doesNotRet=*/false,
1541 /*isReturnValueUsed=*/true,
1542 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1544 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1546 return CallResult.second;
1549 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1550 const PPCSubtarget &Subtarget) const {
1551 MachineFunction &MF = DAG.getMachineFunction();
1552 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1554 DebugLoc dl = Op.getDebugLoc();
1556 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1557 // vastart just stores the address of the VarArgsFrameIndex slot into the
1558 // memory location argument.
1559 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1560 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1561 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1562 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1563 MachinePointerInfo(SV),
1567 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1568 // We suppose the given va_list is already allocated.
1571 // char gpr; /* index into the array of 8 GPRs
1572 // * stored in the register save area
1573 // * gpr=0 corresponds to r3,
1574 // * gpr=1 to r4, etc.
1576 // char fpr; /* index into the array of 8 FPRs
1577 // * stored in the register save area
1578 // * fpr=0 corresponds to f1,
1579 // * fpr=1 to f2, etc.
1581 // char *overflow_arg_area;
1582 // /* location on stack that holds
1583 // * the next overflow argument
1585 // char *reg_save_area;
1586 // /* where r3:r10 and f1:f8 (if saved)
1592 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1593 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1596 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1598 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1600 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1603 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1604 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1606 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1607 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1609 uint64_t FPROffset = 1;
1610 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1612 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1614 // Store first byte : number of int regs
1615 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1617 MachinePointerInfo(SV),
1618 MVT::i8, false, false, 0);
1619 uint64_t nextOffset = FPROffset;
1620 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1623 // Store second byte : number of float regs
1624 SDValue secondStore =
1625 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1626 MachinePointerInfo(SV, nextOffset), MVT::i8,
1628 nextOffset += StackOffset;
1629 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1631 // Store second word : arguments given on stack
1632 SDValue thirdStore =
1633 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1634 MachinePointerInfo(SV, nextOffset),
1636 nextOffset += FrameOffset;
1637 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1639 // Store third word : arguments given in registers
1640 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1641 MachinePointerInfo(SV, nextOffset),
1646 #include "PPCGenCallingConv.inc"
1648 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1649 CCValAssign::LocInfo &LocInfo,
1650 ISD::ArgFlagsTy &ArgFlags,
1655 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1657 CCValAssign::LocInfo &LocInfo,
1658 ISD::ArgFlagsTy &ArgFlags,
1660 static const uint16_t ArgRegs[] = {
1661 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1662 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1664 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1666 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1668 // Skip one register if the first unallocated register has an even register
1669 // number and there are still argument registers available which have not been
1670 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1671 // need to skip a register if RegNum is odd.
1672 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1673 State.AllocateReg(ArgRegs[RegNum]);
1676 // Always return false here, as this function only makes sure that the first
1677 // unallocated register has an odd register number and does not actually
1678 // allocate a register for the current argument.
1682 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1684 CCValAssign::LocInfo &LocInfo,
1685 ISD::ArgFlagsTy &ArgFlags,
1687 static const uint16_t ArgRegs[] = {
1688 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1692 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1694 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1696 // If there is only one Floating-point register left we need to put both f64
1697 // values of a split ppc_fp128 value on the stack.
1698 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1699 State.AllocateReg(ArgRegs[RegNum]);
1702 // Always return false here, as this function only makes sure that the two f64
1703 // values a ppc_fp128 value is split into are both passed in registers or both
1704 // passed on the stack and does not actually allocate a register for the
1705 // current argument.
1709 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1711 static const uint16_t *GetFPR() {
1712 static const uint16_t FPR[] = {
1713 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1714 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1720 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1722 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1723 unsigned PtrByteSize) {
1724 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1725 if (Flags.isByVal())
1726 ArgSize = Flags.getByValSize();
1727 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1733 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1734 CallingConv::ID CallConv, bool isVarArg,
1735 const SmallVectorImpl<ISD::InputArg>
1737 DebugLoc dl, SelectionDAG &DAG,
1738 SmallVectorImpl<SDValue> &InVals)
1740 if (PPCSubTarget.isSVR4ABI()) {
1741 if (PPCSubTarget.isPPC64())
1742 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1745 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1748 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1754 PPCTargetLowering::LowerFormalArguments_32SVR4(
1756 CallingConv::ID CallConv, bool isVarArg,
1757 const SmallVectorImpl<ISD::InputArg>
1759 DebugLoc dl, SelectionDAG &DAG,
1760 SmallVectorImpl<SDValue> &InVals) const {
1762 // 32-bit SVR4 ABI Stack Frame Layout:
1763 // +-----------------------------------+
1764 // +--> | Back chain |
1765 // | +-----------------------------------+
1766 // | | Floating-point register save area |
1767 // | +-----------------------------------+
1768 // | | General register save area |
1769 // | +-----------------------------------+
1770 // | | CR save word |
1771 // | +-----------------------------------+
1772 // | | VRSAVE save word |
1773 // | +-----------------------------------+
1774 // | | Alignment padding |
1775 // | +-----------------------------------+
1776 // | | Vector register save area |
1777 // | +-----------------------------------+
1778 // | | Local variable space |
1779 // | +-----------------------------------+
1780 // | | Parameter list area |
1781 // | +-----------------------------------+
1782 // | | LR save word |
1783 // | +-----------------------------------+
1784 // SP--> +--- | Back chain |
1785 // +-----------------------------------+
1788 // System V Application Binary Interface PowerPC Processor Supplement
1789 // AltiVec Technology Programming Interface Manual
1791 MachineFunction &MF = DAG.getMachineFunction();
1792 MachineFrameInfo *MFI = MF.getFrameInfo();
1793 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1795 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1796 // Potential tail calls could cause overwriting of argument stack slots.
1797 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1798 (CallConv == CallingConv::Fast));
1799 unsigned PtrByteSize = 4;
1801 // Assign locations to all of the incoming arguments.
1802 SmallVector<CCValAssign, 16> ArgLocs;
1803 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1804 getTargetMachine(), ArgLocs, *DAG.getContext());
1806 // Reserve space for the linkage area on the stack.
1807 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1809 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4);
1811 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1812 CCValAssign &VA = ArgLocs[i];
1814 // Arguments stored in registers.
1815 if (VA.isRegLoc()) {
1816 const TargetRegisterClass *RC;
1817 EVT ValVT = VA.getValVT();
1819 switch (ValVT.getSimpleVT().SimpleTy) {
1821 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1823 RC = &PPC::GPRCRegClass;
1826 RC = &PPC::F4RCRegClass;
1829 RC = &PPC::F8RCRegClass;
1835 RC = &PPC::VRRCRegClass;
1839 // Transform the arguments stored in physical registers into virtual ones.
1840 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1841 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1843 InVals.push_back(ArgValue);
1845 // Argument stored in memory.
1846 assert(VA.isMemLoc());
1848 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1849 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1852 // Create load nodes to retrieve arguments from the stack.
1853 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1854 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1855 MachinePointerInfo(),
1856 false, false, false, 0));
1860 // Assign locations to all of the incoming aggregate by value arguments.
1861 // Aggregates passed by value are stored in the local variable space of the
1862 // caller's stack frame, right above the parameter list area.
1863 SmallVector<CCValAssign, 16> ByValArgLocs;
1864 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1865 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1867 // Reserve stack space for the allocations in CCInfo.
1868 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1870 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal);
1872 // Area that is at least reserved in the caller of this function.
1873 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1875 // Set the size that is at least reserved in caller of this function. Tail
1876 // call optimized function's reserved stack space needs to be aligned so that
1877 // taking the difference between two stack areas will result in an aligned
1879 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1882 std::max(MinReservedArea,
1883 PPCFrameLowering::getMinCallFrameSize(false, false));
1885 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1886 getStackAlignment();
1887 unsigned AlignMask = TargetAlign-1;
1888 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1890 FI->setMinReservedArea(MinReservedArea);
1892 SmallVector<SDValue, 8> MemOps;
1894 // If the function takes variable number of arguments, make a frame index for
1895 // the start of the first vararg value... for expansion of llvm.va_start.
1897 static const uint16_t GPArgRegs[] = {
1898 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1899 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1901 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
1903 static const uint16_t FPArgRegs[] = {
1904 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1907 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
1909 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
1911 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
1914 // Make room for NumGPArgRegs and NumFPArgRegs.
1915 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
1916 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
1918 FuncInfo->setVarArgsStackOffset(
1919 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
1920 CCInfo.getNextStackOffset(), true));
1922 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
1923 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1925 // The fixed integer arguments of a variadic function are stored to the
1926 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
1927 // the result of va_next.
1928 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
1929 // Get an existing live-in vreg, or add a new one.
1930 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
1932 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
1934 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
1935 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1936 MachinePointerInfo(), false, false, 0);
1937 MemOps.push_back(Store);
1938 // Increment the address by four for the next argument to store
1939 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
1940 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1943 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
1945 // The double arguments are stored to the VarArgsFrameIndex
1947 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
1948 // Get an existing live-in vreg, or add a new one.
1949 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
1951 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
1953 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
1954 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
1955 MachinePointerInfo(), false, false, 0);
1956 MemOps.push_back(Store);
1957 // Increment the address by eight for the next argument to store
1958 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
1960 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
1964 if (!MemOps.empty())
1965 Chain = DAG.getNode(ISD::TokenFactor, dl,
1966 MVT::Other, &MemOps[0], MemOps.size());
1971 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
1972 // value to MVT::i64 and then truncate to the correct register size.
1974 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
1975 SelectionDAG &DAG, SDValue ArgVal,
1976 DebugLoc dl) const {
1978 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
1979 DAG.getValueType(ObjectVT));
1980 else if (Flags.isZExt())
1981 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
1982 DAG.getValueType(ObjectVT));
1984 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
1987 // Set the size that is at least reserved in caller of this function. Tail
1988 // call optimized functions' reserved stack space needs to be aligned so that
1989 // taking the difference between two stack areas will result in an aligned
1992 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
1993 unsigned nAltivecParamsAtEnd,
1994 unsigned MinReservedArea,
1995 bool isPPC64) const {
1996 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1997 // Add the Altivec parameters at the end, if needed.
1998 if (nAltivecParamsAtEnd) {
1999 MinReservedArea = ((MinReservedArea+15)/16)*16;
2000 MinReservedArea += 16*nAltivecParamsAtEnd;
2003 std::max(MinReservedArea,
2004 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2005 unsigned TargetAlign
2006 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2007 getStackAlignment();
2008 unsigned AlignMask = TargetAlign-1;
2009 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2010 FI->setMinReservedArea(MinReservedArea);
2014 PPCTargetLowering::LowerFormalArguments_64SVR4(
2016 CallingConv::ID CallConv, bool isVarArg,
2017 const SmallVectorImpl<ISD::InputArg>
2019 DebugLoc dl, SelectionDAG &DAG,
2020 SmallVectorImpl<SDValue> &InVals) const {
2021 // TODO: add description of PPC stack frame format, or at least some docs.
2023 MachineFunction &MF = DAG.getMachineFunction();
2024 MachineFrameInfo *MFI = MF.getFrameInfo();
2025 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2027 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2028 // Potential tail calls could cause overwriting of argument stack slots.
2029 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2030 (CallConv == CallingConv::Fast));
2031 unsigned PtrByteSize = 8;
2033 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2034 // Area that is at least reserved in caller of this function.
2035 unsigned MinReservedArea = ArgOffset;
2037 static const uint16_t GPR[] = {
2038 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2039 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2042 static const uint16_t *FPR = GetFPR();
2044 static const uint16_t VR[] = {
2045 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2046 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2049 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2050 const unsigned Num_FPR_Regs = 13;
2051 const unsigned Num_VR_Regs = array_lengthof(VR);
2053 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2055 // Add DAG nodes to load the arguments or copy them out of registers. On
2056 // entry to a function on PPC, the arguments start after the linkage area,
2057 // although the first ones are often in registers.
2059 SmallVector<SDValue, 8> MemOps;
2060 unsigned nAltivecParamsAtEnd = 0;
2061 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2062 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2064 bool needsLoad = false;
2065 EVT ObjectVT = Ins[ArgNo].VT;
2066 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2067 unsigned ArgSize = ObjSize;
2068 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2070 unsigned CurArgOffset = ArgOffset;
2072 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2073 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2074 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2076 MinReservedArea = ((MinReservedArea+15)/16)*16;
2077 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2081 nAltivecParamsAtEnd++;
2083 // Calculate min reserved area.
2084 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2088 // FIXME the codegen can be much improved in some cases.
2089 // We do not have to keep everything in memory.
2090 if (Flags.isByVal()) {
2091 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2092 ObjSize = Flags.getByValSize();
2093 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2094 // Empty aggregate parameters do not take up registers. Examples:
2098 // etc. However, we have to provide a place-holder in InVals, so
2099 // pretend we have an 8-byte item at the current address for that
2102 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2103 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2104 InVals.push_back(FIN);
2107 // All aggregates smaller than 8 bytes must be passed right-justified.
2108 if (ObjSize < PtrByteSize)
2109 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2110 // The value of the object is its address.
2111 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2112 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2113 InVals.push_back(FIN);
2116 if (GPR_idx != Num_GPR_Regs) {
2117 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2118 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2121 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2122 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2123 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2124 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2125 MachinePointerInfo(FuncArg, CurArgOffset),
2126 ObjType, false, false, 0);
2128 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2129 // store the whole register as-is to the parameter save area
2130 // slot. The address of the parameter was already calculated
2131 // above (InVals.push_back(FIN)) to be the right-justified
2132 // offset within the slot. For this store, we need a new
2133 // frame index that points at the beginning of the slot.
2134 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2135 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2136 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2137 MachinePointerInfo(FuncArg, ArgOffset),
2141 MemOps.push_back(Store);
2144 // Whether we copied from a register or not, advance the offset
2145 // into the parameter save area by a full doubleword.
2146 ArgOffset += PtrByteSize;
2150 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2151 // Store whatever pieces of the object are in registers
2152 // to memory. ArgOffset will be the address of the beginning
2154 if (GPR_idx != Num_GPR_Regs) {
2156 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2157 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2158 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2159 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2160 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2161 MachinePointerInfo(FuncArg, ArgOffset),
2163 MemOps.push_back(Store);
2165 ArgOffset += PtrByteSize;
2167 ArgOffset += ArgSize - j;
2174 switch (ObjectVT.getSimpleVT().SimpleTy) {
2175 default: llvm_unreachable("Unhandled argument type!");
2178 if (GPR_idx != Num_GPR_Regs) {
2179 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2180 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2182 if (ObjectVT == MVT::i32)
2183 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2184 // value to MVT::i64 and then truncate to the correct register size.
2185 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2190 ArgSize = PtrByteSize;
2197 // Every 8 bytes of argument space consumes one of the GPRs available for
2198 // argument passing.
2199 if (GPR_idx != Num_GPR_Regs) {
2202 if (FPR_idx != Num_FPR_Regs) {
2205 if (ObjectVT == MVT::f32)
2206 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2208 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2210 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2214 ArgSize = PtrByteSize;
2223 // Note that vector arguments in registers don't reserve stack space,
2224 // except in varargs functions.
2225 if (VR_idx != Num_VR_Regs) {
2226 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2227 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2229 while ((ArgOffset % 16) != 0) {
2230 ArgOffset += PtrByteSize;
2231 if (GPR_idx != Num_GPR_Regs)
2235 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2239 // Vectors are aligned.
2240 ArgOffset = ((ArgOffset+15)/16)*16;
2241 CurArgOffset = ArgOffset;
2248 // We need to load the argument to a virtual register if we determined
2249 // above that we ran out of physical registers of the appropriate type.
2251 int FI = MFI->CreateFixedObject(ObjSize,
2252 CurArgOffset + (ArgSize - ObjSize),
2254 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2255 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2256 false, false, false, 0);
2259 InVals.push_back(ArgVal);
2262 // Set the size that is at least reserved in caller of this function. Tail
2263 // call optimized functions' reserved stack space needs to be aligned so that
2264 // taking the difference between two stack areas will result in an aligned
2266 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2268 // If the function takes variable number of arguments, make a frame index for
2269 // the start of the first vararg value... for expansion of llvm.va_start.
2271 int Depth = ArgOffset;
2273 FuncInfo->setVarArgsFrameIndex(
2274 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2275 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2277 // If this function is vararg, store any remaining integer argument regs
2278 // to their spots on the stack so that they may be loaded by deferencing the
2279 // result of va_next.
2280 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2281 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2282 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2283 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2284 MachinePointerInfo(), false, false, 0);
2285 MemOps.push_back(Store);
2286 // Increment the address by four for the next argument to store
2287 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2288 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2292 if (!MemOps.empty())
2293 Chain = DAG.getNode(ISD::TokenFactor, dl,
2294 MVT::Other, &MemOps[0], MemOps.size());
2300 PPCTargetLowering::LowerFormalArguments_Darwin(
2302 CallingConv::ID CallConv, bool isVarArg,
2303 const SmallVectorImpl<ISD::InputArg>
2305 DebugLoc dl, SelectionDAG &DAG,
2306 SmallVectorImpl<SDValue> &InVals) const {
2307 // TODO: add description of PPC stack frame format, or at least some docs.
2309 MachineFunction &MF = DAG.getMachineFunction();
2310 MachineFrameInfo *MFI = MF.getFrameInfo();
2311 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2313 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2314 bool isPPC64 = PtrVT == MVT::i64;
2315 // Potential tail calls could cause overwriting of argument stack slots.
2316 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2317 (CallConv == CallingConv::Fast));
2318 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2320 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2321 // Area that is at least reserved in caller of this function.
2322 unsigned MinReservedArea = ArgOffset;
2324 static const uint16_t GPR_32[] = { // 32-bit registers.
2325 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2326 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2328 static const uint16_t GPR_64[] = { // 64-bit registers.
2329 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2330 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2333 static const uint16_t *FPR = GetFPR();
2335 static const uint16_t VR[] = {
2336 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2337 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2340 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2341 const unsigned Num_FPR_Regs = 13;
2342 const unsigned Num_VR_Regs = array_lengthof( VR);
2344 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2346 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2348 // In 32-bit non-varargs functions, the stack space for vectors is after the
2349 // stack space for non-vectors. We do not use this space unless we have
2350 // too many vectors to fit in registers, something that only occurs in
2351 // constructed examples:), but we have to walk the arglist to figure
2352 // that out...for the pathological case, compute VecArgOffset as the
2353 // start of the vector parameter area. Computing VecArgOffset is the
2354 // entire point of the following loop.
2355 unsigned VecArgOffset = ArgOffset;
2356 if (!isVarArg && !isPPC64) {
2357 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2359 EVT ObjectVT = Ins[ArgNo].VT;
2360 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2362 if (Flags.isByVal()) {
2363 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2364 unsigned ObjSize = Flags.getByValSize();
2366 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2367 VecArgOffset += ArgSize;
2371 switch(ObjectVT.getSimpleVT().SimpleTy) {
2372 default: llvm_unreachable("Unhandled argument type!");
2377 case MVT::i64: // PPC64
2379 // FIXME: We are guaranteed to be !isPPC64 at this point.
2380 // Does MVT::i64 apply?
2387 // Nothing to do, we're only looking at Nonvector args here.
2392 // We've found where the vector parameter area in memory is. Skip the
2393 // first 12 parameters; these don't use that memory.
2394 VecArgOffset = ((VecArgOffset+15)/16)*16;
2395 VecArgOffset += 12*16;
2397 // Add DAG nodes to load the arguments or copy them out of registers. On
2398 // entry to a function on PPC, the arguments start after the linkage area,
2399 // although the first ones are often in registers.
2401 SmallVector<SDValue, 8> MemOps;
2402 unsigned nAltivecParamsAtEnd = 0;
2403 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2404 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2406 bool needsLoad = false;
2407 EVT ObjectVT = Ins[ArgNo].VT;
2408 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2409 unsigned ArgSize = ObjSize;
2410 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2412 unsigned CurArgOffset = ArgOffset;
2414 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2415 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2416 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2417 if (isVarArg || isPPC64) {
2418 MinReservedArea = ((MinReservedArea+15)/16)*16;
2419 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2422 } else nAltivecParamsAtEnd++;
2424 // Calculate min reserved area.
2425 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2429 // FIXME the codegen can be much improved in some cases.
2430 // We do not have to keep everything in memory.
2431 if (Flags.isByVal()) {
2432 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2433 ObjSize = Flags.getByValSize();
2434 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2435 // Objects of size 1 and 2 are right justified, everything else is
2436 // left justified. This means the memory address is adjusted forwards.
2437 if (ObjSize==1 || ObjSize==2) {
2438 CurArgOffset = CurArgOffset + (4 - ObjSize);
2440 // The value of the object is its address.
2441 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2442 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2443 InVals.push_back(FIN);
2444 if (ObjSize==1 || ObjSize==2) {
2445 if (GPR_idx != Num_GPR_Regs) {
2448 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2450 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2451 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2452 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2453 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2454 MachinePointerInfo(FuncArg,
2456 ObjType, false, false, 0);
2457 MemOps.push_back(Store);
2461 ArgOffset += PtrByteSize;
2465 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2466 // Store whatever pieces of the object are in registers
2467 // to memory. ArgOffset will be the address of the beginning
2469 if (GPR_idx != Num_GPR_Regs) {
2472 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2474 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2475 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2476 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2477 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2478 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2479 MachinePointerInfo(FuncArg, ArgOffset),
2481 MemOps.push_back(Store);
2483 ArgOffset += PtrByteSize;
2485 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2492 switch (ObjectVT.getSimpleVT().SimpleTy) {
2493 default: llvm_unreachable("Unhandled argument type!");
2496 if (GPR_idx != Num_GPR_Regs) {
2497 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2498 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2502 ArgSize = PtrByteSize;
2504 // All int arguments reserve stack space in the Darwin ABI.
2505 ArgOffset += PtrByteSize;
2509 case MVT::i64: // PPC64
2510 if (GPR_idx != Num_GPR_Regs) {
2511 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2512 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2514 if (ObjectVT == MVT::i32)
2515 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2516 // value to MVT::i64 and then truncate to the correct register size.
2517 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2522 ArgSize = PtrByteSize;
2524 // All int arguments reserve stack space in the Darwin ABI.
2530 // Every 4 bytes of argument space consumes one of the GPRs available for
2531 // argument passing.
2532 if (GPR_idx != Num_GPR_Regs) {
2534 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2537 if (FPR_idx != Num_FPR_Regs) {
2540 if (ObjectVT == MVT::f32)
2541 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2543 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2545 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2551 // All FP arguments reserve stack space in the Darwin ABI.
2552 ArgOffset += isPPC64 ? 8 : ObjSize;
2558 // Note that vector arguments in registers don't reserve stack space,
2559 // except in varargs functions.
2560 if (VR_idx != Num_VR_Regs) {
2561 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2562 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2564 while ((ArgOffset % 16) != 0) {
2565 ArgOffset += PtrByteSize;
2566 if (GPR_idx != Num_GPR_Regs)
2570 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2574 if (!isVarArg && !isPPC64) {
2575 // Vectors go after all the nonvectors.
2576 CurArgOffset = VecArgOffset;
2579 // Vectors are aligned.
2580 ArgOffset = ((ArgOffset+15)/16)*16;
2581 CurArgOffset = ArgOffset;
2589 // We need to load the argument to a virtual register if we determined above
2590 // that we ran out of physical registers of the appropriate type.
2592 int FI = MFI->CreateFixedObject(ObjSize,
2593 CurArgOffset + (ArgSize - ObjSize),
2595 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2596 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2597 false, false, false, 0);
2600 InVals.push_back(ArgVal);
2603 // Set the size that is at least reserved in caller of this function. Tail
2604 // call optimized functions' reserved stack space needs to be aligned so that
2605 // taking the difference between two stack areas will result in an aligned
2607 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2609 // If the function takes variable number of arguments, make a frame index for
2610 // the start of the first vararg value... for expansion of llvm.va_start.
2612 int Depth = ArgOffset;
2614 FuncInfo->setVarArgsFrameIndex(
2615 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2617 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2619 // If this function is vararg, store any remaining integer argument regs
2620 // to their spots on the stack so that they may be loaded by deferencing the
2621 // result of va_next.
2622 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2626 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2628 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2630 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2631 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2632 MachinePointerInfo(), false, false, 0);
2633 MemOps.push_back(Store);
2634 // Increment the address by four for the next argument to store
2635 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2636 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2640 if (!MemOps.empty())
2641 Chain = DAG.getNode(ISD::TokenFactor, dl,
2642 MVT::Other, &MemOps[0], MemOps.size());
2647 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2648 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2650 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2654 const SmallVectorImpl<ISD::OutputArg>
2656 const SmallVectorImpl<SDValue> &OutVals,
2657 unsigned &nAltivecParamsAtEnd) {
2658 // Count how many bytes are to be pushed on the stack, including the linkage
2659 // area, and parameter passing area. We start with 24/48 bytes, which is
2660 // prereserved space for [SP][CR][LR][3 x unused].
2661 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2662 unsigned NumOps = Outs.size();
2663 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2665 // Add up all the space actually used.
2666 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2667 // they all go in registers, but we must reserve stack space for them for
2668 // possible use by the caller. In varargs or 64-bit calls, parameters are
2669 // assigned stack space in order, with padding so Altivec parameters are
2671 nAltivecParamsAtEnd = 0;
2672 for (unsigned i = 0; i != NumOps; ++i) {
2673 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2674 EVT ArgVT = Outs[i].VT;
2675 // Varargs Altivec parameters are padded to a 16 byte boundary.
2676 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2677 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2678 if (!isVarArg && !isPPC64) {
2679 // Non-varargs Altivec parameters go after all the non-Altivec
2680 // parameters; handle those later so we know how much padding we need.
2681 nAltivecParamsAtEnd++;
2684 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2685 NumBytes = ((NumBytes+15)/16)*16;
2687 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2690 // Allow for Altivec parameters at the end, if needed.
2691 if (nAltivecParamsAtEnd) {
2692 NumBytes = ((NumBytes+15)/16)*16;
2693 NumBytes += 16*nAltivecParamsAtEnd;
2696 // The prolog code of the callee may store up to 8 GPR argument registers to
2697 // the stack, allowing va_start to index over them in memory if its varargs.
2698 // Because we cannot tell if this is needed on the caller side, we have to
2699 // conservatively assume that it is needed. As such, make sure we have at
2700 // least enough stack space for the caller to store the 8 GPRs.
2701 NumBytes = std::max(NumBytes,
2702 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2704 // Tail call needs the stack to be aligned.
2705 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2706 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2707 getFrameLowering()->getStackAlignment();
2708 unsigned AlignMask = TargetAlign-1;
2709 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2715 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2716 /// adjusted to accommodate the arguments for the tailcall.
2717 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2718 unsigned ParamSize) {
2720 if (!isTailCall) return 0;
2722 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2723 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2724 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2725 // Remember only if the new adjustement is bigger.
2726 if (SPDiff < FI->getTailCallSPDelta())
2727 FI->setTailCallSPDelta(SPDiff);
2732 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2733 /// for tail call optimization. Targets which want to do tail call
2734 /// optimization should implement this function.
2736 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2737 CallingConv::ID CalleeCC,
2739 const SmallVectorImpl<ISD::InputArg> &Ins,
2740 SelectionDAG& DAG) const {
2741 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2744 // Variable argument functions are not supported.
2748 MachineFunction &MF = DAG.getMachineFunction();
2749 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2750 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2751 // Functions containing by val parameters are not supported.
2752 for (unsigned i = 0; i != Ins.size(); i++) {
2753 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2754 if (Flags.isByVal()) return false;
2757 // Non PIC/GOT tail calls are supported.
2758 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2761 // At the moment we can only do local tail calls (in same module, hidden
2762 // or protected) if we are generating PIC.
2763 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2764 return G->getGlobal()->hasHiddenVisibility()
2765 || G->getGlobal()->hasProtectedVisibility();
2771 /// isCallCompatibleAddress - Return the immediate to use if the specified
2772 /// 32-bit value is representable in the immediate field of a BxA instruction.
2773 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2774 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2777 int Addr = C->getZExtValue();
2778 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2779 SignExtend32<26>(Addr) != Addr)
2780 return 0; // Top 6 bits have to be sext of immediate.
2782 return DAG.getConstant((int)C->getZExtValue() >> 2,
2783 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2788 struct TailCallArgumentInfo {
2793 TailCallArgumentInfo() : FrameIdx(0) {}
2798 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2800 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2802 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2803 SmallVector<SDValue, 8> &MemOpChains,
2805 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2806 SDValue Arg = TailCallArgs[i].Arg;
2807 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2808 int FI = TailCallArgs[i].FrameIdx;
2809 // Store relative to framepointer.
2810 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2811 MachinePointerInfo::getFixedStack(FI),
2816 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2817 /// the appropriate stack slot for the tail call optimized function call.
2818 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2819 MachineFunction &MF,
2828 // Calculate the new stack slot for the return address.
2829 int SlotSize = isPPC64 ? 8 : 4;
2830 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2832 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2833 NewRetAddrLoc, true);
2834 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2835 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2836 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2837 MachinePointerInfo::getFixedStack(NewRetAddr),
2840 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2841 // slot as the FP is never overwritten.
2844 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2845 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2847 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2848 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2849 MachinePointerInfo::getFixedStack(NewFPIdx),
2856 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2857 /// the position of the argument.
2859 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2860 SDValue Arg, int SPDiff, unsigned ArgOffset,
2861 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2862 int Offset = ArgOffset + SPDiff;
2863 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2864 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2865 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2866 SDValue FIN = DAG.getFrameIndex(FI, VT);
2867 TailCallArgumentInfo Info;
2869 Info.FrameIdxOp = FIN;
2871 TailCallArguments.push_back(Info);
2874 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2875 /// stack slot. Returns the chain as result and the loaded frame pointers in
2876 /// LROpOut/FPOpout. Used when tail calling.
2877 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2883 DebugLoc dl) const {
2885 // Load the LR and FP stack slot for later adjusting.
2886 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2887 LROpOut = getReturnAddrFrameIndex(DAG);
2888 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
2889 false, false, false, 0);
2890 Chain = SDValue(LROpOut.getNode(), 1);
2892 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
2893 // slot as the FP is never overwritten.
2895 FPOpOut = getFramePointerFrameIndex(DAG);
2896 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
2897 false, false, false, 0);
2898 Chain = SDValue(FPOpOut.getNode(), 1);
2904 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2905 /// by "Src" to address "Dst" of size "Size". Alignment information is
2906 /// specified by the specific parameter attribute. The copy will be passed as
2907 /// a byval function parameter.
2908 /// Sometimes what we are copying is the end of a larger object, the part that
2909 /// does not fit in registers.
2911 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2912 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2914 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2915 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2916 false, false, MachinePointerInfo(0),
2917 MachinePointerInfo(0));
2920 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
2923 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
2924 SDValue Arg, SDValue PtrOff, int SPDiff,
2925 unsigned ArgOffset, bool isPPC64, bool isTailCall,
2926 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
2927 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
2929 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2934 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
2936 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
2937 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
2938 DAG.getConstant(ArgOffset, PtrVT));
2940 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2941 MachinePointerInfo(), false, false, 0));
2942 // Calculate and remember argument location.
2943 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
2948 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
2949 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
2950 SDValue LROp, SDValue FPOp, bool isDarwinABI,
2951 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
2952 MachineFunction &MF = DAG.getMachineFunction();
2954 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
2955 // might overwrite each other in case of tail call optimization.
2956 SmallVector<SDValue, 8> MemOpChains2;
2957 // Do not flag preceding copytoreg stuff together with the following stuff.
2959 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
2961 if (!MemOpChains2.empty())
2962 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2963 &MemOpChains2[0], MemOpChains2.size());
2965 // Store the return address to the appropriate stack slot.
2966 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
2967 isPPC64, isDarwinABI, dl);
2969 // Emit callseq_end just before tailcall node.
2970 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2971 DAG.getIntPtrConstant(0, true), InFlag);
2972 InFlag = Chain.getValue(1);
2976 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
2977 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
2978 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
2979 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
2980 const PPCSubtarget &PPCSubTarget) {
2982 bool isPPC64 = PPCSubTarget.isPPC64();
2983 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
2985 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2986 NodeTys.push_back(MVT::Other); // Returns a chain
2987 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
2989 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
2991 bool needIndirectCall = true;
2992 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
2993 // If this is an absolute destination address, use the munged value.
2994 Callee = SDValue(Dest, 0);
2995 needIndirectCall = false;
2998 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2999 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3000 // Use indirect calls for ALL functions calls in JIT mode, since the
3001 // far-call stubs may be outside relocation limits for a BL instruction.
3002 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3003 unsigned OpFlags = 0;
3004 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3005 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3006 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3007 (G->getGlobal()->isDeclaration() ||
3008 G->getGlobal()->isWeakForLinker())) {
3009 // PC-relative references to external symbols should go through $stub,
3010 // unless we're building with the leopard linker or later, which
3011 // automatically synthesizes these stubs.
3012 OpFlags = PPCII::MO_DARWIN_STUB;
3015 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3016 // every direct call is) turn it into a TargetGlobalAddress /
3017 // TargetExternalSymbol node so that legalize doesn't hack it.
3018 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3019 Callee.getValueType(),
3021 needIndirectCall = false;
3025 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3026 unsigned char OpFlags = 0;
3028 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3029 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3030 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3031 // PC-relative references to external symbols should go through $stub,
3032 // unless we're building with the leopard linker or later, which
3033 // automatically synthesizes these stubs.
3034 OpFlags = PPCII::MO_DARWIN_STUB;
3037 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3039 needIndirectCall = false;
3042 if (needIndirectCall) {
3043 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3044 // to do the call, we can't use PPCISD::CALL.
3045 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3047 if (isSVR4ABI && isPPC64) {
3048 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3049 // entry point, but to the function descriptor (the function entry point
3050 // address is part of the function descriptor though).
3051 // The function descriptor is a three doubleword structure with the
3052 // following fields: function entry point, TOC base address and
3053 // environment pointer.
3054 // Thus for a call through a function pointer, the following actions need
3056 // 1. Save the TOC of the caller in the TOC save area of its stack
3057 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3058 // 2. Load the address of the function entry point from the function
3060 // 3. Load the TOC of the callee from the function descriptor into r2.
3061 // 4. Load the environment pointer from the function descriptor into
3063 // 5. Branch to the function entry point address.
3064 // 6. On return of the callee, the TOC of the caller needs to be
3065 // restored (this is done in FinishCall()).
3067 // All those operations are flagged together to ensure that no other
3068 // operations can be scheduled in between. E.g. without flagging the
3069 // operations together, a TOC access in the caller could be scheduled
3070 // between the load of the callee TOC and the branch to the callee, which
3071 // results in the TOC access going through the TOC of the callee instead
3072 // of going through the TOC of the caller, which leads to incorrect code.
3074 // Load the address of the function entry point from the function
3076 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3077 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3078 InFlag.getNode() ? 3 : 2);
3079 Chain = LoadFuncPtr.getValue(1);
3080 InFlag = LoadFuncPtr.getValue(2);
3082 // Load environment pointer into r11.
3083 // Offset of the environment pointer within the function descriptor.
3084 SDValue PtrOff = DAG.getIntPtrConstant(16);
3086 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3087 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3089 Chain = LoadEnvPtr.getValue(1);
3090 InFlag = LoadEnvPtr.getValue(2);
3092 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3094 Chain = EnvVal.getValue(0);
3095 InFlag = EnvVal.getValue(1);
3097 // Load TOC of the callee into r2. We are using a target-specific load
3098 // with r2 hard coded, because the result of a target-independent load
3099 // would never go directly into r2, since r2 is a reserved register (which
3100 // prevents the register allocator from allocating it), resulting in an
3101 // additional register being allocated and an unnecessary move instruction
3103 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3104 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3106 Chain = LoadTOCPtr.getValue(0);
3107 InFlag = LoadTOCPtr.getValue(1);
3109 MTCTROps[0] = Chain;
3110 MTCTROps[1] = LoadFuncPtr;
3111 MTCTROps[2] = InFlag;
3114 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3115 2 + (InFlag.getNode() != 0));
3116 InFlag = Chain.getValue(1);
3119 NodeTys.push_back(MVT::Other);
3120 NodeTys.push_back(MVT::Glue);
3121 Ops.push_back(Chain);
3122 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
3124 // Add CTR register as callee so a bctr can be emitted later.
3126 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3129 // If this is a direct call, pass the chain and the callee.
3130 if (Callee.getNode()) {
3131 Ops.push_back(Chain);
3132 Ops.push_back(Callee);
3134 // If this is a tail call add stack pointer delta.
3136 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3138 // Add argument registers to the end of the list so that they are known live
3140 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3141 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3142 RegsToPass[i].second.getValueType()));
3148 bool isLocalCall(const SDValue &Callee)
3150 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3151 return !G->getGlobal()->isDeclaration() &&
3152 !G->getGlobal()->isWeakForLinker();
3157 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3158 CallingConv::ID CallConv, bool isVarArg,
3159 const SmallVectorImpl<ISD::InputArg> &Ins,
3160 DebugLoc dl, SelectionDAG &DAG,
3161 SmallVectorImpl<SDValue> &InVals) const {
3163 SmallVector<CCValAssign, 16> RVLocs;
3164 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3165 getTargetMachine(), RVLocs, *DAG.getContext());
3166 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3168 // Copy all of the result registers out of their specified physreg.
3169 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3170 CCValAssign &VA = RVLocs[i];
3171 EVT VT = VA.getValVT();
3172 assert(VA.isRegLoc() && "Can only return in registers!");
3173 Chain = DAG.getCopyFromReg(Chain, dl,
3174 VA.getLocReg(), VT, InFlag).getValue(1);
3175 InVals.push_back(Chain.getValue(0));
3176 InFlag = Chain.getValue(2);
3183 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3184 bool isTailCall, bool isVarArg,
3186 SmallVector<std::pair<unsigned, SDValue>, 8>
3188 SDValue InFlag, SDValue Chain,
3190 int SPDiff, unsigned NumBytes,
3191 const SmallVectorImpl<ISD::InputArg> &Ins,
3192 SmallVectorImpl<SDValue> &InVals) const {
3193 std::vector<EVT> NodeTys;
3194 SmallVector<SDValue, 8> Ops;
3195 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3196 isTailCall, RegsToPass, Ops, NodeTys,
3199 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3200 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3201 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3203 // When performing tail call optimization the callee pops its arguments off
3204 // the stack. Account for this here so these bytes can be pushed back on in
3205 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
3206 int BytesCalleePops =
3207 (CallConv == CallingConv::Fast &&
3208 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3210 // Add a register mask operand representing the call-preserved registers.
3211 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3212 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3213 assert(Mask && "Missing call preserved mask for calling convention");
3214 Ops.push_back(DAG.getRegisterMask(Mask));
3216 if (InFlag.getNode())
3217 Ops.push_back(InFlag);
3221 // If this is the first return lowered for this function, add the regs
3222 // to the liveout set for the function.
3223 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3224 SmallVector<CCValAssign, 16> RVLocs;
3225 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3226 getTargetMachine(), RVLocs, *DAG.getContext());
3227 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3228 for (unsigned i = 0; i != RVLocs.size(); ++i)
3229 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3232 assert(((Callee.getOpcode() == ISD::Register &&
3233 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3234 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3235 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3236 isa<ConstantSDNode>(Callee)) &&
3237 "Expecting an global address, external symbol, absolute value or register");
3239 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3242 // Add a NOP immediately after the branch instruction when using the 64-bit
3243 // SVR4 ABI. At link time, if caller and callee are in a different module and
3244 // thus have a different TOC, the call will be replaced with a call to a stub
3245 // function which saves the current TOC, loads the TOC of the callee and
3246 // branches to the callee. The NOP will be replaced with a load instruction
3247 // which restores the TOC of the caller from the TOC save slot of the current
3248 // stack frame. If caller and callee belong to the same module (and have the
3249 // same TOC), the NOP will remain unchanged.
3251 bool needsTOCRestore = false;
3252 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3253 if (CallOpc == PPCISD::BCTRL_SVR4) {
3254 // This is a call through a function pointer.
3255 // Restore the caller TOC from the save area into R2.
3256 // See PrepareCall() for more information about calls through function
3257 // pointers in the 64-bit SVR4 ABI.
3258 // We are using a target-specific load with r2 hard coded, because the
3259 // result of a target-independent load would never go directly into r2,
3260 // since r2 is a reserved register (which prevents the register allocator
3261 // from allocating it), resulting in an additional register being
3262 // allocated and an unnecessary move instruction being generated.
3263 needsTOCRestore = true;
3264 } else if ((CallOpc == PPCISD::CALL_SVR4) && !isLocalCall(Callee)) {
3265 // Otherwise insert NOP for non-local calls.
3266 CallOpc = PPCISD::CALL_NOP_SVR4;
3270 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3271 InFlag = Chain.getValue(1);
3273 if (needsTOCRestore) {
3274 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3275 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3276 InFlag = Chain.getValue(1);
3279 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3280 DAG.getIntPtrConstant(BytesCalleePops, true),
3283 InFlag = Chain.getValue(1);
3285 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3286 Ins, dl, DAG, InVals);
3290 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3291 SmallVectorImpl<SDValue> &InVals) const {
3292 SelectionDAG &DAG = CLI.DAG;
3293 DebugLoc &dl = CLI.DL;
3294 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3295 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3296 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3297 SDValue Chain = CLI.Chain;
3298 SDValue Callee = CLI.Callee;
3299 bool &isTailCall = CLI.IsTailCall;
3300 CallingConv::ID CallConv = CLI.CallConv;
3301 bool isVarArg = CLI.IsVarArg;
3304 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3307 if (PPCSubTarget.isSVR4ABI()) {
3308 if (PPCSubTarget.isPPC64())
3309 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3310 isTailCall, Outs, OutVals, Ins,
3313 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3314 isTailCall, Outs, OutVals, Ins,
3318 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3319 isTailCall, Outs, OutVals, Ins,
3324 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3325 CallingConv::ID CallConv, bool isVarArg,
3327 const SmallVectorImpl<ISD::OutputArg> &Outs,
3328 const SmallVectorImpl<SDValue> &OutVals,
3329 const SmallVectorImpl<ISD::InputArg> &Ins,
3330 DebugLoc dl, SelectionDAG &DAG,
3331 SmallVectorImpl<SDValue> &InVals) const {
3332 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3333 // of the 32-bit SVR4 ABI stack frame layout.
3335 assert((CallConv == CallingConv::C ||
3336 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3338 unsigned PtrByteSize = 4;
3340 MachineFunction &MF = DAG.getMachineFunction();
3342 // Mark this function as potentially containing a function that contains a
3343 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3344 // and restoring the callers stack pointer in this functions epilog. This is
3345 // done because by tail calling the called function might overwrite the value
3346 // in this function's (MF) stack pointer stack slot 0(SP).
3347 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3348 CallConv == CallingConv::Fast)
3349 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3351 // Count how many bytes are to be pushed on the stack, including the linkage
3352 // area, parameter list area and the part of the local variable space which
3353 // contains copies of aggregates which are passed by value.
3355 // Assign locations to all of the outgoing arguments.
3356 SmallVector<CCValAssign, 16> ArgLocs;
3357 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3358 getTargetMachine(), ArgLocs, *DAG.getContext());
3360 // Reserve space for the linkage area on the stack.
3361 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3364 // Handle fixed and variable vector arguments differently.
3365 // Fixed vector arguments go into registers as long as registers are
3366 // available. Variable vector arguments always go into memory.
3367 unsigned NumArgs = Outs.size();
3369 for (unsigned i = 0; i != NumArgs; ++i) {
3370 MVT ArgVT = Outs[i].VT;
3371 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3374 if (Outs[i].IsFixed) {
3375 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3378 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3384 errs() << "Call operand #" << i << " has unhandled type "
3385 << EVT(ArgVT).getEVTString() << "\n";
3387 llvm_unreachable(0);
3391 // All arguments are treated the same.
3392 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4);
3395 // Assign locations to all of the outgoing aggregate by value arguments.
3396 SmallVector<CCValAssign, 16> ByValArgLocs;
3397 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3398 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3400 // Reserve stack space for the allocations in CCInfo.
3401 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3403 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal);
3405 // Size of the linkage area, parameter list area and the part of the local
3406 // space variable where copies of aggregates which are passed by value are
3408 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3410 // Calculate by how many bytes the stack has to be adjusted in case of tail
3411 // call optimization.
3412 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3414 // Adjust the stack pointer for the new arguments...
3415 // These operations are automatically eliminated by the prolog/epilog pass
3416 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3417 SDValue CallSeqStart = Chain;
3419 // Load the return address and frame pointer so it can be moved somewhere else
3422 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3425 // Set up a copy of the stack pointer for use loading and storing any
3426 // arguments that may not fit in the registers available for argument
3428 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3430 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3431 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3432 SmallVector<SDValue, 8> MemOpChains;
3434 bool seenFloatArg = false;
3435 // Walk the register/memloc assignments, inserting copies/loads.
3436 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3439 CCValAssign &VA = ArgLocs[i];
3440 SDValue Arg = OutVals[i];
3441 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3443 if (Flags.isByVal()) {
3444 // Argument is an aggregate which is passed by value, thus we need to
3445 // create a copy of it in the local variable space of the current stack
3446 // frame (which is the stack frame of the caller) and pass the address of
3447 // this copy to the callee.
3448 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3449 CCValAssign &ByValVA = ByValArgLocs[j++];
3450 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3452 // Memory reserved in the local variable space of the callers stack frame.
3453 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3455 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3456 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3458 // Create a copy of the argument in the local area of the current
3460 SDValue MemcpyCall =
3461 CreateCopyOfByValArgument(Arg, PtrOff,
3462 CallSeqStart.getNode()->getOperand(0),
3465 // This must go outside the CALLSEQ_START..END.
3466 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3467 CallSeqStart.getNode()->getOperand(1));
3468 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3469 NewCallSeqStart.getNode());
3470 Chain = CallSeqStart = NewCallSeqStart;
3472 // Pass the address of the aggregate copy on the stack either in a
3473 // physical register or in the parameter list area of the current stack
3474 // frame to the callee.
3478 if (VA.isRegLoc()) {
3479 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3480 // Put argument in a physical register.
3481 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3483 // Put argument in the parameter list area of the current stack frame.
3484 assert(VA.isMemLoc());
3485 unsigned LocMemOffset = VA.getLocMemOffset();
3488 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3489 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3491 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3492 MachinePointerInfo(),
3495 // Calculate and remember argument location.
3496 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3502 if (!MemOpChains.empty())
3503 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3504 &MemOpChains[0], MemOpChains.size());
3506 // Build a sequence of copy-to-reg nodes chained together with token chain
3507 // and flag operands which copy the outgoing args into the appropriate regs.
3509 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3510 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3511 RegsToPass[i].second, InFlag);
3512 InFlag = Chain.getValue(1);
3515 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3518 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3519 SDValue Ops[] = { Chain, InFlag };
3521 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3522 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3524 InFlag = Chain.getValue(1);
3528 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3529 false, TailCallArguments);
3531 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3532 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3536 // Copy an argument into memory, being careful to do this outside the
3537 // call sequence for the call to which the argument belongs.
3539 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3540 SDValue CallSeqStart,
3541 ISD::ArgFlagsTy Flags,
3543 DebugLoc dl) const {
3544 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3545 CallSeqStart.getNode()->getOperand(0),
3547 // The MEMCPY must go outside the CALLSEQ_START..END.
3548 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3549 CallSeqStart.getNode()->getOperand(1));
3550 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3551 NewCallSeqStart.getNode());
3552 return NewCallSeqStart;
3556 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3557 CallingConv::ID CallConv, bool isVarArg,
3559 const SmallVectorImpl<ISD::OutputArg> &Outs,
3560 const SmallVectorImpl<SDValue> &OutVals,
3561 const SmallVectorImpl<ISD::InputArg> &Ins,
3562 DebugLoc dl, SelectionDAG &DAG,
3563 SmallVectorImpl<SDValue> &InVals) const {
3565 unsigned NumOps = Outs.size();
3567 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3568 unsigned PtrByteSize = 8;
3570 MachineFunction &MF = DAG.getMachineFunction();
3572 // Mark this function as potentially containing a function that contains a
3573 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3574 // and restoring the callers stack pointer in this functions epilog. This is
3575 // done because by tail calling the called function might overwrite the value
3576 // in this function's (MF) stack pointer stack slot 0(SP).
3577 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3578 CallConv == CallingConv::Fast)
3579 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3581 unsigned nAltivecParamsAtEnd = 0;
3583 // Count how many bytes are to be pushed on the stack, including the linkage
3584 // area, and parameter passing area. We start with at least 48 bytes, which
3585 // is reserved space for [SP][CR][LR][3 x unused].
3586 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3589 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3590 Outs, OutVals, nAltivecParamsAtEnd);
3592 // Calculate by how many bytes the stack has to be adjusted in case of tail
3593 // call optimization.
3594 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3596 // To protect arguments on the stack from being clobbered in a tail call,
3597 // force all the loads to happen before doing any other lowering.
3599 Chain = DAG.getStackArgumentTokenFactor(Chain);
3601 // Adjust the stack pointer for the new arguments...
3602 // These operations are automatically eliminated by the prolog/epilog pass
3603 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3604 SDValue CallSeqStart = Chain;
3606 // Load the return address and frame pointer so it can be move somewhere else
3609 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3612 // Set up a copy of the stack pointer for use loading and storing any
3613 // arguments that may not fit in the registers available for argument
3615 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3617 // Figure out which arguments are going to go in registers, and which in
3618 // memory. Also, if this is a vararg function, floating point operations
3619 // must be stored to our stack, and loaded into integer regs as well, if
3620 // any integer regs are available for argument passing.
3621 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3622 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3624 static const uint16_t GPR[] = {
3625 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3626 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3628 static const uint16_t *FPR = GetFPR();
3630 static const uint16_t VR[] = {
3631 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3632 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3634 const unsigned NumGPRs = array_lengthof(GPR);
3635 const unsigned NumFPRs = 13;
3636 const unsigned NumVRs = array_lengthof(VR);
3638 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3639 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3641 SmallVector<SDValue, 8> MemOpChains;
3642 for (unsigned i = 0; i != NumOps; ++i) {
3643 SDValue Arg = OutVals[i];
3644 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3646 // PtrOff will be used to store the current argument to the stack if a
3647 // register cannot be found for it.
3650 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3652 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3654 // Promote integers to 64-bit values.
3655 if (Arg.getValueType() == MVT::i32) {
3656 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3657 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3658 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3661 // FIXME memcpy is used way more than necessary. Correctness first.
3662 // Note: "by value" is code for passing a structure by value, not
3664 if (Flags.isByVal()) {
3665 // Note: Size includes alignment padding, so
3666 // struct x { short a; char b; }
3667 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3668 // These are the proper values we need for right-justifying the
3669 // aggregate in a parameter register.
3670 unsigned Size = Flags.getByValSize();
3672 // An empty aggregate parameter takes up no storage and no
3677 // All aggregates smaller than 8 bytes must be passed right-justified.
3678 if (Size==1 || Size==2 || Size==4) {
3679 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3680 if (GPR_idx != NumGPRs) {
3681 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3682 MachinePointerInfo(), VT,
3684 MemOpChains.push_back(Load.getValue(1));
3685 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3687 ArgOffset += PtrByteSize;
3692 if (GPR_idx == NumGPRs && Size < 8) {
3693 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3694 PtrOff.getValueType());
3695 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3696 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3699 ArgOffset += PtrByteSize;
3702 // Copy entire object into memory. There are cases where gcc-generated
3703 // code assumes it is there, even if it could be put entirely into
3704 // registers. (This is not what the doc says.)
3706 // FIXME: The above statement is likely due to a misunderstanding of the
3707 // documents. All arguments must be copied into the parameter area BY
3708 // THE CALLEE in the event that the callee takes the address of any
3709 // formal argument. That has not yet been implemented. However, it is
3710 // reasonable to use the stack area as a staging area for the register
3713 // Skip this for small aggregates, as we will use the same slot for a
3714 // right-justified copy, below.
3716 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3720 // When a register is available, pass a small aggregate right-justified.
3721 if (Size < 8 && GPR_idx != NumGPRs) {
3722 // The easiest way to get this right-justified in a register
3723 // is to copy the structure into the rightmost portion of a
3724 // local variable slot, then load the whole slot into the
3726 // FIXME: The memcpy seems to produce pretty awful code for
3727 // small aggregates, particularly for packed ones.
3728 // FIXME: It would be preferable to use the slot in the
3729 // parameter save area instead of a new local variable.
3730 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3731 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3732 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3736 // Load the slot into the register.
3737 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3738 MachinePointerInfo(),
3739 false, false, false, 0);
3740 MemOpChains.push_back(Load.getValue(1));
3741 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3743 // Done with this argument.
3744 ArgOffset += PtrByteSize;
3748 // For aggregates larger than PtrByteSize, copy the pieces of the
3749 // object that fit into registers from the parameter save area.
3750 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3751 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3752 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3753 if (GPR_idx != NumGPRs) {
3754 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3755 MachinePointerInfo(),
3756 false, false, false, 0);
3757 MemOpChains.push_back(Load.getValue(1));
3758 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3759 ArgOffset += PtrByteSize;
3761 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3768 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3769 default: llvm_unreachable("Unexpected ValueType for argument!");
3772 if (GPR_idx != NumGPRs) {
3773 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3775 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3776 true, isTailCall, false, MemOpChains,
3777 TailCallArguments, dl);
3779 ArgOffset += PtrByteSize;
3783 if (FPR_idx != NumFPRs) {
3784 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3787 // A single float or an aggregate containing only a single float
3788 // must be passed right-justified in the stack doubleword, and
3789 // in the GPR, if one is available.
3791 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3792 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3793 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3797 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3798 MachinePointerInfo(), false, false, 0);
3799 MemOpChains.push_back(Store);
3801 // Float varargs are always shadowed in available integer registers
3802 if (GPR_idx != NumGPRs) {
3803 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3804 MachinePointerInfo(), false, false,
3806 MemOpChains.push_back(Load.getValue(1));
3807 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3809 } else if (GPR_idx != NumGPRs)
3810 // If we have any FPRs remaining, we may also have GPRs remaining.
3813 // Single-precision floating-point values are mapped to the
3814 // second (rightmost) word of the stack doubleword.
3815 if (Arg.getValueType() == MVT::f32) {
3816 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3817 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3820 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3821 true, isTailCall, false, MemOpChains,
3822 TailCallArguments, dl);
3831 // These go aligned on the stack, or in the corresponding R registers
3832 // when within range. The Darwin PPC ABI doc claims they also go in
3833 // V registers; in fact gcc does this only for arguments that are
3834 // prototyped, not for those that match the ... We do it for all
3835 // arguments, seems to work.
3836 while (ArgOffset % 16 !=0) {
3837 ArgOffset += PtrByteSize;
3838 if (GPR_idx != NumGPRs)
3841 // We could elide this store in the case where the object fits
3842 // entirely in R registers. Maybe later.
3843 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3844 DAG.getConstant(ArgOffset, PtrVT));
3845 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3846 MachinePointerInfo(), false, false, 0);
3847 MemOpChains.push_back(Store);
3848 if (VR_idx != NumVRs) {
3849 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3850 MachinePointerInfo(),
3851 false, false, false, 0);
3852 MemOpChains.push_back(Load.getValue(1));
3853 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3856 for (unsigned i=0; i<16; i+=PtrByteSize) {
3857 if (GPR_idx == NumGPRs)
3859 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3860 DAG.getConstant(i, PtrVT));
3861 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3862 false, false, false, 0);
3863 MemOpChains.push_back(Load.getValue(1));
3864 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3869 // Non-varargs Altivec params generally go in registers, but have
3870 // stack space allocated at the end.
3871 if (VR_idx != NumVRs) {
3872 // Doesn't have GPR space allocated.
3873 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3875 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3876 true, isTailCall, true, MemOpChains,
3877 TailCallArguments, dl);
3884 if (!MemOpChains.empty())
3885 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3886 &MemOpChains[0], MemOpChains.size());
3888 // Check if this is an indirect call (MTCTR/BCTRL).
3889 // See PrepareCall() for more information about calls through function
3890 // pointers in the 64-bit SVR4 ABI.
3892 !dyn_cast<GlobalAddressSDNode>(Callee) &&
3893 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
3894 !isBLACompatibleAddress(Callee, DAG)) {
3895 // Load r2 into a virtual register and store it to the TOC save area.
3896 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
3897 // TOC save area offset.
3898 SDValue PtrOff = DAG.getIntPtrConstant(40);
3899 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3900 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
3902 // R12 must contain the address of an indirect callee. This does not
3903 // mean the MTCTR instruction must use R12; it's easier to model this
3904 // as an extra parameter, so do that.
3905 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
3908 // Build a sequence of copy-to-reg nodes chained together with token chain
3909 // and flag operands which copy the outgoing args into the appropriate regs.
3911 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3912 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3913 RegsToPass[i].second, InFlag);
3914 InFlag = Chain.getValue(1);
3918 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
3919 FPOp, true, TailCallArguments);
3921 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3922 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3927 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
3928 CallingConv::ID CallConv, bool isVarArg,
3930 const SmallVectorImpl<ISD::OutputArg> &Outs,
3931 const SmallVectorImpl<SDValue> &OutVals,
3932 const SmallVectorImpl<ISD::InputArg> &Ins,
3933 DebugLoc dl, SelectionDAG &DAG,
3934 SmallVectorImpl<SDValue> &InVals) const {
3936 unsigned NumOps = Outs.size();
3938 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3939 bool isPPC64 = PtrVT == MVT::i64;
3940 unsigned PtrByteSize = isPPC64 ? 8 : 4;
3942 MachineFunction &MF = DAG.getMachineFunction();
3944 // Mark this function as potentially containing a function that contains a
3945 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3946 // and restoring the callers stack pointer in this functions epilog. This is
3947 // done because by tail calling the called function might overwrite the value
3948 // in this function's (MF) stack pointer stack slot 0(SP).
3949 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3950 CallConv == CallingConv::Fast)
3951 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3953 unsigned nAltivecParamsAtEnd = 0;
3955 // Count how many bytes are to be pushed on the stack, including the linkage
3956 // area, and parameter passing area. We start with 24/48 bytes, which is
3957 // prereserved space for [SP][CR][LR][3 x unused].
3959 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
3961 nAltivecParamsAtEnd);
3963 // Calculate by how many bytes the stack has to be adjusted in case of tail
3964 // call optimization.
3965 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3967 // To protect arguments on the stack from being clobbered in a tail call,
3968 // force all the loads to happen before doing any other lowering.
3970 Chain = DAG.getStackArgumentTokenFactor(Chain);
3972 // Adjust the stack pointer for the new arguments...
3973 // These operations are automatically eliminated by the prolog/epilog pass
3974 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3975 SDValue CallSeqStart = Chain;
3977 // Load the return address and frame pointer so it can be move somewhere else
3980 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3983 // Set up a copy of the stack pointer for use loading and storing any
3984 // arguments that may not fit in the registers available for argument
3988 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3990 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3992 // Figure out which arguments are going to go in registers, and which in
3993 // memory. Also, if this is a vararg function, floating point operations
3994 // must be stored to our stack, and loaded into integer regs as well, if
3995 // any integer regs are available for argument passing.
3996 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
3997 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3999 static const uint16_t GPR_32[] = { // 32-bit registers.
4000 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4001 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4003 static const uint16_t GPR_64[] = { // 64-bit registers.
4004 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4005 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4007 static const uint16_t *FPR = GetFPR();
4009 static const uint16_t VR[] = {
4010 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4011 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4013 const unsigned NumGPRs = array_lengthof(GPR_32);
4014 const unsigned NumFPRs = 13;
4015 const unsigned NumVRs = array_lengthof(VR);
4017 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4019 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4020 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4022 SmallVector<SDValue, 8> MemOpChains;
4023 for (unsigned i = 0; i != NumOps; ++i) {
4024 SDValue Arg = OutVals[i];
4025 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4027 // PtrOff will be used to store the current argument to the stack if a
4028 // register cannot be found for it.
4031 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4033 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4035 // On PPC64, promote integers to 64-bit values.
4036 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4037 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4038 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4039 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4042 // FIXME memcpy is used way more than necessary. Correctness first.
4043 // Note: "by value" is code for passing a structure by value, not
4045 if (Flags.isByVal()) {
4046 unsigned Size = Flags.getByValSize();
4047 // Very small objects are passed right-justified. Everything else is
4048 // passed left-justified.
4049 if (Size==1 || Size==2) {
4050 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4051 if (GPR_idx != NumGPRs) {
4052 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4053 MachinePointerInfo(), VT,
4055 MemOpChains.push_back(Load.getValue(1));
4056 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4058 ArgOffset += PtrByteSize;
4060 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4061 PtrOff.getValueType());
4062 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4063 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4066 ArgOffset += PtrByteSize;
4070 // Copy entire object into memory. There are cases where gcc-generated
4071 // code assumes it is there, even if it could be put entirely into
4072 // registers. (This is not what the doc says.)
4073 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4077 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4078 // copy the pieces of the object that fit into registers from the
4079 // parameter save area.
4080 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4081 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4082 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4083 if (GPR_idx != NumGPRs) {
4084 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4085 MachinePointerInfo(),
4086 false, false, false, 0);
4087 MemOpChains.push_back(Load.getValue(1));
4088 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4089 ArgOffset += PtrByteSize;
4091 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4098 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4099 default: llvm_unreachable("Unexpected ValueType for argument!");
4102 if (GPR_idx != NumGPRs) {
4103 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4105 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4106 isPPC64, isTailCall, false, MemOpChains,
4107 TailCallArguments, dl);
4109 ArgOffset += PtrByteSize;
4113 if (FPR_idx != NumFPRs) {
4114 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4117 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4118 MachinePointerInfo(), false, false, 0);
4119 MemOpChains.push_back(Store);
4121 // Float varargs are always shadowed in available integer registers
4122 if (GPR_idx != NumGPRs) {
4123 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4124 MachinePointerInfo(), false, false,
4126 MemOpChains.push_back(Load.getValue(1));
4127 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4129 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4130 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4131 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4132 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4133 MachinePointerInfo(),
4134 false, false, false, 0);
4135 MemOpChains.push_back(Load.getValue(1));
4136 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4139 // If we have any FPRs remaining, we may also have GPRs remaining.
4140 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4142 if (GPR_idx != NumGPRs)
4144 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4145 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4149 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4150 isPPC64, isTailCall, false, MemOpChains,
4151 TailCallArguments, dl);
4155 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4162 // These go aligned on the stack, or in the corresponding R registers
4163 // when within range. The Darwin PPC ABI doc claims they also go in
4164 // V registers; in fact gcc does this only for arguments that are
4165 // prototyped, not for those that match the ... We do it for all
4166 // arguments, seems to work.
4167 while (ArgOffset % 16 !=0) {
4168 ArgOffset += PtrByteSize;
4169 if (GPR_idx != NumGPRs)
4172 // We could elide this store in the case where the object fits
4173 // entirely in R registers. Maybe later.
4174 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4175 DAG.getConstant(ArgOffset, PtrVT));
4176 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4177 MachinePointerInfo(), false, false, 0);
4178 MemOpChains.push_back(Store);
4179 if (VR_idx != NumVRs) {
4180 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4181 MachinePointerInfo(),
4182 false, false, false, 0);
4183 MemOpChains.push_back(Load.getValue(1));
4184 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4187 for (unsigned i=0; i<16; i+=PtrByteSize) {
4188 if (GPR_idx == NumGPRs)
4190 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4191 DAG.getConstant(i, PtrVT));
4192 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4193 false, false, false, 0);
4194 MemOpChains.push_back(Load.getValue(1));
4195 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4200 // Non-varargs Altivec params generally go in registers, but have
4201 // stack space allocated at the end.
4202 if (VR_idx != NumVRs) {
4203 // Doesn't have GPR space allocated.
4204 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4205 } else if (nAltivecParamsAtEnd==0) {
4206 // We are emitting Altivec params in order.
4207 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4208 isPPC64, isTailCall, true, MemOpChains,
4209 TailCallArguments, dl);
4215 // If all Altivec parameters fit in registers, as they usually do,
4216 // they get stack space following the non-Altivec parameters. We
4217 // don't track this here because nobody below needs it.
4218 // If there are more Altivec parameters than fit in registers emit
4220 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4222 // Offset is aligned; skip 1st 12 params which go in V registers.
4223 ArgOffset = ((ArgOffset+15)/16)*16;
4225 for (unsigned i = 0; i != NumOps; ++i) {
4226 SDValue Arg = OutVals[i];
4227 EVT ArgType = Outs[i].VT;
4228 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4229 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4232 // We are emitting Altivec params in order.
4233 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4234 isPPC64, isTailCall, true, MemOpChains,
4235 TailCallArguments, dl);
4242 if (!MemOpChains.empty())
4243 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4244 &MemOpChains[0], MemOpChains.size());
4246 // On Darwin, R12 must contain the address of an indirect callee. This does
4247 // not mean the MTCTR instruction must use R12; it's easier to model this as
4248 // an extra parameter, so do that.
4250 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4251 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4252 !isBLACompatibleAddress(Callee, DAG))
4253 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4254 PPC::R12), Callee));
4256 // Build a sequence of copy-to-reg nodes chained together with token chain
4257 // and flag operands which copy the outgoing args into the appropriate regs.
4259 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4260 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4261 RegsToPass[i].second, InFlag);
4262 InFlag = Chain.getValue(1);
4266 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4267 FPOp, true, TailCallArguments);
4269 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4270 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4275 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4276 MachineFunction &MF, bool isVarArg,
4277 const SmallVectorImpl<ISD::OutputArg> &Outs,
4278 LLVMContext &Context) const {
4279 SmallVector<CCValAssign, 16> RVLocs;
4280 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4282 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4286 PPCTargetLowering::LowerReturn(SDValue Chain,
4287 CallingConv::ID CallConv, bool isVarArg,
4288 const SmallVectorImpl<ISD::OutputArg> &Outs,
4289 const SmallVectorImpl<SDValue> &OutVals,
4290 DebugLoc dl, SelectionDAG &DAG) const {
4292 SmallVector<CCValAssign, 16> RVLocs;
4293 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4294 getTargetMachine(), RVLocs, *DAG.getContext());
4295 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4297 // If this is the first return lowered for this function, add the regs to the
4298 // liveout set for the function.
4299 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
4300 for (unsigned i = 0; i != RVLocs.size(); ++i)
4301 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
4306 // Copy the result values into the output registers.
4307 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4308 CCValAssign &VA = RVLocs[i];
4309 assert(VA.isRegLoc() && "Can only return in registers!");
4310 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
4312 Flag = Chain.getValue(1);
4316 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
4318 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
4321 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4322 const PPCSubtarget &Subtarget) const {
4323 // When we pop the dynamic allocation we need to restore the SP link.
4324 DebugLoc dl = Op.getDebugLoc();
4326 // Get the corect type for pointers.
4327 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4329 // Construct the stack pointer operand.
4330 bool isPPC64 = Subtarget.isPPC64();
4331 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4332 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4334 // Get the operands for the STACKRESTORE.
4335 SDValue Chain = Op.getOperand(0);
4336 SDValue SaveSP = Op.getOperand(1);
4338 // Load the old link SP.
4339 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4340 MachinePointerInfo(),
4341 false, false, false, 0);
4343 // Restore the stack pointer.
4344 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4346 // Store the old link SP.
4347 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4354 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4355 MachineFunction &MF = DAG.getMachineFunction();
4356 bool isPPC64 = PPCSubTarget.isPPC64();
4357 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4358 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4360 // Get current frame pointer save index. The users of this index will be
4361 // primarily DYNALLOC instructions.
4362 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4363 int RASI = FI->getReturnAddrSaveIndex();
4365 // If the frame pointer save index hasn't been defined yet.
4367 // Find out what the fix offset of the frame pointer save area.
4368 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4369 // Allocate the frame index for frame pointer save area.
4370 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4372 FI->setReturnAddrSaveIndex(RASI);
4374 return DAG.getFrameIndex(RASI, PtrVT);
4378 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4379 MachineFunction &MF = DAG.getMachineFunction();
4380 bool isPPC64 = PPCSubTarget.isPPC64();
4381 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4382 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4384 // Get current frame pointer save index. The users of this index will be
4385 // primarily DYNALLOC instructions.
4386 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4387 int FPSI = FI->getFramePointerSaveIndex();
4389 // If the frame pointer save index hasn't been defined yet.
4391 // Find out what the fix offset of the frame pointer save area.
4392 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4395 // Allocate the frame index for frame pointer save area.
4396 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4398 FI->setFramePointerSaveIndex(FPSI);
4400 return DAG.getFrameIndex(FPSI, PtrVT);
4403 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4405 const PPCSubtarget &Subtarget) const {
4407 SDValue Chain = Op.getOperand(0);
4408 SDValue Size = Op.getOperand(1);
4409 DebugLoc dl = Op.getDebugLoc();
4411 // Get the corect type for pointers.
4412 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4414 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4415 DAG.getConstant(0, PtrVT), Size);
4416 // Construct a node for the frame pointer save index.
4417 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4418 // Build a DYNALLOC node.
4419 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4420 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4421 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4424 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4426 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4427 // Not FP? Not a fsel.
4428 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4429 !Op.getOperand(2).getValueType().isFloatingPoint())
4432 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4434 // Cannot handle SETEQ/SETNE.
4435 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4437 EVT ResVT = Op.getValueType();
4438 EVT CmpVT = Op.getOperand(0).getValueType();
4439 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4440 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4441 DebugLoc dl = Op.getDebugLoc();
4443 // If the RHS of the comparison is a 0.0, we don't need to do the
4444 // subtraction at all.
4445 if (isFloatingPointZero(RHS))
4447 default: break; // SETUO etc aren't handled by fsel.
4450 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4453 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4454 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4455 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4458 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4461 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4462 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4463 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4464 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4469 default: break; // SETUO etc aren't handled by fsel.
4472 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4473 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4474 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4475 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4478 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4479 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4480 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4481 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4484 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4485 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4486 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4487 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4490 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4491 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4492 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4493 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4498 // FIXME: Split this code up when LegalizeDAGTypes lands.
4499 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4500 DebugLoc dl) const {
4501 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4502 SDValue Src = Op.getOperand(0);
4503 if (Src.getValueType() == MVT::f32)
4504 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4507 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4508 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4510 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4515 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4519 // Convert the FP value to an int value through memory.
4520 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4522 // Emit a store to the stack slot.
4523 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4524 MachinePointerInfo(), false, false, 0);
4526 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4528 if (Op.getValueType() == MVT::i32)
4529 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4530 DAG.getConstant(4, FIPtr.getValueType()));
4531 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4532 false, false, false, 0);
4535 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4536 SelectionDAG &DAG) const {
4537 DebugLoc dl = Op.getDebugLoc();
4538 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4539 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4542 if (Op.getOperand(0).getValueType() == MVT::i64) {
4543 SDValue SINT = Op.getOperand(0);
4544 // When converting to single-precision, we actually need to convert
4545 // to double-precision first and then round to single-precision.
4546 // To avoid double-rounding effects during that operation, we have
4547 // to prepare the input operand. Bits that might be truncated when
4548 // converting to double-precision are replaced by a bit that won't
4549 // be lost at this stage, but is below the single-precision rounding
4552 // However, if -enable-unsafe-fp-math is in effect, accept double
4553 // rounding to avoid the extra overhead.
4554 if (Op.getValueType() == MVT::f32 &&
4555 !DAG.getTarget().Options.UnsafeFPMath) {
4557 // Twiddle input to make sure the low 11 bits are zero. (If this
4558 // is the case, we are guaranteed the value will fit into the 53 bit
4559 // mantissa of an IEEE double-precision value without rounding.)
4560 // If any of those low 11 bits were not zero originally, make sure
4561 // bit 12 (value 2048) is set instead, so that the final rounding
4562 // to single-precision gets the correct result.
4563 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4564 SINT, DAG.getConstant(2047, MVT::i64));
4565 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4566 Round, DAG.getConstant(2047, MVT::i64));
4567 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4568 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4569 Round, DAG.getConstant(-2048, MVT::i64));
4571 // However, we cannot use that value unconditionally: if the magnitude
4572 // of the input value is small, the bit-twiddling we did above might
4573 // end up visibly changing the output. Fortunately, in that case, we
4574 // don't need to twiddle bits since the original input will convert
4575 // exactly to double-precision floating-point already. Therefore,
4576 // construct a conditional to use the original value if the top 11
4577 // bits are all sign-bit copies, and use the rounded value computed
4579 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4580 SINT, DAG.getConstant(53, MVT::i32));
4581 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4582 Cond, DAG.getConstant(1, MVT::i64));
4583 Cond = DAG.getSetCC(dl, MVT::i32,
4584 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4586 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4588 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4589 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4590 if (Op.getValueType() == MVT::f32)
4591 FP = DAG.getNode(ISD::FP_ROUND, dl,
4592 MVT::f32, FP, DAG.getIntPtrConstant(0));
4596 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4597 "Unhandled SINT_TO_FP type in custom expander!");
4598 // Since we only generate this in 64-bit mode, we can take advantage of
4599 // 64-bit registers. In particular, sign extend the input value into the
4600 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4601 // then lfd it and fcfid it.
4602 MachineFunction &MF = DAG.getMachineFunction();
4603 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4604 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4605 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4606 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4608 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4611 // STD the extended value into the stack slot.
4612 MachineMemOperand *MMO =
4613 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4614 MachineMemOperand::MOStore, 8, 8);
4615 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4617 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4618 Ops, 4, MVT::i64, MMO);
4619 // Load the value as a double.
4620 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4621 false, false, false, 0);
4623 // FCFID it and return it.
4624 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4625 if (Op.getValueType() == MVT::f32)
4626 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4630 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4631 SelectionDAG &DAG) const {
4632 DebugLoc dl = Op.getDebugLoc();
4634 The rounding mode is in bits 30:31 of FPSR, and has the following
4641 FLT_ROUNDS, on the other hand, expects the following:
4648 To perform the conversion, we do:
4649 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4652 MachineFunction &MF = DAG.getMachineFunction();
4653 EVT VT = Op.getValueType();
4654 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4655 std::vector<EVT> NodeTys;
4656 SDValue MFFSreg, InFlag;
4658 // Save FP Control Word to register
4659 NodeTys.push_back(MVT::f64); // return register
4660 NodeTys.push_back(MVT::Glue); // unused in this context
4661 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4663 // Save FP register to stack slot
4664 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4665 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4666 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4667 StackSlot, MachinePointerInfo(), false, false,0);
4669 // Load FP Control Word from low 32 bits of stack slot.
4670 SDValue Four = DAG.getConstant(4, PtrVT);
4671 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4672 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4673 false, false, false, 0);
4675 // Transform as necessary
4677 DAG.getNode(ISD::AND, dl, MVT::i32,
4678 CWD, DAG.getConstant(3, MVT::i32));
4680 DAG.getNode(ISD::SRL, dl, MVT::i32,
4681 DAG.getNode(ISD::AND, dl, MVT::i32,
4682 DAG.getNode(ISD::XOR, dl, MVT::i32,
4683 CWD, DAG.getConstant(3, MVT::i32)),
4684 DAG.getConstant(3, MVT::i32)),
4685 DAG.getConstant(1, MVT::i32));
4688 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4690 return DAG.getNode((VT.getSizeInBits() < 16 ?
4691 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4694 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4695 EVT VT = Op.getValueType();
4696 unsigned BitWidth = VT.getSizeInBits();
4697 DebugLoc dl = Op.getDebugLoc();
4698 assert(Op.getNumOperands() == 3 &&
4699 VT == Op.getOperand(1).getValueType() &&
4702 // Expand into a bunch of logical ops. Note that these ops
4703 // depend on the PPC behavior for oversized shift amounts.
4704 SDValue Lo = Op.getOperand(0);
4705 SDValue Hi = Op.getOperand(1);
4706 SDValue Amt = Op.getOperand(2);
4707 EVT AmtVT = Amt.getValueType();
4709 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4710 DAG.getConstant(BitWidth, AmtVT), Amt);
4711 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4712 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4713 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4714 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4715 DAG.getConstant(-BitWidth, AmtVT));
4716 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4717 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4718 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4719 SDValue OutOps[] = { OutLo, OutHi };
4720 return DAG.getMergeValues(OutOps, 2, dl);
4723 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4724 EVT VT = Op.getValueType();
4725 DebugLoc dl = Op.getDebugLoc();
4726 unsigned BitWidth = VT.getSizeInBits();
4727 assert(Op.getNumOperands() == 3 &&
4728 VT == Op.getOperand(1).getValueType() &&
4731 // Expand into a bunch of logical ops. Note that these ops
4732 // depend on the PPC behavior for oversized shift amounts.
4733 SDValue Lo = Op.getOperand(0);
4734 SDValue Hi = Op.getOperand(1);
4735 SDValue Amt = Op.getOperand(2);
4736 EVT AmtVT = Amt.getValueType();
4738 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4739 DAG.getConstant(BitWidth, AmtVT), Amt);
4740 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4741 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4742 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4743 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4744 DAG.getConstant(-BitWidth, AmtVT));
4745 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4746 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4747 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4748 SDValue OutOps[] = { OutLo, OutHi };
4749 return DAG.getMergeValues(OutOps, 2, dl);
4752 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4753 DebugLoc dl = Op.getDebugLoc();
4754 EVT VT = Op.getValueType();
4755 unsigned BitWidth = VT.getSizeInBits();
4756 assert(Op.getNumOperands() == 3 &&
4757 VT == Op.getOperand(1).getValueType() &&
4760 // Expand into a bunch of logical ops, followed by a select_cc.
4761 SDValue Lo = Op.getOperand(0);
4762 SDValue Hi = Op.getOperand(1);
4763 SDValue Amt = Op.getOperand(2);
4764 EVT AmtVT = Amt.getValueType();
4766 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4767 DAG.getConstant(BitWidth, AmtVT), Amt);
4768 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4769 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4770 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4771 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4772 DAG.getConstant(-BitWidth, AmtVT));
4773 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4774 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4775 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4776 Tmp4, Tmp6, ISD::SETLE);
4777 SDValue OutOps[] = { OutLo, OutHi };
4778 return DAG.getMergeValues(OutOps, 2, dl);
4781 //===----------------------------------------------------------------------===//
4782 // Vector related lowering.
4785 /// BuildSplatI - Build a canonical splati of Val with an element size of
4786 /// SplatSize. Cast the result to VT.
4787 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4788 SelectionDAG &DAG, DebugLoc dl) {
4789 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4791 static const EVT VTys[] = { // canonical VT to use for each size.
4792 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4795 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4797 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4801 EVT CanonicalVT = VTys[SplatSize-1];
4803 // Build a canonical splat for this value.
4804 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4805 SmallVector<SDValue, 8> Ops;
4806 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4807 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4808 &Ops[0], Ops.size());
4809 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4812 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
4813 /// specified intrinsic ID.
4814 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
4815 SelectionDAG &DAG, DebugLoc dl,
4816 EVT DestVT = MVT::Other) {
4817 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
4818 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4819 DAG.getConstant(IID, MVT::i32), LHS, RHS);
4822 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
4823 /// specified intrinsic ID.
4824 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
4825 SDValue Op2, SelectionDAG &DAG,
4826 DebugLoc dl, EVT DestVT = MVT::Other) {
4827 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
4828 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4829 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
4833 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
4834 /// amount. The result has the specified value type.
4835 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
4836 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4837 // Force LHS/RHS to be the right type.
4838 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
4839 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
4842 for (unsigned i = 0; i != 16; ++i)
4844 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
4845 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4848 // If this is a case we can't handle, return null and let the default
4849 // expansion code take care of it. If we CAN select this case, and if it
4850 // selects to a single instruction, return Op. Otherwise, if we can codegen
4851 // this case more efficiently than a constant pool load, lower it to the
4852 // sequence of ops that should be used.
4853 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
4854 SelectionDAG &DAG) const {
4855 DebugLoc dl = Op.getDebugLoc();
4856 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4857 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
4859 // Check if this is a splat of a constant value.
4860 APInt APSplatBits, APSplatUndef;
4861 unsigned SplatBitSize;
4863 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
4864 HasAnyUndefs, 0, true) || SplatBitSize > 32)
4867 unsigned SplatBits = APSplatBits.getZExtValue();
4868 unsigned SplatUndef = APSplatUndef.getZExtValue();
4869 unsigned SplatSize = SplatBitSize / 8;
4871 // First, handle single instruction cases.
4874 if (SplatBits == 0) {
4875 // Canonicalize all zero vectors to be v4i32.
4876 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
4877 SDValue Z = DAG.getConstant(0, MVT::i32);
4878 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
4879 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
4884 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
4885 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
4887 if (SextVal >= -16 && SextVal <= 15)
4888 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
4891 // Two instruction sequences.
4893 // If this value is in the range [-32,30] and is even, use:
4894 // tmp = VSPLTI[bhw], result = add tmp, tmp
4895 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
4896 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
4897 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
4898 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4901 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
4902 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
4904 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
4905 // Make -1 and vspltisw -1:
4906 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
4908 // Make the VSLW intrinsic, computing 0x8000_0000.
4909 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
4912 // xor by OnesV to invert it.
4913 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
4914 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4917 // Check to see if this is a wide variety of vsplti*, binop self cases.
4918 static const signed char SplatCsts[] = {
4919 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
4920 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
4923 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
4924 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
4925 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
4926 int i = SplatCsts[idx];
4928 // Figure out what shift amount will be used by altivec if shifted by i in
4930 unsigned TypeShiftAmt = i & (SplatBitSize-1);
4932 // vsplti + shl self.
4933 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
4934 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4935 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4936 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
4937 Intrinsic::ppc_altivec_vslw
4939 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4940 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4943 // vsplti + srl self.
4944 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
4945 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4946 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4947 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
4948 Intrinsic::ppc_altivec_vsrw
4950 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4951 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4954 // vsplti + sra self.
4955 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
4956 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4957 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4958 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
4959 Intrinsic::ppc_altivec_vsraw
4961 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4962 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4965 // vsplti + rol self.
4966 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
4967 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
4968 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
4969 static const unsigned IIDs[] = { // Intrinsic to use for each size.
4970 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
4971 Intrinsic::ppc_altivec_vrlw
4973 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
4974 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
4977 // t = vsplti c, result = vsldoi t, t, 1
4978 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
4979 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4980 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
4982 // t = vsplti c, result = vsldoi t, t, 2
4983 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
4984 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4985 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
4987 // t = vsplti c, result = vsldoi t, t, 3
4988 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
4989 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
4990 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
4994 // Three instruction sequences.
4996 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
4997 if (SextVal >= 0 && SextVal <= 31) {
4998 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
4999 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5000 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
5001 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5003 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
5004 if (SextVal >= -31 && SextVal <= 0) {
5005 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
5006 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5007 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
5008 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5014 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5015 /// the specified operations to build the shuffle.
5016 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5017 SDValue RHS, SelectionDAG &DAG,
5019 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5020 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5021 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5024 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5036 if (OpNum == OP_COPY) {
5037 if (LHSID == (1*9+2)*9+3) return LHS;
5038 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5042 SDValue OpLHS, OpRHS;
5043 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5044 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5048 default: llvm_unreachable("Unknown i32 permute!");
5050 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5051 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5052 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5053 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5056 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5057 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5058 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5059 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5062 for (unsigned i = 0; i != 16; ++i)
5063 ShufIdxs[i] = (i&3)+0;
5066 for (unsigned i = 0; i != 16; ++i)
5067 ShufIdxs[i] = (i&3)+4;
5070 for (unsigned i = 0; i != 16; ++i)
5071 ShufIdxs[i] = (i&3)+8;
5074 for (unsigned i = 0; i != 16; ++i)
5075 ShufIdxs[i] = (i&3)+12;
5078 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5080 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5082 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5084 EVT VT = OpLHS.getValueType();
5085 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5086 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5087 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5088 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5091 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5092 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5093 /// return the code it can be lowered into. Worst case, it can always be
5094 /// lowered into a vperm.
5095 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5096 SelectionDAG &DAG) const {
5097 DebugLoc dl = Op.getDebugLoc();
5098 SDValue V1 = Op.getOperand(0);
5099 SDValue V2 = Op.getOperand(1);
5100 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5101 EVT VT = Op.getValueType();
5103 // Cases that are handled by instructions that take permute immediates
5104 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5105 // selected by the instruction selector.
5106 if (V2.getOpcode() == ISD::UNDEF) {
5107 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5108 PPC::isSplatShuffleMask(SVOp, 2) ||
5109 PPC::isSplatShuffleMask(SVOp, 4) ||
5110 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5111 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5112 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5113 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5114 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5115 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5116 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5117 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5118 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5123 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5124 // and produce a fixed permutation. If any of these match, do not lower to
5126 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5127 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5128 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5129 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5130 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5131 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5132 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5133 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5134 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5137 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5138 // perfect shuffle table to emit an optimal matching sequence.
5139 ArrayRef<int> PermMask = SVOp->getMask();
5141 unsigned PFIndexes[4];
5142 bool isFourElementShuffle = true;
5143 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5144 unsigned EltNo = 8; // Start out undef.
5145 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5146 if (PermMask[i*4+j] < 0)
5147 continue; // Undef, ignore it.
5149 unsigned ByteSource = PermMask[i*4+j];
5150 if ((ByteSource & 3) != j) {
5151 isFourElementShuffle = false;
5156 EltNo = ByteSource/4;
5157 } else if (EltNo != ByteSource/4) {
5158 isFourElementShuffle = false;
5162 PFIndexes[i] = EltNo;
5165 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5166 // perfect shuffle vector to determine if it is cost effective to do this as
5167 // discrete instructions, or whether we should use a vperm.
5168 if (isFourElementShuffle) {
5169 // Compute the index in the perfect shuffle table.
5170 unsigned PFTableIndex =
5171 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5173 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5174 unsigned Cost = (PFEntry >> 30);
5176 // Determining when to avoid vperm is tricky. Many things affect the cost
5177 // of vperm, particularly how many times the perm mask needs to be computed.
5178 // For example, if the perm mask can be hoisted out of a loop or is already
5179 // used (perhaps because there are multiple permutes with the same shuffle
5180 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5181 // the loop requires an extra register.
5183 // As a compromise, we only emit discrete instructions if the shuffle can be
5184 // generated in 3 or fewer operations. When we have loop information
5185 // available, if this block is within a loop, we should avoid using vperm
5186 // for 3-operation perms and use a constant pool load instead.
5188 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5191 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5192 // vector that will get spilled to the constant pool.
5193 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5195 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5196 // that it is in input element units, not in bytes. Convert now.
5197 EVT EltVT = V1.getValueType().getVectorElementType();
5198 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5200 SmallVector<SDValue, 16> ResultMask;
5201 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5202 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5204 for (unsigned j = 0; j != BytesPerElement; ++j)
5205 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5209 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5210 &ResultMask[0], ResultMask.size());
5211 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5214 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5215 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5216 /// information about the intrinsic.
5217 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5219 unsigned IntrinsicID =
5220 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5223 switch (IntrinsicID) {
5224 default: return false;
5225 // Comparison predicates.
5226 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5227 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5228 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5229 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5230 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5231 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5232 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5233 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5234 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5235 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5236 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5237 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5238 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5240 // Normal Comparisons.
5241 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5242 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5243 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5244 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5245 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5246 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5247 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5248 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5249 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5250 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5251 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5252 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5253 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5258 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5259 /// lower, do it, otherwise return null.
5260 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5261 SelectionDAG &DAG) const {
5262 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5263 // opcode number of the comparison.
5264 DebugLoc dl = Op.getDebugLoc();
5267 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5268 return SDValue(); // Don't custom lower most intrinsics.
5270 // If this is a non-dot comparison, make the VCMP node and we are done.
5272 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5273 Op.getOperand(1), Op.getOperand(2),
5274 DAG.getConstant(CompareOpc, MVT::i32));
5275 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5278 // Create the PPCISD altivec 'dot' comparison node.
5280 Op.getOperand(2), // LHS
5281 Op.getOperand(3), // RHS
5282 DAG.getConstant(CompareOpc, MVT::i32)
5284 std::vector<EVT> VTs;
5285 VTs.push_back(Op.getOperand(2).getValueType());
5286 VTs.push_back(MVT::Glue);
5287 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5289 // Now that we have the comparison, emit a copy from the CR to a GPR.
5290 // This is flagged to the above dot comparison.
5291 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5292 DAG.getRegister(PPC::CR6, MVT::i32),
5293 CompNode.getValue(1));
5295 // Unpack the result based on how the target uses it.
5296 unsigned BitNo; // Bit # of CR6.
5297 bool InvertBit; // Invert result?
5298 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5299 default: // Can't happen, don't crash on invalid number though.
5300 case 0: // Return the value of the EQ bit of CR6.
5301 BitNo = 0; InvertBit = false;
5303 case 1: // Return the inverted value of the EQ bit of CR6.
5304 BitNo = 0; InvertBit = true;
5306 case 2: // Return the value of the LT bit of CR6.
5307 BitNo = 2; InvertBit = false;
5309 case 3: // Return the inverted value of the LT bit of CR6.
5310 BitNo = 2; InvertBit = true;
5314 // Shift the bit into the low position.
5315 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5316 DAG.getConstant(8-(3-BitNo), MVT::i32));
5318 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5319 DAG.getConstant(1, MVT::i32));
5321 // If we are supposed to, toggle the bit.
5323 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5324 DAG.getConstant(1, MVT::i32));
5328 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5329 SelectionDAG &DAG) const {
5330 DebugLoc dl = Op.getDebugLoc();
5331 // Create a stack slot that is 16-byte aligned.
5332 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5333 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5334 EVT PtrVT = getPointerTy();
5335 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5337 // Store the input value into Value#0 of the stack slot.
5338 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5339 Op.getOperand(0), FIdx, MachinePointerInfo(),
5342 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5343 false, false, false, 0);
5346 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5347 DebugLoc dl = Op.getDebugLoc();
5348 if (Op.getValueType() == MVT::v4i32) {
5349 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5351 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5352 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5354 SDValue RHSSwap = // = vrlw RHS, 16
5355 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5357 // Shrinkify inputs to v8i16.
5358 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5359 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5360 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5362 // Low parts multiplied together, generating 32-bit results (we ignore the
5364 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5365 LHS, RHS, DAG, dl, MVT::v4i32);
5367 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5368 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5369 // Shift the high parts up 16 bits.
5370 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5372 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5373 } else if (Op.getValueType() == MVT::v8i16) {
5374 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5376 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5378 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5379 LHS, RHS, Zero, DAG, dl);
5380 } else if (Op.getValueType() == MVT::v16i8) {
5381 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5383 // Multiply the even 8-bit parts, producing 16-bit sums.
5384 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5385 LHS, RHS, DAG, dl, MVT::v8i16);
5386 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5388 // Multiply the odd 8-bit parts, producing 16-bit sums.
5389 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5390 LHS, RHS, DAG, dl, MVT::v8i16);
5391 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5393 // Merge the results together.
5395 for (unsigned i = 0; i != 8; ++i) {
5397 Ops[i*2+1] = 2*i+1+16;
5399 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5401 llvm_unreachable("Unknown mul to lower!");
5405 /// LowerOperation - Provide custom lowering hooks for some operations.
5407 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5408 switch (Op.getOpcode()) {
5409 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5410 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5411 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5412 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5413 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5414 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5415 case ISD::SETCC: return LowerSETCC(Op, DAG);
5416 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5417 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5419 return LowerVASTART(Op, DAG, PPCSubTarget);
5422 return LowerVAARG(Op, DAG, PPCSubTarget);
5424 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5425 case ISD::DYNAMIC_STACKALLOC:
5426 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5428 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5429 case ISD::FP_TO_UINT:
5430 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5432 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5433 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5435 // Lower 64-bit shifts.
5436 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5437 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5438 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5440 // Vector-related lowering.
5441 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5442 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5443 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5444 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5445 case ISD::MUL: return LowerMUL(Op, DAG);
5447 // Frame & Return address.
5448 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5449 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5453 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5454 SmallVectorImpl<SDValue>&Results,
5455 SelectionDAG &DAG) const {
5456 const TargetMachine &TM = getTargetMachine();
5457 DebugLoc dl = N->getDebugLoc();
5458 switch (N->getOpcode()) {
5460 llvm_unreachable("Do not know how to custom type legalize this operation!");
5462 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5463 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5466 EVT VT = N->getValueType(0);
5468 if (VT == MVT::i64) {
5469 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5471 Results.push_back(NewNode);
5472 Results.push_back(NewNode.getValue(1));
5476 case ISD::FP_ROUND_INREG: {
5477 assert(N->getValueType(0) == MVT::ppcf128);
5478 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5479 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5480 MVT::f64, N->getOperand(0),
5481 DAG.getIntPtrConstant(0));
5482 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5483 MVT::f64, N->getOperand(0),
5484 DAG.getIntPtrConstant(1));
5486 // This sequence changes FPSCR to do round-to-zero, adds the two halves
5487 // of the long double, and puts FPSCR back the way it was. We do not
5488 // actually model FPSCR.
5489 std::vector<EVT> NodeTys;
5490 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
5492 NodeTys.push_back(MVT::f64); // Return register
5493 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
5494 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5495 MFFSreg = Result.getValue(0);
5496 InFlag = Result.getValue(1);
5499 NodeTys.push_back(MVT::Glue); // Returns a flag
5500 Ops[0] = DAG.getConstant(31, MVT::i32);
5502 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
5503 InFlag = Result.getValue(0);
5506 NodeTys.push_back(MVT::Glue); // Returns a flag
5507 Ops[0] = DAG.getConstant(30, MVT::i32);
5509 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
5510 InFlag = Result.getValue(0);
5513 NodeTys.push_back(MVT::f64); // result of add
5514 NodeTys.push_back(MVT::Glue); // Returns a flag
5518 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
5519 FPreg = Result.getValue(0);
5520 InFlag = Result.getValue(1);
5523 NodeTys.push_back(MVT::f64);
5524 Ops[0] = DAG.getConstant(1, MVT::i32);
5528 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
5529 FPreg = Result.getValue(0);
5531 // We know the low half is about to be thrown away, so just use something
5533 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5537 case ISD::FP_TO_SINT:
5538 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5544 //===----------------------------------------------------------------------===//
5545 // Other Lowering Code
5546 //===----------------------------------------------------------------------===//
5549 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5550 bool is64bit, unsigned BinOpcode) const {
5551 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5552 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5554 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5555 MachineFunction *F = BB->getParent();
5556 MachineFunction::iterator It = BB;
5559 unsigned dest = MI->getOperand(0).getReg();
5560 unsigned ptrA = MI->getOperand(1).getReg();
5561 unsigned ptrB = MI->getOperand(2).getReg();
5562 unsigned incr = MI->getOperand(3).getReg();
5563 DebugLoc dl = MI->getDebugLoc();
5565 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5566 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5567 F->insert(It, loopMBB);
5568 F->insert(It, exitMBB);
5569 exitMBB->splice(exitMBB->begin(), BB,
5570 llvm::next(MachineBasicBlock::iterator(MI)),
5572 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5574 MachineRegisterInfo &RegInfo = F->getRegInfo();
5575 unsigned TmpReg = (!BinOpcode) ? incr :
5576 RegInfo.createVirtualRegister(
5577 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5578 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5582 // fallthrough --> loopMBB
5583 BB->addSuccessor(loopMBB);
5586 // l[wd]arx dest, ptr
5587 // add r0, dest, incr
5588 // st[wd]cx. r0, ptr
5590 // fallthrough --> exitMBB
5592 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5593 .addReg(ptrA).addReg(ptrB);
5595 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5596 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5597 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5598 BuildMI(BB, dl, TII->get(PPC::BCC))
5599 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5600 BB->addSuccessor(loopMBB);
5601 BB->addSuccessor(exitMBB);
5610 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5611 MachineBasicBlock *BB,
5612 bool is8bit, // operation
5613 unsigned BinOpcode) const {
5614 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5615 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5616 // In 64 bit mode we have to use 64 bits for addresses, even though the
5617 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5618 // registers without caring whether they're 32 or 64, but here we're
5619 // doing actual arithmetic on the addresses.
5620 bool is64bit = PPCSubTarget.isPPC64();
5621 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
5623 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5624 MachineFunction *F = BB->getParent();
5625 MachineFunction::iterator It = BB;
5628 unsigned dest = MI->getOperand(0).getReg();
5629 unsigned ptrA = MI->getOperand(1).getReg();
5630 unsigned ptrB = MI->getOperand(2).getReg();
5631 unsigned incr = MI->getOperand(3).getReg();
5632 DebugLoc dl = MI->getDebugLoc();
5634 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5635 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5636 F->insert(It, loopMBB);
5637 F->insert(It, exitMBB);
5638 exitMBB->splice(exitMBB->begin(), BB,
5639 llvm::next(MachineBasicBlock::iterator(MI)),
5641 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5643 MachineRegisterInfo &RegInfo = F->getRegInfo();
5644 const TargetRegisterClass *RC =
5645 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5646 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5647 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5648 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5649 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5650 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5651 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5652 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5653 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5654 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5655 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5656 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5657 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5659 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5663 // fallthrough --> loopMBB
5664 BB->addSuccessor(loopMBB);
5666 // The 4-byte load must be aligned, while a char or short may be
5667 // anywhere in the word. Hence all this nasty bookkeeping code.
5668 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5669 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5670 // xori shift, shift1, 24 [16]
5671 // rlwinm ptr, ptr1, 0, 0, 29
5672 // slw incr2, incr, shift
5673 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5674 // slw mask, mask2, shift
5676 // lwarx tmpDest, ptr
5677 // add tmp, tmpDest, incr2
5678 // andc tmp2, tmpDest, mask
5679 // and tmp3, tmp, mask
5680 // or tmp4, tmp3, tmp2
5683 // fallthrough --> exitMBB
5684 // srw dest, tmpDest, shift
5685 if (ptrA != ZeroReg) {
5686 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5687 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5688 .addReg(ptrA).addReg(ptrB);
5692 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5693 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5694 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5695 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5697 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5698 .addReg(Ptr1Reg).addImm(0).addImm(61);
5700 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5701 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5702 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5703 .addReg(incr).addReg(ShiftReg);
5705 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5707 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5708 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5710 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5711 .addReg(Mask2Reg).addReg(ShiftReg);
5714 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5715 .addReg(ZeroReg).addReg(PtrReg);
5717 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5718 .addReg(Incr2Reg).addReg(TmpDestReg);
5719 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5720 .addReg(TmpDestReg).addReg(MaskReg);
5721 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5722 .addReg(TmpReg).addReg(MaskReg);
5723 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5724 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5725 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5726 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5727 BuildMI(BB, dl, TII->get(PPC::BCC))
5728 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5729 BB->addSuccessor(loopMBB);
5730 BB->addSuccessor(exitMBB);
5735 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5741 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5742 MachineBasicBlock *BB) const {
5743 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5745 // To "insert" these instructions we actually have to insert their
5746 // control-flow patterns.
5747 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5748 MachineFunction::iterator It = BB;
5751 MachineFunction *F = BB->getParent();
5753 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5754 MI->getOpcode() == PPC::SELECT_CC_I8)) {
5755 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
5756 PPC::ISEL8 : PPC::ISEL;
5757 unsigned SelectPred = MI->getOperand(4).getImm();
5758 DebugLoc dl = MI->getDebugLoc();
5760 // The SelectPred is ((BI << 5) | BO) for a BCC
5761 unsigned BO = SelectPred & 0xF;
5762 assert((BO == 12 || BO == 4) && "invalid predicate BO field for isel");
5764 unsigned TrueOpNo, FalseOpNo;
5771 SelectPred = PPC::InvertPredicate((PPC::Predicate)SelectPred);
5774 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
5775 .addReg(MI->getOperand(TrueOpNo).getReg())
5776 .addReg(MI->getOperand(FalseOpNo).getReg())
5777 .addImm(SelectPred).addReg(MI->getOperand(1).getReg());
5778 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5779 MI->getOpcode() == PPC::SELECT_CC_I8 ||
5780 MI->getOpcode() == PPC::SELECT_CC_F4 ||
5781 MI->getOpcode() == PPC::SELECT_CC_F8 ||
5782 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
5785 // The incoming instruction knows the destination vreg to set, the
5786 // condition code register to branch on, the true/false values to
5787 // select between, and a branch opcode to use.
5792 // cmpTY ccX, r1, r2
5794 // fallthrough --> copy0MBB
5795 MachineBasicBlock *thisMBB = BB;
5796 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5797 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
5798 unsigned SelectPred = MI->getOperand(4).getImm();
5799 DebugLoc dl = MI->getDebugLoc();
5800 F->insert(It, copy0MBB);
5801 F->insert(It, sinkMBB);
5803 // Transfer the remainder of BB and its successor edges to sinkMBB.
5804 sinkMBB->splice(sinkMBB->begin(), BB,
5805 llvm::next(MachineBasicBlock::iterator(MI)),
5807 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5809 // Next, add the true and fallthrough blocks as its successors.
5810 BB->addSuccessor(copy0MBB);
5811 BB->addSuccessor(sinkMBB);
5813 BuildMI(BB, dl, TII->get(PPC::BCC))
5814 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
5817 // %FalseValue = ...
5818 // # fallthrough to sinkMBB
5821 // Update machine-CFG edges
5822 BB->addSuccessor(sinkMBB);
5825 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5828 BuildMI(*BB, BB->begin(), dl,
5829 TII->get(PPC::PHI), MI->getOperand(0).getReg())
5830 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
5831 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5833 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
5834 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
5835 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
5836 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
5837 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
5838 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
5839 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
5840 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
5842 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
5843 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
5844 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
5845 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
5846 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
5847 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
5848 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
5849 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
5851 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
5852 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
5853 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
5854 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
5855 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
5856 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
5857 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
5858 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
5860 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
5861 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
5862 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
5863 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
5864 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
5865 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
5866 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
5867 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
5869 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
5870 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
5871 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
5872 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
5873 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
5874 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
5875 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
5876 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
5878 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
5879 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
5880 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
5881 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
5882 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
5883 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
5884 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
5885 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
5887 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
5888 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
5889 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
5890 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
5891 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
5892 BB = EmitAtomicBinary(MI, BB, false, 0);
5893 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
5894 BB = EmitAtomicBinary(MI, BB, true, 0);
5896 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
5897 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
5898 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
5900 unsigned dest = MI->getOperand(0).getReg();
5901 unsigned ptrA = MI->getOperand(1).getReg();
5902 unsigned ptrB = MI->getOperand(2).getReg();
5903 unsigned oldval = MI->getOperand(3).getReg();
5904 unsigned newval = MI->getOperand(4).getReg();
5905 DebugLoc dl = MI->getDebugLoc();
5907 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
5908 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
5909 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
5910 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5911 F->insert(It, loop1MBB);
5912 F->insert(It, loop2MBB);
5913 F->insert(It, midMBB);
5914 F->insert(It, exitMBB);
5915 exitMBB->splice(exitMBB->begin(), BB,
5916 llvm::next(MachineBasicBlock::iterator(MI)),
5918 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5922 // fallthrough --> loopMBB
5923 BB->addSuccessor(loop1MBB);
5926 // l[wd]arx dest, ptr
5927 // cmp[wd] dest, oldval
5930 // st[wd]cx. newval, ptr
5934 // st[wd]cx. dest, ptr
5937 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5938 .addReg(ptrA).addReg(ptrB);
5939 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
5940 .addReg(oldval).addReg(dest);
5941 BuildMI(BB, dl, TII->get(PPC::BCC))
5942 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
5943 BB->addSuccessor(loop2MBB);
5944 BB->addSuccessor(midMBB);
5947 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5948 .addReg(newval).addReg(ptrA).addReg(ptrB);
5949 BuildMI(BB, dl, TII->get(PPC::BCC))
5950 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
5951 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
5952 BB->addSuccessor(loop1MBB);
5953 BB->addSuccessor(exitMBB);
5956 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5957 .addReg(dest).addReg(ptrA).addReg(ptrB);
5958 BB->addSuccessor(exitMBB);
5963 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
5964 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
5965 // We must use 64-bit registers for addresses when targeting 64-bit,
5966 // since we're actually doing arithmetic on them. Other registers
5968 bool is64bit = PPCSubTarget.isPPC64();
5969 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
5971 unsigned dest = MI->getOperand(0).getReg();
5972 unsigned ptrA = MI->getOperand(1).getReg();
5973 unsigned ptrB = MI->getOperand(2).getReg();
5974 unsigned oldval = MI->getOperand(3).getReg();
5975 unsigned newval = MI->getOperand(4).getReg();
5976 DebugLoc dl = MI->getDebugLoc();
5978 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
5979 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
5980 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
5981 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5982 F->insert(It, loop1MBB);
5983 F->insert(It, loop2MBB);
5984 F->insert(It, midMBB);
5985 F->insert(It, exitMBB);
5986 exitMBB->splice(exitMBB->begin(), BB,
5987 llvm::next(MachineBasicBlock::iterator(MI)),
5989 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5991 MachineRegisterInfo &RegInfo = F->getRegInfo();
5992 const TargetRegisterClass *RC =
5993 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5994 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5995 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5996 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5997 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5998 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
5999 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6000 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6001 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6002 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6003 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6004 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6005 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6006 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6007 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6009 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6010 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
6013 // fallthrough --> loopMBB
6014 BB->addSuccessor(loop1MBB);
6016 // The 4-byte load must be aligned, while a char or short may be
6017 // anywhere in the word. Hence all this nasty bookkeeping code.
6018 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6019 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6020 // xori shift, shift1, 24 [16]
6021 // rlwinm ptr, ptr1, 0, 0, 29
6022 // slw newval2, newval, shift
6023 // slw oldval2, oldval,shift
6024 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6025 // slw mask, mask2, shift
6026 // and newval3, newval2, mask
6027 // and oldval3, oldval2, mask
6029 // lwarx tmpDest, ptr
6030 // and tmp, tmpDest, mask
6031 // cmpw tmp, oldval3
6034 // andc tmp2, tmpDest, mask
6035 // or tmp4, tmp2, newval3
6040 // stwcx. tmpDest, ptr
6042 // srw dest, tmpDest, shift
6043 if (ptrA != ZeroReg) {
6044 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6045 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6046 .addReg(ptrA).addReg(ptrB);
6050 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6051 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6052 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6053 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6055 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6056 .addReg(Ptr1Reg).addImm(0).addImm(61);
6058 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6059 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6060 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6061 .addReg(newval).addReg(ShiftReg);
6062 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6063 .addReg(oldval).addReg(ShiftReg);
6065 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6067 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6068 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6069 .addReg(Mask3Reg).addImm(65535);
6071 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6072 .addReg(Mask2Reg).addReg(ShiftReg);
6073 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6074 .addReg(NewVal2Reg).addReg(MaskReg);
6075 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6076 .addReg(OldVal2Reg).addReg(MaskReg);
6079 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6080 .addReg(ZeroReg).addReg(PtrReg);
6081 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6082 .addReg(TmpDestReg).addReg(MaskReg);
6083 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6084 .addReg(TmpReg).addReg(OldVal3Reg);
6085 BuildMI(BB, dl, TII->get(PPC::BCC))
6086 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6087 BB->addSuccessor(loop2MBB);
6088 BB->addSuccessor(midMBB);
6091 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6092 .addReg(TmpDestReg).addReg(MaskReg);
6093 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6094 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6095 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6096 .addReg(ZeroReg).addReg(PtrReg);
6097 BuildMI(BB, dl, TII->get(PPC::BCC))
6098 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6099 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6100 BB->addSuccessor(loop1MBB);
6101 BB->addSuccessor(exitMBB);
6104 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6105 .addReg(ZeroReg).addReg(PtrReg);
6106 BB->addSuccessor(exitMBB);
6111 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6114 llvm_unreachable("Unexpected instr type to insert");
6117 MI->eraseFromParent(); // The pseudo instruction is gone now.
6121 //===----------------------------------------------------------------------===//
6122 // Target Optimization Hooks
6123 //===----------------------------------------------------------------------===//
6125 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6126 DAGCombinerInfo &DCI) const {
6127 const TargetMachine &TM = getTargetMachine();
6128 SelectionDAG &DAG = DCI.DAG;
6129 DebugLoc dl = N->getDebugLoc();
6130 switch (N->getOpcode()) {
6133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6134 if (C->isNullValue()) // 0 << V -> 0.
6135 return N->getOperand(0);
6139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6140 if (C->isNullValue()) // 0 >>u V -> 0.
6141 return N->getOperand(0);
6145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6146 if (C->isNullValue() || // 0 >>s V -> 0.
6147 C->isAllOnesValue()) // -1 >>s V -> -1.
6148 return N->getOperand(0);
6152 case ISD::SINT_TO_FP:
6153 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6154 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6155 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6156 // We allow the src/dst to be either f32/f64, but the intermediate
6157 // type must be i64.
6158 if (N->getOperand(0).getValueType() == MVT::i64 &&
6159 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6160 SDValue Val = N->getOperand(0).getOperand(0);
6161 if (Val.getValueType() == MVT::f32) {
6162 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6163 DCI.AddToWorklist(Val.getNode());
6166 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6167 DCI.AddToWorklist(Val.getNode());
6168 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6169 DCI.AddToWorklist(Val.getNode());
6170 if (N->getValueType(0) == MVT::f32) {
6171 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6172 DAG.getIntPtrConstant(0));
6173 DCI.AddToWorklist(Val.getNode());
6176 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6177 // If the intermediate type is i32, we can avoid the load/store here
6184 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6185 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6186 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6187 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6188 N->getOperand(1).getValueType() == MVT::i32 &&
6189 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6190 SDValue Val = N->getOperand(1).getOperand(0);
6191 if (Val.getValueType() == MVT::f32) {
6192 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6193 DCI.AddToWorklist(Val.getNode());
6195 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6196 DCI.AddToWorklist(Val.getNode());
6198 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6199 N->getOperand(2), N->getOperand(3));
6200 DCI.AddToWorklist(Val.getNode());
6204 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6205 if (cast<StoreSDNode>(N)->isUnindexed() &&
6206 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6207 N->getOperand(1).getNode()->hasOneUse() &&
6208 (N->getOperand(1).getValueType() == MVT::i32 ||
6209 N->getOperand(1).getValueType() == MVT::i16)) {
6210 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6211 // Do an any-extend to 32-bits if this is a half-word input.
6212 if (BSwapOp.getValueType() == MVT::i16)
6213 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6216 N->getOperand(0), BSwapOp, N->getOperand(2),
6217 DAG.getValueType(N->getOperand(1).getValueType())
6220 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6221 Ops, array_lengthof(Ops),
6222 cast<StoreSDNode>(N)->getMemoryVT(),
6223 cast<StoreSDNode>(N)->getMemOperand());
6227 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6228 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6229 N->getOperand(0).hasOneUse() &&
6230 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6231 SDValue Load = N->getOperand(0);
6232 LoadSDNode *LD = cast<LoadSDNode>(Load);
6233 // Create the byte-swapping load.
6235 LD->getChain(), // Chain
6236 LD->getBasePtr(), // Ptr
6237 DAG.getValueType(N->getValueType(0)) // VT
6240 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6241 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6242 LD->getMemoryVT(), LD->getMemOperand());
6244 // If this is an i16 load, insert the truncate.
6245 SDValue ResVal = BSLoad;
6246 if (N->getValueType(0) == MVT::i16)
6247 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6249 // First, combine the bswap away. This makes the value produced by the
6251 DCI.CombineTo(N, ResVal);
6253 // Next, combine the load away, we give it a bogus result value but a real
6254 // chain result. The result value is dead because the bswap is dead.
6255 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6257 // Return N so it doesn't get rechecked!
6258 return SDValue(N, 0);
6262 case PPCISD::VCMP: {
6263 // If a VCMPo node already exists with exactly the same operands as this
6264 // node, use its result instead of this node (VCMPo computes both a CR6 and
6265 // a normal output).
6267 if (!N->getOperand(0).hasOneUse() &&
6268 !N->getOperand(1).hasOneUse() &&
6269 !N->getOperand(2).hasOneUse()) {
6271 // Scan all of the users of the LHS, looking for VCMPo's that match.
6272 SDNode *VCMPoNode = 0;
6274 SDNode *LHSN = N->getOperand(0).getNode();
6275 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6277 if (UI->getOpcode() == PPCISD::VCMPo &&
6278 UI->getOperand(1) == N->getOperand(1) &&
6279 UI->getOperand(2) == N->getOperand(2) &&
6280 UI->getOperand(0) == N->getOperand(0)) {
6285 // If there is no VCMPo node, or if the flag value has a single use, don't
6287 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6290 // Look at the (necessarily single) use of the flag value. If it has a
6291 // chain, this transformation is more complex. Note that multiple things
6292 // could use the value result, which we should ignore.
6293 SDNode *FlagUser = 0;
6294 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6295 FlagUser == 0; ++UI) {
6296 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6298 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6299 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6306 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6307 // give up for right now.
6308 if (FlagUser->getOpcode() == PPCISD::MFCR)
6309 return SDValue(VCMPoNode, 0);
6314 // If this is a branch on an altivec predicate comparison, lower this so
6315 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6316 // lowering is done pre-legalize, because the legalizer lowers the predicate
6317 // compare down to code that is difficult to reassemble.
6318 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6319 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6323 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6324 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6325 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6326 assert(isDot && "Can't compare against a vector result!");
6328 // If this is a comparison against something other than 0/1, then we know
6329 // that the condition is never/always true.
6330 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6331 if (Val != 0 && Val != 1) {
6332 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6333 return N->getOperand(0);
6334 // Always !=, turn it into an unconditional branch.
6335 return DAG.getNode(ISD::BR, dl, MVT::Other,
6336 N->getOperand(0), N->getOperand(4));
6339 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6341 // Create the PPCISD altivec 'dot' comparison node.
6342 std::vector<EVT> VTs;
6344 LHS.getOperand(2), // LHS of compare
6345 LHS.getOperand(3), // RHS of compare
6346 DAG.getConstant(CompareOpc, MVT::i32)
6348 VTs.push_back(LHS.getOperand(2).getValueType());
6349 VTs.push_back(MVT::Glue);
6350 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6352 // Unpack the result based on how the target uses it.
6353 PPC::Predicate CompOpc;
6354 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6355 default: // Can't happen, don't crash on invalid number though.
6356 case 0: // Branch on the value of the EQ bit of CR6.
6357 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6359 case 1: // Branch on the inverted value of the EQ bit of CR6.
6360 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6362 case 2: // Branch on the value of the LT bit of CR6.
6363 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6365 case 3: // Branch on the inverted value of the LT bit of CR6.
6366 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6370 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6371 DAG.getConstant(CompOpc, MVT::i32),
6372 DAG.getRegister(PPC::CR6, MVT::i32),
6373 N->getOperand(4), CompNode.getValue(1));
6382 //===----------------------------------------------------------------------===//
6383 // Inline Assembly Support
6384 //===----------------------------------------------------------------------===//
6386 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6389 const SelectionDAG &DAG,
6390 unsigned Depth) const {
6391 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6392 switch (Op.getOpcode()) {
6394 case PPCISD::LBRX: {
6395 // lhbrx is known to have the top bits cleared out.
6396 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6397 KnownZero = 0xFFFF0000;
6400 case ISD::INTRINSIC_WO_CHAIN: {
6401 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6403 case Intrinsic::ppc_altivec_vcmpbfp_p:
6404 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6405 case Intrinsic::ppc_altivec_vcmpequb_p:
6406 case Intrinsic::ppc_altivec_vcmpequh_p:
6407 case Intrinsic::ppc_altivec_vcmpequw_p:
6408 case Intrinsic::ppc_altivec_vcmpgefp_p:
6409 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6410 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6411 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6412 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6413 case Intrinsic::ppc_altivec_vcmpgtub_p:
6414 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6415 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6416 KnownZero = ~1U; // All bits but the low one are known to be zero.
6424 /// getConstraintType - Given a constraint, return the type of
6425 /// constraint it is for this target.
6426 PPCTargetLowering::ConstraintType
6427 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6428 if (Constraint.size() == 1) {
6429 switch (Constraint[0]) {
6436 return C_RegisterClass;
6439 return TargetLowering::getConstraintType(Constraint);
6442 /// Examine constraint type and operand type and determine a weight value.
6443 /// This object must already have been set up with the operand type
6444 /// and the current alternative constraint selected.
6445 TargetLowering::ConstraintWeight
6446 PPCTargetLowering::getSingleConstraintMatchWeight(
6447 AsmOperandInfo &info, const char *constraint) const {
6448 ConstraintWeight weight = CW_Invalid;
6449 Value *CallOperandVal = info.CallOperandVal;
6450 // If we don't have a value, we can't do a match,
6451 // but allow it at the lowest weight.
6452 if (CallOperandVal == NULL)
6454 Type *type = CallOperandVal->getType();
6455 // Look at the constraint type.
6456 switch (*constraint) {
6458 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6461 if (type->isIntegerTy())
6462 weight = CW_Register;
6465 if (type->isFloatTy())
6466 weight = CW_Register;
6469 if (type->isDoubleTy())
6470 weight = CW_Register;
6473 if (type->isVectorTy())
6474 weight = CW_Register;
6477 weight = CW_Register;
6483 std::pair<unsigned, const TargetRegisterClass*>
6484 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6486 if (Constraint.size() == 1) {
6487 // GCC RS6000 Constraint Letters
6488 switch (Constraint[0]) {
6491 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6492 return std::make_pair(0U, &PPC::G8RCRegClass);
6493 return std::make_pair(0U, &PPC::GPRCRegClass);
6495 if (VT == MVT::f32 || VT == MVT::i32)
6496 return std::make_pair(0U, &PPC::F4RCRegClass);
6497 if (VT == MVT::f64 || VT == MVT::i64)
6498 return std::make_pair(0U, &PPC::F8RCRegClass);
6501 return std::make_pair(0U, &PPC::VRRCRegClass);
6503 return std::make_pair(0U, &PPC::CRRCRegClass);
6507 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6511 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6512 /// vector. If it is invalid, don't add anything to Ops.
6513 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6514 std::string &Constraint,
6515 std::vector<SDValue>&Ops,
6516 SelectionDAG &DAG) const {
6517 SDValue Result(0,0);
6519 // Only support length 1 constraints.
6520 if (Constraint.length() > 1) return;
6522 char Letter = Constraint[0];
6533 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6534 if (!CST) return; // Must be an immediate to match.
6535 unsigned Value = CST->getZExtValue();
6537 default: llvm_unreachable("Unknown constraint letter!");
6538 case 'I': // "I" is a signed 16-bit constant.
6539 if ((short)Value == (int)Value)
6540 Result = DAG.getTargetConstant(Value, Op.getValueType());
6542 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6543 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6544 if ((short)Value == 0)
6545 Result = DAG.getTargetConstant(Value, Op.getValueType());
6547 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6548 if ((Value >> 16) == 0)
6549 Result = DAG.getTargetConstant(Value, Op.getValueType());
6551 case 'M': // "M" is a constant that is greater than 31.
6553 Result = DAG.getTargetConstant(Value, Op.getValueType());
6555 case 'N': // "N" is a positive constant that is an exact power of two.
6556 if ((int)Value > 0 && isPowerOf2_32(Value))
6557 Result = DAG.getTargetConstant(Value, Op.getValueType());
6559 case 'O': // "O" is the constant zero.
6561 Result = DAG.getTargetConstant(Value, Op.getValueType());
6563 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6564 if ((short)-Value == (int)-Value)
6565 Result = DAG.getTargetConstant(Value, Op.getValueType());
6572 if (Result.getNode()) {
6573 Ops.push_back(Result);
6577 // Handle standard constraint letters.
6578 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6581 // isLegalAddressingMode - Return true if the addressing mode represented
6582 // by AM is legal for this target, for a load/store of the specified type.
6583 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6585 // FIXME: PPC does not allow r+i addressing modes for vectors!
6587 // PPC allows a sign-extended 16-bit immediate field.
6588 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6591 // No global is ever allowed as a base.
6595 // PPC only support r+r,
6597 case 0: // "r+i" or just "i", depending on HasBaseReg.
6600 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
6602 // Otherwise we have r+r or r+i.
6605 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
6607 // Allow 2*r as r+r.
6610 // No other scales are supported.
6617 /// isLegalAddressImmediate - Return true if the integer value can be used
6618 /// as the offset of the target addressing mode for load / store of the
6620 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
6621 // PPC allows a sign-extended 16-bit immediate field.
6622 return (V > -(1 << 16) && V < (1 << 16)-1);
6625 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
6629 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
6630 SelectionDAG &DAG) const {
6631 MachineFunction &MF = DAG.getMachineFunction();
6632 MachineFrameInfo *MFI = MF.getFrameInfo();
6633 MFI->setReturnAddressIsTaken(true);
6635 DebugLoc dl = Op.getDebugLoc();
6636 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6638 // Make sure the function does not optimize away the store of the RA to
6640 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6641 FuncInfo->setLRStoreRequired();
6642 bool isPPC64 = PPCSubTarget.isPPC64();
6643 bool isDarwinABI = PPCSubTarget.isDarwinABI();
6646 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6649 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
6650 isPPC64? MVT::i64 : MVT::i32);
6651 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6652 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6654 MachinePointerInfo(), false, false, false, 0);
6657 // Just load the return address off the stack.
6658 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
6659 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6660 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
6663 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
6664 SelectionDAG &DAG) const {
6665 DebugLoc dl = Op.getDebugLoc();
6666 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6668 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6669 bool isPPC64 = PtrVT == MVT::i64;
6671 MachineFunction &MF = DAG.getMachineFunction();
6672 MachineFrameInfo *MFI = MF.getFrameInfo();
6673 MFI->setFrameAddressIsTaken(true);
6674 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) ||
6675 MFI->hasVarSizedObjects()) &&
6676 MFI->getStackSize() &&
6677 !MF.getFunction()->getFnAttributes().
6678 hasAttribute(Attributes::Naked);
6679 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
6680 (is31 ? PPC::R31 : PPC::R1);
6681 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
6684 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
6685 FrameAddr, MachinePointerInfo(), false, false,
6691 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6692 // The PowerPC target isn't yet aware of offsets.
6696 /// getOptimalMemOpType - Returns the target specific optimal type for load
6697 /// and store operations as a result of memset, memcpy, and memmove
6698 /// lowering. If DstAlign is zero that means it's safe to destination
6699 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
6700 /// means there isn't a need to check it against alignment requirement,
6701 /// probably because the source does not need to be loaded. If
6702 /// 'IsZeroVal' is true, that means it's safe to return a
6703 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
6704 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
6705 /// constant so it does not need to be loaded.
6706 /// It returns EVT::Other if the type should be determined using generic
6707 /// target-independent logic.
6708 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
6709 unsigned DstAlign, unsigned SrcAlign,
6712 MachineFunction &MF) const {
6713 if (this->PPCSubTarget.isPPC64()) {
6720 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
6721 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
6722 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
6723 /// is expanded to mul + add.
6724 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
6728 switch (VT.getSimpleVT().SimpleTy) {
6740 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
6742 return TargetLowering::getSchedulingPreference(N);