1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the PPCISelLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "PPCISelLowering.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPCMachineFunctionInfo.h"
17 #include "PPCPerfectShuffle.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Function.h"
31 #include "llvm/Intrinsics.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::FSQRT, VT, Expand);
351 setOperationAction(ISD::FLOG, VT, Expand);
352 setOperationAction(ISD::FLOG10, VT, Expand);
353 setOperationAction(ISD::FLOG2, VT, Expand);
354 setOperationAction(ISD::FEXP, VT, Expand);
355 setOperationAction(ISD::FEXP2, VT, Expand);
356 setOperationAction(ISD::FSIN, VT, Expand);
357 setOperationAction(ISD::FCOS, VT, Expand);
358 setOperationAction(ISD::FABS, VT, Expand);
359 setOperationAction(ISD::FPOWI, VT, Expand);
360 setOperationAction(ISD::FFLOOR, VT, Expand);
361 setOperationAction(ISD::FCEIL, VT, Expand);
362 setOperationAction(ISD::FTRUNC, VT, Expand);
363 setOperationAction(ISD::FRINT, VT, Expand);
364 setOperationAction(ISD::FNEARBYINT, VT, Expand);
365 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
366 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
367 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
368 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
369 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
370 setOperationAction(ISD::UDIVREM, VT, Expand);
371 setOperationAction(ISD::SDIVREM, VT, Expand);
372 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
373 setOperationAction(ISD::FPOW, VT, Expand);
374 setOperationAction(ISD::CTPOP, VT, Expand);
375 setOperationAction(ISD::CTLZ, VT, Expand);
376 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
377 setOperationAction(ISD::CTTZ, VT, Expand);
378 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
379 setOperationAction(ISD::VSELECT, VT, Expand);
380 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
382 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
383 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
384 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
385 setTruncStoreAction(VT, InnerVT, Expand);
387 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
388 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
389 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
392 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
393 // with merges, splats, etc.
394 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
396 setOperationAction(ISD::AND , MVT::v4i32, Legal);
397 setOperationAction(ISD::OR , MVT::v4i32, Legal);
398 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
399 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
400 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
401 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
402 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
403 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
404 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
405 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
406 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
407 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
408 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
409 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
411 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
412 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
413 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
414 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
416 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
417 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
418 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
419 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
420 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
422 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
423 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
425 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
426 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
427 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
428 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
430 // Altivec does not contain unordered floating-point compare instructions
431 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
432 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
433 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
434 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
435 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
436 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
439 if (Subtarget->has64BitSupport()) {
440 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
441 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
444 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
445 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
446 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
447 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
449 setBooleanContents(ZeroOrOneBooleanContent);
450 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
453 setStackPointerRegisterToSaveRestore(PPC::X1);
454 setExceptionPointerRegister(PPC::X3);
455 setExceptionSelectorRegister(PPC::X4);
457 setStackPointerRegisterToSaveRestore(PPC::R1);
458 setExceptionPointerRegister(PPC::R3);
459 setExceptionSelectorRegister(PPC::R4);
462 // We have target-specific dag combine patterns for the following nodes:
463 setTargetDAGCombine(ISD::SINT_TO_FP);
464 setTargetDAGCombine(ISD::STORE);
465 setTargetDAGCombine(ISD::BR_CC);
466 setTargetDAGCombine(ISD::BSWAP);
468 // Darwin long double math library functions have $LDBL128 appended.
469 if (Subtarget->isDarwin()) {
470 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
471 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
472 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
473 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
474 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
475 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
476 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
477 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
478 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
479 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
482 setMinFunctionAlignment(2);
483 if (PPCSubTarget.isDarwin())
484 setPrefFunctionAlignment(4);
486 if (isPPC64 && Subtarget->isJITCodeModel())
487 // Temporary workaround for the inability of PPC64 JIT to handle jump
489 setSupportJumpTables(false);
491 setInsertFencesForAtomic(true);
493 setSchedulingPreference(Sched::Hybrid);
495 computeRegisterProperties();
497 // The Freescale cores does better with aggressive inlining of memcpy and
498 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
499 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
500 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
501 maxStoresPerMemset = 32;
502 maxStoresPerMemsetOptSize = 16;
503 maxStoresPerMemcpy = 32;
504 maxStoresPerMemcpyOptSize = 8;
505 maxStoresPerMemmove = 32;
506 maxStoresPerMemmoveOptSize = 8;
508 setPrefFunctionAlignment(4);
509 benefitFromCodePlacementOpt = true;
513 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
514 /// function arguments in the caller parameter area.
515 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
516 const TargetMachine &TM = getTargetMachine();
517 // Darwin passes everything on 4 byte boundary.
518 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
521 // 16byte and wider vectors are passed on 16byte boundary.
522 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
523 if (VTy->getBitWidth() >= 128)
526 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
527 if (PPCSubTarget.isPPC64())
533 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
536 case PPCISD::FSEL: return "PPCISD::FSEL";
537 case PPCISD::FCFID: return "PPCISD::FCFID";
538 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
539 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
540 case PPCISD::STFIWX: return "PPCISD::STFIWX";
541 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
542 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
543 case PPCISD::VPERM: return "PPCISD::VPERM";
544 case PPCISD::Hi: return "PPCISD::Hi";
545 case PPCISD::Lo: return "PPCISD::Lo";
546 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
547 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
548 case PPCISD::LOAD: return "PPCISD::LOAD";
549 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
550 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
551 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
552 case PPCISD::SRL: return "PPCISD::SRL";
553 case PPCISD::SRA: return "PPCISD::SRA";
554 case PPCISD::SHL: return "PPCISD::SHL";
555 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
556 case PPCISD::STD_32: return "PPCISD::STD_32";
557 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
558 case PPCISD::CALL_NOP_SVR4: return "PPCISD::CALL_NOP_SVR4";
559 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
560 case PPCISD::NOP: return "PPCISD::NOP";
561 case PPCISD::MTCTR: return "PPCISD::MTCTR";
562 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
563 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
564 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
565 case PPCISD::MFCR: return "PPCISD::MFCR";
566 case PPCISD::VCMP: return "PPCISD::VCMP";
567 case PPCISD::VCMPo: return "PPCISD::VCMPo";
568 case PPCISD::LBRX: return "PPCISD::LBRX";
569 case PPCISD::STBRX: return "PPCISD::STBRX";
570 case PPCISD::LARX: return "PPCISD::LARX";
571 case PPCISD::STCX: return "PPCISD::STCX";
572 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
573 case PPCISD::MFFS: return "PPCISD::MFFS";
574 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
575 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
576 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
577 case PPCISD::MTFSF: return "PPCISD::MTFSF";
578 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
579 case PPCISD::CR6SET: return "PPCISD::CR6SET";
580 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
581 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
582 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
583 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
584 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
585 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
586 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
587 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
588 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
589 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
590 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
591 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
592 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
593 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
594 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
598 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
601 return VT.changeVectorElementTypeToInteger();
604 //===----------------------------------------------------------------------===//
605 // Node matching predicates, for use by the tblgen matching code.
606 //===----------------------------------------------------------------------===//
608 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
609 static bool isFloatingPointZero(SDValue Op) {
610 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
611 return CFP->getValueAPF().isZero();
612 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
613 // Maybe this has already been legalized into the constant pool?
614 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
615 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
616 return CFP->getValueAPF().isZero();
621 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
622 /// true if Op is undef or if it matches the specified value.
623 static bool isConstantOrUndef(int Op, int Val) {
624 return Op < 0 || Op == Val;
627 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
628 /// VPKUHUM instruction.
629 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
631 for (unsigned i = 0; i != 16; ++i)
632 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
635 for (unsigned i = 0; i != 8; ++i)
636 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
637 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
643 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
644 /// VPKUWUM instruction.
645 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
647 for (unsigned i = 0; i != 16; i += 2)
648 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
649 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
652 for (unsigned i = 0; i != 8; i += 2)
653 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
654 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
655 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
656 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
662 /// isVMerge - Common function, used to match vmrg* shuffles.
664 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
665 unsigned LHSStart, unsigned RHSStart) {
666 assert(N->getValueType(0) == MVT::v16i8 &&
667 "PPC only supports shuffles by bytes!");
668 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
669 "Unsupported merge size!");
671 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
672 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
673 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
674 LHSStart+j+i*UnitSize) ||
675 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
676 RHSStart+j+i*UnitSize))
682 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
683 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
684 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
687 return isVMerge(N, UnitSize, 8, 24);
688 return isVMerge(N, UnitSize, 8, 8);
691 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
692 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
693 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
696 return isVMerge(N, UnitSize, 0, 16);
697 return isVMerge(N, UnitSize, 0, 0);
701 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
702 /// amount, otherwise return -1.
703 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
704 assert(N->getValueType(0) == MVT::v16i8 &&
705 "PPC only supports shuffles by bytes!");
707 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
709 // Find the first non-undef value in the shuffle mask.
711 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
714 if (i == 16) return -1; // all undef.
716 // Otherwise, check to see if the rest of the elements are consecutively
717 // numbered from this value.
718 unsigned ShiftAmt = SVOp->getMaskElt(i);
719 if (ShiftAmt < i) return -1;
723 // Check the rest of the elements to see if they are consecutive.
724 for (++i; i != 16; ++i)
725 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
728 // Check the rest of the elements to see if they are consecutive.
729 for (++i; i != 16; ++i)
730 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
736 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
737 /// specifies a splat of a single element that is suitable for input to
738 /// VSPLTB/VSPLTH/VSPLTW.
739 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
740 assert(N->getValueType(0) == MVT::v16i8 &&
741 (EltSize == 1 || EltSize == 2 || EltSize == 4));
743 // This is a splat operation if each element of the permute is the same, and
744 // if the value doesn't reference the second vector.
745 unsigned ElementBase = N->getMaskElt(0);
747 // FIXME: Handle UNDEF elements too!
748 if (ElementBase >= 16)
751 // Check that the indices are consecutive, in the case of a multi-byte element
752 // splatted with a v16i8 mask.
753 for (unsigned i = 1; i != EltSize; ++i)
754 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
757 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
758 if (N->getMaskElt(i) < 0) continue;
759 for (unsigned j = 0; j != EltSize; ++j)
760 if (N->getMaskElt(i+j) != N->getMaskElt(j))
766 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
768 bool PPC::isAllNegativeZeroVector(SDNode *N) {
769 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
771 APInt APVal, APUndef;
775 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
776 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
777 return CFP->getValueAPF().isNegZero();
782 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
783 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
784 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
785 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
786 assert(isSplatShuffleMask(SVOp, EltSize));
787 return SVOp->getMaskElt(0) / EltSize;
790 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
791 /// by using a vspltis[bhw] instruction of the specified element size, return
792 /// the constant being splatted. The ByteSize field indicates the number of
793 /// bytes of each element [124] -> [bhw].
794 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
797 // If ByteSize of the splat is bigger than the element size of the
798 // build_vector, then we have a case where we are checking for a splat where
799 // multiple elements of the buildvector are folded together into a single
800 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
801 unsigned EltSize = 16/N->getNumOperands();
802 if (EltSize < ByteSize) {
803 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
804 SDValue UniquedVals[4];
805 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
807 // See if all of the elements in the buildvector agree across.
808 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
809 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
810 // If the element isn't a constant, bail fully out.
811 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
814 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
815 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
816 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
817 return SDValue(); // no match.
820 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
821 // either constant or undef values that are identical for each chunk. See
822 // if these chunks can form into a larger vspltis*.
824 // Check to see if all of the leading entries are either 0 or -1. If
825 // neither, then this won't fit into the immediate field.
826 bool LeadingZero = true;
827 bool LeadingOnes = true;
828 for (unsigned i = 0; i != Multiple-1; ++i) {
829 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
831 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
832 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
834 // Finally, check the least significant entry.
836 if (UniquedVals[Multiple-1].getNode() == 0)
837 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
838 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
840 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
843 if (UniquedVals[Multiple-1].getNode() == 0)
844 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
845 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
846 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
847 return DAG.getTargetConstant(Val, MVT::i32);
853 // Check to see if this buildvec has a single non-undef value in its elements.
854 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
855 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
856 if (OpVal.getNode() == 0)
857 OpVal = N->getOperand(i);
858 else if (OpVal != N->getOperand(i))
862 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
864 unsigned ValSizeInBytes = EltSize;
866 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
867 Value = CN->getZExtValue();
868 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
869 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
870 Value = FloatToBits(CN->getValueAPF().convertToFloat());
873 // If the splat value is larger than the element value, then we can never do
874 // this splat. The only case that we could fit the replicated bits into our
875 // immediate field for would be zero, and we prefer to use vxor for it.
876 if (ValSizeInBytes < ByteSize) return SDValue();
878 // If the element value is larger than the splat value, cut it in half and
879 // check to see if the two halves are equal. Continue doing this until we
880 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
881 while (ValSizeInBytes > ByteSize) {
882 ValSizeInBytes >>= 1;
884 // If the top half equals the bottom half, we're still ok.
885 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
886 (Value & ((1 << (8*ValSizeInBytes))-1)))
890 // Properly sign extend the value.
891 int MaskVal = SignExtend32(Value, ByteSize * 8);
893 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
894 if (MaskVal == 0) return SDValue();
896 // Finally, if this value fits in a 5 bit sext field, return it
897 if (SignExtend32<5>(MaskVal) == MaskVal)
898 return DAG.getTargetConstant(MaskVal, MVT::i32);
902 //===----------------------------------------------------------------------===//
903 // Addressing Mode Selection
904 //===----------------------------------------------------------------------===//
906 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
907 /// or 64-bit immediate, and if the value can be accurately represented as a
908 /// sign extension from a 16-bit value. If so, this returns true and the
910 static bool isIntS16Immediate(SDNode *N, short &Imm) {
911 if (N->getOpcode() != ISD::Constant)
914 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
915 if (N->getValueType(0) == MVT::i32)
916 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
918 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
920 static bool isIntS16Immediate(SDValue Op, short &Imm) {
921 return isIntS16Immediate(Op.getNode(), Imm);
925 /// SelectAddressRegReg - Given the specified addressed, check to see if it
926 /// can be represented as an indexed [r+r] operation. Returns false if it
927 /// can be more efficiently represented with [r+imm].
928 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
930 SelectionDAG &DAG) const {
932 if (N.getOpcode() == ISD::ADD) {
933 if (isIntS16Immediate(N.getOperand(1), imm))
935 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
938 Base = N.getOperand(0);
939 Index = N.getOperand(1);
941 } else if (N.getOpcode() == ISD::OR) {
942 if (isIntS16Immediate(N.getOperand(1), imm))
943 return false; // r+i can fold it if we can.
945 // If this is an or of disjoint bitfields, we can codegen this as an add
946 // (for better address arithmetic) if the LHS and RHS of the OR are provably
948 APInt LHSKnownZero, LHSKnownOne;
949 APInt RHSKnownZero, RHSKnownOne;
950 DAG.ComputeMaskedBits(N.getOperand(0),
951 LHSKnownZero, LHSKnownOne);
953 if (LHSKnownZero.getBoolValue()) {
954 DAG.ComputeMaskedBits(N.getOperand(1),
955 RHSKnownZero, RHSKnownOne);
956 // If all of the bits are known zero on the LHS or RHS, the add won't
958 if (~(LHSKnownZero | RHSKnownZero) == 0) {
959 Base = N.getOperand(0);
960 Index = N.getOperand(1);
969 /// Returns true if the address N can be represented by a base register plus
970 /// a signed 16-bit displacement [r+imm], and if it is not better
971 /// represented as reg+reg.
972 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
974 SelectionDAG &DAG) const {
975 // FIXME dl should come from parent load or store, not from address
976 DebugLoc dl = N.getDebugLoc();
977 // If this can be more profitably realized as r+r, fail.
978 if (SelectAddressRegReg(N, Disp, Base, DAG))
981 if (N.getOpcode() == ISD::ADD) {
983 if (isIntS16Immediate(N.getOperand(1), imm)) {
984 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
985 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
986 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
988 Base = N.getOperand(0);
990 return true; // [r+i]
991 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
992 // Match LOAD (ADD (X, Lo(G))).
993 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
994 && "Cannot handle constant offsets yet!");
995 Disp = N.getOperand(1).getOperand(0); // The global address.
996 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
997 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
998 Disp.getOpcode() == ISD::TargetConstantPool ||
999 Disp.getOpcode() == ISD::TargetJumpTable);
1000 Base = N.getOperand(0);
1001 return true; // [&g+r]
1003 } else if (N.getOpcode() == ISD::OR) {
1005 if (isIntS16Immediate(N.getOperand(1), imm)) {
1006 // If this is an or of disjoint bitfields, we can codegen this as an add
1007 // (for better address arithmetic) if the LHS and RHS of the OR are
1008 // provably disjoint.
1009 APInt LHSKnownZero, LHSKnownOne;
1010 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1012 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1013 // If all of the bits are known zero on the LHS or RHS, the add won't
1015 Base = N.getOperand(0);
1016 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1020 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1021 // Loading from a constant address.
1023 // If this address fits entirely in a 16-bit sext immediate field, codegen
1026 if (isIntS16Immediate(CN, Imm)) {
1027 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1028 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1029 CN->getValueType(0));
1033 // Handle 32-bit sext immediates with LIS + addr mode.
1034 if (CN->getValueType(0) == MVT::i32 ||
1035 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1036 int Addr = (int)CN->getZExtValue();
1038 // Otherwise, break this down into an LIS + disp.
1039 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1041 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1042 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1043 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1048 Disp = DAG.getTargetConstant(0, getPointerTy());
1049 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1050 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1053 return true; // [r+0]
1056 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1057 /// represented as an indexed [r+r] operation.
1058 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1060 SelectionDAG &DAG) const {
1061 // Check to see if we can easily represent this as an [r+r] address. This
1062 // will fail if it thinks that the address is more profitably represented as
1063 // reg+imm, e.g. where imm = 0.
1064 if (SelectAddressRegReg(N, Base, Index, DAG))
1067 // If the operand is an addition, always emit this as [r+r], since this is
1068 // better (for code size, and execution, as the memop does the add for free)
1069 // than emitting an explicit add.
1070 if (N.getOpcode() == ISD::ADD) {
1071 Base = N.getOperand(0);
1072 Index = N.getOperand(1);
1076 // Otherwise, do it the hard way, using R0 as the base register.
1077 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1083 /// SelectAddressRegImmShift - Returns true if the address N can be
1084 /// represented by a base register plus a signed 14-bit displacement
1085 /// [r+imm*4]. Suitable for use by STD and friends.
1086 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1088 SelectionDAG &DAG) const {
1089 // FIXME dl should come from the parent load or store, not the address
1090 DebugLoc dl = N.getDebugLoc();
1091 // If this can be more profitably realized as r+r, fail.
1092 if (SelectAddressRegReg(N, Disp, Base, DAG))
1095 if (N.getOpcode() == ISD::ADD) {
1097 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1098 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1099 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1100 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1102 Base = N.getOperand(0);
1104 return true; // [r+i]
1105 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1106 // Match LOAD (ADD (X, Lo(G))).
1107 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1108 && "Cannot handle constant offsets yet!");
1109 Disp = N.getOperand(1).getOperand(0); // The global address.
1110 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1111 Disp.getOpcode() == ISD::TargetConstantPool ||
1112 Disp.getOpcode() == ISD::TargetJumpTable);
1113 Base = N.getOperand(0);
1114 return true; // [&g+r]
1116 } else if (N.getOpcode() == ISD::OR) {
1118 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1119 // If this is an or of disjoint bitfields, we can codegen this as an add
1120 // (for better address arithmetic) if the LHS and RHS of the OR are
1121 // provably disjoint.
1122 APInt LHSKnownZero, LHSKnownOne;
1123 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1124 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1125 // If all of the bits are known zero on the LHS or RHS, the add won't
1127 Base = N.getOperand(0);
1128 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1132 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1133 // Loading from a constant address. Verify low two bits are clear.
1134 if ((CN->getZExtValue() & 3) == 0) {
1135 // If this address fits entirely in a 14-bit sext immediate field, codegen
1138 if (isIntS16Immediate(CN, Imm)) {
1139 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1140 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1141 CN->getValueType(0));
1145 // Fold the low-part of 32-bit absolute addresses into addr mode.
1146 if (CN->getValueType(0) == MVT::i32 ||
1147 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1148 int Addr = (int)CN->getZExtValue();
1150 // Otherwise, break this down into an LIS + disp.
1151 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1152 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1153 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1154 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1160 Disp = DAG.getTargetConstant(0, getPointerTy());
1161 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1162 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1165 return true; // [r+0]
1169 /// getPreIndexedAddressParts - returns true by value, base pointer and
1170 /// offset pointer and addressing mode by reference if the node's address
1171 /// can be legally represented as pre-indexed load / store address.
1172 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1174 ISD::MemIndexedMode &AM,
1175 SelectionDAG &DAG) const {
1176 if (DisablePPCPreinc) return false;
1180 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1181 Ptr = LD->getBasePtr();
1182 VT = LD->getMemoryVT();
1184 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1185 Ptr = ST->getBasePtr();
1186 VT = ST->getMemoryVT();
1190 // PowerPC doesn't have preinc load/store instructions for vectors.
1194 if (SelectAddressRegReg(Ptr, Offset, Base, DAG)) {
1199 // LDU/STU use reg+imm*4, others use reg+imm.
1200 if (VT != MVT::i64) {
1202 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1206 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1210 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1211 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1212 // sext i32 to i64 when addr mode is r+i.
1213 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1214 LD->getExtensionType() == ISD::SEXTLOAD &&
1215 isa<ConstantSDNode>(Offset))
1223 //===----------------------------------------------------------------------===//
1224 // LowerOperation implementation
1225 //===----------------------------------------------------------------------===//
1227 /// GetLabelAccessInfo - Return true if we should reference labels using a
1228 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1229 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1230 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1231 HiOpFlags = PPCII::MO_HA16;
1232 LoOpFlags = PPCII::MO_LO16;
1234 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1235 // non-darwin platform. We don't support PIC on other platforms yet.
1236 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1237 TM.getSubtarget<PPCSubtarget>().isDarwin();
1239 HiOpFlags |= PPCII::MO_PIC_FLAG;
1240 LoOpFlags |= PPCII::MO_PIC_FLAG;
1243 // If this is a reference to a global value that requires a non-lazy-ptr, make
1244 // sure that instruction lowering adds it.
1245 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1246 HiOpFlags |= PPCII::MO_NLP_FLAG;
1247 LoOpFlags |= PPCII::MO_NLP_FLAG;
1249 if (GV->hasHiddenVisibility()) {
1250 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1251 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1258 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1259 SelectionDAG &DAG) {
1260 EVT PtrVT = HiPart.getValueType();
1261 SDValue Zero = DAG.getConstant(0, PtrVT);
1262 DebugLoc DL = HiPart.getDebugLoc();
1264 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1265 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1267 // With PIC, the first instruction is actually "GR+hi(&G)".
1269 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1270 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1272 // Generate non-pic code that has direct accesses to the constant pool.
1273 // The address of the global is just (hi(&g)+lo(&g)).
1274 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1277 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1278 SelectionDAG &DAG) const {
1279 EVT PtrVT = Op.getValueType();
1280 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1281 const Constant *C = CP->getConstVal();
1283 // 64-bit SVR4 ABI code is always position-independent.
1284 // The actual address of the GlobalValue is stored in the TOC.
1285 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1286 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1287 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1288 DAG.getRegister(PPC::X2, MVT::i64));
1291 unsigned MOHiFlag, MOLoFlag;
1292 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1294 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1296 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1297 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1300 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1301 EVT PtrVT = Op.getValueType();
1302 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1304 // 64-bit SVR4 ABI code is always position-independent.
1305 // The actual address of the GlobalValue is stored in the TOC.
1306 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1307 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1308 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1309 DAG.getRegister(PPC::X2, MVT::i64));
1312 unsigned MOHiFlag, MOLoFlag;
1313 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1314 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1315 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1316 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1319 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1320 SelectionDAG &DAG) const {
1321 EVT PtrVT = Op.getValueType();
1323 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1325 unsigned MOHiFlag, MOLoFlag;
1326 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1327 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1328 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1329 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1332 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1333 SelectionDAG &DAG) const {
1335 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1336 DebugLoc dl = GA->getDebugLoc();
1337 const GlobalValue *GV = GA->getGlobal();
1338 EVT PtrVT = getPointerTy();
1339 bool is64bit = PPCSubTarget.isPPC64();
1341 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1343 if (Model == TLSModel::LocalExec) {
1344 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1345 PPCII::MO_TPREL16_HA);
1346 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1347 PPCII::MO_TPREL16_LO);
1348 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1349 is64bit ? MVT::i64 : MVT::i32);
1350 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1351 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1355 llvm_unreachable("only local-exec is currently supported for ppc32");
1357 if (Model == TLSModel::InitialExec) {
1358 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1359 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1360 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1361 PtrVT, GOTReg, TGA);
1362 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1363 PtrVT, TGA, TPOffsetHi);
1364 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1367 if (Model == TLSModel::GeneralDynamic) {
1368 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1369 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1370 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1372 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1375 // We need a chain node, and don't have one handy. The underlying
1376 // call has no side effects, so using the function entry node
1378 SDValue Chain = DAG.getEntryNode();
1379 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1380 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1381 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1382 PtrVT, ParmReg, TGA);
1383 // The return value from GET_TLS_ADDR really is in X3 already, but
1384 // some hacks are needed here to tie everything together. The extra
1385 // copies dissolve during subsequent transforms.
1386 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1387 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1390 if (Model == TLSModel::LocalDynamic) {
1391 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1392 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1393 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1395 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1398 // We need a chain node, and don't have one handy. The underlying
1399 // call has no side effects, so using the function entry node
1401 SDValue Chain = DAG.getEntryNode();
1402 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1403 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1404 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1405 PtrVT, ParmReg, TGA);
1406 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1407 // some hacks are needed here to tie everything together. The extra
1408 // copies dissolve during subsequent transforms.
1409 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1410 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1411 Chain, ParmReg, TGA);
1412 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1415 llvm_unreachable("Unknown TLS model!");
1418 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1419 SelectionDAG &DAG) const {
1420 EVT PtrVT = Op.getValueType();
1421 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1422 DebugLoc DL = GSDN->getDebugLoc();
1423 const GlobalValue *GV = GSDN->getGlobal();
1425 // 64-bit SVR4 ABI code is always position-independent.
1426 // The actual address of the GlobalValue is stored in the TOC.
1427 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1428 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1429 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1430 DAG.getRegister(PPC::X2, MVT::i64));
1433 unsigned MOHiFlag, MOLoFlag;
1434 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1437 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1439 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1441 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1443 // If the global reference is actually to a non-lazy-pointer, we have to do an
1444 // extra load to get the address of the global.
1445 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1446 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1447 false, false, false, 0);
1451 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1452 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1453 DebugLoc dl = Op.getDebugLoc();
1455 // If we're comparing for equality to zero, expose the fact that this is
1456 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1457 // fold the new nodes.
1458 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1459 if (C->isNullValue() && CC == ISD::SETEQ) {
1460 EVT VT = Op.getOperand(0).getValueType();
1461 SDValue Zext = Op.getOperand(0);
1462 if (VT.bitsLT(MVT::i32)) {
1464 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1466 unsigned Log2b = Log2_32(VT.getSizeInBits());
1467 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1468 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1469 DAG.getConstant(Log2b, MVT::i32));
1470 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1472 // Leave comparisons against 0 and -1 alone for now, since they're usually
1473 // optimized. FIXME: revisit this when we can custom lower all setcc
1475 if (C->isAllOnesValue() || C->isNullValue())
1479 // If we have an integer seteq/setne, turn it into a compare against zero
1480 // by xor'ing the rhs with the lhs, which is faster than setting a
1481 // condition register, reading it back out, and masking the correct bit. The
1482 // normal approach here uses sub to do this instead of xor. Using xor exposes
1483 // the result to other bit-twiddling opportunities.
1484 EVT LHSVT = Op.getOperand(0).getValueType();
1485 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1486 EVT VT = Op.getValueType();
1487 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1489 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1494 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1495 const PPCSubtarget &Subtarget) const {
1496 SDNode *Node = Op.getNode();
1497 EVT VT = Node->getValueType(0);
1498 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1499 SDValue InChain = Node->getOperand(0);
1500 SDValue VAListPtr = Node->getOperand(1);
1501 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1502 DebugLoc dl = Node->getDebugLoc();
1504 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1507 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1508 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1510 InChain = GprIndex.getValue(1);
1512 if (VT == MVT::i64) {
1513 // Check if GprIndex is even
1514 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1515 DAG.getConstant(1, MVT::i32));
1516 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1517 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1518 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1519 DAG.getConstant(1, MVT::i32));
1520 // Align GprIndex to be even if it isn't
1521 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1525 // fpr index is 1 byte after gpr
1526 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1527 DAG.getConstant(1, MVT::i32));
1530 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1531 FprPtr, MachinePointerInfo(SV), MVT::i8,
1533 InChain = FprIndex.getValue(1);
1535 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1536 DAG.getConstant(8, MVT::i32));
1538 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1539 DAG.getConstant(4, MVT::i32));
1542 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1543 MachinePointerInfo(), false, false,
1545 InChain = OverflowArea.getValue(1);
1547 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1548 MachinePointerInfo(), false, false,
1550 InChain = RegSaveArea.getValue(1);
1552 // select overflow_area if index > 8
1553 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1554 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1556 // adjustment constant gpr_index * 4/8
1557 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1558 VT.isInteger() ? GprIndex : FprIndex,
1559 DAG.getConstant(VT.isInteger() ? 4 : 8,
1562 // OurReg = RegSaveArea + RegConstant
1563 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1566 // Floating types are 32 bytes into RegSaveArea
1567 if (VT.isFloatingPoint())
1568 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1569 DAG.getConstant(32, MVT::i32));
1571 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1572 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1573 VT.isInteger() ? GprIndex : FprIndex,
1574 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1577 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1578 VT.isInteger() ? VAListPtr : FprPtr,
1579 MachinePointerInfo(SV),
1580 MVT::i8, false, false, 0);
1582 // determine if we should load from reg_save_area or overflow_area
1583 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1585 // increase overflow_area by 4/8 if gpr/fpr > 8
1586 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1587 DAG.getConstant(VT.isInteger() ? 4 : 8,
1590 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1593 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1595 MachinePointerInfo(),
1596 MVT::i32, false, false, 0);
1598 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1599 false, false, false, 0);
1602 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1603 SelectionDAG &DAG) const {
1604 return Op.getOperand(0);
1607 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1608 SelectionDAG &DAG) const {
1609 SDValue Chain = Op.getOperand(0);
1610 SDValue Trmp = Op.getOperand(1); // trampoline
1611 SDValue FPtr = Op.getOperand(2); // nested function
1612 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1613 DebugLoc dl = Op.getDebugLoc();
1615 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1616 bool isPPC64 = (PtrVT == MVT::i64);
1618 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1621 TargetLowering::ArgListTy Args;
1622 TargetLowering::ArgListEntry Entry;
1624 Entry.Ty = IntPtrTy;
1625 Entry.Node = Trmp; Args.push_back(Entry);
1627 // TrampSize == (isPPC64 ? 48 : 40);
1628 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1629 isPPC64 ? MVT::i64 : MVT::i32);
1630 Args.push_back(Entry);
1632 Entry.Node = FPtr; Args.push_back(Entry);
1633 Entry.Node = Nest; Args.push_back(Entry);
1635 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1636 TargetLowering::CallLoweringInfo CLI(Chain,
1637 Type::getVoidTy(*DAG.getContext()),
1638 false, false, false, false, 0,
1640 /*isTailCall=*/false,
1641 /*doesNotRet=*/false,
1642 /*isReturnValueUsed=*/true,
1643 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1645 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1647 return CallResult.second;
1650 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1651 const PPCSubtarget &Subtarget) const {
1652 MachineFunction &MF = DAG.getMachineFunction();
1653 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1655 DebugLoc dl = Op.getDebugLoc();
1657 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1658 // vastart just stores the address of the VarArgsFrameIndex slot into the
1659 // memory location argument.
1660 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1661 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1662 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1663 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1664 MachinePointerInfo(SV),
1668 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1669 // We suppose the given va_list is already allocated.
1672 // char gpr; /* index into the array of 8 GPRs
1673 // * stored in the register save area
1674 // * gpr=0 corresponds to r3,
1675 // * gpr=1 to r4, etc.
1677 // char fpr; /* index into the array of 8 FPRs
1678 // * stored in the register save area
1679 // * fpr=0 corresponds to f1,
1680 // * fpr=1 to f2, etc.
1682 // char *overflow_arg_area;
1683 // /* location on stack that holds
1684 // * the next overflow argument
1686 // char *reg_save_area;
1687 // /* where r3:r10 and f1:f8 (if saved)
1693 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1694 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1697 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1699 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1701 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1704 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1705 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1707 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1708 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1710 uint64_t FPROffset = 1;
1711 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1713 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1715 // Store first byte : number of int regs
1716 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1718 MachinePointerInfo(SV),
1719 MVT::i8, false, false, 0);
1720 uint64_t nextOffset = FPROffset;
1721 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1724 // Store second byte : number of float regs
1725 SDValue secondStore =
1726 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1727 MachinePointerInfo(SV, nextOffset), MVT::i8,
1729 nextOffset += StackOffset;
1730 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1732 // Store second word : arguments given on stack
1733 SDValue thirdStore =
1734 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1735 MachinePointerInfo(SV, nextOffset),
1737 nextOffset += FrameOffset;
1738 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1740 // Store third word : arguments given in registers
1741 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1742 MachinePointerInfo(SV, nextOffset),
1747 #include "PPCGenCallingConv.inc"
1749 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1750 CCValAssign::LocInfo &LocInfo,
1751 ISD::ArgFlagsTy &ArgFlags,
1756 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1758 CCValAssign::LocInfo &LocInfo,
1759 ISD::ArgFlagsTy &ArgFlags,
1761 static const uint16_t ArgRegs[] = {
1762 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1763 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1765 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1767 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1769 // Skip one register if the first unallocated register has an even register
1770 // number and there are still argument registers available which have not been
1771 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1772 // need to skip a register if RegNum is odd.
1773 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1774 State.AllocateReg(ArgRegs[RegNum]);
1777 // Always return false here, as this function only makes sure that the first
1778 // unallocated register has an odd register number and does not actually
1779 // allocate a register for the current argument.
1783 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1785 CCValAssign::LocInfo &LocInfo,
1786 ISD::ArgFlagsTy &ArgFlags,
1788 static const uint16_t ArgRegs[] = {
1789 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1793 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1795 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1797 // If there is only one Floating-point register left we need to put both f64
1798 // values of a split ppc_fp128 value on the stack.
1799 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1800 State.AllocateReg(ArgRegs[RegNum]);
1803 // Always return false here, as this function only makes sure that the two f64
1804 // values a ppc_fp128 value is split into are both passed in registers or both
1805 // passed on the stack and does not actually allocate a register for the
1806 // current argument.
1810 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1812 static const uint16_t *GetFPR() {
1813 static const uint16_t FPR[] = {
1814 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1815 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1821 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1823 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1824 unsigned PtrByteSize) {
1825 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1826 if (Flags.isByVal())
1827 ArgSize = Flags.getByValSize();
1828 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1834 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1835 CallingConv::ID CallConv, bool isVarArg,
1836 const SmallVectorImpl<ISD::InputArg>
1838 DebugLoc dl, SelectionDAG &DAG,
1839 SmallVectorImpl<SDValue> &InVals)
1841 if (PPCSubTarget.isSVR4ABI()) {
1842 if (PPCSubTarget.isPPC64())
1843 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1846 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1849 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1855 PPCTargetLowering::LowerFormalArguments_32SVR4(
1857 CallingConv::ID CallConv, bool isVarArg,
1858 const SmallVectorImpl<ISD::InputArg>
1860 DebugLoc dl, SelectionDAG &DAG,
1861 SmallVectorImpl<SDValue> &InVals) const {
1863 // 32-bit SVR4 ABI Stack Frame Layout:
1864 // +-----------------------------------+
1865 // +--> | Back chain |
1866 // | +-----------------------------------+
1867 // | | Floating-point register save area |
1868 // | +-----------------------------------+
1869 // | | General register save area |
1870 // | +-----------------------------------+
1871 // | | CR save word |
1872 // | +-----------------------------------+
1873 // | | VRSAVE save word |
1874 // | +-----------------------------------+
1875 // | | Alignment padding |
1876 // | +-----------------------------------+
1877 // | | Vector register save area |
1878 // | +-----------------------------------+
1879 // | | Local variable space |
1880 // | +-----------------------------------+
1881 // | | Parameter list area |
1882 // | +-----------------------------------+
1883 // | | LR save word |
1884 // | +-----------------------------------+
1885 // SP--> +--- | Back chain |
1886 // +-----------------------------------+
1889 // System V Application Binary Interface PowerPC Processor Supplement
1890 // AltiVec Technology Programming Interface Manual
1892 MachineFunction &MF = DAG.getMachineFunction();
1893 MachineFrameInfo *MFI = MF.getFrameInfo();
1894 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1896 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1897 // Potential tail calls could cause overwriting of argument stack slots.
1898 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1899 (CallConv == CallingConv::Fast));
1900 unsigned PtrByteSize = 4;
1902 // Assign locations to all of the incoming arguments.
1903 SmallVector<CCValAssign, 16> ArgLocs;
1904 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1905 getTargetMachine(), ArgLocs, *DAG.getContext());
1907 // Reserve space for the linkage area on the stack.
1908 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1910 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4);
1912 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1913 CCValAssign &VA = ArgLocs[i];
1915 // Arguments stored in registers.
1916 if (VA.isRegLoc()) {
1917 const TargetRegisterClass *RC;
1918 EVT ValVT = VA.getValVT();
1920 switch (ValVT.getSimpleVT().SimpleTy) {
1922 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1924 RC = &PPC::GPRCRegClass;
1927 RC = &PPC::F4RCRegClass;
1930 RC = &PPC::F8RCRegClass;
1936 RC = &PPC::VRRCRegClass;
1940 // Transform the arguments stored in physical registers into virtual ones.
1941 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1942 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1944 InVals.push_back(ArgValue);
1946 // Argument stored in memory.
1947 assert(VA.isMemLoc());
1949 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1950 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1953 // Create load nodes to retrieve arguments from the stack.
1954 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1955 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1956 MachinePointerInfo(),
1957 false, false, false, 0));
1961 // Assign locations to all of the incoming aggregate by value arguments.
1962 // Aggregates passed by value are stored in the local variable space of the
1963 // caller's stack frame, right above the parameter list area.
1964 SmallVector<CCValAssign, 16> ByValArgLocs;
1965 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1966 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1968 // Reserve stack space for the allocations in CCInfo.
1969 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1971 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal);
1973 // Area that is at least reserved in the caller of this function.
1974 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1976 // Set the size that is at least reserved in caller of this function. Tail
1977 // call optimized function's reserved stack space needs to be aligned so that
1978 // taking the difference between two stack areas will result in an aligned
1980 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1983 std::max(MinReservedArea,
1984 PPCFrameLowering::getMinCallFrameSize(false, false));
1986 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1987 getStackAlignment();
1988 unsigned AlignMask = TargetAlign-1;
1989 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1991 FI->setMinReservedArea(MinReservedArea);
1993 SmallVector<SDValue, 8> MemOps;
1995 // If the function takes variable number of arguments, make a frame index for
1996 // the start of the first vararg value... for expansion of llvm.va_start.
1998 static const uint16_t GPArgRegs[] = {
1999 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2000 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2002 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2004 static const uint16_t FPArgRegs[] = {
2005 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2008 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2010 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2012 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2015 // Make room for NumGPArgRegs and NumFPArgRegs.
2016 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2017 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2019 FuncInfo->setVarArgsStackOffset(
2020 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2021 CCInfo.getNextStackOffset(), true));
2023 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2024 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2026 // The fixed integer arguments of a variadic function are stored to the
2027 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2028 // the result of va_next.
2029 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2030 // Get an existing live-in vreg, or add a new one.
2031 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2033 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2035 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2036 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2037 MachinePointerInfo(), false, false, 0);
2038 MemOps.push_back(Store);
2039 // Increment the address by four for the next argument to store
2040 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2041 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2044 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2046 // The double arguments are stored to the VarArgsFrameIndex
2048 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2049 // Get an existing live-in vreg, or add a new one.
2050 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2052 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2054 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2055 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2056 MachinePointerInfo(), false, false, 0);
2057 MemOps.push_back(Store);
2058 // Increment the address by eight for the next argument to store
2059 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2061 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2065 if (!MemOps.empty())
2066 Chain = DAG.getNode(ISD::TokenFactor, dl,
2067 MVT::Other, &MemOps[0], MemOps.size());
2072 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2073 // value to MVT::i64 and then truncate to the correct register size.
2075 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2076 SelectionDAG &DAG, SDValue ArgVal,
2077 DebugLoc dl) const {
2079 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2080 DAG.getValueType(ObjectVT));
2081 else if (Flags.isZExt())
2082 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2083 DAG.getValueType(ObjectVT));
2085 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2088 // Set the size that is at least reserved in caller of this function. Tail
2089 // call optimized functions' reserved stack space needs to be aligned so that
2090 // taking the difference between two stack areas will result in an aligned
2093 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2094 unsigned nAltivecParamsAtEnd,
2095 unsigned MinReservedArea,
2096 bool isPPC64) const {
2097 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2098 // Add the Altivec parameters at the end, if needed.
2099 if (nAltivecParamsAtEnd) {
2100 MinReservedArea = ((MinReservedArea+15)/16)*16;
2101 MinReservedArea += 16*nAltivecParamsAtEnd;
2104 std::max(MinReservedArea,
2105 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2106 unsigned TargetAlign
2107 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2108 getStackAlignment();
2109 unsigned AlignMask = TargetAlign-1;
2110 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2111 FI->setMinReservedArea(MinReservedArea);
2115 PPCTargetLowering::LowerFormalArguments_64SVR4(
2117 CallingConv::ID CallConv, bool isVarArg,
2118 const SmallVectorImpl<ISD::InputArg>
2120 DebugLoc dl, SelectionDAG &DAG,
2121 SmallVectorImpl<SDValue> &InVals) const {
2122 // TODO: add description of PPC stack frame format, or at least some docs.
2124 MachineFunction &MF = DAG.getMachineFunction();
2125 MachineFrameInfo *MFI = MF.getFrameInfo();
2126 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2128 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2129 // Potential tail calls could cause overwriting of argument stack slots.
2130 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2131 (CallConv == CallingConv::Fast));
2132 unsigned PtrByteSize = 8;
2134 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2135 // Area that is at least reserved in caller of this function.
2136 unsigned MinReservedArea = ArgOffset;
2138 static const uint16_t GPR[] = {
2139 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2140 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2143 static const uint16_t *FPR = GetFPR();
2145 static const uint16_t VR[] = {
2146 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2147 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2150 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2151 const unsigned Num_FPR_Regs = 13;
2152 const unsigned Num_VR_Regs = array_lengthof(VR);
2154 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2156 // Add DAG nodes to load the arguments or copy them out of registers. On
2157 // entry to a function on PPC, the arguments start after the linkage area,
2158 // although the first ones are often in registers.
2160 SmallVector<SDValue, 8> MemOps;
2161 unsigned nAltivecParamsAtEnd = 0;
2162 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2163 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2165 bool needsLoad = false;
2166 EVT ObjectVT = Ins[ArgNo].VT;
2167 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2168 unsigned ArgSize = ObjSize;
2169 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2171 unsigned CurArgOffset = ArgOffset;
2173 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2174 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2175 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2177 MinReservedArea = ((MinReservedArea+15)/16)*16;
2178 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2182 nAltivecParamsAtEnd++;
2184 // Calculate min reserved area.
2185 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2189 // FIXME the codegen can be much improved in some cases.
2190 // We do not have to keep everything in memory.
2191 if (Flags.isByVal()) {
2192 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2193 ObjSize = Flags.getByValSize();
2194 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2195 // Empty aggregate parameters do not take up registers. Examples:
2199 // etc. However, we have to provide a place-holder in InVals, so
2200 // pretend we have an 8-byte item at the current address for that
2203 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2204 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2205 InVals.push_back(FIN);
2208 // All aggregates smaller than 8 bytes must be passed right-justified.
2209 if (ObjSize < PtrByteSize)
2210 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2211 // The value of the object is its address.
2212 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2213 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2214 InVals.push_back(FIN);
2217 if (GPR_idx != Num_GPR_Regs) {
2218 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2219 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2222 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2223 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2224 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2225 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2226 MachinePointerInfo(FuncArg, CurArgOffset),
2227 ObjType, false, false, 0);
2229 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2230 // store the whole register as-is to the parameter save area
2231 // slot. The address of the parameter was already calculated
2232 // above (InVals.push_back(FIN)) to be the right-justified
2233 // offset within the slot. For this store, we need a new
2234 // frame index that points at the beginning of the slot.
2235 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2236 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2237 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2238 MachinePointerInfo(FuncArg, ArgOffset),
2242 MemOps.push_back(Store);
2245 // Whether we copied from a register or not, advance the offset
2246 // into the parameter save area by a full doubleword.
2247 ArgOffset += PtrByteSize;
2251 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2252 // Store whatever pieces of the object are in registers
2253 // to memory. ArgOffset will be the address of the beginning
2255 if (GPR_idx != Num_GPR_Regs) {
2257 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2258 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2259 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2260 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2261 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2262 MachinePointerInfo(FuncArg, ArgOffset),
2264 MemOps.push_back(Store);
2266 ArgOffset += PtrByteSize;
2268 ArgOffset += ArgSize - j;
2275 switch (ObjectVT.getSimpleVT().SimpleTy) {
2276 default: llvm_unreachable("Unhandled argument type!");
2279 if (GPR_idx != Num_GPR_Regs) {
2280 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2281 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2283 if (ObjectVT == MVT::i32)
2284 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2285 // value to MVT::i64 and then truncate to the correct register size.
2286 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2291 ArgSize = PtrByteSize;
2298 // Every 8 bytes of argument space consumes one of the GPRs available for
2299 // argument passing.
2300 if (GPR_idx != Num_GPR_Regs) {
2303 if (FPR_idx != Num_FPR_Regs) {
2306 if (ObjectVT == MVT::f32)
2307 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2309 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2311 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2315 ArgSize = PtrByteSize;
2324 // Note that vector arguments in registers don't reserve stack space,
2325 // except in varargs functions.
2326 if (VR_idx != Num_VR_Regs) {
2327 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2328 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2330 while ((ArgOffset % 16) != 0) {
2331 ArgOffset += PtrByteSize;
2332 if (GPR_idx != Num_GPR_Regs)
2336 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2340 // Vectors are aligned.
2341 ArgOffset = ((ArgOffset+15)/16)*16;
2342 CurArgOffset = ArgOffset;
2349 // We need to load the argument to a virtual register if we determined
2350 // above that we ran out of physical registers of the appropriate type.
2352 int FI = MFI->CreateFixedObject(ObjSize,
2353 CurArgOffset + (ArgSize - ObjSize),
2355 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2356 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2357 false, false, false, 0);
2360 InVals.push_back(ArgVal);
2363 // Set the size that is at least reserved in caller of this function. Tail
2364 // call optimized functions' reserved stack space needs to be aligned so that
2365 // taking the difference between two stack areas will result in an aligned
2367 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2369 // If the function takes variable number of arguments, make a frame index for
2370 // the start of the first vararg value... for expansion of llvm.va_start.
2372 int Depth = ArgOffset;
2374 FuncInfo->setVarArgsFrameIndex(
2375 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2376 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2378 // If this function is vararg, store any remaining integer argument regs
2379 // to their spots on the stack so that they may be loaded by deferencing the
2380 // result of va_next.
2381 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2382 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2383 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2384 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2385 MachinePointerInfo(), false, false, 0);
2386 MemOps.push_back(Store);
2387 // Increment the address by four for the next argument to store
2388 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2389 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2393 if (!MemOps.empty())
2394 Chain = DAG.getNode(ISD::TokenFactor, dl,
2395 MVT::Other, &MemOps[0], MemOps.size());
2401 PPCTargetLowering::LowerFormalArguments_Darwin(
2403 CallingConv::ID CallConv, bool isVarArg,
2404 const SmallVectorImpl<ISD::InputArg>
2406 DebugLoc dl, SelectionDAG &DAG,
2407 SmallVectorImpl<SDValue> &InVals) const {
2408 // TODO: add description of PPC stack frame format, or at least some docs.
2410 MachineFunction &MF = DAG.getMachineFunction();
2411 MachineFrameInfo *MFI = MF.getFrameInfo();
2412 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2414 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2415 bool isPPC64 = PtrVT == MVT::i64;
2416 // Potential tail calls could cause overwriting of argument stack slots.
2417 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2418 (CallConv == CallingConv::Fast));
2419 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2421 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2422 // Area that is at least reserved in caller of this function.
2423 unsigned MinReservedArea = ArgOffset;
2425 static const uint16_t GPR_32[] = { // 32-bit registers.
2426 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2427 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2429 static const uint16_t GPR_64[] = { // 64-bit registers.
2430 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2431 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2434 static const uint16_t *FPR = GetFPR();
2436 static const uint16_t VR[] = {
2437 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2438 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2441 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2442 const unsigned Num_FPR_Regs = 13;
2443 const unsigned Num_VR_Regs = array_lengthof( VR);
2445 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2447 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2449 // In 32-bit non-varargs functions, the stack space for vectors is after the
2450 // stack space for non-vectors. We do not use this space unless we have
2451 // too many vectors to fit in registers, something that only occurs in
2452 // constructed examples:), but we have to walk the arglist to figure
2453 // that out...for the pathological case, compute VecArgOffset as the
2454 // start of the vector parameter area. Computing VecArgOffset is the
2455 // entire point of the following loop.
2456 unsigned VecArgOffset = ArgOffset;
2457 if (!isVarArg && !isPPC64) {
2458 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2460 EVT ObjectVT = Ins[ArgNo].VT;
2461 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2463 if (Flags.isByVal()) {
2464 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2465 unsigned ObjSize = Flags.getByValSize();
2467 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2468 VecArgOffset += ArgSize;
2472 switch(ObjectVT.getSimpleVT().SimpleTy) {
2473 default: llvm_unreachable("Unhandled argument type!");
2478 case MVT::i64: // PPC64
2480 // FIXME: We are guaranteed to be !isPPC64 at this point.
2481 // Does MVT::i64 apply?
2488 // Nothing to do, we're only looking at Nonvector args here.
2493 // We've found where the vector parameter area in memory is. Skip the
2494 // first 12 parameters; these don't use that memory.
2495 VecArgOffset = ((VecArgOffset+15)/16)*16;
2496 VecArgOffset += 12*16;
2498 // Add DAG nodes to load the arguments or copy them out of registers. On
2499 // entry to a function on PPC, the arguments start after the linkage area,
2500 // although the first ones are often in registers.
2502 SmallVector<SDValue, 8> MemOps;
2503 unsigned nAltivecParamsAtEnd = 0;
2504 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2505 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2507 bool needsLoad = false;
2508 EVT ObjectVT = Ins[ArgNo].VT;
2509 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2510 unsigned ArgSize = ObjSize;
2511 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2513 unsigned CurArgOffset = ArgOffset;
2515 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2516 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2517 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2518 if (isVarArg || isPPC64) {
2519 MinReservedArea = ((MinReservedArea+15)/16)*16;
2520 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2523 } else nAltivecParamsAtEnd++;
2525 // Calculate min reserved area.
2526 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2530 // FIXME the codegen can be much improved in some cases.
2531 // We do not have to keep everything in memory.
2532 if (Flags.isByVal()) {
2533 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2534 ObjSize = Flags.getByValSize();
2535 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2536 // Objects of size 1 and 2 are right justified, everything else is
2537 // left justified. This means the memory address is adjusted forwards.
2538 if (ObjSize==1 || ObjSize==2) {
2539 CurArgOffset = CurArgOffset + (4 - ObjSize);
2541 // The value of the object is its address.
2542 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2543 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2544 InVals.push_back(FIN);
2545 if (ObjSize==1 || ObjSize==2) {
2546 if (GPR_idx != Num_GPR_Regs) {
2549 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2551 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2552 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2553 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2554 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2555 MachinePointerInfo(FuncArg,
2557 ObjType, false, false, 0);
2558 MemOps.push_back(Store);
2562 ArgOffset += PtrByteSize;
2566 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2567 // Store whatever pieces of the object are in registers
2568 // to memory. ArgOffset will be the address of the beginning
2570 if (GPR_idx != Num_GPR_Regs) {
2573 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2575 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2576 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2577 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2578 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2579 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2580 MachinePointerInfo(FuncArg, ArgOffset),
2582 MemOps.push_back(Store);
2584 ArgOffset += PtrByteSize;
2586 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2593 switch (ObjectVT.getSimpleVT().SimpleTy) {
2594 default: llvm_unreachable("Unhandled argument type!");
2597 if (GPR_idx != Num_GPR_Regs) {
2598 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2599 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2603 ArgSize = PtrByteSize;
2605 // All int arguments reserve stack space in the Darwin ABI.
2606 ArgOffset += PtrByteSize;
2610 case MVT::i64: // PPC64
2611 if (GPR_idx != Num_GPR_Regs) {
2612 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2613 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2615 if (ObjectVT == MVT::i32)
2616 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2617 // value to MVT::i64 and then truncate to the correct register size.
2618 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2623 ArgSize = PtrByteSize;
2625 // All int arguments reserve stack space in the Darwin ABI.
2631 // Every 4 bytes of argument space consumes one of the GPRs available for
2632 // argument passing.
2633 if (GPR_idx != Num_GPR_Regs) {
2635 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2638 if (FPR_idx != Num_FPR_Regs) {
2641 if (ObjectVT == MVT::f32)
2642 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2644 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2646 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2652 // All FP arguments reserve stack space in the Darwin ABI.
2653 ArgOffset += isPPC64 ? 8 : ObjSize;
2659 // Note that vector arguments in registers don't reserve stack space,
2660 // except in varargs functions.
2661 if (VR_idx != Num_VR_Regs) {
2662 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2663 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2665 while ((ArgOffset % 16) != 0) {
2666 ArgOffset += PtrByteSize;
2667 if (GPR_idx != Num_GPR_Regs)
2671 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2675 if (!isVarArg && !isPPC64) {
2676 // Vectors go after all the nonvectors.
2677 CurArgOffset = VecArgOffset;
2680 // Vectors are aligned.
2681 ArgOffset = ((ArgOffset+15)/16)*16;
2682 CurArgOffset = ArgOffset;
2690 // We need to load the argument to a virtual register if we determined above
2691 // that we ran out of physical registers of the appropriate type.
2693 int FI = MFI->CreateFixedObject(ObjSize,
2694 CurArgOffset + (ArgSize - ObjSize),
2696 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2697 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2698 false, false, false, 0);
2701 InVals.push_back(ArgVal);
2704 // Set the size that is at least reserved in caller of this function. Tail
2705 // call optimized functions' reserved stack space needs to be aligned so that
2706 // taking the difference between two stack areas will result in an aligned
2708 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2710 // If the function takes variable number of arguments, make a frame index for
2711 // the start of the first vararg value... for expansion of llvm.va_start.
2713 int Depth = ArgOffset;
2715 FuncInfo->setVarArgsFrameIndex(
2716 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2718 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2720 // If this function is vararg, store any remaining integer argument regs
2721 // to their spots on the stack so that they may be loaded by deferencing the
2722 // result of va_next.
2723 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2727 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2729 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2731 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2732 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2733 MachinePointerInfo(), false, false, 0);
2734 MemOps.push_back(Store);
2735 // Increment the address by four for the next argument to store
2736 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2737 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2741 if (!MemOps.empty())
2742 Chain = DAG.getNode(ISD::TokenFactor, dl,
2743 MVT::Other, &MemOps[0], MemOps.size());
2748 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2749 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2751 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2755 const SmallVectorImpl<ISD::OutputArg>
2757 const SmallVectorImpl<SDValue> &OutVals,
2758 unsigned &nAltivecParamsAtEnd) {
2759 // Count how many bytes are to be pushed on the stack, including the linkage
2760 // area, and parameter passing area. We start with 24/48 bytes, which is
2761 // prereserved space for [SP][CR][LR][3 x unused].
2762 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2763 unsigned NumOps = Outs.size();
2764 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2766 // Add up all the space actually used.
2767 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2768 // they all go in registers, but we must reserve stack space for them for
2769 // possible use by the caller. In varargs or 64-bit calls, parameters are
2770 // assigned stack space in order, with padding so Altivec parameters are
2772 nAltivecParamsAtEnd = 0;
2773 for (unsigned i = 0; i != NumOps; ++i) {
2774 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2775 EVT ArgVT = Outs[i].VT;
2776 // Varargs Altivec parameters are padded to a 16 byte boundary.
2777 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2778 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2779 if (!isVarArg && !isPPC64) {
2780 // Non-varargs Altivec parameters go after all the non-Altivec
2781 // parameters; handle those later so we know how much padding we need.
2782 nAltivecParamsAtEnd++;
2785 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2786 NumBytes = ((NumBytes+15)/16)*16;
2788 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2791 // Allow for Altivec parameters at the end, if needed.
2792 if (nAltivecParamsAtEnd) {
2793 NumBytes = ((NumBytes+15)/16)*16;
2794 NumBytes += 16*nAltivecParamsAtEnd;
2797 // The prolog code of the callee may store up to 8 GPR argument registers to
2798 // the stack, allowing va_start to index over them in memory if its varargs.
2799 // Because we cannot tell if this is needed on the caller side, we have to
2800 // conservatively assume that it is needed. As such, make sure we have at
2801 // least enough stack space for the caller to store the 8 GPRs.
2802 NumBytes = std::max(NumBytes,
2803 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2805 // Tail call needs the stack to be aligned.
2806 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2807 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2808 getFrameLowering()->getStackAlignment();
2809 unsigned AlignMask = TargetAlign-1;
2810 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2816 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2817 /// adjusted to accommodate the arguments for the tailcall.
2818 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2819 unsigned ParamSize) {
2821 if (!isTailCall) return 0;
2823 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2824 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2825 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2826 // Remember only if the new adjustement is bigger.
2827 if (SPDiff < FI->getTailCallSPDelta())
2828 FI->setTailCallSPDelta(SPDiff);
2833 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2834 /// for tail call optimization. Targets which want to do tail call
2835 /// optimization should implement this function.
2837 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2838 CallingConv::ID CalleeCC,
2840 const SmallVectorImpl<ISD::InputArg> &Ins,
2841 SelectionDAG& DAG) const {
2842 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2845 // Variable argument functions are not supported.
2849 MachineFunction &MF = DAG.getMachineFunction();
2850 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2851 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2852 // Functions containing by val parameters are not supported.
2853 for (unsigned i = 0; i != Ins.size(); i++) {
2854 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2855 if (Flags.isByVal()) return false;
2858 // Non PIC/GOT tail calls are supported.
2859 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2862 // At the moment we can only do local tail calls (in same module, hidden
2863 // or protected) if we are generating PIC.
2864 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2865 return G->getGlobal()->hasHiddenVisibility()
2866 || G->getGlobal()->hasProtectedVisibility();
2872 /// isCallCompatibleAddress - Return the immediate to use if the specified
2873 /// 32-bit value is representable in the immediate field of a BxA instruction.
2874 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2875 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2878 int Addr = C->getZExtValue();
2879 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2880 SignExtend32<26>(Addr) != Addr)
2881 return 0; // Top 6 bits have to be sext of immediate.
2883 return DAG.getConstant((int)C->getZExtValue() >> 2,
2884 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2889 struct TailCallArgumentInfo {
2894 TailCallArgumentInfo() : FrameIdx(0) {}
2899 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2901 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2903 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2904 SmallVector<SDValue, 8> &MemOpChains,
2906 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2907 SDValue Arg = TailCallArgs[i].Arg;
2908 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2909 int FI = TailCallArgs[i].FrameIdx;
2910 // Store relative to framepointer.
2911 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2912 MachinePointerInfo::getFixedStack(FI),
2917 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2918 /// the appropriate stack slot for the tail call optimized function call.
2919 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2920 MachineFunction &MF,
2929 // Calculate the new stack slot for the return address.
2930 int SlotSize = isPPC64 ? 8 : 4;
2931 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2933 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2934 NewRetAddrLoc, true);
2935 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2936 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2937 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2938 MachinePointerInfo::getFixedStack(NewRetAddr),
2941 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2942 // slot as the FP is never overwritten.
2945 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2946 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2948 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2949 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2950 MachinePointerInfo::getFixedStack(NewFPIdx),
2957 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2958 /// the position of the argument.
2960 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2961 SDValue Arg, int SPDiff, unsigned ArgOffset,
2962 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2963 int Offset = ArgOffset + SPDiff;
2964 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2965 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2966 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2967 SDValue FIN = DAG.getFrameIndex(FI, VT);
2968 TailCallArgumentInfo Info;
2970 Info.FrameIdxOp = FIN;
2972 TailCallArguments.push_back(Info);
2975 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2976 /// stack slot. Returns the chain as result and the loaded frame pointers in
2977 /// LROpOut/FPOpout. Used when tail calling.
2978 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2984 DebugLoc dl) const {
2986 // Load the LR and FP stack slot for later adjusting.
2987 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2988 LROpOut = getReturnAddrFrameIndex(DAG);
2989 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
2990 false, false, false, 0);
2991 Chain = SDValue(LROpOut.getNode(), 1);
2993 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
2994 // slot as the FP is never overwritten.
2996 FPOpOut = getFramePointerFrameIndex(DAG);
2997 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
2998 false, false, false, 0);
2999 Chain = SDValue(FPOpOut.getNode(), 1);
3005 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3006 /// by "Src" to address "Dst" of size "Size". Alignment information is
3007 /// specified by the specific parameter attribute. The copy will be passed as
3008 /// a byval function parameter.
3009 /// Sometimes what we are copying is the end of a larger object, the part that
3010 /// does not fit in registers.
3012 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3013 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3015 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3016 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3017 false, false, MachinePointerInfo(0),
3018 MachinePointerInfo(0));
3021 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3024 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3025 SDValue Arg, SDValue PtrOff, int SPDiff,
3026 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3027 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3028 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3030 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3035 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3037 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3038 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3039 DAG.getConstant(ArgOffset, PtrVT));
3041 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3042 MachinePointerInfo(), false, false, 0));
3043 // Calculate and remember argument location.
3044 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3049 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3050 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3051 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3052 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3053 MachineFunction &MF = DAG.getMachineFunction();
3055 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3056 // might overwrite each other in case of tail call optimization.
3057 SmallVector<SDValue, 8> MemOpChains2;
3058 // Do not flag preceding copytoreg stuff together with the following stuff.
3060 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3062 if (!MemOpChains2.empty())
3063 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3064 &MemOpChains2[0], MemOpChains2.size());
3066 // Store the return address to the appropriate stack slot.
3067 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3068 isPPC64, isDarwinABI, dl);
3070 // Emit callseq_end just before tailcall node.
3071 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3072 DAG.getIntPtrConstant(0, true), InFlag);
3073 InFlag = Chain.getValue(1);
3077 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3078 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3079 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3080 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3081 const PPCSubtarget &PPCSubTarget) {
3083 bool isPPC64 = PPCSubTarget.isPPC64();
3084 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3086 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3087 NodeTys.push_back(MVT::Other); // Returns a chain
3088 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3090 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
3092 bool needIndirectCall = true;
3093 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3094 // If this is an absolute destination address, use the munged value.
3095 Callee = SDValue(Dest, 0);
3096 needIndirectCall = false;
3099 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3100 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3101 // Use indirect calls for ALL functions calls in JIT mode, since the
3102 // far-call stubs may be outside relocation limits for a BL instruction.
3103 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3104 unsigned OpFlags = 0;
3105 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3106 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3107 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3108 (G->getGlobal()->isDeclaration() ||
3109 G->getGlobal()->isWeakForLinker())) {
3110 // PC-relative references to external symbols should go through $stub,
3111 // unless we're building with the leopard linker or later, which
3112 // automatically synthesizes these stubs.
3113 OpFlags = PPCII::MO_DARWIN_STUB;
3116 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3117 // every direct call is) turn it into a TargetGlobalAddress /
3118 // TargetExternalSymbol node so that legalize doesn't hack it.
3119 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3120 Callee.getValueType(),
3122 needIndirectCall = false;
3126 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3127 unsigned char OpFlags = 0;
3129 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3130 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3131 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3132 // PC-relative references to external symbols should go through $stub,
3133 // unless we're building with the leopard linker or later, which
3134 // automatically synthesizes these stubs.
3135 OpFlags = PPCII::MO_DARWIN_STUB;
3138 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3140 needIndirectCall = false;
3143 if (needIndirectCall) {
3144 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3145 // to do the call, we can't use PPCISD::CALL.
3146 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3148 if (isSVR4ABI && isPPC64) {
3149 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3150 // entry point, but to the function descriptor (the function entry point
3151 // address is part of the function descriptor though).
3152 // The function descriptor is a three doubleword structure with the
3153 // following fields: function entry point, TOC base address and
3154 // environment pointer.
3155 // Thus for a call through a function pointer, the following actions need
3157 // 1. Save the TOC of the caller in the TOC save area of its stack
3158 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3159 // 2. Load the address of the function entry point from the function
3161 // 3. Load the TOC of the callee from the function descriptor into r2.
3162 // 4. Load the environment pointer from the function descriptor into
3164 // 5. Branch to the function entry point address.
3165 // 6. On return of the callee, the TOC of the caller needs to be
3166 // restored (this is done in FinishCall()).
3168 // All those operations are flagged together to ensure that no other
3169 // operations can be scheduled in between. E.g. without flagging the
3170 // operations together, a TOC access in the caller could be scheduled
3171 // between the load of the callee TOC and the branch to the callee, which
3172 // results in the TOC access going through the TOC of the callee instead
3173 // of going through the TOC of the caller, which leads to incorrect code.
3175 // Load the address of the function entry point from the function
3177 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3178 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3179 InFlag.getNode() ? 3 : 2);
3180 Chain = LoadFuncPtr.getValue(1);
3181 InFlag = LoadFuncPtr.getValue(2);
3183 // Load environment pointer into r11.
3184 // Offset of the environment pointer within the function descriptor.
3185 SDValue PtrOff = DAG.getIntPtrConstant(16);
3187 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3188 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3190 Chain = LoadEnvPtr.getValue(1);
3191 InFlag = LoadEnvPtr.getValue(2);
3193 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3195 Chain = EnvVal.getValue(0);
3196 InFlag = EnvVal.getValue(1);
3198 // Load TOC of the callee into r2. We are using a target-specific load
3199 // with r2 hard coded, because the result of a target-independent load
3200 // would never go directly into r2, since r2 is a reserved register (which
3201 // prevents the register allocator from allocating it), resulting in an
3202 // additional register being allocated and an unnecessary move instruction
3204 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3205 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3207 Chain = LoadTOCPtr.getValue(0);
3208 InFlag = LoadTOCPtr.getValue(1);
3210 MTCTROps[0] = Chain;
3211 MTCTROps[1] = LoadFuncPtr;
3212 MTCTROps[2] = InFlag;
3215 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3216 2 + (InFlag.getNode() != 0));
3217 InFlag = Chain.getValue(1);
3220 NodeTys.push_back(MVT::Other);
3221 NodeTys.push_back(MVT::Glue);
3222 Ops.push_back(Chain);
3223 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
3225 // Add CTR register as callee so a bctr can be emitted later.
3227 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3230 // If this is a direct call, pass the chain and the callee.
3231 if (Callee.getNode()) {
3232 Ops.push_back(Chain);
3233 Ops.push_back(Callee);
3235 // If this is a tail call add stack pointer delta.
3237 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3239 // Add argument registers to the end of the list so that they are known live
3241 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3242 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3243 RegsToPass[i].second.getValueType()));
3249 bool isLocalCall(const SDValue &Callee)
3251 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3252 return !G->getGlobal()->isDeclaration() &&
3253 !G->getGlobal()->isWeakForLinker();
3258 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3259 CallingConv::ID CallConv, bool isVarArg,
3260 const SmallVectorImpl<ISD::InputArg> &Ins,
3261 DebugLoc dl, SelectionDAG &DAG,
3262 SmallVectorImpl<SDValue> &InVals) const {
3264 SmallVector<CCValAssign, 16> RVLocs;
3265 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3266 getTargetMachine(), RVLocs, *DAG.getContext());
3267 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3269 // Copy all of the result registers out of their specified physreg.
3270 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3271 CCValAssign &VA = RVLocs[i];
3272 assert(VA.isRegLoc() && "Can only return in registers!");
3274 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3275 VA.getLocReg(), VA.getLocVT(), InFlag);
3276 Chain = Val.getValue(1);
3277 InFlag = Val.getValue(2);
3279 switch (VA.getLocInfo()) {
3280 default: llvm_unreachable("Unknown loc info!");
3281 case CCValAssign::Full: break;
3282 case CCValAssign::AExt:
3283 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3285 case CCValAssign::ZExt:
3286 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3287 DAG.getValueType(VA.getValVT()));
3288 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3290 case CCValAssign::SExt:
3291 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3292 DAG.getValueType(VA.getValVT()));
3293 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3297 InVals.push_back(Val);
3304 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3305 bool isTailCall, bool isVarArg,
3307 SmallVector<std::pair<unsigned, SDValue>, 8>
3309 SDValue InFlag, SDValue Chain,
3311 int SPDiff, unsigned NumBytes,
3312 const SmallVectorImpl<ISD::InputArg> &Ins,
3313 SmallVectorImpl<SDValue> &InVals) const {
3314 std::vector<EVT> NodeTys;
3315 SmallVector<SDValue, 8> Ops;
3316 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3317 isTailCall, RegsToPass, Ops, NodeTys,
3320 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3321 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3322 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3324 // When performing tail call optimization the callee pops its arguments off
3325 // the stack. Account for this here so these bytes can be pushed back on in
3326 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
3327 int BytesCalleePops =
3328 (CallConv == CallingConv::Fast &&
3329 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3331 // Add a register mask operand representing the call-preserved registers.
3332 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3333 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3334 assert(Mask && "Missing call preserved mask for calling convention");
3335 Ops.push_back(DAG.getRegisterMask(Mask));
3337 if (InFlag.getNode())
3338 Ops.push_back(InFlag);
3342 // If this is the first return lowered for this function, add the regs
3343 // to the liveout set for the function.
3344 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3345 SmallVector<CCValAssign, 16> RVLocs;
3346 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3347 getTargetMachine(), RVLocs, *DAG.getContext());
3348 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3349 for (unsigned i = 0; i != RVLocs.size(); ++i)
3350 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3353 assert(((Callee.getOpcode() == ISD::Register &&
3354 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3355 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3356 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3357 isa<ConstantSDNode>(Callee)) &&
3358 "Expecting an global address, external symbol, absolute value or register");
3360 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3363 // Add a NOP immediately after the branch instruction when using the 64-bit
3364 // SVR4 ABI. At link time, if caller and callee are in a different module and
3365 // thus have a different TOC, the call will be replaced with a call to a stub
3366 // function which saves the current TOC, loads the TOC of the callee and
3367 // branches to the callee. The NOP will be replaced with a load instruction
3368 // which restores the TOC of the caller from the TOC save slot of the current
3369 // stack frame. If caller and callee belong to the same module (and have the
3370 // same TOC), the NOP will remain unchanged.
3372 bool needsTOCRestore = false;
3373 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3374 if (CallOpc == PPCISD::BCTRL_SVR4) {
3375 // This is a call through a function pointer.
3376 // Restore the caller TOC from the save area into R2.
3377 // See PrepareCall() for more information about calls through function
3378 // pointers in the 64-bit SVR4 ABI.
3379 // We are using a target-specific load with r2 hard coded, because the
3380 // result of a target-independent load would never go directly into r2,
3381 // since r2 is a reserved register (which prevents the register allocator
3382 // from allocating it), resulting in an additional register being
3383 // allocated and an unnecessary move instruction being generated.
3384 needsTOCRestore = true;
3385 } else if ((CallOpc == PPCISD::CALL_SVR4) && !isLocalCall(Callee)) {
3386 // Otherwise insert NOP for non-local calls.
3387 CallOpc = PPCISD::CALL_NOP_SVR4;
3391 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3392 InFlag = Chain.getValue(1);
3394 if (needsTOCRestore) {
3395 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3396 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3397 InFlag = Chain.getValue(1);
3400 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3401 DAG.getIntPtrConstant(BytesCalleePops, true),
3404 InFlag = Chain.getValue(1);
3406 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3407 Ins, dl, DAG, InVals);
3411 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3412 SmallVectorImpl<SDValue> &InVals) const {
3413 SelectionDAG &DAG = CLI.DAG;
3414 DebugLoc &dl = CLI.DL;
3415 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3416 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3417 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3418 SDValue Chain = CLI.Chain;
3419 SDValue Callee = CLI.Callee;
3420 bool &isTailCall = CLI.IsTailCall;
3421 CallingConv::ID CallConv = CLI.CallConv;
3422 bool isVarArg = CLI.IsVarArg;
3425 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3428 if (PPCSubTarget.isSVR4ABI()) {
3429 if (PPCSubTarget.isPPC64())
3430 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3431 isTailCall, Outs, OutVals, Ins,
3434 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3435 isTailCall, Outs, OutVals, Ins,
3439 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3440 isTailCall, Outs, OutVals, Ins,
3445 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3446 CallingConv::ID CallConv, bool isVarArg,
3448 const SmallVectorImpl<ISD::OutputArg> &Outs,
3449 const SmallVectorImpl<SDValue> &OutVals,
3450 const SmallVectorImpl<ISD::InputArg> &Ins,
3451 DebugLoc dl, SelectionDAG &DAG,
3452 SmallVectorImpl<SDValue> &InVals) const {
3453 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3454 // of the 32-bit SVR4 ABI stack frame layout.
3456 assert((CallConv == CallingConv::C ||
3457 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3459 unsigned PtrByteSize = 4;
3461 MachineFunction &MF = DAG.getMachineFunction();
3463 // Mark this function as potentially containing a function that contains a
3464 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3465 // and restoring the callers stack pointer in this functions epilog. This is
3466 // done because by tail calling the called function might overwrite the value
3467 // in this function's (MF) stack pointer stack slot 0(SP).
3468 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3469 CallConv == CallingConv::Fast)
3470 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3472 // Count how many bytes are to be pushed on the stack, including the linkage
3473 // area, parameter list area and the part of the local variable space which
3474 // contains copies of aggregates which are passed by value.
3476 // Assign locations to all of the outgoing arguments.
3477 SmallVector<CCValAssign, 16> ArgLocs;
3478 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3479 getTargetMachine(), ArgLocs, *DAG.getContext());
3481 // Reserve space for the linkage area on the stack.
3482 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3485 // Handle fixed and variable vector arguments differently.
3486 // Fixed vector arguments go into registers as long as registers are
3487 // available. Variable vector arguments always go into memory.
3488 unsigned NumArgs = Outs.size();
3490 for (unsigned i = 0; i != NumArgs; ++i) {
3491 MVT ArgVT = Outs[i].VT;
3492 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3495 if (Outs[i].IsFixed) {
3496 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3499 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3505 errs() << "Call operand #" << i << " has unhandled type "
3506 << EVT(ArgVT).getEVTString() << "\n";
3508 llvm_unreachable(0);
3512 // All arguments are treated the same.
3513 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4);
3516 // Assign locations to all of the outgoing aggregate by value arguments.
3517 SmallVector<CCValAssign, 16> ByValArgLocs;
3518 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3519 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3521 // Reserve stack space for the allocations in CCInfo.
3522 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3524 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal);
3526 // Size of the linkage area, parameter list area and the part of the local
3527 // space variable where copies of aggregates which are passed by value are
3529 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3531 // Calculate by how many bytes the stack has to be adjusted in case of tail
3532 // call optimization.
3533 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3535 // Adjust the stack pointer for the new arguments...
3536 // These operations are automatically eliminated by the prolog/epilog pass
3537 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3538 SDValue CallSeqStart = Chain;
3540 // Load the return address and frame pointer so it can be moved somewhere else
3543 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3546 // Set up a copy of the stack pointer for use loading and storing any
3547 // arguments that may not fit in the registers available for argument
3549 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3551 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3552 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3553 SmallVector<SDValue, 8> MemOpChains;
3555 bool seenFloatArg = false;
3556 // Walk the register/memloc assignments, inserting copies/loads.
3557 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3560 CCValAssign &VA = ArgLocs[i];
3561 SDValue Arg = OutVals[i];
3562 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3564 if (Flags.isByVal()) {
3565 // Argument is an aggregate which is passed by value, thus we need to
3566 // create a copy of it in the local variable space of the current stack
3567 // frame (which is the stack frame of the caller) and pass the address of
3568 // this copy to the callee.
3569 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3570 CCValAssign &ByValVA = ByValArgLocs[j++];
3571 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3573 // Memory reserved in the local variable space of the callers stack frame.
3574 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3576 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3577 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3579 // Create a copy of the argument in the local area of the current
3581 SDValue MemcpyCall =
3582 CreateCopyOfByValArgument(Arg, PtrOff,
3583 CallSeqStart.getNode()->getOperand(0),
3586 // This must go outside the CALLSEQ_START..END.
3587 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3588 CallSeqStart.getNode()->getOperand(1));
3589 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3590 NewCallSeqStart.getNode());
3591 Chain = CallSeqStart = NewCallSeqStart;
3593 // Pass the address of the aggregate copy on the stack either in a
3594 // physical register or in the parameter list area of the current stack
3595 // frame to the callee.
3599 if (VA.isRegLoc()) {
3600 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3601 // Put argument in a physical register.
3602 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3604 // Put argument in the parameter list area of the current stack frame.
3605 assert(VA.isMemLoc());
3606 unsigned LocMemOffset = VA.getLocMemOffset();
3609 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3610 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3612 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3613 MachinePointerInfo(),
3616 // Calculate and remember argument location.
3617 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3623 if (!MemOpChains.empty())
3624 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3625 &MemOpChains[0], MemOpChains.size());
3627 // Build a sequence of copy-to-reg nodes chained together with token chain
3628 // and flag operands which copy the outgoing args into the appropriate regs.
3630 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3631 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3632 RegsToPass[i].second, InFlag);
3633 InFlag = Chain.getValue(1);
3636 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3639 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3640 SDValue Ops[] = { Chain, InFlag };
3642 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3643 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3645 InFlag = Chain.getValue(1);
3649 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3650 false, TailCallArguments);
3652 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3653 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3657 // Copy an argument into memory, being careful to do this outside the
3658 // call sequence for the call to which the argument belongs.
3660 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3661 SDValue CallSeqStart,
3662 ISD::ArgFlagsTy Flags,
3664 DebugLoc dl) const {
3665 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3666 CallSeqStart.getNode()->getOperand(0),
3668 // The MEMCPY must go outside the CALLSEQ_START..END.
3669 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3670 CallSeqStart.getNode()->getOperand(1));
3671 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3672 NewCallSeqStart.getNode());
3673 return NewCallSeqStart;
3677 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3678 CallingConv::ID CallConv, bool isVarArg,
3680 const SmallVectorImpl<ISD::OutputArg> &Outs,
3681 const SmallVectorImpl<SDValue> &OutVals,
3682 const SmallVectorImpl<ISD::InputArg> &Ins,
3683 DebugLoc dl, SelectionDAG &DAG,
3684 SmallVectorImpl<SDValue> &InVals) const {
3686 unsigned NumOps = Outs.size();
3688 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3689 unsigned PtrByteSize = 8;
3691 MachineFunction &MF = DAG.getMachineFunction();
3693 // Mark this function as potentially containing a function that contains a
3694 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3695 // and restoring the callers stack pointer in this functions epilog. This is
3696 // done because by tail calling the called function might overwrite the value
3697 // in this function's (MF) stack pointer stack slot 0(SP).
3698 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3699 CallConv == CallingConv::Fast)
3700 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3702 unsigned nAltivecParamsAtEnd = 0;
3704 // Count how many bytes are to be pushed on the stack, including the linkage
3705 // area, and parameter passing area. We start with at least 48 bytes, which
3706 // is reserved space for [SP][CR][LR][3 x unused].
3707 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3710 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3711 Outs, OutVals, nAltivecParamsAtEnd);
3713 // Calculate by how many bytes the stack has to be adjusted in case of tail
3714 // call optimization.
3715 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3717 // To protect arguments on the stack from being clobbered in a tail call,
3718 // force all the loads to happen before doing any other lowering.
3720 Chain = DAG.getStackArgumentTokenFactor(Chain);
3722 // Adjust the stack pointer for the new arguments...
3723 // These operations are automatically eliminated by the prolog/epilog pass
3724 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3725 SDValue CallSeqStart = Chain;
3727 // Load the return address and frame pointer so it can be move somewhere else
3730 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3733 // Set up a copy of the stack pointer for use loading and storing any
3734 // arguments that may not fit in the registers available for argument
3736 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3738 // Figure out which arguments are going to go in registers, and which in
3739 // memory. Also, if this is a vararg function, floating point operations
3740 // must be stored to our stack, and loaded into integer regs as well, if
3741 // any integer regs are available for argument passing.
3742 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3743 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3745 static const uint16_t GPR[] = {
3746 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3747 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3749 static const uint16_t *FPR = GetFPR();
3751 static const uint16_t VR[] = {
3752 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3753 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3755 const unsigned NumGPRs = array_lengthof(GPR);
3756 const unsigned NumFPRs = 13;
3757 const unsigned NumVRs = array_lengthof(VR);
3759 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3760 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3762 SmallVector<SDValue, 8> MemOpChains;
3763 for (unsigned i = 0; i != NumOps; ++i) {
3764 SDValue Arg = OutVals[i];
3765 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3767 // PtrOff will be used to store the current argument to the stack if a
3768 // register cannot be found for it.
3771 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3773 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3775 // Promote integers to 64-bit values.
3776 if (Arg.getValueType() == MVT::i32) {
3777 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3778 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3779 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3782 // FIXME memcpy is used way more than necessary. Correctness first.
3783 // Note: "by value" is code for passing a structure by value, not
3785 if (Flags.isByVal()) {
3786 // Note: Size includes alignment padding, so
3787 // struct x { short a; char b; }
3788 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3789 // These are the proper values we need for right-justifying the
3790 // aggregate in a parameter register.
3791 unsigned Size = Flags.getByValSize();
3793 // An empty aggregate parameter takes up no storage and no
3798 // All aggregates smaller than 8 bytes must be passed right-justified.
3799 if (Size==1 || Size==2 || Size==4) {
3800 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3801 if (GPR_idx != NumGPRs) {
3802 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3803 MachinePointerInfo(), VT,
3805 MemOpChains.push_back(Load.getValue(1));
3806 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3808 ArgOffset += PtrByteSize;
3813 if (GPR_idx == NumGPRs && Size < 8) {
3814 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3815 PtrOff.getValueType());
3816 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3817 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3820 ArgOffset += PtrByteSize;
3823 // Copy entire object into memory. There are cases where gcc-generated
3824 // code assumes it is there, even if it could be put entirely into
3825 // registers. (This is not what the doc says.)
3827 // FIXME: The above statement is likely due to a misunderstanding of the
3828 // documents. All arguments must be copied into the parameter area BY
3829 // THE CALLEE in the event that the callee takes the address of any
3830 // formal argument. That has not yet been implemented. However, it is
3831 // reasonable to use the stack area as a staging area for the register
3834 // Skip this for small aggregates, as we will use the same slot for a
3835 // right-justified copy, below.
3837 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3841 // When a register is available, pass a small aggregate right-justified.
3842 if (Size < 8 && GPR_idx != NumGPRs) {
3843 // The easiest way to get this right-justified in a register
3844 // is to copy the structure into the rightmost portion of a
3845 // local variable slot, then load the whole slot into the
3847 // FIXME: The memcpy seems to produce pretty awful code for
3848 // small aggregates, particularly for packed ones.
3849 // FIXME: It would be preferable to use the slot in the
3850 // parameter save area instead of a new local variable.
3851 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3852 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3853 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3857 // Load the slot into the register.
3858 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3859 MachinePointerInfo(),
3860 false, false, false, 0);
3861 MemOpChains.push_back(Load.getValue(1));
3862 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3864 // Done with this argument.
3865 ArgOffset += PtrByteSize;
3869 // For aggregates larger than PtrByteSize, copy the pieces of the
3870 // object that fit into registers from the parameter save area.
3871 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3872 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3873 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3874 if (GPR_idx != NumGPRs) {
3875 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3876 MachinePointerInfo(),
3877 false, false, false, 0);
3878 MemOpChains.push_back(Load.getValue(1));
3879 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3880 ArgOffset += PtrByteSize;
3882 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3889 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3890 default: llvm_unreachable("Unexpected ValueType for argument!");
3893 if (GPR_idx != NumGPRs) {
3894 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3896 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3897 true, isTailCall, false, MemOpChains,
3898 TailCallArguments, dl);
3900 ArgOffset += PtrByteSize;
3904 if (FPR_idx != NumFPRs) {
3905 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3908 // A single float or an aggregate containing only a single float
3909 // must be passed right-justified in the stack doubleword, and
3910 // in the GPR, if one is available.
3912 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3913 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3914 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3918 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3919 MachinePointerInfo(), false, false, 0);
3920 MemOpChains.push_back(Store);
3922 // Float varargs are always shadowed in available integer registers
3923 if (GPR_idx != NumGPRs) {
3924 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3925 MachinePointerInfo(), false, false,
3927 MemOpChains.push_back(Load.getValue(1));
3928 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3930 } else if (GPR_idx != NumGPRs)
3931 // If we have any FPRs remaining, we may also have GPRs remaining.
3934 // Single-precision floating-point values are mapped to the
3935 // second (rightmost) word of the stack doubleword.
3936 if (Arg.getValueType() == MVT::f32) {
3937 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3938 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3941 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3942 true, isTailCall, false, MemOpChains,
3943 TailCallArguments, dl);
3952 // These go aligned on the stack, or in the corresponding R registers
3953 // when within range. The Darwin PPC ABI doc claims they also go in
3954 // V registers; in fact gcc does this only for arguments that are
3955 // prototyped, not for those that match the ... We do it for all
3956 // arguments, seems to work.
3957 while (ArgOffset % 16 !=0) {
3958 ArgOffset += PtrByteSize;
3959 if (GPR_idx != NumGPRs)
3962 // We could elide this store in the case where the object fits
3963 // entirely in R registers. Maybe later.
3964 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3965 DAG.getConstant(ArgOffset, PtrVT));
3966 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3967 MachinePointerInfo(), false, false, 0);
3968 MemOpChains.push_back(Store);
3969 if (VR_idx != NumVRs) {
3970 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3971 MachinePointerInfo(),
3972 false, false, false, 0);
3973 MemOpChains.push_back(Load.getValue(1));
3974 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3977 for (unsigned i=0; i<16; i+=PtrByteSize) {
3978 if (GPR_idx == NumGPRs)
3980 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3981 DAG.getConstant(i, PtrVT));
3982 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3983 false, false, false, 0);
3984 MemOpChains.push_back(Load.getValue(1));
3985 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3990 // Non-varargs Altivec params generally go in registers, but have
3991 // stack space allocated at the end.
3992 if (VR_idx != NumVRs) {
3993 // Doesn't have GPR space allocated.
3994 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3996 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3997 true, isTailCall, true, MemOpChains,
3998 TailCallArguments, dl);
4005 if (!MemOpChains.empty())
4006 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4007 &MemOpChains[0], MemOpChains.size());
4009 // Check if this is an indirect call (MTCTR/BCTRL).
4010 // See PrepareCall() for more information about calls through function
4011 // pointers in the 64-bit SVR4 ABI.
4013 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4014 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4015 !isBLACompatibleAddress(Callee, DAG)) {
4016 // Load r2 into a virtual register and store it to the TOC save area.
4017 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4018 // TOC save area offset.
4019 SDValue PtrOff = DAG.getIntPtrConstant(40);
4020 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4021 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4023 // R12 must contain the address of an indirect callee. This does not
4024 // mean the MTCTR instruction must use R12; it's easier to model this
4025 // as an extra parameter, so do that.
4026 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4029 // Build a sequence of copy-to-reg nodes chained together with token chain
4030 // and flag operands which copy the outgoing args into the appropriate regs.
4032 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4033 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4034 RegsToPass[i].second, InFlag);
4035 InFlag = Chain.getValue(1);
4039 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4040 FPOp, true, TailCallArguments);
4042 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4043 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4048 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4049 CallingConv::ID CallConv, bool isVarArg,
4051 const SmallVectorImpl<ISD::OutputArg> &Outs,
4052 const SmallVectorImpl<SDValue> &OutVals,
4053 const SmallVectorImpl<ISD::InputArg> &Ins,
4054 DebugLoc dl, SelectionDAG &DAG,
4055 SmallVectorImpl<SDValue> &InVals) const {
4057 unsigned NumOps = Outs.size();
4059 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4060 bool isPPC64 = PtrVT == MVT::i64;
4061 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4063 MachineFunction &MF = DAG.getMachineFunction();
4065 // Mark this function as potentially containing a function that contains a
4066 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4067 // and restoring the callers stack pointer in this functions epilog. This is
4068 // done because by tail calling the called function might overwrite the value
4069 // in this function's (MF) stack pointer stack slot 0(SP).
4070 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4071 CallConv == CallingConv::Fast)
4072 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4074 unsigned nAltivecParamsAtEnd = 0;
4076 // Count how many bytes are to be pushed on the stack, including the linkage
4077 // area, and parameter passing area. We start with 24/48 bytes, which is
4078 // prereserved space for [SP][CR][LR][3 x unused].
4080 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4082 nAltivecParamsAtEnd);
4084 // Calculate by how many bytes the stack has to be adjusted in case of tail
4085 // call optimization.
4086 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4088 // To protect arguments on the stack from being clobbered in a tail call,
4089 // force all the loads to happen before doing any other lowering.
4091 Chain = DAG.getStackArgumentTokenFactor(Chain);
4093 // Adjust the stack pointer for the new arguments...
4094 // These operations are automatically eliminated by the prolog/epilog pass
4095 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4096 SDValue CallSeqStart = Chain;
4098 // Load the return address and frame pointer so it can be move somewhere else
4101 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4104 // Set up a copy of the stack pointer for use loading and storing any
4105 // arguments that may not fit in the registers available for argument
4109 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4111 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4113 // Figure out which arguments are going to go in registers, and which in
4114 // memory. Also, if this is a vararg function, floating point operations
4115 // must be stored to our stack, and loaded into integer regs as well, if
4116 // any integer regs are available for argument passing.
4117 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4118 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4120 static const uint16_t GPR_32[] = { // 32-bit registers.
4121 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4122 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4124 static const uint16_t GPR_64[] = { // 64-bit registers.
4125 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4126 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4128 static const uint16_t *FPR = GetFPR();
4130 static const uint16_t VR[] = {
4131 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4132 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4134 const unsigned NumGPRs = array_lengthof(GPR_32);
4135 const unsigned NumFPRs = 13;
4136 const unsigned NumVRs = array_lengthof(VR);
4138 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4140 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4141 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4143 SmallVector<SDValue, 8> MemOpChains;
4144 for (unsigned i = 0; i != NumOps; ++i) {
4145 SDValue Arg = OutVals[i];
4146 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4148 // PtrOff will be used to store the current argument to the stack if a
4149 // register cannot be found for it.
4152 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4154 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4156 // On PPC64, promote integers to 64-bit values.
4157 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4158 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4159 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4160 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4163 // FIXME memcpy is used way more than necessary. Correctness first.
4164 // Note: "by value" is code for passing a structure by value, not
4166 if (Flags.isByVal()) {
4167 unsigned Size = Flags.getByValSize();
4168 // Very small objects are passed right-justified. Everything else is
4169 // passed left-justified.
4170 if (Size==1 || Size==2) {
4171 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4172 if (GPR_idx != NumGPRs) {
4173 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4174 MachinePointerInfo(), VT,
4176 MemOpChains.push_back(Load.getValue(1));
4177 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4179 ArgOffset += PtrByteSize;
4181 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4182 PtrOff.getValueType());
4183 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4184 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4187 ArgOffset += PtrByteSize;
4191 // Copy entire object into memory. There are cases where gcc-generated
4192 // code assumes it is there, even if it could be put entirely into
4193 // registers. (This is not what the doc says.)
4194 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4198 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4199 // copy the pieces of the object that fit into registers from the
4200 // parameter save area.
4201 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4202 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4203 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4204 if (GPR_idx != NumGPRs) {
4205 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4206 MachinePointerInfo(),
4207 false, false, false, 0);
4208 MemOpChains.push_back(Load.getValue(1));
4209 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4210 ArgOffset += PtrByteSize;
4212 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4219 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4220 default: llvm_unreachable("Unexpected ValueType for argument!");
4223 if (GPR_idx != NumGPRs) {
4224 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4226 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4227 isPPC64, isTailCall, false, MemOpChains,
4228 TailCallArguments, dl);
4230 ArgOffset += PtrByteSize;
4234 if (FPR_idx != NumFPRs) {
4235 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4238 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4239 MachinePointerInfo(), false, false, 0);
4240 MemOpChains.push_back(Store);
4242 // Float varargs are always shadowed in available integer registers
4243 if (GPR_idx != NumGPRs) {
4244 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4245 MachinePointerInfo(), false, false,
4247 MemOpChains.push_back(Load.getValue(1));
4248 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4250 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4251 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4252 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4253 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4254 MachinePointerInfo(),
4255 false, false, false, 0);
4256 MemOpChains.push_back(Load.getValue(1));
4257 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4260 // If we have any FPRs remaining, we may also have GPRs remaining.
4261 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4263 if (GPR_idx != NumGPRs)
4265 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4266 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4270 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4271 isPPC64, isTailCall, false, MemOpChains,
4272 TailCallArguments, dl);
4276 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4283 // These go aligned on the stack, or in the corresponding R registers
4284 // when within range. The Darwin PPC ABI doc claims they also go in
4285 // V registers; in fact gcc does this only for arguments that are
4286 // prototyped, not for those that match the ... We do it for all
4287 // arguments, seems to work.
4288 while (ArgOffset % 16 !=0) {
4289 ArgOffset += PtrByteSize;
4290 if (GPR_idx != NumGPRs)
4293 // We could elide this store in the case where the object fits
4294 // entirely in R registers. Maybe later.
4295 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4296 DAG.getConstant(ArgOffset, PtrVT));
4297 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4298 MachinePointerInfo(), false, false, 0);
4299 MemOpChains.push_back(Store);
4300 if (VR_idx != NumVRs) {
4301 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4302 MachinePointerInfo(),
4303 false, false, false, 0);
4304 MemOpChains.push_back(Load.getValue(1));
4305 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4308 for (unsigned i=0; i<16; i+=PtrByteSize) {
4309 if (GPR_idx == NumGPRs)
4311 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4312 DAG.getConstant(i, PtrVT));
4313 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4314 false, false, false, 0);
4315 MemOpChains.push_back(Load.getValue(1));
4316 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4321 // Non-varargs Altivec params generally go in registers, but have
4322 // stack space allocated at the end.
4323 if (VR_idx != NumVRs) {
4324 // Doesn't have GPR space allocated.
4325 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4326 } else if (nAltivecParamsAtEnd==0) {
4327 // We are emitting Altivec params in order.
4328 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4329 isPPC64, isTailCall, true, MemOpChains,
4330 TailCallArguments, dl);
4336 // If all Altivec parameters fit in registers, as they usually do,
4337 // they get stack space following the non-Altivec parameters. We
4338 // don't track this here because nobody below needs it.
4339 // If there are more Altivec parameters than fit in registers emit
4341 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4343 // Offset is aligned; skip 1st 12 params which go in V registers.
4344 ArgOffset = ((ArgOffset+15)/16)*16;
4346 for (unsigned i = 0; i != NumOps; ++i) {
4347 SDValue Arg = OutVals[i];
4348 EVT ArgType = Outs[i].VT;
4349 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4350 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4353 // We are emitting Altivec params in order.
4354 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4355 isPPC64, isTailCall, true, MemOpChains,
4356 TailCallArguments, dl);
4363 if (!MemOpChains.empty())
4364 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4365 &MemOpChains[0], MemOpChains.size());
4367 // On Darwin, R12 must contain the address of an indirect callee. This does
4368 // not mean the MTCTR instruction must use R12; it's easier to model this as
4369 // an extra parameter, so do that.
4371 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4372 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4373 !isBLACompatibleAddress(Callee, DAG))
4374 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4375 PPC::R12), Callee));
4377 // Build a sequence of copy-to-reg nodes chained together with token chain
4378 // and flag operands which copy the outgoing args into the appropriate regs.
4380 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4381 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4382 RegsToPass[i].second, InFlag);
4383 InFlag = Chain.getValue(1);
4387 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4388 FPOp, true, TailCallArguments);
4390 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4391 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4396 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4397 MachineFunction &MF, bool isVarArg,
4398 const SmallVectorImpl<ISD::OutputArg> &Outs,
4399 LLVMContext &Context) const {
4400 SmallVector<CCValAssign, 16> RVLocs;
4401 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4403 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4407 PPCTargetLowering::LowerReturn(SDValue Chain,
4408 CallingConv::ID CallConv, bool isVarArg,
4409 const SmallVectorImpl<ISD::OutputArg> &Outs,
4410 const SmallVectorImpl<SDValue> &OutVals,
4411 DebugLoc dl, SelectionDAG &DAG) const {
4413 SmallVector<CCValAssign, 16> RVLocs;
4414 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4415 getTargetMachine(), RVLocs, *DAG.getContext());
4416 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4418 // If this is the first return lowered for this function, add the regs to the
4419 // liveout set for the function.
4420 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
4421 for (unsigned i = 0; i != RVLocs.size(); ++i)
4422 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
4427 // Copy the result values into the output registers.
4428 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4429 CCValAssign &VA = RVLocs[i];
4430 assert(VA.isRegLoc() && "Can only return in registers!");
4432 SDValue Arg = OutVals[i];
4434 switch (VA.getLocInfo()) {
4435 default: llvm_unreachable("Unknown loc info!");
4436 case CCValAssign::Full: break;
4437 case CCValAssign::AExt:
4438 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4440 case CCValAssign::ZExt:
4441 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4443 case CCValAssign::SExt:
4444 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4448 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4449 Flag = Chain.getValue(1);
4453 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
4455 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
4458 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4459 const PPCSubtarget &Subtarget) const {
4460 // When we pop the dynamic allocation we need to restore the SP link.
4461 DebugLoc dl = Op.getDebugLoc();
4463 // Get the corect type for pointers.
4464 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4466 // Construct the stack pointer operand.
4467 bool isPPC64 = Subtarget.isPPC64();
4468 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4469 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4471 // Get the operands for the STACKRESTORE.
4472 SDValue Chain = Op.getOperand(0);
4473 SDValue SaveSP = Op.getOperand(1);
4475 // Load the old link SP.
4476 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4477 MachinePointerInfo(),
4478 false, false, false, 0);
4480 // Restore the stack pointer.
4481 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4483 // Store the old link SP.
4484 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4491 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4492 MachineFunction &MF = DAG.getMachineFunction();
4493 bool isPPC64 = PPCSubTarget.isPPC64();
4494 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4495 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4497 // Get current frame pointer save index. The users of this index will be
4498 // primarily DYNALLOC instructions.
4499 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4500 int RASI = FI->getReturnAddrSaveIndex();
4502 // If the frame pointer save index hasn't been defined yet.
4504 // Find out what the fix offset of the frame pointer save area.
4505 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4506 // Allocate the frame index for frame pointer save area.
4507 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4509 FI->setReturnAddrSaveIndex(RASI);
4511 return DAG.getFrameIndex(RASI, PtrVT);
4515 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4516 MachineFunction &MF = DAG.getMachineFunction();
4517 bool isPPC64 = PPCSubTarget.isPPC64();
4518 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4519 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4521 // Get current frame pointer save index. The users of this index will be
4522 // primarily DYNALLOC instructions.
4523 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4524 int FPSI = FI->getFramePointerSaveIndex();
4526 // If the frame pointer save index hasn't been defined yet.
4528 // Find out what the fix offset of the frame pointer save area.
4529 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4532 // Allocate the frame index for frame pointer save area.
4533 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4535 FI->setFramePointerSaveIndex(FPSI);
4537 return DAG.getFrameIndex(FPSI, PtrVT);
4540 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4542 const PPCSubtarget &Subtarget) const {
4544 SDValue Chain = Op.getOperand(0);
4545 SDValue Size = Op.getOperand(1);
4546 DebugLoc dl = Op.getDebugLoc();
4548 // Get the corect type for pointers.
4549 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4551 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4552 DAG.getConstant(0, PtrVT), Size);
4553 // Construct a node for the frame pointer save index.
4554 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4555 // Build a DYNALLOC node.
4556 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4557 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4558 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4561 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4563 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4564 // Not FP? Not a fsel.
4565 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4566 !Op.getOperand(2).getValueType().isFloatingPoint())
4569 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4571 // Cannot handle SETEQ/SETNE.
4572 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4574 EVT ResVT = Op.getValueType();
4575 EVT CmpVT = Op.getOperand(0).getValueType();
4576 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4577 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4578 DebugLoc dl = Op.getDebugLoc();
4580 // If the RHS of the comparison is a 0.0, we don't need to do the
4581 // subtraction at all.
4582 if (isFloatingPointZero(RHS))
4584 default: break; // SETUO etc aren't handled by fsel.
4587 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4590 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4591 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4592 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4595 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4598 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4599 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4600 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4601 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4606 default: break; // SETUO etc aren't handled by fsel.
4609 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4610 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4611 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4612 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4615 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4616 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4617 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4618 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4621 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4622 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4623 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4624 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4627 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4628 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4629 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4630 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4635 // FIXME: Split this code up when LegalizeDAGTypes lands.
4636 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4637 DebugLoc dl) const {
4638 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4639 SDValue Src = Op.getOperand(0);
4640 if (Src.getValueType() == MVT::f32)
4641 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4644 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4645 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4647 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4652 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4656 // Convert the FP value to an int value through memory.
4657 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4659 // Emit a store to the stack slot.
4660 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4661 MachinePointerInfo(), false, false, 0);
4663 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4665 if (Op.getValueType() == MVT::i32)
4666 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4667 DAG.getConstant(4, FIPtr.getValueType()));
4668 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4669 false, false, false, 0);
4672 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4673 SelectionDAG &DAG) const {
4674 DebugLoc dl = Op.getDebugLoc();
4675 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4676 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4679 if (Op.getOperand(0).getValueType() == MVT::i64) {
4680 SDValue SINT = Op.getOperand(0);
4681 // When converting to single-precision, we actually need to convert
4682 // to double-precision first and then round to single-precision.
4683 // To avoid double-rounding effects during that operation, we have
4684 // to prepare the input operand. Bits that might be truncated when
4685 // converting to double-precision are replaced by a bit that won't
4686 // be lost at this stage, but is below the single-precision rounding
4689 // However, if -enable-unsafe-fp-math is in effect, accept double
4690 // rounding to avoid the extra overhead.
4691 if (Op.getValueType() == MVT::f32 &&
4692 !DAG.getTarget().Options.UnsafeFPMath) {
4694 // Twiddle input to make sure the low 11 bits are zero. (If this
4695 // is the case, we are guaranteed the value will fit into the 53 bit
4696 // mantissa of an IEEE double-precision value without rounding.)
4697 // If any of those low 11 bits were not zero originally, make sure
4698 // bit 12 (value 2048) is set instead, so that the final rounding
4699 // to single-precision gets the correct result.
4700 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4701 SINT, DAG.getConstant(2047, MVT::i64));
4702 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4703 Round, DAG.getConstant(2047, MVT::i64));
4704 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4705 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4706 Round, DAG.getConstant(-2048, MVT::i64));
4708 // However, we cannot use that value unconditionally: if the magnitude
4709 // of the input value is small, the bit-twiddling we did above might
4710 // end up visibly changing the output. Fortunately, in that case, we
4711 // don't need to twiddle bits since the original input will convert
4712 // exactly to double-precision floating-point already. Therefore,
4713 // construct a conditional to use the original value if the top 11
4714 // bits are all sign-bit copies, and use the rounded value computed
4716 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4717 SINT, DAG.getConstant(53, MVT::i32));
4718 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4719 Cond, DAG.getConstant(1, MVT::i64));
4720 Cond = DAG.getSetCC(dl, MVT::i32,
4721 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4723 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4725 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4726 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4727 if (Op.getValueType() == MVT::f32)
4728 FP = DAG.getNode(ISD::FP_ROUND, dl,
4729 MVT::f32, FP, DAG.getIntPtrConstant(0));
4733 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4734 "Unhandled SINT_TO_FP type in custom expander!");
4735 // Since we only generate this in 64-bit mode, we can take advantage of
4736 // 64-bit registers. In particular, sign extend the input value into the
4737 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4738 // then lfd it and fcfid it.
4739 MachineFunction &MF = DAG.getMachineFunction();
4740 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4741 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4742 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4743 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4745 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4748 // STD the extended value into the stack slot.
4749 MachineMemOperand *MMO =
4750 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4751 MachineMemOperand::MOStore, 8, 8);
4752 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4754 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4755 Ops, 4, MVT::i64, MMO);
4756 // Load the value as a double.
4757 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4758 false, false, false, 0);
4760 // FCFID it and return it.
4761 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4762 if (Op.getValueType() == MVT::f32)
4763 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4767 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4768 SelectionDAG &DAG) const {
4769 DebugLoc dl = Op.getDebugLoc();
4771 The rounding mode is in bits 30:31 of FPSR, and has the following
4778 FLT_ROUNDS, on the other hand, expects the following:
4785 To perform the conversion, we do:
4786 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4789 MachineFunction &MF = DAG.getMachineFunction();
4790 EVT VT = Op.getValueType();
4791 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4792 std::vector<EVT> NodeTys;
4793 SDValue MFFSreg, InFlag;
4795 // Save FP Control Word to register
4796 NodeTys.push_back(MVT::f64); // return register
4797 NodeTys.push_back(MVT::Glue); // unused in this context
4798 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4800 // Save FP register to stack slot
4801 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4802 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4803 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4804 StackSlot, MachinePointerInfo(), false, false,0);
4806 // Load FP Control Word from low 32 bits of stack slot.
4807 SDValue Four = DAG.getConstant(4, PtrVT);
4808 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4809 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4810 false, false, false, 0);
4812 // Transform as necessary
4814 DAG.getNode(ISD::AND, dl, MVT::i32,
4815 CWD, DAG.getConstant(3, MVT::i32));
4817 DAG.getNode(ISD::SRL, dl, MVT::i32,
4818 DAG.getNode(ISD::AND, dl, MVT::i32,
4819 DAG.getNode(ISD::XOR, dl, MVT::i32,
4820 CWD, DAG.getConstant(3, MVT::i32)),
4821 DAG.getConstant(3, MVT::i32)),
4822 DAG.getConstant(1, MVT::i32));
4825 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4827 return DAG.getNode((VT.getSizeInBits() < 16 ?
4828 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4831 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4832 EVT VT = Op.getValueType();
4833 unsigned BitWidth = VT.getSizeInBits();
4834 DebugLoc dl = Op.getDebugLoc();
4835 assert(Op.getNumOperands() == 3 &&
4836 VT == Op.getOperand(1).getValueType() &&
4839 // Expand into a bunch of logical ops. Note that these ops
4840 // depend on the PPC behavior for oversized shift amounts.
4841 SDValue Lo = Op.getOperand(0);
4842 SDValue Hi = Op.getOperand(1);
4843 SDValue Amt = Op.getOperand(2);
4844 EVT AmtVT = Amt.getValueType();
4846 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4847 DAG.getConstant(BitWidth, AmtVT), Amt);
4848 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4849 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4850 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4851 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4852 DAG.getConstant(-BitWidth, AmtVT));
4853 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4854 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4855 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4856 SDValue OutOps[] = { OutLo, OutHi };
4857 return DAG.getMergeValues(OutOps, 2, dl);
4860 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4861 EVT VT = Op.getValueType();
4862 DebugLoc dl = Op.getDebugLoc();
4863 unsigned BitWidth = VT.getSizeInBits();
4864 assert(Op.getNumOperands() == 3 &&
4865 VT == Op.getOperand(1).getValueType() &&
4868 // Expand into a bunch of logical ops. Note that these ops
4869 // depend on the PPC behavior for oversized shift amounts.
4870 SDValue Lo = Op.getOperand(0);
4871 SDValue Hi = Op.getOperand(1);
4872 SDValue Amt = Op.getOperand(2);
4873 EVT AmtVT = Amt.getValueType();
4875 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4876 DAG.getConstant(BitWidth, AmtVT), Amt);
4877 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4878 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4879 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4880 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4881 DAG.getConstant(-BitWidth, AmtVT));
4882 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4883 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4884 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4885 SDValue OutOps[] = { OutLo, OutHi };
4886 return DAG.getMergeValues(OutOps, 2, dl);
4889 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4890 DebugLoc dl = Op.getDebugLoc();
4891 EVT VT = Op.getValueType();
4892 unsigned BitWidth = VT.getSizeInBits();
4893 assert(Op.getNumOperands() == 3 &&
4894 VT == Op.getOperand(1).getValueType() &&
4897 // Expand into a bunch of logical ops, followed by a select_cc.
4898 SDValue Lo = Op.getOperand(0);
4899 SDValue Hi = Op.getOperand(1);
4900 SDValue Amt = Op.getOperand(2);
4901 EVT AmtVT = Amt.getValueType();
4903 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4904 DAG.getConstant(BitWidth, AmtVT), Amt);
4905 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4906 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4907 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4908 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4909 DAG.getConstant(-BitWidth, AmtVT));
4910 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4911 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4912 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4913 Tmp4, Tmp6, ISD::SETLE);
4914 SDValue OutOps[] = { OutLo, OutHi };
4915 return DAG.getMergeValues(OutOps, 2, dl);
4918 //===----------------------------------------------------------------------===//
4919 // Vector related lowering.
4922 /// BuildSplatI - Build a canonical splati of Val with an element size of
4923 /// SplatSize. Cast the result to VT.
4924 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4925 SelectionDAG &DAG, DebugLoc dl) {
4926 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4928 static const EVT VTys[] = { // canonical VT to use for each size.
4929 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4932 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4934 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4938 EVT CanonicalVT = VTys[SplatSize-1];
4940 // Build a canonical splat for this value.
4941 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4942 SmallVector<SDValue, 8> Ops;
4943 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4944 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4945 &Ops[0], Ops.size());
4946 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4949 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
4950 /// specified intrinsic ID.
4951 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
4952 SelectionDAG &DAG, DebugLoc dl,
4953 EVT DestVT = MVT::Other) {
4954 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
4955 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4956 DAG.getConstant(IID, MVT::i32), LHS, RHS);
4959 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
4960 /// specified intrinsic ID.
4961 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
4962 SDValue Op2, SelectionDAG &DAG,
4963 DebugLoc dl, EVT DestVT = MVT::Other) {
4964 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
4965 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4966 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
4970 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
4971 /// amount. The result has the specified value type.
4972 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
4973 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4974 // Force LHS/RHS to be the right type.
4975 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
4976 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
4979 for (unsigned i = 0; i != 16; ++i)
4981 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
4982 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4985 // If this is a case we can't handle, return null and let the default
4986 // expansion code take care of it. If we CAN select this case, and if it
4987 // selects to a single instruction, return Op. Otherwise, if we can codegen
4988 // this case more efficiently than a constant pool load, lower it to the
4989 // sequence of ops that should be used.
4990 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
4991 SelectionDAG &DAG) const {
4992 DebugLoc dl = Op.getDebugLoc();
4993 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4994 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
4996 // Check if this is a splat of a constant value.
4997 APInt APSplatBits, APSplatUndef;
4998 unsigned SplatBitSize;
5000 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5001 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5004 unsigned SplatBits = APSplatBits.getZExtValue();
5005 unsigned SplatUndef = APSplatUndef.getZExtValue();
5006 unsigned SplatSize = SplatBitSize / 8;
5008 // First, handle single instruction cases.
5011 if (SplatBits == 0) {
5012 // Canonicalize all zero vectors to be v4i32.
5013 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5014 SDValue Z = DAG.getConstant(0, MVT::i32);
5015 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5016 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5021 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5022 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5024 if (SextVal >= -16 && SextVal <= 15)
5025 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5028 // Two instruction sequences.
5030 // If this value is in the range [-32,30] and is even, use:
5031 // tmp = VSPLTI[bhw], result = add tmp, tmp
5032 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
5033 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
5034 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
5035 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5038 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5039 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5041 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5042 // Make -1 and vspltisw -1:
5043 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5045 // Make the VSLW intrinsic, computing 0x8000_0000.
5046 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5049 // xor by OnesV to invert it.
5050 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5051 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5054 // Check to see if this is a wide variety of vsplti*, binop self cases.
5055 static const signed char SplatCsts[] = {
5056 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5057 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5060 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5061 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5062 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5063 int i = SplatCsts[idx];
5065 // Figure out what shift amount will be used by altivec if shifted by i in
5067 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5069 // vsplti + shl self.
5070 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5071 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5072 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5073 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5074 Intrinsic::ppc_altivec_vslw
5076 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5077 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5080 // vsplti + srl self.
5081 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5082 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5083 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5084 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5085 Intrinsic::ppc_altivec_vsrw
5087 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5088 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5091 // vsplti + sra self.
5092 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5093 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5094 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5095 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5096 Intrinsic::ppc_altivec_vsraw
5098 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5099 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5102 // vsplti + rol self.
5103 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5104 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5105 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5106 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5107 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5108 Intrinsic::ppc_altivec_vrlw
5110 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5111 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5114 // t = vsplti c, result = vsldoi t, t, 1
5115 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5116 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5117 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5119 // t = vsplti c, result = vsldoi t, t, 2
5120 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5121 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5122 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5124 // t = vsplti c, result = vsldoi t, t, 3
5125 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5126 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5127 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5131 // Three instruction sequences.
5133 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
5134 if (SextVal >= 0 && SextVal <= 31) {
5135 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
5136 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5137 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
5138 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5140 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
5141 if (SextVal >= -31 && SextVal <= 0) {
5142 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
5143 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5144 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
5145 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5151 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5152 /// the specified operations to build the shuffle.
5153 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5154 SDValue RHS, SelectionDAG &DAG,
5156 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5157 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5158 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5161 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5173 if (OpNum == OP_COPY) {
5174 if (LHSID == (1*9+2)*9+3) return LHS;
5175 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5179 SDValue OpLHS, OpRHS;
5180 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5181 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5185 default: llvm_unreachable("Unknown i32 permute!");
5187 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5188 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5189 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5190 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5193 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5194 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5195 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5196 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5199 for (unsigned i = 0; i != 16; ++i)
5200 ShufIdxs[i] = (i&3)+0;
5203 for (unsigned i = 0; i != 16; ++i)
5204 ShufIdxs[i] = (i&3)+4;
5207 for (unsigned i = 0; i != 16; ++i)
5208 ShufIdxs[i] = (i&3)+8;
5211 for (unsigned i = 0; i != 16; ++i)
5212 ShufIdxs[i] = (i&3)+12;
5215 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5217 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5219 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5221 EVT VT = OpLHS.getValueType();
5222 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5223 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5224 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5225 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5228 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5229 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5230 /// return the code it can be lowered into. Worst case, it can always be
5231 /// lowered into a vperm.
5232 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5233 SelectionDAG &DAG) const {
5234 DebugLoc dl = Op.getDebugLoc();
5235 SDValue V1 = Op.getOperand(0);
5236 SDValue V2 = Op.getOperand(1);
5237 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5238 EVT VT = Op.getValueType();
5240 // Cases that are handled by instructions that take permute immediates
5241 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5242 // selected by the instruction selector.
5243 if (V2.getOpcode() == ISD::UNDEF) {
5244 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5245 PPC::isSplatShuffleMask(SVOp, 2) ||
5246 PPC::isSplatShuffleMask(SVOp, 4) ||
5247 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5248 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5249 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5250 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5251 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5252 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5253 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5254 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5255 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5260 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5261 // and produce a fixed permutation. If any of these match, do not lower to
5263 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5264 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5265 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5266 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5267 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5268 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5269 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5270 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5271 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5274 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5275 // perfect shuffle table to emit an optimal matching sequence.
5276 ArrayRef<int> PermMask = SVOp->getMask();
5278 unsigned PFIndexes[4];
5279 bool isFourElementShuffle = true;
5280 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5281 unsigned EltNo = 8; // Start out undef.
5282 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5283 if (PermMask[i*4+j] < 0)
5284 continue; // Undef, ignore it.
5286 unsigned ByteSource = PermMask[i*4+j];
5287 if ((ByteSource & 3) != j) {
5288 isFourElementShuffle = false;
5293 EltNo = ByteSource/4;
5294 } else if (EltNo != ByteSource/4) {
5295 isFourElementShuffle = false;
5299 PFIndexes[i] = EltNo;
5302 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5303 // perfect shuffle vector to determine if it is cost effective to do this as
5304 // discrete instructions, or whether we should use a vperm.
5305 if (isFourElementShuffle) {
5306 // Compute the index in the perfect shuffle table.
5307 unsigned PFTableIndex =
5308 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5310 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5311 unsigned Cost = (PFEntry >> 30);
5313 // Determining when to avoid vperm is tricky. Many things affect the cost
5314 // of vperm, particularly how many times the perm mask needs to be computed.
5315 // For example, if the perm mask can be hoisted out of a loop or is already
5316 // used (perhaps because there are multiple permutes with the same shuffle
5317 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5318 // the loop requires an extra register.
5320 // As a compromise, we only emit discrete instructions if the shuffle can be
5321 // generated in 3 or fewer operations. When we have loop information
5322 // available, if this block is within a loop, we should avoid using vperm
5323 // for 3-operation perms and use a constant pool load instead.
5325 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5328 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5329 // vector that will get spilled to the constant pool.
5330 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5332 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5333 // that it is in input element units, not in bytes. Convert now.
5334 EVT EltVT = V1.getValueType().getVectorElementType();
5335 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5337 SmallVector<SDValue, 16> ResultMask;
5338 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5339 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5341 for (unsigned j = 0; j != BytesPerElement; ++j)
5342 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5346 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5347 &ResultMask[0], ResultMask.size());
5348 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5351 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5352 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5353 /// information about the intrinsic.
5354 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5356 unsigned IntrinsicID =
5357 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5360 switch (IntrinsicID) {
5361 default: return false;
5362 // Comparison predicates.
5363 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5364 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5365 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5366 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5367 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5368 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5369 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5370 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5371 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5372 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5373 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5374 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5375 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5377 // Normal Comparisons.
5378 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5379 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5380 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5381 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5382 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5383 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5384 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5385 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5386 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5387 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5388 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5389 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5390 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5395 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5396 /// lower, do it, otherwise return null.
5397 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5398 SelectionDAG &DAG) const {
5399 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5400 // opcode number of the comparison.
5401 DebugLoc dl = Op.getDebugLoc();
5404 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5405 return SDValue(); // Don't custom lower most intrinsics.
5407 // If this is a non-dot comparison, make the VCMP node and we are done.
5409 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5410 Op.getOperand(1), Op.getOperand(2),
5411 DAG.getConstant(CompareOpc, MVT::i32));
5412 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5415 // Create the PPCISD altivec 'dot' comparison node.
5417 Op.getOperand(2), // LHS
5418 Op.getOperand(3), // RHS
5419 DAG.getConstant(CompareOpc, MVT::i32)
5421 std::vector<EVT> VTs;
5422 VTs.push_back(Op.getOperand(2).getValueType());
5423 VTs.push_back(MVT::Glue);
5424 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5426 // Now that we have the comparison, emit a copy from the CR to a GPR.
5427 // This is flagged to the above dot comparison.
5428 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5429 DAG.getRegister(PPC::CR6, MVT::i32),
5430 CompNode.getValue(1));
5432 // Unpack the result based on how the target uses it.
5433 unsigned BitNo; // Bit # of CR6.
5434 bool InvertBit; // Invert result?
5435 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5436 default: // Can't happen, don't crash on invalid number though.
5437 case 0: // Return the value of the EQ bit of CR6.
5438 BitNo = 0; InvertBit = false;
5440 case 1: // Return the inverted value of the EQ bit of CR6.
5441 BitNo = 0; InvertBit = true;
5443 case 2: // Return the value of the LT bit of CR6.
5444 BitNo = 2; InvertBit = false;
5446 case 3: // Return the inverted value of the LT bit of CR6.
5447 BitNo = 2; InvertBit = true;
5451 // Shift the bit into the low position.
5452 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5453 DAG.getConstant(8-(3-BitNo), MVT::i32));
5455 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5456 DAG.getConstant(1, MVT::i32));
5458 // If we are supposed to, toggle the bit.
5460 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5461 DAG.getConstant(1, MVT::i32));
5465 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5466 SelectionDAG &DAG) const {
5467 DebugLoc dl = Op.getDebugLoc();
5468 // Create a stack slot that is 16-byte aligned.
5469 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5470 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5471 EVT PtrVT = getPointerTy();
5472 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5474 // Store the input value into Value#0 of the stack slot.
5475 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5476 Op.getOperand(0), FIdx, MachinePointerInfo(),
5479 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5480 false, false, false, 0);
5483 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5484 DebugLoc dl = Op.getDebugLoc();
5485 if (Op.getValueType() == MVT::v4i32) {
5486 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5488 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5489 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5491 SDValue RHSSwap = // = vrlw RHS, 16
5492 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5494 // Shrinkify inputs to v8i16.
5495 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5496 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5497 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5499 // Low parts multiplied together, generating 32-bit results (we ignore the
5501 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5502 LHS, RHS, DAG, dl, MVT::v4i32);
5504 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5505 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5506 // Shift the high parts up 16 bits.
5507 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5509 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5510 } else if (Op.getValueType() == MVT::v8i16) {
5511 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5513 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5515 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5516 LHS, RHS, Zero, DAG, dl);
5517 } else if (Op.getValueType() == MVT::v16i8) {
5518 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5520 // Multiply the even 8-bit parts, producing 16-bit sums.
5521 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5522 LHS, RHS, DAG, dl, MVT::v8i16);
5523 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5525 // Multiply the odd 8-bit parts, producing 16-bit sums.
5526 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5527 LHS, RHS, DAG, dl, MVT::v8i16);
5528 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5530 // Merge the results together.
5532 for (unsigned i = 0; i != 8; ++i) {
5534 Ops[i*2+1] = 2*i+1+16;
5536 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5538 llvm_unreachable("Unknown mul to lower!");
5542 /// LowerOperation - Provide custom lowering hooks for some operations.
5544 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5545 switch (Op.getOpcode()) {
5546 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5547 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5548 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5549 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5550 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5551 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5552 case ISD::SETCC: return LowerSETCC(Op, DAG);
5553 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5554 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5556 return LowerVASTART(Op, DAG, PPCSubTarget);
5559 return LowerVAARG(Op, DAG, PPCSubTarget);
5561 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5562 case ISD::DYNAMIC_STACKALLOC:
5563 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5565 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5566 case ISD::FP_TO_UINT:
5567 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5569 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5570 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5572 // Lower 64-bit shifts.
5573 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5574 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5575 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5577 // Vector-related lowering.
5578 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5579 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5580 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5581 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5582 case ISD::MUL: return LowerMUL(Op, DAG);
5584 // Frame & Return address.
5585 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5586 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5590 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5591 SmallVectorImpl<SDValue>&Results,
5592 SelectionDAG &DAG) const {
5593 const TargetMachine &TM = getTargetMachine();
5594 DebugLoc dl = N->getDebugLoc();
5595 switch (N->getOpcode()) {
5597 llvm_unreachable("Do not know how to custom type legalize this operation!");
5599 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5600 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5603 EVT VT = N->getValueType(0);
5605 if (VT == MVT::i64) {
5606 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5608 Results.push_back(NewNode);
5609 Results.push_back(NewNode.getValue(1));
5613 case ISD::FP_ROUND_INREG: {
5614 assert(N->getValueType(0) == MVT::ppcf128);
5615 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5616 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5617 MVT::f64, N->getOperand(0),
5618 DAG.getIntPtrConstant(0));
5619 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5620 MVT::f64, N->getOperand(0),
5621 DAG.getIntPtrConstant(1));
5623 // This sequence changes FPSCR to do round-to-zero, adds the two halves
5624 // of the long double, and puts FPSCR back the way it was. We do not
5625 // actually model FPSCR.
5626 std::vector<EVT> NodeTys;
5627 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
5629 NodeTys.push_back(MVT::f64); // Return register
5630 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
5631 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5632 MFFSreg = Result.getValue(0);
5633 InFlag = Result.getValue(1);
5636 NodeTys.push_back(MVT::Glue); // Returns a flag
5637 Ops[0] = DAG.getConstant(31, MVT::i32);
5639 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
5640 InFlag = Result.getValue(0);
5643 NodeTys.push_back(MVT::Glue); // Returns a flag
5644 Ops[0] = DAG.getConstant(30, MVT::i32);
5646 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
5647 InFlag = Result.getValue(0);
5650 NodeTys.push_back(MVT::f64); // result of add
5651 NodeTys.push_back(MVT::Glue); // Returns a flag
5655 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
5656 FPreg = Result.getValue(0);
5657 InFlag = Result.getValue(1);
5660 NodeTys.push_back(MVT::f64);
5661 Ops[0] = DAG.getConstant(1, MVT::i32);
5665 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
5666 FPreg = Result.getValue(0);
5668 // We know the low half is about to be thrown away, so just use something
5670 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5674 case ISD::FP_TO_SINT:
5675 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5681 //===----------------------------------------------------------------------===//
5682 // Other Lowering Code
5683 //===----------------------------------------------------------------------===//
5686 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5687 bool is64bit, unsigned BinOpcode) const {
5688 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5689 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5691 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5692 MachineFunction *F = BB->getParent();
5693 MachineFunction::iterator It = BB;
5696 unsigned dest = MI->getOperand(0).getReg();
5697 unsigned ptrA = MI->getOperand(1).getReg();
5698 unsigned ptrB = MI->getOperand(2).getReg();
5699 unsigned incr = MI->getOperand(3).getReg();
5700 DebugLoc dl = MI->getDebugLoc();
5702 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5703 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5704 F->insert(It, loopMBB);
5705 F->insert(It, exitMBB);
5706 exitMBB->splice(exitMBB->begin(), BB,
5707 llvm::next(MachineBasicBlock::iterator(MI)),
5709 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5711 MachineRegisterInfo &RegInfo = F->getRegInfo();
5712 unsigned TmpReg = (!BinOpcode) ? incr :
5713 RegInfo.createVirtualRegister(
5714 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5715 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5719 // fallthrough --> loopMBB
5720 BB->addSuccessor(loopMBB);
5723 // l[wd]arx dest, ptr
5724 // add r0, dest, incr
5725 // st[wd]cx. r0, ptr
5727 // fallthrough --> exitMBB
5729 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5730 .addReg(ptrA).addReg(ptrB);
5732 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5733 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5734 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5735 BuildMI(BB, dl, TII->get(PPC::BCC))
5736 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5737 BB->addSuccessor(loopMBB);
5738 BB->addSuccessor(exitMBB);
5747 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5748 MachineBasicBlock *BB,
5749 bool is8bit, // operation
5750 unsigned BinOpcode) const {
5751 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5752 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5753 // In 64 bit mode we have to use 64 bits for addresses, even though the
5754 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5755 // registers without caring whether they're 32 or 64, but here we're
5756 // doing actual arithmetic on the addresses.
5757 bool is64bit = PPCSubTarget.isPPC64();
5758 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
5760 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5761 MachineFunction *F = BB->getParent();
5762 MachineFunction::iterator It = BB;
5765 unsigned dest = MI->getOperand(0).getReg();
5766 unsigned ptrA = MI->getOperand(1).getReg();
5767 unsigned ptrB = MI->getOperand(2).getReg();
5768 unsigned incr = MI->getOperand(3).getReg();
5769 DebugLoc dl = MI->getDebugLoc();
5771 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5772 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5773 F->insert(It, loopMBB);
5774 F->insert(It, exitMBB);
5775 exitMBB->splice(exitMBB->begin(), BB,
5776 llvm::next(MachineBasicBlock::iterator(MI)),
5778 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5780 MachineRegisterInfo &RegInfo = F->getRegInfo();
5781 const TargetRegisterClass *RC =
5782 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5783 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5784 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5785 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5786 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5787 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5788 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5789 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5790 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5791 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5792 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5793 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5794 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5796 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5800 // fallthrough --> loopMBB
5801 BB->addSuccessor(loopMBB);
5803 // The 4-byte load must be aligned, while a char or short may be
5804 // anywhere in the word. Hence all this nasty bookkeeping code.
5805 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5806 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5807 // xori shift, shift1, 24 [16]
5808 // rlwinm ptr, ptr1, 0, 0, 29
5809 // slw incr2, incr, shift
5810 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5811 // slw mask, mask2, shift
5813 // lwarx tmpDest, ptr
5814 // add tmp, tmpDest, incr2
5815 // andc tmp2, tmpDest, mask
5816 // and tmp3, tmp, mask
5817 // or tmp4, tmp3, tmp2
5820 // fallthrough --> exitMBB
5821 // srw dest, tmpDest, shift
5822 if (ptrA != ZeroReg) {
5823 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5824 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5825 .addReg(ptrA).addReg(ptrB);
5829 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5830 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5831 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5832 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5834 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5835 .addReg(Ptr1Reg).addImm(0).addImm(61);
5837 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5838 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5839 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5840 .addReg(incr).addReg(ShiftReg);
5842 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5844 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5845 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5847 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5848 .addReg(Mask2Reg).addReg(ShiftReg);
5851 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5852 .addReg(ZeroReg).addReg(PtrReg);
5854 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5855 .addReg(Incr2Reg).addReg(TmpDestReg);
5856 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5857 .addReg(TmpDestReg).addReg(MaskReg);
5858 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5859 .addReg(TmpReg).addReg(MaskReg);
5860 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5861 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5862 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5863 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5864 BuildMI(BB, dl, TII->get(PPC::BCC))
5865 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5866 BB->addSuccessor(loopMBB);
5867 BB->addSuccessor(exitMBB);
5872 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5878 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5879 MachineBasicBlock *BB) const {
5880 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5882 // To "insert" these instructions we actually have to insert their
5883 // control-flow patterns.
5884 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5885 MachineFunction::iterator It = BB;
5888 MachineFunction *F = BB->getParent();
5890 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5891 MI->getOpcode() == PPC::SELECT_CC_I8)) {
5892 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
5893 PPC::ISEL8 : PPC::ISEL;
5894 unsigned SelectPred = MI->getOperand(4).getImm();
5895 DebugLoc dl = MI->getDebugLoc();
5897 // The SelectPred is ((BI << 5) | BO) for a BCC
5898 unsigned BO = SelectPred & 0xF;
5899 assert((BO == 12 || BO == 4) && "invalid predicate BO field for isel");
5901 unsigned TrueOpNo, FalseOpNo;
5908 SelectPred = PPC::InvertPredicate((PPC::Predicate)SelectPred);
5911 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
5912 .addReg(MI->getOperand(TrueOpNo).getReg())
5913 .addReg(MI->getOperand(FalseOpNo).getReg())
5914 .addImm(SelectPred).addReg(MI->getOperand(1).getReg());
5915 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5916 MI->getOpcode() == PPC::SELECT_CC_I8 ||
5917 MI->getOpcode() == PPC::SELECT_CC_F4 ||
5918 MI->getOpcode() == PPC::SELECT_CC_F8 ||
5919 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
5922 // The incoming instruction knows the destination vreg to set, the
5923 // condition code register to branch on, the true/false values to
5924 // select between, and a branch opcode to use.
5929 // cmpTY ccX, r1, r2
5931 // fallthrough --> copy0MBB
5932 MachineBasicBlock *thisMBB = BB;
5933 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5934 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
5935 unsigned SelectPred = MI->getOperand(4).getImm();
5936 DebugLoc dl = MI->getDebugLoc();
5937 F->insert(It, copy0MBB);
5938 F->insert(It, sinkMBB);
5940 // Transfer the remainder of BB and its successor edges to sinkMBB.
5941 sinkMBB->splice(sinkMBB->begin(), BB,
5942 llvm::next(MachineBasicBlock::iterator(MI)),
5944 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5946 // Next, add the true and fallthrough blocks as its successors.
5947 BB->addSuccessor(copy0MBB);
5948 BB->addSuccessor(sinkMBB);
5950 BuildMI(BB, dl, TII->get(PPC::BCC))
5951 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
5954 // %FalseValue = ...
5955 // # fallthrough to sinkMBB
5958 // Update machine-CFG edges
5959 BB->addSuccessor(sinkMBB);
5962 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5965 BuildMI(*BB, BB->begin(), dl,
5966 TII->get(PPC::PHI), MI->getOperand(0).getReg())
5967 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
5968 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5970 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
5971 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
5972 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
5973 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
5974 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
5975 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
5976 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
5977 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
5979 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
5980 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
5981 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
5982 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
5983 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
5984 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
5985 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
5986 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
5988 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
5989 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
5990 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
5991 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
5992 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
5993 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
5994 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
5995 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
5997 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
5998 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
5999 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6000 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6001 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6002 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6003 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6004 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6006 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6007 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6008 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6009 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6010 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6011 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6012 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6013 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6015 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6016 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6017 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6018 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6019 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6020 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6021 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6022 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6024 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6025 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6026 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6027 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6028 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6029 BB = EmitAtomicBinary(MI, BB, false, 0);
6030 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6031 BB = EmitAtomicBinary(MI, BB, true, 0);
6033 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6034 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6035 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6037 unsigned dest = MI->getOperand(0).getReg();
6038 unsigned ptrA = MI->getOperand(1).getReg();
6039 unsigned ptrB = MI->getOperand(2).getReg();
6040 unsigned oldval = MI->getOperand(3).getReg();
6041 unsigned newval = MI->getOperand(4).getReg();
6042 DebugLoc dl = MI->getDebugLoc();
6044 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6045 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6046 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6047 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6048 F->insert(It, loop1MBB);
6049 F->insert(It, loop2MBB);
6050 F->insert(It, midMBB);
6051 F->insert(It, exitMBB);
6052 exitMBB->splice(exitMBB->begin(), BB,
6053 llvm::next(MachineBasicBlock::iterator(MI)),
6055 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6059 // fallthrough --> loopMBB
6060 BB->addSuccessor(loop1MBB);
6063 // l[wd]arx dest, ptr
6064 // cmp[wd] dest, oldval
6067 // st[wd]cx. newval, ptr
6071 // st[wd]cx. dest, ptr
6074 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6075 .addReg(ptrA).addReg(ptrB);
6076 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6077 .addReg(oldval).addReg(dest);
6078 BuildMI(BB, dl, TII->get(PPC::BCC))
6079 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6080 BB->addSuccessor(loop2MBB);
6081 BB->addSuccessor(midMBB);
6084 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6085 .addReg(newval).addReg(ptrA).addReg(ptrB);
6086 BuildMI(BB, dl, TII->get(PPC::BCC))
6087 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6088 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6089 BB->addSuccessor(loop1MBB);
6090 BB->addSuccessor(exitMBB);
6093 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6094 .addReg(dest).addReg(ptrA).addReg(ptrB);
6095 BB->addSuccessor(exitMBB);
6100 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6101 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6102 // We must use 64-bit registers for addresses when targeting 64-bit,
6103 // since we're actually doing arithmetic on them. Other registers
6105 bool is64bit = PPCSubTarget.isPPC64();
6106 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6108 unsigned dest = MI->getOperand(0).getReg();
6109 unsigned ptrA = MI->getOperand(1).getReg();
6110 unsigned ptrB = MI->getOperand(2).getReg();
6111 unsigned oldval = MI->getOperand(3).getReg();
6112 unsigned newval = MI->getOperand(4).getReg();
6113 DebugLoc dl = MI->getDebugLoc();
6115 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6116 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6117 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6118 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6119 F->insert(It, loop1MBB);
6120 F->insert(It, loop2MBB);
6121 F->insert(It, midMBB);
6122 F->insert(It, exitMBB);
6123 exitMBB->splice(exitMBB->begin(), BB,
6124 llvm::next(MachineBasicBlock::iterator(MI)),
6126 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6128 MachineRegisterInfo &RegInfo = F->getRegInfo();
6129 const TargetRegisterClass *RC =
6130 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6131 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6132 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6133 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6134 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6135 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6136 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6137 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6138 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6139 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6140 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6141 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6142 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6143 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6144 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6146 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6147 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
6150 // fallthrough --> loopMBB
6151 BB->addSuccessor(loop1MBB);
6153 // The 4-byte load must be aligned, while a char or short may be
6154 // anywhere in the word. Hence all this nasty bookkeeping code.
6155 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6156 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6157 // xori shift, shift1, 24 [16]
6158 // rlwinm ptr, ptr1, 0, 0, 29
6159 // slw newval2, newval, shift
6160 // slw oldval2, oldval,shift
6161 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6162 // slw mask, mask2, shift
6163 // and newval3, newval2, mask
6164 // and oldval3, oldval2, mask
6166 // lwarx tmpDest, ptr
6167 // and tmp, tmpDest, mask
6168 // cmpw tmp, oldval3
6171 // andc tmp2, tmpDest, mask
6172 // or tmp4, tmp2, newval3
6177 // stwcx. tmpDest, ptr
6179 // srw dest, tmpDest, shift
6180 if (ptrA != ZeroReg) {
6181 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6182 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6183 .addReg(ptrA).addReg(ptrB);
6187 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6188 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6189 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6190 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6192 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6193 .addReg(Ptr1Reg).addImm(0).addImm(61);
6195 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6196 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6197 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6198 .addReg(newval).addReg(ShiftReg);
6199 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6200 .addReg(oldval).addReg(ShiftReg);
6202 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6204 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6205 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6206 .addReg(Mask3Reg).addImm(65535);
6208 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6209 .addReg(Mask2Reg).addReg(ShiftReg);
6210 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6211 .addReg(NewVal2Reg).addReg(MaskReg);
6212 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6213 .addReg(OldVal2Reg).addReg(MaskReg);
6216 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6217 .addReg(ZeroReg).addReg(PtrReg);
6218 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6219 .addReg(TmpDestReg).addReg(MaskReg);
6220 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6221 .addReg(TmpReg).addReg(OldVal3Reg);
6222 BuildMI(BB, dl, TII->get(PPC::BCC))
6223 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6224 BB->addSuccessor(loop2MBB);
6225 BB->addSuccessor(midMBB);
6228 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6229 .addReg(TmpDestReg).addReg(MaskReg);
6230 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6231 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6232 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6233 .addReg(ZeroReg).addReg(PtrReg);
6234 BuildMI(BB, dl, TII->get(PPC::BCC))
6235 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6236 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6237 BB->addSuccessor(loop1MBB);
6238 BB->addSuccessor(exitMBB);
6241 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6242 .addReg(ZeroReg).addReg(PtrReg);
6243 BB->addSuccessor(exitMBB);
6248 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6251 llvm_unreachable("Unexpected instr type to insert");
6254 MI->eraseFromParent(); // The pseudo instruction is gone now.
6258 //===----------------------------------------------------------------------===//
6259 // Target Optimization Hooks
6260 //===----------------------------------------------------------------------===//
6262 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6263 DAGCombinerInfo &DCI) const {
6264 const TargetMachine &TM = getTargetMachine();
6265 SelectionDAG &DAG = DCI.DAG;
6266 DebugLoc dl = N->getDebugLoc();
6267 switch (N->getOpcode()) {
6270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6271 if (C->isNullValue()) // 0 << V -> 0.
6272 return N->getOperand(0);
6276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6277 if (C->isNullValue()) // 0 >>u V -> 0.
6278 return N->getOperand(0);
6282 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6283 if (C->isNullValue() || // 0 >>s V -> 0.
6284 C->isAllOnesValue()) // -1 >>s V -> -1.
6285 return N->getOperand(0);
6289 case ISD::SINT_TO_FP:
6290 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6291 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6292 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6293 // We allow the src/dst to be either f32/f64, but the intermediate
6294 // type must be i64.
6295 if (N->getOperand(0).getValueType() == MVT::i64 &&
6296 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6297 SDValue Val = N->getOperand(0).getOperand(0);
6298 if (Val.getValueType() == MVT::f32) {
6299 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6300 DCI.AddToWorklist(Val.getNode());
6303 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6304 DCI.AddToWorklist(Val.getNode());
6305 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6306 DCI.AddToWorklist(Val.getNode());
6307 if (N->getValueType(0) == MVT::f32) {
6308 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6309 DAG.getIntPtrConstant(0));
6310 DCI.AddToWorklist(Val.getNode());
6313 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6314 // If the intermediate type is i32, we can avoid the load/store here
6321 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6322 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6323 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6324 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6325 N->getOperand(1).getValueType() == MVT::i32 &&
6326 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6327 SDValue Val = N->getOperand(1).getOperand(0);
6328 if (Val.getValueType() == MVT::f32) {
6329 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6330 DCI.AddToWorklist(Val.getNode());
6332 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6333 DCI.AddToWorklist(Val.getNode());
6335 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6336 N->getOperand(2), N->getOperand(3));
6337 DCI.AddToWorklist(Val.getNode());
6341 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6342 if (cast<StoreSDNode>(N)->isUnindexed() &&
6343 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6344 N->getOperand(1).getNode()->hasOneUse() &&
6345 (N->getOperand(1).getValueType() == MVT::i32 ||
6346 N->getOperand(1).getValueType() == MVT::i16)) {
6347 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6348 // Do an any-extend to 32-bits if this is a half-word input.
6349 if (BSwapOp.getValueType() == MVT::i16)
6350 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6353 N->getOperand(0), BSwapOp, N->getOperand(2),
6354 DAG.getValueType(N->getOperand(1).getValueType())
6357 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6358 Ops, array_lengthof(Ops),
6359 cast<StoreSDNode>(N)->getMemoryVT(),
6360 cast<StoreSDNode>(N)->getMemOperand());
6364 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6365 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6366 N->getOperand(0).hasOneUse() &&
6367 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6368 SDValue Load = N->getOperand(0);
6369 LoadSDNode *LD = cast<LoadSDNode>(Load);
6370 // Create the byte-swapping load.
6372 LD->getChain(), // Chain
6373 LD->getBasePtr(), // Ptr
6374 DAG.getValueType(N->getValueType(0)) // VT
6377 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6378 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6379 LD->getMemoryVT(), LD->getMemOperand());
6381 // If this is an i16 load, insert the truncate.
6382 SDValue ResVal = BSLoad;
6383 if (N->getValueType(0) == MVT::i16)
6384 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6386 // First, combine the bswap away. This makes the value produced by the
6388 DCI.CombineTo(N, ResVal);
6390 // Next, combine the load away, we give it a bogus result value but a real
6391 // chain result. The result value is dead because the bswap is dead.
6392 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6394 // Return N so it doesn't get rechecked!
6395 return SDValue(N, 0);
6399 case PPCISD::VCMP: {
6400 // If a VCMPo node already exists with exactly the same operands as this
6401 // node, use its result instead of this node (VCMPo computes both a CR6 and
6402 // a normal output).
6404 if (!N->getOperand(0).hasOneUse() &&
6405 !N->getOperand(1).hasOneUse() &&
6406 !N->getOperand(2).hasOneUse()) {
6408 // Scan all of the users of the LHS, looking for VCMPo's that match.
6409 SDNode *VCMPoNode = 0;
6411 SDNode *LHSN = N->getOperand(0).getNode();
6412 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6414 if (UI->getOpcode() == PPCISD::VCMPo &&
6415 UI->getOperand(1) == N->getOperand(1) &&
6416 UI->getOperand(2) == N->getOperand(2) &&
6417 UI->getOperand(0) == N->getOperand(0)) {
6422 // If there is no VCMPo node, or if the flag value has a single use, don't
6424 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6427 // Look at the (necessarily single) use of the flag value. If it has a
6428 // chain, this transformation is more complex. Note that multiple things
6429 // could use the value result, which we should ignore.
6430 SDNode *FlagUser = 0;
6431 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6432 FlagUser == 0; ++UI) {
6433 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6435 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6436 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6443 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6444 // give up for right now.
6445 if (FlagUser->getOpcode() == PPCISD::MFCR)
6446 return SDValue(VCMPoNode, 0);
6451 // If this is a branch on an altivec predicate comparison, lower this so
6452 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6453 // lowering is done pre-legalize, because the legalizer lowers the predicate
6454 // compare down to code that is difficult to reassemble.
6455 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6456 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6460 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6461 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6462 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6463 assert(isDot && "Can't compare against a vector result!");
6465 // If this is a comparison against something other than 0/1, then we know
6466 // that the condition is never/always true.
6467 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6468 if (Val != 0 && Val != 1) {
6469 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6470 return N->getOperand(0);
6471 // Always !=, turn it into an unconditional branch.
6472 return DAG.getNode(ISD::BR, dl, MVT::Other,
6473 N->getOperand(0), N->getOperand(4));
6476 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6478 // Create the PPCISD altivec 'dot' comparison node.
6479 std::vector<EVT> VTs;
6481 LHS.getOperand(2), // LHS of compare
6482 LHS.getOperand(3), // RHS of compare
6483 DAG.getConstant(CompareOpc, MVT::i32)
6485 VTs.push_back(LHS.getOperand(2).getValueType());
6486 VTs.push_back(MVT::Glue);
6487 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6489 // Unpack the result based on how the target uses it.
6490 PPC::Predicate CompOpc;
6491 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6492 default: // Can't happen, don't crash on invalid number though.
6493 case 0: // Branch on the value of the EQ bit of CR6.
6494 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6496 case 1: // Branch on the inverted value of the EQ bit of CR6.
6497 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6499 case 2: // Branch on the value of the LT bit of CR6.
6500 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6502 case 3: // Branch on the inverted value of the LT bit of CR6.
6503 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6507 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6508 DAG.getConstant(CompOpc, MVT::i32),
6509 DAG.getRegister(PPC::CR6, MVT::i32),
6510 N->getOperand(4), CompNode.getValue(1));
6519 //===----------------------------------------------------------------------===//
6520 // Inline Assembly Support
6521 //===----------------------------------------------------------------------===//
6523 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6526 const SelectionDAG &DAG,
6527 unsigned Depth) const {
6528 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6529 switch (Op.getOpcode()) {
6531 case PPCISD::LBRX: {
6532 // lhbrx is known to have the top bits cleared out.
6533 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6534 KnownZero = 0xFFFF0000;
6537 case ISD::INTRINSIC_WO_CHAIN: {
6538 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6540 case Intrinsic::ppc_altivec_vcmpbfp_p:
6541 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6542 case Intrinsic::ppc_altivec_vcmpequb_p:
6543 case Intrinsic::ppc_altivec_vcmpequh_p:
6544 case Intrinsic::ppc_altivec_vcmpequw_p:
6545 case Intrinsic::ppc_altivec_vcmpgefp_p:
6546 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6547 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6548 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6549 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6550 case Intrinsic::ppc_altivec_vcmpgtub_p:
6551 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6552 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6553 KnownZero = ~1U; // All bits but the low one are known to be zero.
6561 /// getConstraintType - Given a constraint, return the type of
6562 /// constraint it is for this target.
6563 PPCTargetLowering::ConstraintType
6564 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6565 if (Constraint.size() == 1) {
6566 switch (Constraint[0]) {
6573 return C_RegisterClass;
6575 // FIXME: While Z does indicate a memory constraint, it specifically
6576 // indicates an r+r address (used in conjunction with the 'y' modifier
6577 // in the replacement string). Currently, we're forcing the base
6578 // register to be r0 in the asm printer (which is interpreted as zero)
6579 // and forming the complete address in the second register. This is
6584 return TargetLowering::getConstraintType(Constraint);
6587 /// Examine constraint type and operand type and determine a weight value.
6588 /// This object must already have been set up with the operand type
6589 /// and the current alternative constraint selected.
6590 TargetLowering::ConstraintWeight
6591 PPCTargetLowering::getSingleConstraintMatchWeight(
6592 AsmOperandInfo &info, const char *constraint) const {
6593 ConstraintWeight weight = CW_Invalid;
6594 Value *CallOperandVal = info.CallOperandVal;
6595 // If we don't have a value, we can't do a match,
6596 // but allow it at the lowest weight.
6597 if (CallOperandVal == NULL)
6599 Type *type = CallOperandVal->getType();
6600 // Look at the constraint type.
6601 switch (*constraint) {
6603 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6606 if (type->isIntegerTy())
6607 weight = CW_Register;
6610 if (type->isFloatTy())
6611 weight = CW_Register;
6614 if (type->isDoubleTy())
6615 weight = CW_Register;
6618 if (type->isVectorTy())
6619 weight = CW_Register;
6622 weight = CW_Register;
6631 std::pair<unsigned, const TargetRegisterClass*>
6632 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6634 if (Constraint.size() == 1) {
6635 // GCC RS6000 Constraint Letters
6636 switch (Constraint[0]) {
6639 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6640 return std::make_pair(0U, &PPC::G8RCRegClass);
6641 return std::make_pair(0U, &PPC::GPRCRegClass);
6643 if (VT == MVT::f32 || VT == MVT::i32)
6644 return std::make_pair(0U, &PPC::F4RCRegClass);
6645 if (VT == MVT::f64 || VT == MVT::i64)
6646 return std::make_pair(0U, &PPC::F8RCRegClass);
6649 return std::make_pair(0U, &PPC::VRRCRegClass);
6651 return std::make_pair(0U, &PPC::CRRCRegClass);
6655 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6659 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6660 /// vector. If it is invalid, don't add anything to Ops.
6661 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6662 std::string &Constraint,
6663 std::vector<SDValue>&Ops,
6664 SelectionDAG &DAG) const {
6665 SDValue Result(0,0);
6667 // Only support length 1 constraints.
6668 if (Constraint.length() > 1) return;
6670 char Letter = Constraint[0];
6681 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6682 if (!CST) return; // Must be an immediate to match.
6683 unsigned Value = CST->getZExtValue();
6685 default: llvm_unreachable("Unknown constraint letter!");
6686 case 'I': // "I" is a signed 16-bit constant.
6687 if ((short)Value == (int)Value)
6688 Result = DAG.getTargetConstant(Value, Op.getValueType());
6690 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6691 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6692 if ((short)Value == 0)
6693 Result = DAG.getTargetConstant(Value, Op.getValueType());
6695 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6696 if ((Value >> 16) == 0)
6697 Result = DAG.getTargetConstant(Value, Op.getValueType());
6699 case 'M': // "M" is a constant that is greater than 31.
6701 Result = DAG.getTargetConstant(Value, Op.getValueType());
6703 case 'N': // "N" is a positive constant that is an exact power of two.
6704 if ((int)Value > 0 && isPowerOf2_32(Value))
6705 Result = DAG.getTargetConstant(Value, Op.getValueType());
6707 case 'O': // "O" is the constant zero.
6709 Result = DAG.getTargetConstant(Value, Op.getValueType());
6711 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6712 if ((short)-Value == (int)-Value)
6713 Result = DAG.getTargetConstant(Value, Op.getValueType());
6720 if (Result.getNode()) {
6721 Ops.push_back(Result);
6725 // Handle standard constraint letters.
6726 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6729 // isLegalAddressingMode - Return true if the addressing mode represented
6730 // by AM is legal for this target, for a load/store of the specified type.
6731 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6733 // FIXME: PPC does not allow r+i addressing modes for vectors!
6735 // PPC allows a sign-extended 16-bit immediate field.
6736 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6739 // No global is ever allowed as a base.
6743 // PPC only support r+r,
6745 case 0: // "r+i" or just "i", depending on HasBaseReg.
6748 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
6750 // Otherwise we have r+r or r+i.
6753 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
6755 // Allow 2*r as r+r.
6758 // No other scales are supported.
6765 /// isLegalAddressImmediate - Return true if the integer value can be used
6766 /// as the offset of the target addressing mode for load / store of the
6768 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
6769 // PPC allows a sign-extended 16-bit immediate field.
6770 return (V > -(1 << 16) && V < (1 << 16)-1);
6773 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
6777 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
6778 SelectionDAG &DAG) const {
6779 MachineFunction &MF = DAG.getMachineFunction();
6780 MachineFrameInfo *MFI = MF.getFrameInfo();
6781 MFI->setReturnAddressIsTaken(true);
6783 DebugLoc dl = Op.getDebugLoc();
6784 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6786 // Make sure the function does not optimize away the store of the RA to
6788 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6789 FuncInfo->setLRStoreRequired();
6790 bool isPPC64 = PPCSubTarget.isPPC64();
6791 bool isDarwinABI = PPCSubTarget.isDarwinABI();
6794 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6797 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
6798 isPPC64? MVT::i64 : MVT::i32);
6799 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6800 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6802 MachinePointerInfo(), false, false, false, 0);
6805 // Just load the return address off the stack.
6806 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
6807 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6808 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
6811 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
6812 SelectionDAG &DAG) const {
6813 DebugLoc dl = Op.getDebugLoc();
6814 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6816 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6817 bool isPPC64 = PtrVT == MVT::i64;
6819 MachineFunction &MF = DAG.getMachineFunction();
6820 MachineFrameInfo *MFI = MF.getFrameInfo();
6821 MFI->setFrameAddressIsTaken(true);
6822 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) ||
6823 MFI->hasVarSizedObjects()) &&
6824 MFI->getStackSize() &&
6825 !MF.getFunction()->getAttributes().
6826 hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked);
6827 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
6828 (is31 ? PPC::R31 : PPC::R1);
6829 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
6832 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
6833 FrameAddr, MachinePointerInfo(), false, false,
6839 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6840 // The PowerPC target isn't yet aware of offsets.
6844 /// getOptimalMemOpType - Returns the target specific optimal type for load
6845 /// and store operations as a result of memset, memcpy, and memmove
6846 /// lowering. If DstAlign is zero that means it's safe to destination
6847 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
6848 /// means there isn't a need to check it against alignment requirement,
6849 /// probably because the source does not need to be loaded. If 'IsMemset' is
6850 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
6851 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
6852 /// source is constant so it does not need to be loaded.
6853 /// It returns EVT::Other if the type should be determined using generic
6854 /// target-independent logic.
6855 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
6856 unsigned DstAlign, unsigned SrcAlign,
6857 bool IsMemset, bool ZeroMemset,
6859 MachineFunction &MF) const {
6860 if (this->PPCSubTarget.isPPC64()) {
6867 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
6868 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
6869 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
6870 /// is expanded to mul + add.
6871 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
6875 switch (VT.getSimpleVT().SimpleTy) {
6887 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
6889 return TargetLowering::getSchedulingPreference(N);