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/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
27 #include "llvm/IR/CallingConv.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/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::FSINCOS, MVT::f64, Expand);
136 setOperationAction(ISD::FREM , MVT::f64, Expand);
137 setOperationAction(ISD::FPOW , MVT::f64, Expand);
138 setOperationAction(ISD::FMA , MVT::f64, Legal);
139 setOperationAction(ISD::FSIN , MVT::f32, Expand);
140 setOperationAction(ISD::FCOS , MVT::f32, Expand);
141 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
142 setOperationAction(ISD::FREM , MVT::f32, Expand);
143 setOperationAction(ISD::FPOW , MVT::f32, Expand);
144 setOperationAction(ISD::FMA , MVT::f32, Legal);
146 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
148 // If we're enabling GP optimizations, use hardware square root
149 if (!Subtarget->hasFSQRT()) {
150 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
151 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
154 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
155 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
157 // PowerPC does not have BSWAP, CTPOP or CTTZ
158 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
159 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
160 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
161 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
162 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
163 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
164 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
165 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
166 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
167 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
169 // PowerPC does not have ROTR
170 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
171 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
173 // PowerPC does not have Select
174 setOperationAction(ISD::SELECT, MVT::i32, Expand);
175 setOperationAction(ISD::SELECT, MVT::i64, Expand);
176 setOperationAction(ISD::SELECT, MVT::f32, Expand);
177 setOperationAction(ISD::SELECT, MVT::f64, Expand);
179 // PowerPC wants to turn select_cc of FP into fsel when possible.
180 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
181 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
183 // PowerPC wants to optimize integer setcc a bit
184 setOperationAction(ISD::SETCC, MVT::i32, Custom);
186 // PowerPC does not have BRCOND which requires SetCC
187 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
189 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
191 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
192 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
194 // PowerPC does not have [U|S]INT_TO_FP
195 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
196 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
198 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
199 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
200 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
201 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
203 // We cannot sextinreg(i1). Expand to shifts.
204 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
206 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
207 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
208 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
209 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
212 // We want to legalize GlobalAddress and ConstantPool nodes into the
213 // appropriate instructions to materialize the address.
214 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
215 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
216 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
217 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
218 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
219 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
220 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
221 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
222 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
223 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
226 setOperationAction(ISD::TRAP, MVT::Other, Legal);
228 // TRAMPOLINE is custom lowered.
229 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
230 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
232 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
233 setOperationAction(ISD::VASTART , MVT::Other, Custom);
235 if (Subtarget->isSVR4ABI()) {
237 // VAARG always uses double-word chunks, so promote anything smaller.
238 setOperationAction(ISD::VAARG, MVT::i1, Promote);
239 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
240 setOperationAction(ISD::VAARG, MVT::i8, Promote);
241 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
242 setOperationAction(ISD::VAARG, MVT::i16, Promote);
243 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
244 setOperationAction(ISD::VAARG, MVT::i32, Promote);
245 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
246 setOperationAction(ISD::VAARG, MVT::Other, Expand);
248 // VAARG is custom lowered with the 32-bit SVR4 ABI.
249 setOperationAction(ISD::VAARG, MVT::Other, Custom);
250 setOperationAction(ISD::VAARG, MVT::i64, Custom);
253 setOperationAction(ISD::VAARG, MVT::Other, Expand);
255 // Use the default implementation.
256 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
257 setOperationAction(ISD::VAEND , MVT::Other, Expand);
258 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
259 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
260 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
261 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
263 // We want to custom lower some of our intrinsics.
264 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
266 // Comparisons that require checking two conditions.
267 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
268 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
269 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
270 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
271 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
272 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
273 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
274 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
275 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
276 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
277 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
278 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
280 if (Subtarget->has64BitSupport()) {
281 // They also have instructions for converting between i64 and fp.
282 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
283 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
284 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
285 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
286 // This is just the low 32 bits of a (signed) fp->i64 conversion.
287 // We cannot do this with Promote because i64 is not a legal type.
288 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
290 // FIXME: disable this lowered code. This generates 64-bit register values,
291 // and we don't model the fact that the top part is clobbered by calls. We
292 // need to flag these together so that the value isn't live across a call.
293 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
295 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
296 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
299 if (Subtarget->use64BitRegs()) {
300 // 64-bit PowerPC implementations can support i64 types directly
301 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
302 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
303 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
304 // 64-bit PowerPC wants to expand i128 shifts itself.
305 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
306 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
307 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
309 // 32-bit PowerPC wants to expand i64 shifts itself.
310 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
311 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
312 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
315 if (Subtarget->hasAltivec()) {
316 // First set operation action for all vector types to expand. Then we
317 // will selectively turn on ones that can be effectively codegen'd.
318 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
319 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
320 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
322 // add/sub are legal for all supported vector VT's.
323 setOperationAction(ISD::ADD , VT, Legal);
324 setOperationAction(ISD::SUB , VT, Legal);
326 // We promote all shuffles to v16i8.
327 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
328 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
330 // We promote all non-typed operations to v4i32.
331 setOperationAction(ISD::AND , VT, Promote);
332 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
333 setOperationAction(ISD::OR , VT, Promote);
334 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
335 setOperationAction(ISD::XOR , VT, Promote);
336 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
337 setOperationAction(ISD::LOAD , VT, Promote);
338 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
339 setOperationAction(ISD::SELECT, VT, Promote);
340 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
341 setOperationAction(ISD::STORE, VT, Promote);
342 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
344 // No other operations are legal.
345 setOperationAction(ISD::MUL , VT, Expand);
346 setOperationAction(ISD::SDIV, VT, Expand);
347 setOperationAction(ISD::SREM, VT, Expand);
348 setOperationAction(ISD::UDIV, VT, Expand);
349 setOperationAction(ISD::UREM, VT, Expand);
350 setOperationAction(ISD::FDIV, VT, Expand);
351 setOperationAction(ISD::FNEG, VT, Expand);
352 setOperationAction(ISD::FSQRT, VT, Expand);
353 setOperationAction(ISD::FLOG, VT, Expand);
354 setOperationAction(ISD::FLOG10, VT, Expand);
355 setOperationAction(ISD::FLOG2, VT, Expand);
356 setOperationAction(ISD::FEXP, VT, Expand);
357 setOperationAction(ISD::FEXP2, VT, Expand);
358 setOperationAction(ISD::FSIN, VT, Expand);
359 setOperationAction(ISD::FCOS, VT, Expand);
360 setOperationAction(ISD::FABS, VT, Expand);
361 setOperationAction(ISD::FPOWI, VT, Expand);
362 setOperationAction(ISD::FFLOOR, VT, Expand);
363 setOperationAction(ISD::FCEIL, VT, Expand);
364 setOperationAction(ISD::FTRUNC, VT, Expand);
365 setOperationAction(ISD::FRINT, VT, Expand);
366 setOperationAction(ISD::FNEARBYINT, VT, Expand);
367 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
368 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
369 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
370 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
371 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
372 setOperationAction(ISD::UDIVREM, VT, Expand);
373 setOperationAction(ISD::SDIVREM, VT, Expand);
374 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
375 setOperationAction(ISD::FPOW, VT, Expand);
376 setOperationAction(ISD::CTPOP, VT, Expand);
377 setOperationAction(ISD::CTLZ, VT, Expand);
378 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
379 setOperationAction(ISD::CTTZ, VT, Expand);
380 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
381 setOperationAction(ISD::VSELECT, VT, Expand);
382 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
384 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
385 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
386 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
387 setTruncStoreAction(VT, InnerVT, Expand);
389 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
390 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
391 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
394 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
395 // with merges, splats, etc.
396 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
398 setOperationAction(ISD::AND , MVT::v4i32, Legal);
399 setOperationAction(ISD::OR , MVT::v4i32, Legal);
400 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
401 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
402 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
403 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
404 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
405 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
406 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
407 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
408 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
409 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
410 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
411 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
413 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
414 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
415 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
416 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
418 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
419 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
420 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
421 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
422 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
424 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
425 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
427 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
428 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
429 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
430 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
432 // Altivec does not contain unordered floating-point compare instructions
433 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
434 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
435 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
436 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
437 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
438 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
441 if (Subtarget->has64BitSupport()) {
442 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
443 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
447 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
448 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
449 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
451 setBooleanContents(ZeroOrOneBooleanContent);
452 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
455 setStackPointerRegisterToSaveRestore(PPC::X1);
456 setExceptionPointerRegister(PPC::X3);
457 setExceptionSelectorRegister(PPC::X4);
459 setStackPointerRegisterToSaveRestore(PPC::R1);
460 setExceptionPointerRegister(PPC::R3);
461 setExceptionSelectorRegister(PPC::R4);
464 // We have target-specific dag combine patterns for the following nodes:
465 setTargetDAGCombine(ISD::SINT_TO_FP);
466 setTargetDAGCombine(ISD::STORE);
467 setTargetDAGCombine(ISD::BR_CC);
468 setTargetDAGCombine(ISD::BSWAP);
470 // Darwin long double math library functions have $LDBL128 appended.
471 if (Subtarget->isDarwin()) {
472 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
473 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
474 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
475 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
476 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
477 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
478 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
479 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
480 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
481 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
484 setMinFunctionAlignment(2);
485 if (PPCSubTarget.isDarwin())
486 setPrefFunctionAlignment(4);
488 if (isPPC64 && Subtarget->isJITCodeModel())
489 // Temporary workaround for the inability of PPC64 JIT to handle jump
491 setSupportJumpTables(false);
493 setInsertFencesForAtomic(true);
495 setSchedulingPreference(Sched::Hybrid);
497 computeRegisterProperties();
499 // The Freescale cores does better with aggressive inlining of memcpy and
500 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
501 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
502 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
503 maxStoresPerMemset = 32;
504 maxStoresPerMemsetOptSize = 16;
505 maxStoresPerMemcpy = 32;
506 maxStoresPerMemcpyOptSize = 8;
507 maxStoresPerMemmove = 32;
508 maxStoresPerMemmoveOptSize = 8;
510 setPrefFunctionAlignment(4);
511 benefitFromCodePlacementOpt = true;
515 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
516 /// function arguments in the caller parameter area.
517 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
518 const TargetMachine &TM = getTargetMachine();
519 // Darwin passes everything on 4 byte boundary.
520 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
523 // 16byte and wider vectors are passed on 16byte boundary.
524 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
525 if (VTy->getBitWidth() >= 128)
528 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
529 if (PPCSubTarget.isPPC64())
535 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
538 case PPCISD::FSEL: return "PPCISD::FSEL";
539 case PPCISD::FCFID: return "PPCISD::FCFID";
540 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
541 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
542 case PPCISD::STFIWX: return "PPCISD::STFIWX";
543 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
544 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
545 case PPCISD::VPERM: return "PPCISD::VPERM";
546 case PPCISD::Hi: return "PPCISD::Hi";
547 case PPCISD::Lo: return "PPCISD::Lo";
548 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
549 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
550 case PPCISD::LOAD: return "PPCISD::LOAD";
551 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
552 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
553 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
554 case PPCISD::SRL: return "PPCISD::SRL";
555 case PPCISD::SRA: return "PPCISD::SRA";
556 case PPCISD::SHL: return "PPCISD::SHL";
557 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
558 case PPCISD::STD_32: return "PPCISD::STD_32";
559 case PPCISD::CALL_SVR4: return "PPCISD::CALL_SVR4";
560 case PPCISD::CALL_NOP_SVR4: return "PPCISD::CALL_NOP_SVR4";
561 case PPCISD::CALL_Darwin: return "PPCISD::CALL_Darwin";
562 case PPCISD::NOP: return "PPCISD::NOP";
563 case PPCISD::MTCTR: return "PPCISD::MTCTR";
564 case PPCISD::BCTRL_Darwin: return "PPCISD::BCTRL_Darwin";
565 case PPCISD::BCTRL_SVR4: return "PPCISD::BCTRL_SVR4";
566 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
567 case PPCISD::MFCR: return "PPCISD::MFCR";
568 case PPCISD::VCMP: return "PPCISD::VCMP";
569 case PPCISD::VCMPo: return "PPCISD::VCMPo";
570 case PPCISD::LBRX: return "PPCISD::LBRX";
571 case PPCISD::STBRX: return "PPCISD::STBRX";
572 case PPCISD::LARX: return "PPCISD::LARX";
573 case PPCISD::STCX: return "PPCISD::STCX";
574 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
575 case PPCISD::MFFS: return "PPCISD::MFFS";
576 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
577 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
578 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
579 case PPCISD::MTFSF: return "PPCISD::MTFSF";
580 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
581 case PPCISD::CR6SET: return "PPCISD::CR6SET";
582 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
583 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
584 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
585 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
586 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
587 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
588 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
589 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
590 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
591 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
592 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
593 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
594 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
595 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
596 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
600 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
603 return VT.changeVectorElementTypeToInteger();
606 //===----------------------------------------------------------------------===//
607 // Node matching predicates, for use by the tblgen matching code.
608 //===----------------------------------------------------------------------===//
610 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
611 static bool isFloatingPointZero(SDValue Op) {
612 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
613 return CFP->getValueAPF().isZero();
614 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
615 // Maybe this has already been legalized into the constant pool?
616 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
617 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
618 return CFP->getValueAPF().isZero();
623 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
624 /// true if Op is undef or if it matches the specified value.
625 static bool isConstantOrUndef(int Op, int Val) {
626 return Op < 0 || Op == Val;
629 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
630 /// VPKUHUM instruction.
631 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
633 for (unsigned i = 0; i != 16; ++i)
634 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
637 for (unsigned i = 0; i != 8; ++i)
638 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
639 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
645 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
646 /// VPKUWUM instruction.
647 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
649 for (unsigned i = 0; i != 16; i += 2)
650 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
651 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
654 for (unsigned i = 0; i != 8; i += 2)
655 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
656 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
657 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
658 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
664 /// isVMerge - Common function, used to match vmrg* shuffles.
666 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
667 unsigned LHSStart, unsigned RHSStart) {
668 assert(N->getValueType(0) == MVT::v16i8 &&
669 "PPC only supports shuffles by bytes!");
670 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
671 "Unsupported merge size!");
673 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
674 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
675 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
676 LHSStart+j+i*UnitSize) ||
677 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
678 RHSStart+j+i*UnitSize))
684 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
685 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
686 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
689 return isVMerge(N, UnitSize, 8, 24);
690 return isVMerge(N, UnitSize, 8, 8);
693 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
694 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
695 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
698 return isVMerge(N, UnitSize, 0, 16);
699 return isVMerge(N, UnitSize, 0, 0);
703 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
704 /// amount, otherwise return -1.
705 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
706 assert(N->getValueType(0) == MVT::v16i8 &&
707 "PPC only supports shuffles by bytes!");
709 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
711 // Find the first non-undef value in the shuffle mask.
713 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
716 if (i == 16) return -1; // all undef.
718 // Otherwise, check to see if the rest of the elements are consecutively
719 // numbered from this value.
720 unsigned ShiftAmt = SVOp->getMaskElt(i);
721 if (ShiftAmt < i) return -1;
725 // Check the rest of the elements to see if they are consecutive.
726 for (++i; i != 16; ++i)
727 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
730 // Check the rest of the elements to see if they are consecutive.
731 for (++i; i != 16; ++i)
732 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
738 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
739 /// specifies a splat of a single element that is suitable for input to
740 /// VSPLTB/VSPLTH/VSPLTW.
741 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
742 assert(N->getValueType(0) == MVT::v16i8 &&
743 (EltSize == 1 || EltSize == 2 || EltSize == 4));
745 // This is a splat operation if each element of the permute is the same, and
746 // if the value doesn't reference the second vector.
747 unsigned ElementBase = N->getMaskElt(0);
749 // FIXME: Handle UNDEF elements too!
750 if (ElementBase >= 16)
753 // Check that the indices are consecutive, in the case of a multi-byte element
754 // splatted with a v16i8 mask.
755 for (unsigned i = 1; i != EltSize; ++i)
756 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
759 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
760 if (N->getMaskElt(i) < 0) continue;
761 for (unsigned j = 0; j != EltSize; ++j)
762 if (N->getMaskElt(i+j) != N->getMaskElt(j))
768 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
770 bool PPC::isAllNegativeZeroVector(SDNode *N) {
771 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
773 APInt APVal, APUndef;
777 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
778 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
779 return CFP->getValueAPF().isNegZero();
784 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
785 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
786 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
787 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
788 assert(isSplatShuffleMask(SVOp, EltSize));
789 return SVOp->getMaskElt(0) / EltSize;
792 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
793 /// by using a vspltis[bhw] instruction of the specified element size, return
794 /// the constant being splatted. The ByteSize field indicates the number of
795 /// bytes of each element [124] -> [bhw].
796 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
799 // If ByteSize of the splat is bigger than the element size of the
800 // build_vector, then we have a case where we are checking for a splat where
801 // multiple elements of the buildvector are folded together into a single
802 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
803 unsigned EltSize = 16/N->getNumOperands();
804 if (EltSize < ByteSize) {
805 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
806 SDValue UniquedVals[4];
807 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
809 // See if all of the elements in the buildvector agree across.
810 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
811 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
812 // If the element isn't a constant, bail fully out.
813 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
816 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
817 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
818 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
819 return SDValue(); // no match.
822 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
823 // either constant or undef values that are identical for each chunk. See
824 // if these chunks can form into a larger vspltis*.
826 // Check to see if all of the leading entries are either 0 or -1. If
827 // neither, then this won't fit into the immediate field.
828 bool LeadingZero = true;
829 bool LeadingOnes = true;
830 for (unsigned i = 0; i != Multiple-1; ++i) {
831 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
833 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
834 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
836 // Finally, check the least significant entry.
838 if (UniquedVals[Multiple-1].getNode() == 0)
839 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
840 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
842 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
845 if (UniquedVals[Multiple-1].getNode() == 0)
846 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
847 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
848 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
849 return DAG.getTargetConstant(Val, MVT::i32);
855 // Check to see if this buildvec has a single non-undef value in its elements.
856 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
857 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
858 if (OpVal.getNode() == 0)
859 OpVal = N->getOperand(i);
860 else if (OpVal != N->getOperand(i))
864 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
866 unsigned ValSizeInBytes = EltSize;
868 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
869 Value = CN->getZExtValue();
870 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
871 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
872 Value = FloatToBits(CN->getValueAPF().convertToFloat());
875 // If the splat value is larger than the element value, then we can never do
876 // this splat. The only case that we could fit the replicated bits into our
877 // immediate field for would be zero, and we prefer to use vxor for it.
878 if (ValSizeInBytes < ByteSize) return SDValue();
880 // If the element value is larger than the splat value, cut it in half and
881 // check to see if the two halves are equal. Continue doing this until we
882 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
883 while (ValSizeInBytes > ByteSize) {
884 ValSizeInBytes >>= 1;
886 // If the top half equals the bottom half, we're still ok.
887 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
888 (Value & ((1 << (8*ValSizeInBytes))-1)))
892 // Properly sign extend the value.
893 int MaskVal = SignExtend32(Value, ByteSize * 8);
895 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
896 if (MaskVal == 0) return SDValue();
898 // Finally, if this value fits in a 5 bit sext field, return it
899 if (SignExtend32<5>(MaskVal) == MaskVal)
900 return DAG.getTargetConstant(MaskVal, MVT::i32);
904 //===----------------------------------------------------------------------===//
905 // Addressing Mode Selection
906 //===----------------------------------------------------------------------===//
908 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
909 /// or 64-bit immediate, and if the value can be accurately represented as a
910 /// sign extension from a 16-bit value. If so, this returns true and the
912 static bool isIntS16Immediate(SDNode *N, short &Imm) {
913 if (N->getOpcode() != ISD::Constant)
916 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
917 if (N->getValueType(0) == MVT::i32)
918 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
920 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
922 static bool isIntS16Immediate(SDValue Op, short &Imm) {
923 return isIntS16Immediate(Op.getNode(), Imm);
927 /// SelectAddressRegReg - Given the specified addressed, check to see if it
928 /// can be represented as an indexed [r+r] operation. Returns false if it
929 /// can be more efficiently represented with [r+imm].
930 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
932 SelectionDAG &DAG) const {
934 if (N.getOpcode() == ISD::ADD) {
935 if (isIntS16Immediate(N.getOperand(1), imm))
937 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
940 Base = N.getOperand(0);
941 Index = N.getOperand(1);
943 } else if (N.getOpcode() == ISD::OR) {
944 if (isIntS16Immediate(N.getOperand(1), imm))
945 return false; // r+i can fold it if we can.
947 // If this is an or of disjoint bitfields, we can codegen this as an add
948 // (for better address arithmetic) if the LHS and RHS of the OR are provably
950 APInt LHSKnownZero, LHSKnownOne;
951 APInt RHSKnownZero, RHSKnownOne;
952 DAG.ComputeMaskedBits(N.getOperand(0),
953 LHSKnownZero, LHSKnownOne);
955 if (LHSKnownZero.getBoolValue()) {
956 DAG.ComputeMaskedBits(N.getOperand(1),
957 RHSKnownZero, RHSKnownOne);
958 // If all of the bits are known zero on the LHS or RHS, the add won't
960 if (~(LHSKnownZero | RHSKnownZero) == 0) {
961 Base = N.getOperand(0);
962 Index = N.getOperand(1);
971 /// Returns true if the address N can be represented by a base register plus
972 /// a signed 16-bit displacement [r+imm], and if it is not better
973 /// represented as reg+reg.
974 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
976 SelectionDAG &DAG) const {
977 // FIXME dl should come from parent load or store, not from address
978 DebugLoc dl = N.getDebugLoc();
979 // If this can be more profitably realized as r+r, fail.
980 if (SelectAddressRegReg(N, Disp, Base, DAG))
983 if (N.getOpcode() == ISD::ADD) {
985 if (isIntS16Immediate(N.getOperand(1), imm)) {
986 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
987 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
988 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
990 Base = N.getOperand(0);
992 return true; // [r+i]
993 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
994 // Match LOAD (ADD (X, Lo(G))).
995 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
996 && "Cannot handle constant offsets yet!");
997 Disp = N.getOperand(1).getOperand(0); // The global address.
998 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
999 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1000 Disp.getOpcode() == ISD::TargetConstantPool ||
1001 Disp.getOpcode() == ISD::TargetJumpTable);
1002 Base = N.getOperand(0);
1003 return true; // [&g+r]
1005 } else if (N.getOpcode() == ISD::OR) {
1007 if (isIntS16Immediate(N.getOperand(1), imm)) {
1008 // If this is an or of disjoint bitfields, we can codegen this as an add
1009 // (for better address arithmetic) if the LHS and RHS of the OR are
1010 // provably disjoint.
1011 APInt LHSKnownZero, LHSKnownOne;
1012 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1014 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1015 // If all of the bits are known zero on the LHS or RHS, the add won't
1017 Base = N.getOperand(0);
1018 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1022 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1023 // Loading from a constant address.
1025 // If this address fits entirely in a 16-bit sext immediate field, codegen
1028 if (isIntS16Immediate(CN, Imm)) {
1029 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1030 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1031 CN->getValueType(0));
1035 // Handle 32-bit sext immediates with LIS + addr mode.
1036 if (CN->getValueType(0) == MVT::i32 ||
1037 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1038 int Addr = (int)CN->getZExtValue();
1040 // Otherwise, break this down into an LIS + disp.
1041 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1043 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1044 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1045 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1050 Disp = DAG.getTargetConstant(0, getPointerTy());
1051 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1052 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1055 return true; // [r+0]
1058 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1059 /// represented as an indexed [r+r] operation.
1060 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1062 SelectionDAG &DAG) const {
1063 // Check to see if we can easily represent this as an [r+r] address. This
1064 // will fail if it thinks that the address is more profitably represented as
1065 // reg+imm, e.g. where imm = 0.
1066 if (SelectAddressRegReg(N, Base, Index, DAG))
1069 // If the operand is an addition, always emit this as [r+r], since this is
1070 // better (for code size, and execution, as the memop does the add for free)
1071 // than emitting an explicit add.
1072 if (N.getOpcode() == ISD::ADD) {
1073 Base = N.getOperand(0);
1074 Index = N.getOperand(1);
1078 // Otherwise, do it the hard way, using R0 as the base register.
1079 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1085 /// SelectAddressRegImmShift - Returns true if the address N can be
1086 /// represented by a base register plus a signed 14-bit displacement
1087 /// [r+imm*4]. Suitable for use by STD and friends.
1088 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1090 SelectionDAG &DAG) const {
1091 // FIXME dl should come from the parent load or store, not the address
1092 DebugLoc dl = N.getDebugLoc();
1093 // If this can be more profitably realized as r+r, fail.
1094 if (SelectAddressRegReg(N, Disp, Base, DAG))
1097 if (N.getOpcode() == ISD::ADD) {
1099 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1100 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1101 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1102 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1104 Base = N.getOperand(0);
1106 return true; // [r+i]
1107 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1108 // Match LOAD (ADD (X, Lo(G))).
1109 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1110 && "Cannot handle constant offsets yet!");
1111 Disp = N.getOperand(1).getOperand(0); // The global address.
1112 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1113 Disp.getOpcode() == ISD::TargetConstantPool ||
1114 Disp.getOpcode() == ISD::TargetJumpTable);
1115 Base = N.getOperand(0);
1116 return true; // [&g+r]
1118 } else if (N.getOpcode() == ISD::OR) {
1120 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1121 // If this is an or of disjoint bitfields, we can codegen this as an add
1122 // (for better address arithmetic) if the LHS and RHS of the OR are
1123 // provably disjoint.
1124 APInt LHSKnownZero, LHSKnownOne;
1125 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1126 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1127 // If all of the bits are known zero on the LHS or RHS, the add won't
1129 Base = N.getOperand(0);
1130 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1134 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1135 // Loading from a constant address. Verify low two bits are clear.
1136 if ((CN->getZExtValue() & 3) == 0) {
1137 // If this address fits entirely in a 14-bit sext immediate field, codegen
1140 if (isIntS16Immediate(CN, Imm)) {
1141 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1142 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::X0 : PPC::R0,
1143 CN->getValueType(0));
1147 // Fold the low-part of 32-bit absolute addresses into addr mode.
1148 if (CN->getValueType(0) == MVT::i32 ||
1149 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1150 int Addr = (int)CN->getZExtValue();
1152 // Otherwise, break this down into an LIS + disp.
1153 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1154 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1155 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1156 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1162 Disp = DAG.getTargetConstant(0, getPointerTy());
1163 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1164 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1167 return true; // [r+0]
1171 /// getPreIndexedAddressParts - returns true by value, base pointer and
1172 /// offset pointer and addressing mode by reference if the node's address
1173 /// can be legally represented as pre-indexed load / store address.
1174 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1176 ISD::MemIndexedMode &AM,
1177 SelectionDAG &DAG) const {
1178 if (DisablePPCPreinc) return false;
1182 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1183 Ptr = LD->getBasePtr();
1184 VT = LD->getMemoryVT();
1186 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1187 Ptr = ST->getBasePtr();
1188 VT = ST->getMemoryVT();
1192 // PowerPC doesn't have preinc load/store instructions for vectors.
1196 if (SelectAddressRegReg(Ptr, Offset, Base, DAG)) {
1201 // LDU/STU use reg+imm*4, others use reg+imm.
1202 if (VT != MVT::i64) {
1204 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1208 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1212 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1213 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1214 // sext i32 to i64 when addr mode is r+i.
1215 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1216 LD->getExtensionType() == ISD::SEXTLOAD &&
1217 isa<ConstantSDNode>(Offset))
1225 //===----------------------------------------------------------------------===//
1226 // LowerOperation implementation
1227 //===----------------------------------------------------------------------===//
1229 /// GetLabelAccessInfo - Return true if we should reference labels using a
1230 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1231 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1232 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1233 HiOpFlags = PPCII::MO_HA16;
1234 LoOpFlags = PPCII::MO_LO16;
1236 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1237 // non-darwin platform. We don't support PIC on other platforms yet.
1238 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1239 TM.getSubtarget<PPCSubtarget>().isDarwin();
1241 HiOpFlags |= PPCII::MO_PIC_FLAG;
1242 LoOpFlags |= PPCII::MO_PIC_FLAG;
1245 // If this is a reference to a global value that requires a non-lazy-ptr, make
1246 // sure that instruction lowering adds it.
1247 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1248 HiOpFlags |= PPCII::MO_NLP_FLAG;
1249 LoOpFlags |= PPCII::MO_NLP_FLAG;
1251 if (GV->hasHiddenVisibility()) {
1252 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1253 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1260 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1261 SelectionDAG &DAG) {
1262 EVT PtrVT = HiPart.getValueType();
1263 SDValue Zero = DAG.getConstant(0, PtrVT);
1264 DebugLoc DL = HiPart.getDebugLoc();
1266 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1267 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1269 // With PIC, the first instruction is actually "GR+hi(&G)".
1271 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1272 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1274 // Generate non-pic code that has direct accesses to the constant pool.
1275 // The address of the global is just (hi(&g)+lo(&g)).
1276 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1279 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1280 SelectionDAG &DAG) const {
1281 EVT PtrVT = Op.getValueType();
1282 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1283 const Constant *C = CP->getConstVal();
1285 // 64-bit SVR4 ABI code is always position-independent.
1286 // The actual address of the GlobalValue is stored in the TOC.
1287 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1288 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1289 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1290 DAG.getRegister(PPC::X2, MVT::i64));
1293 unsigned MOHiFlag, MOLoFlag;
1294 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1296 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1298 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1299 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1302 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1303 EVT PtrVT = Op.getValueType();
1304 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1306 // 64-bit SVR4 ABI code is always position-independent.
1307 // The actual address of the GlobalValue is stored in the TOC.
1308 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1309 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1310 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1311 DAG.getRegister(PPC::X2, MVT::i64));
1314 unsigned MOHiFlag, MOLoFlag;
1315 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1316 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1317 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1318 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1321 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1322 SelectionDAG &DAG) const {
1323 EVT PtrVT = Op.getValueType();
1325 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1327 unsigned MOHiFlag, MOLoFlag;
1328 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1329 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1330 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1331 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1334 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1335 SelectionDAG &DAG) const {
1337 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1338 DebugLoc dl = GA->getDebugLoc();
1339 const GlobalValue *GV = GA->getGlobal();
1340 EVT PtrVT = getPointerTy();
1341 bool is64bit = PPCSubTarget.isPPC64();
1343 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1345 if (Model == TLSModel::LocalExec) {
1346 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1347 PPCII::MO_TPREL16_HA);
1348 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1349 PPCII::MO_TPREL16_LO);
1350 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1351 is64bit ? MVT::i64 : MVT::i32);
1352 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1353 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1357 llvm_unreachable("only local-exec is currently supported for ppc32");
1359 if (Model == TLSModel::InitialExec) {
1360 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1361 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1362 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1363 PtrVT, GOTReg, TGA);
1364 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1365 PtrVT, TGA, TPOffsetHi);
1366 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1369 if (Model == TLSModel::GeneralDynamic) {
1370 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1371 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1372 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1374 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1377 // We need a chain node, and don't have one handy. The underlying
1378 // call has no side effects, so using the function entry node
1380 SDValue Chain = DAG.getEntryNode();
1381 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1382 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1383 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1384 PtrVT, ParmReg, TGA);
1385 // The return value from GET_TLS_ADDR really is in X3 already, but
1386 // some hacks are needed here to tie everything together. The extra
1387 // copies dissolve during subsequent transforms.
1388 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1389 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1392 if (Model == TLSModel::LocalDynamic) {
1393 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1394 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1395 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1397 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1400 // We need a chain node, and don't have one handy. The underlying
1401 // call has no side effects, so using the function entry node
1403 SDValue Chain = DAG.getEntryNode();
1404 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1405 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1406 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1407 PtrVT, ParmReg, TGA);
1408 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1409 // some hacks are needed here to tie everything together. The extra
1410 // copies dissolve during subsequent transforms.
1411 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1412 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1413 Chain, ParmReg, TGA);
1414 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1417 llvm_unreachable("Unknown TLS model!");
1420 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1421 SelectionDAG &DAG) const {
1422 EVT PtrVT = Op.getValueType();
1423 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1424 DebugLoc DL = GSDN->getDebugLoc();
1425 const GlobalValue *GV = GSDN->getGlobal();
1427 // 64-bit SVR4 ABI code is always position-independent.
1428 // The actual address of the GlobalValue is stored in the TOC.
1429 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1430 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1431 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1432 DAG.getRegister(PPC::X2, MVT::i64));
1435 unsigned MOHiFlag, MOLoFlag;
1436 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1439 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1441 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1443 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1445 // If the global reference is actually to a non-lazy-pointer, we have to do an
1446 // extra load to get the address of the global.
1447 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1448 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1449 false, false, false, 0);
1453 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1454 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1455 DebugLoc dl = Op.getDebugLoc();
1457 // If we're comparing for equality to zero, expose the fact that this is
1458 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1459 // fold the new nodes.
1460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1461 if (C->isNullValue() && CC == ISD::SETEQ) {
1462 EVT VT = Op.getOperand(0).getValueType();
1463 SDValue Zext = Op.getOperand(0);
1464 if (VT.bitsLT(MVT::i32)) {
1466 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1468 unsigned Log2b = Log2_32(VT.getSizeInBits());
1469 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1470 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1471 DAG.getConstant(Log2b, MVT::i32));
1472 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1474 // Leave comparisons against 0 and -1 alone for now, since they're usually
1475 // optimized. FIXME: revisit this when we can custom lower all setcc
1477 if (C->isAllOnesValue() || C->isNullValue())
1481 // If we have an integer seteq/setne, turn it into a compare against zero
1482 // by xor'ing the rhs with the lhs, which is faster than setting a
1483 // condition register, reading it back out, and masking the correct bit. The
1484 // normal approach here uses sub to do this instead of xor. Using xor exposes
1485 // the result to other bit-twiddling opportunities.
1486 EVT LHSVT = Op.getOperand(0).getValueType();
1487 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1488 EVT VT = Op.getValueType();
1489 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1491 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1496 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1497 const PPCSubtarget &Subtarget) const {
1498 SDNode *Node = Op.getNode();
1499 EVT VT = Node->getValueType(0);
1500 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1501 SDValue InChain = Node->getOperand(0);
1502 SDValue VAListPtr = Node->getOperand(1);
1503 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1504 DebugLoc dl = Node->getDebugLoc();
1506 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1509 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1510 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1512 InChain = GprIndex.getValue(1);
1514 if (VT == MVT::i64) {
1515 // Check if GprIndex is even
1516 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1517 DAG.getConstant(1, MVT::i32));
1518 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1519 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1520 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1521 DAG.getConstant(1, MVT::i32));
1522 // Align GprIndex to be even if it isn't
1523 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1527 // fpr index is 1 byte after gpr
1528 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1529 DAG.getConstant(1, MVT::i32));
1532 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1533 FprPtr, MachinePointerInfo(SV), MVT::i8,
1535 InChain = FprIndex.getValue(1);
1537 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1538 DAG.getConstant(8, MVT::i32));
1540 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1541 DAG.getConstant(4, MVT::i32));
1544 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1545 MachinePointerInfo(), false, false,
1547 InChain = OverflowArea.getValue(1);
1549 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1550 MachinePointerInfo(), false, false,
1552 InChain = RegSaveArea.getValue(1);
1554 // select overflow_area if index > 8
1555 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1556 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1558 // adjustment constant gpr_index * 4/8
1559 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1560 VT.isInteger() ? GprIndex : FprIndex,
1561 DAG.getConstant(VT.isInteger() ? 4 : 8,
1564 // OurReg = RegSaveArea + RegConstant
1565 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1568 // Floating types are 32 bytes into RegSaveArea
1569 if (VT.isFloatingPoint())
1570 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1571 DAG.getConstant(32, MVT::i32));
1573 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1574 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1575 VT.isInteger() ? GprIndex : FprIndex,
1576 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1579 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1580 VT.isInteger() ? VAListPtr : FprPtr,
1581 MachinePointerInfo(SV),
1582 MVT::i8, false, false, 0);
1584 // determine if we should load from reg_save_area or overflow_area
1585 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1587 // increase overflow_area by 4/8 if gpr/fpr > 8
1588 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1589 DAG.getConstant(VT.isInteger() ? 4 : 8,
1592 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1595 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1597 MachinePointerInfo(),
1598 MVT::i32, false, false, 0);
1600 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1601 false, false, false, 0);
1604 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1605 SelectionDAG &DAG) const {
1606 return Op.getOperand(0);
1609 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1610 SelectionDAG &DAG) const {
1611 SDValue Chain = Op.getOperand(0);
1612 SDValue Trmp = Op.getOperand(1); // trampoline
1613 SDValue FPtr = Op.getOperand(2); // nested function
1614 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1615 DebugLoc dl = Op.getDebugLoc();
1617 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1618 bool isPPC64 = (PtrVT == MVT::i64);
1620 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1623 TargetLowering::ArgListTy Args;
1624 TargetLowering::ArgListEntry Entry;
1626 Entry.Ty = IntPtrTy;
1627 Entry.Node = Trmp; Args.push_back(Entry);
1629 // TrampSize == (isPPC64 ? 48 : 40);
1630 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1631 isPPC64 ? MVT::i64 : MVT::i32);
1632 Args.push_back(Entry);
1634 Entry.Node = FPtr; Args.push_back(Entry);
1635 Entry.Node = Nest; Args.push_back(Entry);
1637 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1638 TargetLowering::CallLoweringInfo CLI(Chain,
1639 Type::getVoidTy(*DAG.getContext()),
1640 false, false, false, false, 0,
1642 /*isTailCall=*/false,
1643 /*doesNotRet=*/false,
1644 /*isReturnValueUsed=*/true,
1645 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1647 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1649 return CallResult.second;
1652 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1653 const PPCSubtarget &Subtarget) const {
1654 MachineFunction &MF = DAG.getMachineFunction();
1655 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1657 DebugLoc dl = Op.getDebugLoc();
1659 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1660 // vastart just stores the address of the VarArgsFrameIndex slot into the
1661 // memory location argument.
1662 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1663 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1664 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1665 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1666 MachinePointerInfo(SV),
1670 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1671 // We suppose the given va_list is already allocated.
1674 // char gpr; /* index into the array of 8 GPRs
1675 // * stored in the register save area
1676 // * gpr=0 corresponds to r3,
1677 // * gpr=1 to r4, etc.
1679 // char fpr; /* index into the array of 8 FPRs
1680 // * stored in the register save area
1681 // * fpr=0 corresponds to f1,
1682 // * fpr=1 to f2, etc.
1684 // char *overflow_arg_area;
1685 // /* location on stack that holds
1686 // * the next overflow argument
1688 // char *reg_save_area;
1689 // /* where r3:r10 and f1:f8 (if saved)
1695 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1696 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1699 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1701 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1703 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1706 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1707 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1709 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1710 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1712 uint64_t FPROffset = 1;
1713 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1715 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1717 // Store first byte : number of int regs
1718 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1720 MachinePointerInfo(SV),
1721 MVT::i8, false, false, 0);
1722 uint64_t nextOffset = FPROffset;
1723 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1726 // Store second byte : number of float regs
1727 SDValue secondStore =
1728 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1729 MachinePointerInfo(SV, nextOffset), MVT::i8,
1731 nextOffset += StackOffset;
1732 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1734 // Store second word : arguments given on stack
1735 SDValue thirdStore =
1736 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1737 MachinePointerInfo(SV, nextOffset),
1739 nextOffset += FrameOffset;
1740 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1742 // Store third word : arguments given in registers
1743 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1744 MachinePointerInfo(SV, nextOffset),
1749 #include "PPCGenCallingConv.inc"
1751 static bool CC_PPC_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1752 CCValAssign::LocInfo &LocInfo,
1753 ISD::ArgFlagsTy &ArgFlags,
1758 static bool CC_PPC_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1760 CCValAssign::LocInfo &LocInfo,
1761 ISD::ArgFlagsTy &ArgFlags,
1763 static const uint16_t ArgRegs[] = {
1764 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1765 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1767 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1769 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1771 // Skip one register if the first unallocated register has an even register
1772 // number and there are still argument registers available which have not been
1773 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1774 // need to skip a register if RegNum is odd.
1775 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1776 State.AllocateReg(ArgRegs[RegNum]);
1779 // Always return false here, as this function only makes sure that the first
1780 // unallocated register has an odd register number and does not actually
1781 // allocate a register for the current argument.
1785 static bool CC_PPC_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1787 CCValAssign::LocInfo &LocInfo,
1788 ISD::ArgFlagsTy &ArgFlags,
1790 static const uint16_t ArgRegs[] = {
1791 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1795 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1797 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1799 // If there is only one Floating-point register left we need to put both f64
1800 // values of a split ppc_fp128 value on the stack.
1801 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1802 State.AllocateReg(ArgRegs[RegNum]);
1805 // Always return false here, as this function only makes sure that the two f64
1806 // values a ppc_fp128 value is split into are both passed in registers or both
1807 // passed on the stack and does not actually allocate a register for the
1808 // current argument.
1812 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1814 static const uint16_t *GetFPR() {
1815 static const uint16_t FPR[] = {
1816 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1817 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1823 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1825 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1826 unsigned PtrByteSize) {
1827 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1828 if (Flags.isByVal())
1829 ArgSize = Flags.getByValSize();
1830 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1836 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1837 CallingConv::ID CallConv, bool isVarArg,
1838 const SmallVectorImpl<ISD::InputArg>
1840 DebugLoc dl, SelectionDAG &DAG,
1841 SmallVectorImpl<SDValue> &InVals)
1843 if (PPCSubTarget.isSVR4ABI()) {
1844 if (PPCSubTarget.isPPC64())
1845 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1848 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1851 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1857 PPCTargetLowering::LowerFormalArguments_32SVR4(
1859 CallingConv::ID CallConv, bool isVarArg,
1860 const SmallVectorImpl<ISD::InputArg>
1862 DebugLoc dl, SelectionDAG &DAG,
1863 SmallVectorImpl<SDValue> &InVals) const {
1865 // 32-bit SVR4 ABI Stack Frame Layout:
1866 // +-----------------------------------+
1867 // +--> | Back chain |
1868 // | +-----------------------------------+
1869 // | | Floating-point register save area |
1870 // | +-----------------------------------+
1871 // | | General register save area |
1872 // | +-----------------------------------+
1873 // | | CR save word |
1874 // | +-----------------------------------+
1875 // | | VRSAVE save word |
1876 // | +-----------------------------------+
1877 // | | Alignment padding |
1878 // | +-----------------------------------+
1879 // | | Vector register save area |
1880 // | +-----------------------------------+
1881 // | | Local variable space |
1882 // | +-----------------------------------+
1883 // | | Parameter list area |
1884 // | +-----------------------------------+
1885 // | | LR save word |
1886 // | +-----------------------------------+
1887 // SP--> +--- | Back chain |
1888 // +-----------------------------------+
1891 // System V Application Binary Interface PowerPC Processor Supplement
1892 // AltiVec Technology Programming Interface Manual
1894 MachineFunction &MF = DAG.getMachineFunction();
1895 MachineFrameInfo *MFI = MF.getFrameInfo();
1896 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1898 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1899 // Potential tail calls could cause overwriting of argument stack slots.
1900 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1901 (CallConv == CallingConv::Fast));
1902 unsigned PtrByteSize = 4;
1904 // Assign locations to all of the incoming arguments.
1905 SmallVector<CCValAssign, 16> ArgLocs;
1906 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1907 getTargetMachine(), ArgLocs, *DAG.getContext());
1909 // Reserve space for the linkage area on the stack.
1910 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1912 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4);
1914 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1915 CCValAssign &VA = ArgLocs[i];
1917 // Arguments stored in registers.
1918 if (VA.isRegLoc()) {
1919 const TargetRegisterClass *RC;
1920 EVT ValVT = VA.getValVT();
1922 switch (ValVT.getSimpleVT().SimpleTy) {
1924 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1926 RC = &PPC::GPRCRegClass;
1929 RC = &PPC::F4RCRegClass;
1932 RC = &PPC::F8RCRegClass;
1938 RC = &PPC::VRRCRegClass;
1942 // Transform the arguments stored in physical registers into virtual ones.
1943 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1944 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1946 InVals.push_back(ArgValue);
1948 // Argument stored in memory.
1949 assert(VA.isMemLoc());
1951 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1952 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1955 // Create load nodes to retrieve arguments from the stack.
1956 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1957 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1958 MachinePointerInfo(),
1959 false, false, false, 0));
1963 // Assign locations to all of the incoming aggregate by value arguments.
1964 // Aggregates passed by value are stored in the local variable space of the
1965 // caller's stack frame, right above the parameter list area.
1966 SmallVector<CCValAssign, 16> ByValArgLocs;
1967 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1968 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1970 // Reserve stack space for the allocations in CCInfo.
1971 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1973 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC_SVR4_ByVal);
1975 // Area that is at least reserved in the caller of this function.
1976 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1978 // Set the size that is at least reserved in caller of this function. Tail
1979 // call optimized function's reserved stack space needs to be aligned so that
1980 // taking the difference between two stack areas will result in an aligned
1982 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1985 std::max(MinReservedArea,
1986 PPCFrameLowering::getMinCallFrameSize(false, false));
1988 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1989 getStackAlignment();
1990 unsigned AlignMask = TargetAlign-1;
1991 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
1993 FI->setMinReservedArea(MinReservedArea);
1995 SmallVector<SDValue, 8> MemOps;
1997 // If the function takes variable number of arguments, make a frame index for
1998 // the start of the first vararg value... for expansion of llvm.va_start.
2000 static const uint16_t GPArgRegs[] = {
2001 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2002 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2004 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2006 static const uint16_t FPArgRegs[] = {
2007 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2010 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2012 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2014 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2017 // Make room for NumGPArgRegs and NumFPArgRegs.
2018 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2019 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2021 FuncInfo->setVarArgsStackOffset(
2022 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2023 CCInfo.getNextStackOffset(), true));
2025 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2026 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2028 // The fixed integer arguments of a variadic function are stored to the
2029 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2030 // the result of va_next.
2031 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2032 // Get an existing live-in vreg, or add a new one.
2033 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2035 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2037 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2038 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2039 MachinePointerInfo(), false, false, 0);
2040 MemOps.push_back(Store);
2041 // Increment the address by four for the next argument to store
2042 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2043 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2046 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2048 // The double arguments are stored to the VarArgsFrameIndex
2050 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2051 // Get an existing live-in vreg, or add a new one.
2052 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2054 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2056 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2057 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2058 MachinePointerInfo(), false, false, 0);
2059 MemOps.push_back(Store);
2060 // Increment the address by eight for the next argument to store
2061 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2063 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2067 if (!MemOps.empty())
2068 Chain = DAG.getNode(ISD::TokenFactor, dl,
2069 MVT::Other, &MemOps[0], MemOps.size());
2074 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2075 // value to MVT::i64 and then truncate to the correct register size.
2077 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2078 SelectionDAG &DAG, SDValue ArgVal,
2079 DebugLoc dl) const {
2081 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2082 DAG.getValueType(ObjectVT));
2083 else if (Flags.isZExt())
2084 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2085 DAG.getValueType(ObjectVT));
2087 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2090 // Set the size that is at least reserved in caller of this function. Tail
2091 // call optimized functions' reserved stack space needs to be aligned so that
2092 // taking the difference between two stack areas will result in an aligned
2095 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2096 unsigned nAltivecParamsAtEnd,
2097 unsigned MinReservedArea,
2098 bool isPPC64) const {
2099 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2100 // Add the Altivec parameters at the end, if needed.
2101 if (nAltivecParamsAtEnd) {
2102 MinReservedArea = ((MinReservedArea+15)/16)*16;
2103 MinReservedArea += 16*nAltivecParamsAtEnd;
2106 std::max(MinReservedArea,
2107 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2108 unsigned TargetAlign
2109 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2110 getStackAlignment();
2111 unsigned AlignMask = TargetAlign-1;
2112 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2113 FI->setMinReservedArea(MinReservedArea);
2117 PPCTargetLowering::LowerFormalArguments_64SVR4(
2119 CallingConv::ID CallConv, bool isVarArg,
2120 const SmallVectorImpl<ISD::InputArg>
2122 DebugLoc dl, SelectionDAG &DAG,
2123 SmallVectorImpl<SDValue> &InVals) const {
2124 // TODO: add description of PPC stack frame format, or at least some docs.
2126 MachineFunction &MF = DAG.getMachineFunction();
2127 MachineFrameInfo *MFI = MF.getFrameInfo();
2128 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2130 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2131 // Potential tail calls could cause overwriting of argument stack slots.
2132 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2133 (CallConv == CallingConv::Fast));
2134 unsigned PtrByteSize = 8;
2136 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2137 // Area that is at least reserved in caller of this function.
2138 unsigned MinReservedArea = ArgOffset;
2140 static const uint16_t GPR[] = {
2141 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2142 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2145 static const uint16_t *FPR = GetFPR();
2147 static const uint16_t VR[] = {
2148 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2149 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2152 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2153 const unsigned Num_FPR_Regs = 13;
2154 const unsigned Num_VR_Regs = array_lengthof(VR);
2156 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2158 // Add DAG nodes to load the arguments or copy them out of registers. On
2159 // entry to a function on PPC, the arguments start after the linkage area,
2160 // although the first ones are often in registers.
2162 SmallVector<SDValue, 8> MemOps;
2163 unsigned nAltivecParamsAtEnd = 0;
2164 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2165 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2167 bool needsLoad = false;
2168 EVT ObjectVT = Ins[ArgNo].VT;
2169 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2170 unsigned ArgSize = ObjSize;
2171 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2173 unsigned CurArgOffset = ArgOffset;
2175 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2176 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2177 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2179 MinReservedArea = ((MinReservedArea+15)/16)*16;
2180 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2184 nAltivecParamsAtEnd++;
2186 // Calculate min reserved area.
2187 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2191 // FIXME the codegen can be much improved in some cases.
2192 // We do not have to keep everything in memory.
2193 if (Flags.isByVal()) {
2194 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2195 ObjSize = Flags.getByValSize();
2196 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2197 // Empty aggregate parameters do not take up registers. Examples:
2201 // etc. However, we have to provide a place-holder in InVals, so
2202 // pretend we have an 8-byte item at the current address for that
2205 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2206 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2207 InVals.push_back(FIN);
2210 // All aggregates smaller than 8 bytes must be passed right-justified.
2211 if (ObjSize < PtrByteSize)
2212 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2213 // The value of the object is its address.
2214 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2215 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2216 InVals.push_back(FIN);
2219 if (GPR_idx != Num_GPR_Regs) {
2220 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2221 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2224 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2225 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2226 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2227 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2228 MachinePointerInfo(FuncArg, CurArgOffset),
2229 ObjType, false, false, 0);
2231 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2232 // store the whole register as-is to the parameter save area
2233 // slot. The address of the parameter was already calculated
2234 // above (InVals.push_back(FIN)) to be the right-justified
2235 // offset within the slot. For this store, we need a new
2236 // frame index that points at the beginning of the slot.
2237 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2238 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2239 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2240 MachinePointerInfo(FuncArg, ArgOffset),
2244 MemOps.push_back(Store);
2247 // Whether we copied from a register or not, advance the offset
2248 // into the parameter save area by a full doubleword.
2249 ArgOffset += PtrByteSize;
2253 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2254 // Store whatever pieces of the object are in registers
2255 // to memory. ArgOffset will be the address of the beginning
2257 if (GPR_idx != Num_GPR_Regs) {
2259 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2260 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2261 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2262 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2263 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2264 MachinePointerInfo(FuncArg, ArgOffset),
2266 MemOps.push_back(Store);
2268 ArgOffset += PtrByteSize;
2270 ArgOffset += ArgSize - j;
2277 switch (ObjectVT.getSimpleVT().SimpleTy) {
2278 default: llvm_unreachable("Unhandled argument type!");
2281 if (GPR_idx != Num_GPR_Regs) {
2282 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2283 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2285 if (ObjectVT == MVT::i32)
2286 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2287 // value to MVT::i64 and then truncate to the correct register size.
2288 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2293 ArgSize = PtrByteSize;
2300 // Every 8 bytes of argument space consumes one of the GPRs available for
2301 // argument passing.
2302 if (GPR_idx != Num_GPR_Regs) {
2305 if (FPR_idx != Num_FPR_Regs) {
2308 if (ObjectVT == MVT::f32)
2309 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2311 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2313 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2317 ArgSize = PtrByteSize;
2326 // Note that vector arguments in registers don't reserve stack space,
2327 // except in varargs functions.
2328 if (VR_idx != Num_VR_Regs) {
2329 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2330 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2332 while ((ArgOffset % 16) != 0) {
2333 ArgOffset += PtrByteSize;
2334 if (GPR_idx != Num_GPR_Regs)
2338 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2342 // Vectors are aligned.
2343 ArgOffset = ((ArgOffset+15)/16)*16;
2344 CurArgOffset = ArgOffset;
2351 // We need to load the argument to a virtual register if we determined
2352 // above that we ran out of physical registers of the appropriate type.
2354 int FI = MFI->CreateFixedObject(ObjSize,
2355 CurArgOffset + (ArgSize - ObjSize),
2357 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2358 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2359 false, false, false, 0);
2362 InVals.push_back(ArgVal);
2365 // Set the size that is at least reserved in caller of this function. Tail
2366 // call optimized functions' reserved stack space needs to be aligned so that
2367 // taking the difference between two stack areas will result in an aligned
2369 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2371 // If the function takes variable number of arguments, make a frame index for
2372 // the start of the first vararg value... for expansion of llvm.va_start.
2374 int Depth = ArgOffset;
2376 FuncInfo->setVarArgsFrameIndex(
2377 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2378 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2380 // If this function is vararg, store any remaining integer argument regs
2381 // to their spots on the stack so that they may be loaded by deferencing the
2382 // result of va_next.
2383 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2384 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2385 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2386 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2387 MachinePointerInfo(), false, false, 0);
2388 MemOps.push_back(Store);
2389 // Increment the address by four for the next argument to store
2390 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2391 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2395 if (!MemOps.empty())
2396 Chain = DAG.getNode(ISD::TokenFactor, dl,
2397 MVT::Other, &MemOps[0], MemOps.size());
2403 PPCTargetLowering::LowerFormalArguments_Darwin(
2405 CallingConv::ID CallConv, bool isVarArg,
2406 const SmallVectorImpl<ISD::InputArg>
2408 DebugLoc dl, SelectionDAG &DAG,
2409 SmallVectorImpl<SDValue> &InVals) const {
2410 // TODO: add description of PPC stack frame format, or at least some docs.
2412 MachineFunction &MF = DAG.getMachineFunction();
2413 MachineFrameInfo *MFI = MF.getFrameInfo();
2414 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2416 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2417 bool isPPC64 = PtrVT == MVT::i64;
2418 // Potential tail calls could cause overwriting of argument stack slots.
2419 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2420 (CallConv == CallingConv::Fast));
2421 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2423 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2424 // Area that is at least reserved in caller of this function.
2425 unsigned MinReservedArea = ArgOffset;
2427 static const uint16_t GPR_32[] = { // 32-bit registers.
2428 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2429 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2431 static const uint16_t GPR_64[] = { // 64-bit registers.
2432 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2433 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2436 static const uint16_t *FPR = GetFPR();
2438 static const uint16_t VR[] = {
2439 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2440 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2443 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2444 const unsigned Num_FPR_Regs = 13;
2445 const unsigned Num_VR_Regs = array_lengthof( VR);
2447 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2449 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2451 // In 32-bit non-varargs functions, the stack space for vectors is after the
2452 // stack space for non-vectors. We do not use this space unless we have
2453 // too many vectors to fit in registers, something that only occurs in
2454 // constructed examples:), but we have to walk the arglist to figure
2455 // that out...for the pathological case, compute VecArgOffset as the
2456 // start of the vector parameter area. Computing VecArgOffset is the
2457 // entire point of the following loop.
2458 unsigned VecArgOffset = ArgOffset;
2459 if (!isVarArg && !isPPC64) {
2460 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2462 EVT ObjectVT = Ins[ArgNo].VT;
2463 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2465 if (Flags.isByVal()) {
2466 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2467 unsigned ObjSize = Flags.getByValSize();
2469 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2470 VecArgOffset += ArgSize;
2474 switch(ObjectVT.getSimpleVT().SimpleTy) {
2475 default: llvm_unreachable("Unhandled argument type!");
2480 case MVT::i64: // PPC64
2482 // FIXME: We are guaranteed to be !isPPC64 at this point.
2483 // Does MVT::i64 apply?
2490 // Nothing to do, we're only looking at Nonvector args here.
2495 // We've found where the vector parameter area in memory is. Skip the
2496 // first 12 parameters; these don't use that memory.
2497 VecArgOffset = ((VecArgOffset+15)/16)*16;
2498 VecArgOffset += 12*16;
2500 // Add DAG nodes to load the arguments or copy them out of registers. On
2501 // entry to a function on PPC, the arguments start after the linkage area,
2502 // although the first ones are often in registers.
2504 SmallVector<SDValue, 8> MemOps;
2505 unsigned nAltivecParamsAtEnd = 0;
2506 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2507 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2509 bool needsLoad = false;
2510 EVT ObjectVT = Ins[ArgNo].VT;
2511 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2512 unsigned ArgSize = ObjSize;
2513 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2515 unsigned CurArgOffset = ArgOffset;
2517 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2518 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2519 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2520 if (isVarArg || isPPC64) {
2521 MinReservedArea = ((MinReservedArea+15)/16)*16;
2522 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2525 } else nAltivecParamsAtEnd++;
2527 // Calculate min reserved area.
2528 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2532 // FIXME the codegen can be much improved in some cases.
2533 // We do not have to keep everything in memory.
2534 if (Flags.isByVal()) {
2535 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2536 ObjSize = Flags.getByValSize();
2537 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2538 // Objects of size 1 and 2 are right justified, everything else is
2539 // left justified. This means the memory address is adjusted forwards.
2540 if (ObjSize==1 || ObjSize==2) {
2541 CurArgOffset = CurArgOffset + (4 - ObjSize);
2543 // The value of the object is its address.
2544 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2545 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2546 InVals.push_back(FIN);
2547 if (ObjSize==1 || ObjSize==2) {
2548 if (GPR_idx != Num_GPR_Regs) {
2551 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2553 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2554 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2555 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2556 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2557 MachinePointerInfo(FuncArg,
2559 ObjType, false, false, 0);
2560 MemOps.push_back(Store);
2564 ArgOffset += PtrByteSize;
2568 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2569 // Store whatever pieces of the object are in registers
2570 // to memory. ArgOffset will be the address of the beginning
2572 if (GPR_idx != Num_GPR_Regs) {
2575 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2577 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2578 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2579 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2580 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2581 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2582 MachinePointerInfo(FuncArg, ArgOffset),
2584 MemOps.push_back(Store);
2586 ArgOffset += PtrByteSize;
2588 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2595 switch (ObjectVT.getSimpleVT().SimpleTy) {
2596 default: llvm_unreachable("Unhandled argument type!");
2599 if (GPR_idx != Num_GPR_Regs) {
2600 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2601 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2605 ArgSize = PtrByteSize;
2607 // All int arguments reserve stack space in the Darwin ABI.
2608 ArgOffset += PtrByteSize;
2612 case MVT::i64: // PPC64
2613 if (GPR_idx != Num_GPR_Regs) {
2614 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2615 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2617 if (ObjectVT == MVT::i32)
2618 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2619 // value to MVT::i64 and then truncate to the correct register size.
2620 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2625 ArgSize = PtrByteSize;
2627 // All int arguments reserve stack space in the Darwin ABI.
2633 // Every 4 bytes of argument space consumes one of the GPRs available for
2634 // argument passing.
2635 if (GPR_idx != Num_GPR_Regs) {
2637 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2640 if (FPR_idx != Num_FPR_Regs) {
2643 if (ObjectVT == MVT::f32)
2644 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2646 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2648 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2654 // All FP arguments reserve stack space in the Darwin ABI.
2655 ArgOffset += isPPC64 ? 8 : ObjSize;
2661 // Note that vector arguments in registers don't reserve stack space,
2662 // except in varargs functions.
2663 if (VR_idx != Num_VR_Regs) {
2664 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2665 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2667 while ((ArgOffset % 16) != 0) {
2668 ArgOffset += PtrByteSize;
2669 if (GPR_idx != Num_GPR_Regs)
2673 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2677 if (!isVarArg && !isPPC64) {
2678 // Vectors go after all the nonvectors.
2679 CurArgOffset = VecArgOffset;
2682 // Vectors are aligned.
2683 ArgOffset = ((ArgOffset+15)/16)*16;
2684 CurArgOffset = ArgOffset;
2692 // We need to load the argument to a virtual register if we determined above
2693 // that we ran out of physical registers of the appropriate type.
2695 int FI = MFI->CreateFixedObject(ObjSize,
2696 CurArgOffset + (ArgSize - ObjSize),
2698 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2699 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2700 false, false, false, 0);
2703 InVals.push_back(ArgVal);
2706 // Set the size that is at least reserved in caller of this function. Tail
2707 // call optimized functions' reserved stack space needs to be aligned so that
2708 // taking the difference between two stack areas will result in an aligned
2710 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2712 // If the function takes variable number of arguments, make a frame index for
2713 // the start of the first vararg value... for expansion of llvm.va_start.
2715 int Depth = ArgOffset;
2717 FuncInfo->setVarArgsFrameIndex(
2718 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2720 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2722 // If this function is vararg, store any remaining integer argument regs
2723 // to their spots on the stack so that they may be loaded by deferencing the
2724 // result of va_next.
2725 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2729 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2731 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2733 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2734 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2735 MachinePointerInfo(), false, false, 0);
2736 MemOps.push_back(Store);
2737 // Increment the address by four for the next argument to store
2738 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2739 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2743 if (!MemOps.empty())
2744 Chain = DAG.getNode(ISD::TokenFactor, dl,
2745 MVT::Other, &MemOps[0], MemOps.size());
2750 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2751 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2753 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2757 const SmallVectorImpl<ISD::OutputArg>
2759 const SmallVectorImpl<SDValue> &OutVals,
2760 unsigned &nAltivecParamsAtEnd) {
2761 // Count how many bytes are to be pushed on the stack, including the linkage
2762 // area, and parameter passing area. We start with 24/48 bytes, which is
2763 // prereserved space for [SP][CR][LR][3 x unused].
2764 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2765 unsigned NumOps = Outs.size();
2766 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2768 // Add up all the space actually used.
2769 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2770 // they all go in registers, but we must reserve stack space for them for
2771 // possible use by the caller. In varargs or 64-bit calls, parameters are
2772 // assigned stack space in order, with padding so Altivec parameters are
2774 nAltivecParamsAtEnd = 0;
2775 for (unsigned i = 0; i != NumOps; ++i) {
2776 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2777 EVT ArgVT = Outs[i].VT;
2778 // Varargs Altivec parameters are padded to a 16 byte boundary.
2779 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2780 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2781 if (!isVarArg && !isPPC64) {
2782 // Non-varargs Altivec parameters go after all the non-Altivec
2783 // parameters; handle those later so we know how much padding we need.
2784 nAltivecParamsAtEnd++;
2787 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2788 NumBytes = ((NumBytes+15)/16)*16;
2790 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2793 // Allow for Altivec parameters at the end, if needed.
2794 if (nAltivecParamsAtEnd) {
2795 NumBytes = ((NumBytes+15)/16)*16;
2796 NumBytes += 16*nAltivecParamsAtEnd;
2799 // The prolog code of the callee may store up to 8 GPR argument registers to
2800 // the stack, allowing va_start to index over them in memory if its varargs.
2801 // Because we cannot tell if this is needed on the caller side, we have to
2802 // conservatively assume that it is needed. As such, make sure we have at
2803 // least enough stack space for the caller to store the 8 GPRs.
2804 NumBytes = std::max(NumBytes,
2805 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2807 // Tail call needs the stack to be aligned.
2808 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2809 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2810 getFrameLowering()->getStackAlignment();
2811 unsigned AlignMask = TargetAlign-1;
2812 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2818 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2819 /// adjusted to accommodate the arguments for the tailcall.
2820 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2821 unsigned ParamSize) {
2823 if (!isTailCall) return 0;
2825 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2826 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2827 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2828 // Remember only if the new adjustement is bigger.
2829 if (SPDiff < FI->getTailCallSPDelta())
2830 FI->setTailCallSPDelta(SPDiff);
2835 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2836 /// for tail call optimization. Targets which want to do tail call
2837 /// optimization should implement this function.
2839 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2840 CallingConv::ID CalleeCC,
2842 const SmallVectorImpl<ISD::InputArg> &Ins,
2843 SelectionDAG& DAG) const {
2844 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2847 // Variable argument functions are not supported.
2851 MachineFunction &MF = DAG.getMachineFunction();
2852 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2853 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2854 // Functions containing by val parameters are not supported.
2855 for (unsigned i = 0; i != Ins.size(); i++) {
2856 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2857 if (Flags.isByVal()) return false;
2860 // Non PIC/GOT tail calls are supported.
2861 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2864 // At the moment we can only do local tail calls (in same module, hidden
2865 // or protected) if we are generating PIC.
2866 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2867 return G->getGlobal()->hasHiddenVisibility()
2868 || G->getGlobal()->hasProtectedVisibility();
2874 /// isCallCompatibleAddress - Return the immediate to use if the specified
2875 /// 32-bit value is representable in the immediate field of a BxA instruction.
2876 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2877 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2880 int Addr = C->getZExtValue();
2881 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2882 SignExtend32<26>(Addr) != Addr)
2883 return 0; // Top 6 bits have to be sext of immediate.
2885 return DAG.getConstant((int)C->getZExtValue() >> 2,
2886 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2891 struct TailCallArgumentInfo {
2896 TailCallArgumentInfo() : FrameIdx(0) {}
2901 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2903 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2905 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2906 SmallVector<SDValue, 8> &MemOpChains,
2908 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2909 SDValue Arg = TailCallArgs[i].Arg;
2910 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2911 int FI = TailCallArgs[i].FrameIdx;
2912 // Store relative to framepointer.
2913 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2914 MachinePointerInfo::getFixedStack(FI),
2919 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2920 /// the appropriate stack slot for the tail call optimized function call.
2921 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2922 MachineFunction &MF,
2931 // Calculate the new stack slot for the return address.
2932 int SlotSize = isPPC64 ? 8 : 4;
2933 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2935 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2936 NewRetAddrLoc, true);
2937 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2938 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2939 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2940 MachinePointerInfo::getFixedStack(NewRetAddr),
2943 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2944 // slot as the FP is never overwritten.
2947 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2948 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2950 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2951 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2952 MachinePointerInfo::getFixedStack(NewFPIdx),
2959 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2960 /// the position of the argument.
2962 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2963 SDValue Arg, int SPDiff, unsigned ArgOffset,
2964 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2965 int Offset = ArgOffset + SPDiff;
2966 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2967 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2968 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2969 SDValue FIN = DAG.getFrameIndex(FI, VT);
2970 TailCallArgumentInfo Info;
2972 Info.FrameIdxOp = FIN;
2974 TailCallArguments.push_back(Info);
2977 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2978 /// stack slot. Returns the chain as result and the loaded frame pointers in
2979 /// LROpOut/FPOpout. Used when tail calling.
2980 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
2986 DebugLoc dl) const {
2988 // Load the LR and FP stack slot for later adjusting.
2989 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
2990 LROpOut = getReturnAddrFrameIndex(DAG);
2991 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
2992 false, false, false, 0);
2993 Chain = SDValue(LROpOut.getNode(), 1);
2995 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
2996 // slot as the FP is never overwritten.
2998 FPOpOut = getFramePointerFrameIndex(DAG);
2999 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3000 false, false, false, 0);
3001 Chain = SDValue(FPOpOut.getNode(), 1);
3007 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3008 /// by "Src" to address "Dst" of size "Size". Alignment information is
3009 /// specified by the specific parameter attribute. The copy will be passed as
3010 /// a byval function parameter.
3011 /// Sometimes what we are copying is the end of a larger object, the part that
3012 /// does not fit in registers.
3014 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3015 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3017 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3018 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3019 false, false, MachinePointerInfo(0),
3020 MachinePointerInfo(0));
3023 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3026 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3027 SDValue Arg, SDValue PtrOff, int SPDiff,
3028 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3029 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3030 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3032 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3037 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3039 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3040 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3041 DAG.getConstant(ArgOffset, PtrVT));
3043 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3044 MachinePointerInfo(), false, false, 0));
3045 // Calculate and remember argument location.
3046 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3051 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3052 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3053 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3054 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3055 MachineFunction &MF = DAG.getMachineFunction();
3057 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3058 // might overwrite each other in case of tail call optimization.
3059 SmallVector<SDValue, 8> MemOpChains2;
3060 // Do not flag preceding copytoreg stuff together with the following stuff.
3062 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3064 if (!MemOpChains2.empty())
3065 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3066 &MemOpChains2[0], MemOpChains2.size());
3068 // Store the return address to the appropriate stack slot.
3069 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3070 isPPC64, isDarwinABI, dl);
3072 // Emit callseq_end just before tailcall node.
3073 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3074 DAG.getIntPtrConstant(0, true), InFlag);
3075 InFlag = Chain.getValue(1);
3079 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3080 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3081 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3082 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3083 const PPCSubtarget &PPCSubTarget) {
3085 bool isPPC64 = PPCSubTarget.isPPC64();
3086 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3088 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3089 NodeTys.push_back(MVT::Other); // Returns a chain
3090 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3092 unsigned CallOpc = isSVR4ABI ? PPCISD::CALL_SVR4 : PPCISD::CALL_Darwin;
3094 bool needIndirectCall = true;
3095 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3096 // If this is an absolute destination address, use the munged value.
3097 Callee = SDValue(Dest, 0);
3098 needIndirectCall = false;
3101 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3102 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3103 // Use indirect calls for ALL functions calls in JIT mode, since the
3104 // far-call stubs may be outside relocation limits for a BL instruction.
3105 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3106 unsigned OpFlags = 0;
3107 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3108 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3109 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3110 (G->getGlobal()->isDeclaration() ||
3111 G->getGlobal()->isWeakForLinker())) {
3112 // PC-relative references to external symbols should go through $stub,
3113 // unless we're building with the leopard linker or later, which
3114 // automatically synthesizes these stubs.
3115 OpFlags = PPCII::MO_DARWIN_STUB;
3118 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3119 // every direct call is) turn it into a TargetGlobalAddress /
3120 // TargetExternalSymbol node so that legalize doesn't hack it.
3121 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3122 Callee.getValueType(),
3124 needIndirectCall = false;
3128 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3129 unsigned char OpFlags = 0;
3131 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3132 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3133 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3134 // PC-relative references to external symbols should go through $stub,
3135 // unless we're building with the leopard linker or later, which
3136 // automatically synthesizes these stubs.
3137 OpFlags = PPCII::MO_DARWIN_STUB;
3140 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3142 needIndirectCall = false;
3145 if (needIndirectCall) {
3146 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3147 // to do the call, we can't use PPCISD::CALL.
3148 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3150 if (isSVR4ABI && isPPC64) {
3151 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3152 // entry point, but to the function descriptor (the function entry point
3153 // address is part of the function descriptor though).
3154 // The function descriptor is a three doubleword structure with the
3155 // following fields: function entry point, TOC base address and
3156 // environment pointer.
3157 // Thus for a call through a function pointer, the following actions need
3159 // 1. Save the TOC of the caller in the TOC save area of its stack
3160 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3161 // 2. Load the address of the function entry point from the function
3163 // 3. Load the TOC of the callee from the function descriptor into r2.
3164 // 4. Load the environment pointer from the function descriptor into
3166 // 5. Branch to the function entry point address.
3167 // 6. On return of the callee, the TOC of the caller needs to be
3168 // restored (this is done in FinishCall()).
3170 // All those operations are flagged together to ensure that no other
3171 // operations can be scheduled in between. E.g. without flagging the
3172 // operations together, a TOC access in the caller could be scheduled
3173 // between the load of the callee TOC and the branch to the callee, which
3174 // results in the TOC access going through the TOC of the callee instead
3175 // of going through the TOC of the caller, which leads to incorrect code.
3177 // Load the address of the function entry point from the function
3179 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3180 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3181 InFlag.getNode() ? 3 : 2);
3182 Chain = LoadFuncPtr.getValue(1);
3183 InFlag = LoadFuncPtr.getValue(2);
3185 // Load environment pointer into r11.
3186 // Offset of the environment pointer within the function descriptor.
3187 SDValue PtrOff = DAG.getIntPtrConstant(16);
3189 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3190 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3192 Chain = LoadEnvPtr.getValue(1);
3193 InFlag = LoadEnvPtr.getValue(2);
3195 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3197 Chain = EnvVal.getValue(0);
3198 InFlag = EnvVal.getValue(1);
3200 // Load TOC of the callee into r2. We are using a target-specific load
3201 // with r2 hard coded, because the result of a target-independent load
3202 // would never go directly into r2, since r2 is a reserved register (which
3203 // prevents the register allocator from allocating it), resulting in an
3204 // additional register being allocated and an unnecessary move instruction
3206 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3207 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3209 Chain = LoadTOCPtr.getValue(0);
3210 InFlag = LoadTOCPtr.getValue(1);
3212 MTCTROps[0] = Chain;
3213 MTCTROps[1] = LoadFuncPtr;
3214 MTCTROps[2] = InFlag;
3217 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3218 2 + (InFlag.getNode() != 0));
3219 InFlag = Chain.getValue(1);
3222 NodeTys.push_back(MVT::Other);
3223 NodeTys.push_back(MVT::Glue);
3224 Ops.push_back(Chain);
3225 CallOpc = isSVR4ABI ? PPCISD::BCTRL_SVR4 : PPCISD::BCTRL_Darwin;
3227 // Add CTR register as callee so a bctr can be emitted later.
3229 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3232 // If this is a direct call, pass the chain and the callee.
3233 if (Callee.getNode()) {
3234 Ops.push_back(Chain);
3235 Ops.push_back(Callee);
3237 // If this is a tail call add stack pointer delta.
3239 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3241 // Add argument registers to the end of the list so that they are known live
3243 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3244 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3245 RegsToPass[i].second.getValueType()));
3251 bool isLocalCall(const SDValue &Callee)
3253 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3254 return !G->getGlobal()->isDeclaration() &&
3255 !G->getGlobal()->isWeakForLinker();
3260 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3261 CallingConv::ID CallConv, bool isVarArg,
3262 const SmallVectorImpl<ISD::InputArg> &Ins,
3263 DebugLoc dl, SelectionDAG &DAG,
3264 SmallVectorImpl<SDValue> &InVals) const {
3266 SmallVector<CCValAssign, 16> RVLocs;
3267 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3268 getTargetMachine(), RVLocs, *DAG.getContext());
3269 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3271 // Copy all of the result registers out of their specified physreg.
3272 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3273 CCValAssign &VA = RVLocs[i];
3274 assert(VA.isRegLoc() && "Can only return in registers!");
3276 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3277 VA.getLocReg(), VA.getLocVT(), InFlag);
3278 Chain = Val.getValue(1);
3279 InFlag = Val.getValue(2);
3281 switch (VA.getLocInfo()) {
3282 default: llvm_unreachable("Unknown loc info!");
3283 case CCValAssign::Full: break;
3284 case CCValAssign::AExt:
3285 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3287 case CCValAssign::ZExt:
3288 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3289 DAG.getValueType(VA.getValVT()));
3290 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3292 case CCValAssign::SExt:
3293 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3294 DAG.getValueType(VA.getValVT()));
3295 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3299 InVals.push_back(Val);
3306 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3307 bool isTailCall, bool isVarArg,
3309 SmallVector<std::pair<unsigned, SDValue>, 8>
3311 SDValue InFlag, SDValue Chain,
3313 int SPDiff, unsigned NumBytes,
3314 const SmallVectorImpl<ISD::InputArg> &Ins,
3315 SmallVectorImpl<SDValue> &InVals) const {
3316 std::vector<EVT> NodeTys;
3317 SmallVector<SDValue, 8> Ops;
3318 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3319 isTailCall, RegsToPass, Ops, NodeTys,
3322 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3323 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3324 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3326 // When performing tail call optimization the callee pops its arguments off
3327 // the stack. Account for this here so these bytes can be pushed back on in
3328 // PPCRegisterInfo::eliminateCallFramePseudoInstr.
3329 int BytesCalleePops =
3330 (CallConv == CallingConv::Fast &&
3331 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3333 // Add a register mask operand representing the call-preserved registers.
3334 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3335 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3336 assert(Mask && "Missing call preserved mask for calling convention");
3337 Ops.push_back(DAG.getRegisterMask(Mask));
3339 if (InFlag.getNode())
3340 Ops.push_back(InFlag);
3344 // If this is the first return lowered for this function, add the regs
3345 // to the liveout set for the function.
3346 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3347 SmallVector<CCValAssign, 16> RVLocs;
3348 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3349 getTargetMachine(), RVLocs, *DAG.getContext());
3350 CCInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3351 for (unsigned i = 0; i != RVLocs.size(); ++i)
3352 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3355 assert(((Callee.getOpcode() == ISD::Register &&
3356 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3357 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3358 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3359 isa<ConstantSDNode>(Callee)) &&
3360 "Expecting an global address, external symbol, absolute value or register");
3362 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3365 // Add a NOP immediately after the branch instruction when using the 64-bit
3366 // SVR4 ABI. At link time, if caller and callee are in a different module and
3367 // thus have a different TOC, the call will be replaced with a call to a stub
3368 // function which saves the current TOC, loads the TOC of the callee and
3369 // branches to the callee. The NOP will be replaced with a load instruction
3370 // which restores the TOC of the caller from the TOC save slot of the current
3371 // stack frame. If caller and callee belong to the same module (and have the
3372 // same TOC), the NOP will remain unchanged.
3374 bool needsTOCRestore = false;
3375 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3376 if (CallOpc == PPCISD::BCTRL_SVR4) {
3377 // This is a call through a function pointer.
3378 // Restore the caller TOC from the save area into R2.
3379 // See PrepareCall() for more information about calls through function
3380 // pointers in the 64-bit SVR4 ABI.
3381 // We are using a target-specific load with r2 hard coded, because the
3382 // result of a target-independent load would never go directly into r2,
3383 // since r2 is a reserved register (which prevents the register allocator
3384 // from allocating it), resulting in an additional register being
3385 // allocated and an unnecessary move instruction being generated.
3386 needsTOCRestore = true;
3387 } else if ((CallOpc == PPCISD::CALL_SVR4) && !isLocalCall(Callee)) {
3388 // Otherwise insert NOP for non-local calls.
3389 CallOpc = PPCISD::CALL_NOP_SVR4;
3393 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3394 InFlag = Chain.getValue(1);
3396 if (needsTOCRestore) {
3397 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3398 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3399 InFlag = Chain.getValue(1);
3402 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3403 DAG.getIntPtrConstant(BytesCalleePops, true),
3406 InFlag = Chain.getValue(1);
3408 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3409 Ins, dl, DAG, InVals);
3413 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3414 SmallVectorImpl<SDValue> &InVals) const {
3415 SelectionDAG &DAG = CLI.DAG;
3416 DebugLoc &dl = CLI.DL;
3417 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3418 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3419 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3420 SDValue Chain = CLI.Chain;
3421 SDValue Callee = CLI.Callee;
3422 bool &isTailCall = CLI.IsTailCall;
3423 CallingConv::ID CallConv = CLI.CallConv;
3424 bool isVarArg = CLI.IsVarArg;
3427 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3430 if (PPCSubTarget.isSVR4ABI()) {
3431 if (PPCSubTarget.isPPC64())
3432 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3433 isTailCall, Outs, OutVals, Ins,
3436 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3437 isTailCall, Outs, OutVals, Ins,
3441 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3442 isTailCall, Outs, OutVals, Ins,
3447 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3448 CallingConv::ID CallConv, bool isVarArg,
3450 const SmallVectorImpl<ISD::OutputArg> &Outs,
3451 const SmallVectorImpl<SDValue> &OutVals,
3452 const SmallVectorImpl<ISD::InputArg> &Ins,
3453 DebugLoc dl, SelectionDAG &DAG,
3454 SmallVectorImpl<SDValue> &InVals) const {
3455 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3456 // of the 32-bit SVR4 ABI stack frame layout.
3458 assert((CallConv == CallingConv::C ||
3459 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3461 unsigned PtrByteSize = 4;
3463 MachineFunction &MF = DAG.getMachineFunction();
3465 // Mark this function as potentially containing a function that contains a
3466 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3467 // and restoring the callers stack pointer in this functions epilog. This is
3468 // done because by tail calling the called function might overwrite the value
3469 // in this function's (MF) stack pointer stack slot 0(SP).
3470 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3471 CallConv == CallingConv::Fast)
3472 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3474 // Count how many bytes are to be pushed on the stack, including the linkage
3475 // area, parameter list area and the part of the local variable space which
3476 // contains copies of aggregates which are passed by value.
3478 // Assign locations to all of the outgoing arguments.
3479 SmallVector<CCValAssign, 16> ArgLocs;
3480 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3481 getTargetMachine(), ArgLocs, *DAG.getContext());
3483 // Reserve space for the linkage area on the stack.
3484 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3487 // Handle fixed and variable vector arguments differently.
3488 // Fixed vector arguments go into registers as long as registers are
3489 // available. Variable vector arguments always go into memory.
3490 unsigned NumArgs = Outs.size();
3492 for (unsigned i = 0; i != NumArgs; ++i) {
3493 MVT ArgVT = Outs[i].VT;
3494 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3497 if (Outs[i].IsFixed) {
3498 Result = CC_PPC_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3501 Result = CC_PPC_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3507 errs() << "Call operand #" << i << " has unhandled type "
3508 << EVT(ArgVT).getEVTString() << "\n";
3510 llvm_unreachable(0);
3514 // All arguments are treated the same.
3515 CCInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4);
3518 // Assign locations to all of the outgoing aggregate by value arguments.
3519 SmallVector<CCValAssign, 16> ByValArgLocs;
3520 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3521 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3523 // Reserve stack space for the allocations in CCInfo.
3524 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3526 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC_SVR4_ByVal);
3528 // Size of the linkage area, parameter list area and the part of the local
3529 // space variable where copies of aggregates which are passed by value are
3531 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3533 // Calculate by how many bytes the stack has to be adjusted in case of tail
3534 // call optimization.
3535 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3537 // Adjust the stack pointer for the new arguments...
3538 // These operations are automatically eliminated by the prolog/epilog pass
3539 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3540 SDValue CallSeqStart = Chain;
3542 // Load the return address and frame pointer so it can be moved somewhere else
3545 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3548 // Set up a copy of the stack pointer for use loading and storing any
3549 // arguments that may not fit in the registers available for argument
3551 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3553 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3554 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3555 SmallVector<SDValue, 8> MemOpChains;
3557 bool seenFloatArg = false;
3558 // Walk the register/memloc assignments, inserting copies/loads.
3559 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3562 CCValAssign &VA = ArgLocs[i];
3563 SDValue Arg = OutVals[i];
3564 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3566 if (Flags.isByVal()) {
3567 // Argument is an aggregate which is passed by value, thus we need to
3568 // create a copy of it in the local variable space of the current stack
3569 // frame (which is the stack frame of the caller) and pass the address of
3570 // this copy to the callee.
3571 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3572 CCValAssign &ByValVA = ByValArgLocs[j++];
3573 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3575 // Memory reserved in the local variable space of the callers stack frame.
3576 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3578 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3579 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3581 // Create a copy of the argument in the local area of the current
3583 SDValue MemcpyCall =
3584 CreateCopyOfByValArgument(Arg, PtrOff,
3585 CallSeqStart.getNode()->getOperand(0),
3588 // This must go outside the CALLSEQ_START..END.
3589 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3590 CallSeqStart.getNode()->getOperand(1));
3591 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3592 NewCallSeqStart.getNode());
3593 Chain = CallSeqStart = NewCallSeqStart;
3595 // Pass the address of the aggregate copy on the stack either in a
3596 // physical register or in the parameter list area of the current stack
3597 // frame to the callee.
3601 if (VA.isRegLoc()) {
3602 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3603 // Put argument in a physical register.
3604 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3606 // Put argument in the parameter list area of the current stack frame.
3607 assert(VA.isMemLoc());
3608 unsigned LocMemOffset = VA.getLocMemOffset();
3611 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3612 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3614 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3615 MachinePointerInfo(),
3618 // Calculate and remember argument location.
3619 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3625 if (!MemOpChains.empty())
3626 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3627 &MemOpChains[0], MemOpChains.size());
3629 // Build a sequence of copy-to-reg nodes chained together with token chain
3630 // and flag operands which copy the outgoing args into the appropriate regs.
3632 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3633 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3634 RegsToPass[i].second, InFlag);
3635 InFlag = Chain.getValue(1);
3638 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3641 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3642 SDValue Ops[] = { Chain, InFlag };
3644 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3645 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3647 InFlag = Chain.getValue(1);
3651 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3652 false, TailCallArguments);
3654 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3655 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3659 // Copy an argument into memory, being careful to do this outside the
3660 // call sequence for the call to which the argument belongs.
3662 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3663 SDValue CallSeqStart,
3664 ISD::ArgFlagsTy Flags,
3666 DebugLoc dl) const {
3667 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3668 CallSeqStart.getNode()->getOperand(0),
3670 // The MEMCPY must go outside the CALLSEQ_START..END.
3671 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3672 CallSeqStart.getNode()->getOperand(1));
3673 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3674 NewCallSeqStart.getNode());
3675 return NewCallSeqStart;
3679 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3680 CallingConv::ID CallConv, bool isVarArg,
3682 const SmallVectorImpl<ISD::OutputArg> &Outs,
3683 const SmallVectorImpl<SDValue> &OutVals,
3684 const SmallVectorImpl<ISD::InputArg> &Ins,
3685 DebugLoc dl, SelectionDAG &DAG,
3686 SmallVectorImpl<SDValue> &InVals) const {
3688 unsigned NumOps = Outs.size();
3690 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3691 unsigned PtrByteSize = 8;
3693 MachineFunction &MF = DAG.getMachineFunction();
3695 // Mark this function as potentially containing a function that contains a
3696 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3697 // and restoring the callers stack pointer in this functions epilog. This is
3698 // done because by tail calling the called function might overwrite the value
3699 // in this function's (MF) stack pointer stack slot 0(SP).
3700 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3701 CallConv == CallingConv::Fast)
3702 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3704 unsigned nAltivecParamsAtEnd = 0;
3706 // Count how many bytes are to be pushed on the stack, including the linkage
3707 // area, and parameter passing area. We start with at least 48 bytes, which
3708 // is reserved space for [SP][CR][LR][3 x unused].
3709 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3712 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3713 Outs, OutVals, nAltivecParamsAtEnd);
3715 // Calculate by how many bytes the stack has to be adjusted in case of tail
3716 // call optimization.
3717 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3719 // To protect arguments on the stack from being clobbered in a tail call,
3720 // force all the loads to happen before doing any other lowering.
3722 Chain = DAG.getStackArgumentTokenFactor(Chain);
3724 // Adjust the stack pointer for the new arguments...
3725 // These operations are automatically eliminated by the prolog/epilog pass
3726 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3727 SDValue CallSeqStart = Chain;
3729 // Load the return address and frame pointer so it can be move somewhere else
3732 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3735 // Set up a copy of the stack pointer for use loading and storing any
3736 // arguments that may not fit in the registers available for argument
3738 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3740 // Figure out which arguments are going to go in registers, and which in
3741 // memory. Also, if this is a vararg function, floating point operations
3742 // must be stored to our stack, and loaded into integer regs as well, if
3743 // any integer regs are available for argument passing.
3744 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3745 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3747 static const uint16_t GPR[] = {
3748 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3749 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3751 static const uint16_t *FPR = GetFPR();
3753 static const uint16_t VR[] = {
3754 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3755 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3757 const unsigned NumGPRs = array_lengthof(GPR);
3758 const unsigned NumFPRs = 13;
3759 const unsigned NumVRs = array_lengthof(VR);
3761 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3762 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3764 SmallVector<SDValue, 8> MemOpChains;
3765 for (unsigned i = 0; i != NumOps; ++i) {
3766 SDValue Arg = OutVals[i];
3767 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3769 // PtrOff will be used to store the current argument to the stack if a
3770 // register cannot be found for it.
3773 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3775 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3777 // Promote integers to 64-bit values.
3778 if (Arg.getValueType() == MVT::i32) {
3779 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3780 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3781 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3784 // FIXME memcpy is used way more than necessary. Correctness first.
3785 // Note: "by value" is code for passing a structure by value, not
3787 if (Flags.isByVal()) {
3788 // Note: Size includes alignment padding, so
3789 // struct x { short a; char b; }
3790 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3791 // These are the proper values we need for right-justifying the
3792 // aggregate in a parameter register.
3793 unsigned Size = Flags.getByValSize();
3795 // An empty aggregate parameter takes up no storage and no
3800 // All aggregates smaller than 8 bytes must be passed right-justified.
3801 if (Size==1 || Size==2 || Size==4) {
3802 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3803 if (GPR_idx != NumGPRs) {
3804 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3805 MachinePointerInfo(), VT,
3807 MemOpChains.push_back(Load.getValue(1));
3808 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3810 ArgOffset += PtrByteSize;
3815 if (GPR_idx == NumGPRs && Size < 8) {
3816 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3817 PtrOff.getValueType());
3818 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3819 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3822 ArgOffset += PtrByteSize;
3825 // Copy entire object into memory. There are cases where gcc-generated
3826 // code assumes it is there, even if it could be put entirely into
3827 // registers. (This is not what the doc says.)
3829 // FIXME: The above statement is likely due to a misunderstanding of the
3830 // documents. All arguments must be copied into the parameter area BY
3831 // THE CALLEE in the event that the callee takes the address of any
3832 // formal argument. That has not yet been implemented. However, it is
3833 // reasonable to use the stack area as a staging area for the register
3836 // Skip this for small aggregates, as we will use the same slot for a
3837 // right-justified copy, below.
3839 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3843 // When a register is available, pass a small aggregate right-justified.
3844 if (Size < 8 && GPR_idx != NumGPRs) {
3845 // The easiest way to get this right-justified in a register
3846 // is to copy the structure into the rightmost portion of a
3847 // local variable slot, then load the whole slot into the
3849 // FIXME: The memcpy seems to produce pretty awful code for
3850 // small aggregates, particularly for packed ones.
3851 // FIXME: It would be preferable to use the slot in the
3852 // parameter save area instead of a new local variable.
3853 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3854 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3855 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3859 // Load the slot into the register.
3860 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3861 MachinePointerInfo(),
3862 false, false, false, 0);
3863 MemOpChains.push_back(Load.getValue(1));
3864 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3866 // Done with this argument.
3867 ArgOffset += PtrByteSize;
3871 // For aggregates larger than PtrByteSize, copy the pieces of the
3872 // object that fit into registers from the parameter save area.
3873 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3874 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3875 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3876 if (GPR_idx != NumGPRs) {
3877 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3878 MachinePointerInfo(),
3879 false, false, false, 0);
3880 MemOpChains.push_back(Load.getValue(1));
3881 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3882 ArgOffset += PtrByteSize;
3884 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3891 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3892 default: llvm_unreachable("Unexpected ValueType for argument!");
3895 if (GPR_idx != NumGPRs) {
3896 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3898 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3899 true, isTailCall, false, MemOpChains,
3900 TailCallArguments, dl);
3902 ArgOffset += PtrByteSize;
3906 if (FPR_idx != NumFPRs) {
3907 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3910 // A single float or an aggregate containing only a single float
3911 // must be passed right-justified in the stack doubleword, and
3912 // in the GPR, if one is available.
3914 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3915 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3916 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3920 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3921 MachinePointerInfo(), false, false, 0);
3922 MemOpChains.push_back(Store);
3924 // Float varargs are always shadowed in available integer registers
3925 if (GPR_idx != NumGPRs) {
3926 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3927 MachinePointerInfo(), false, false,
3929 MemOpChains.push_back(Load.getValue(1));
3930 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3932 } else if (GPR_idx != NumGPRs)
3933 // If we have any FPRs remaining, we may also have GPRs remaining.
3936 // Single-precision floating-point values are mapped to the
3937 // second (rightmost) word of the stack doubleword.
3938 if (Arg.getValueType() == MVT::f32) {
3939 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3940 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3943 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3944 true, isTailCall, false, MemOpChains,
3945 TailCallArguments, dl);
3954 // These go aligned on the stack, or in the corresponding R registers
3955 // when within range. The Darwin PPC ABI doc claims they also go in
3956 // V registers; in fact gcc does this only for arguments that are
3957 // prototyped, not for those that match the ... We do it for all
3958 // arguments, seems to work.
3959 while (ArgOffset % 16 !=0) {
3960 ArgOffset += PtrByteSize;
3961 if (GPR_idx != NumGPRs)
3964 // We could elide this store in the case where the object fits
3965 // entirely in R registers. Maybe later.
3966 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3967 DAG.getConstant(ArgOffset, PtrVT));
3968 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3969 MachinePointerInfo(), false, false, 0);
3970 MemOpChains.push_back(Store);
3971 if (VR_idx != NumVRs) {
3972 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3973 MachinePointerInfo(),
3974 false, false, false, 0);
3975 MemOpChains.push_back(Load.getValue(1));
3976 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3979 for (unsigned i=0; i<16; i+=PtrByteSize) {
3980 if (GPR_idx == NumGPRs)
3982 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3983 DAG.getConstant(i, PtrVT));
3984 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3985 false, false, false, 0);
3986 MemOpChains.push_back(Load.getValue(1));
3987 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3992 // Non-varargs Altivec params generally go in registers, but have
3993 // stack space allocated at the end.
3994 if (VR_idx != NumVRs) {
3995 // Doesn't have GPR space allocated.
3996 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
3998 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3999 true, isTailCall, true, MemOpChains,
4000 TailCallArguments, dl);
4007 if (!MemOpChains.empty())
4008 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4009 &MemOpChains[0], MemOpChains.size());
4011 // Check if this is an indirect call (MTCTR/BCTRL).
4012 // See PrepareCall() for more information about calls through function
4013 // pointers in the 64-bit SVR4 ABI.
4015 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4016 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4017 !isBLACompatibleAddress(Callee, DAG)) {
4018 // Load r2 into a virtual register and store it to the TOC save area.
4019 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4020 // TOC save area offset.
4021 SDValue PtrOff = DAG.getIntPtrConstant(40);
4022 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4023 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4025 // R12 must contain the address of an indirect callee. This does not
4026 // mean the MTCTR instruction must use R12; it's easier to model this
4027 // as an extra parameter, so do that.
4028 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4031 // Build a sequence of copy-to-reg nodes chained together with token chain
4032 // and flag operands which copy the outgoing args into the appropriate regs.
4034 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4035 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4036 RegsToPass[i].second, InFlag);
4037 InFlag = Chain.getValue(1);
4041 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4042 FPOp, true, TailCallArguments);
4044 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4045 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4050 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4051 CallingConv::ID CallConv, bool isVarArg,
4053 const SmallVectorImpl<ISD::OutputArg> &Outs,
4054 const SmallVectorImpl<SDValue> &OutVals,
4055 const SmallVectorImpl<ISD::InputArg> &Ins,
4056 DebugLoc dl, SelectionDAG &DAG,
4057 SmallVectorImpl<SDValue> &InVals) const {
4059 unsigned NumOps = Outs.size();
4061 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4062 bool isPPC64 = PtrVT == MVT::i64;
4063 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4065 MachineFunction &MF = DAG.getMachineFunction();
4067 // Mark this function as potentially containing a function that contains a
4068 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4069 // and restoring the callers stack pointer in this functions epilog. This is
4070 // done because by tail calling the called function might overwrite the value
4071 // in this function's (MF) stack pointer stack slot 0(SP).
4072 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4073 CallConv == CallingConv::Fast)
4074 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4076 unsigned nAltivecParamsAtEnd = 0;
4078 // Count how many bytes are to be pushed on the stack, including the linkage
4079 // area, and parameter passing area. We start with 24/48 bytes, which is
4080 // prereserved space for [SP][CR][LR][3 x unused].
4082 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4084 nAltivecParamsAtEnd);
4086 // Calculate by how many bytes the stack has to be adjusted in case of tail
4087 // call optimization.
4088 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4090 // To protect arguments on the stack from being clobbered in a tail call,
4091 // force all the loads to happen before doing any other lowering.
4093 Chain = DAG.getStackArgumentTokenFactor(Chain);
4095 // Adjust the stack pointer for the new arguments...
4096 // These operations are automatically eliminated by the prolog/epilog pass
4097 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4098 SDValue CallSeqStart = Chain;
4100 // Load the return address and frame pointer so it can be move somewhere else
4103 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4106 // Set up a copy of the stack pointer for use loading and storing any
4107 // arguments that may not fit in the registers available for argument
4111 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4113 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4115 // Figure out which arguments are going to go in registers, and which in
4116 // memory. Also, if this is a vararg function, floating point operations
4117 // must be stored to our stack, and loaded into integer regs as well, if
4118 // any integer regs are available for argument passing.
4119 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4120 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4122 static const uint16_t GPR_32[] = { // 32-bit registers.
4123 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4124 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4126 static const uint16_t GPR_64[] = { // 64-bit registers.
4127 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4128 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4130 static const uint16_t *FPR = GetFPR();
4132 static const uint16_t VR[] = {
4133 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4134 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4136 const unsigned NumGPRs = array_lengthof(GPR_32);
4137 const unsigned NumFPRs = 13;
4138 const unsigned NumVRs = array_lengthof(VR);
4140 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4142 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4143 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4145 SmallVector<SDValue, 8> MemOpChains;
4146 for (unsigned i = 0; i != NumOps; ++i) {
4147 SDValue Arg = OutVals[i];
4148 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4150 // PtrOff will be used to store the current argument to the stack if a
4151 // register cannot be found for it.
4154 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4156 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4158 // On PPC64, promote integers to 64-bit values.
4159 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4160 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4161 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4162 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4165 // FIXME memcpy is used way more than necessary. Correctness first.
4166 // Note: "by value" is code for passing a structure by value, not
4168 if (Flags.isByVal()) {
4169 unsigned Size = Flags.getByValSize();
4170 // Very small objects are passed right-justified. Everything else is
4171 // passed left-justified.
4172 if (Size==1 || Size==2) {
4173 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4174 if (GPR_idx != NumGPRs) {
4175 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4176 MachinePointerInfo(), VT,
4178 MemOpChains.push_back(Load.getValue(1));
4179 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4181 ArgOffset += PtrByteSize;
4183 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4184 PtrOff.getValueType());
4185 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4186 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4189 ArgOffset += PtrByteSize;
4193 // Copy entire object into memory. There are cases where gcc-generated
4194 // code assumes it is there, even if it could be put entirely into
4195 // registers. (This is not what the doc says.)
4196 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4200 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4201 // copy the pieces of the object that fit into registers from the
4202 // parameter save area.
4203 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4204 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4205 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4206 if (GPR_idx != NumGPRs) {
4207 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4208 MachinePointerInfo(),
4209 false, false, false, 0);
4210 MemOpChains.push_back(Load.getValue(1));
4211 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4212 ArgOffset += PtrByteSize;
4214 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4221 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4222 default: llvm_unreachable("Unexpected ValueType for argument!");
4225 if (GPR_idx != NumGPRs) {
4226 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4228 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4229 isPPC64, isTailCall, false, MemOpChains,
4230 TailCallArguments, dl);
4232 ArgOffset += PtrByteSize;
4236 if (FPR_idx != NumFPRs) {
4237 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4240 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4241 MachinePointerInfo(), false, false, 0);
4242 MemOpChains.push_back(Store);
4244 // Float varargs are always shadowed in available integer registers
4245 if (GPR_idx != NumGPRs) {
4246 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4247 MachinePointerInfo(), false, false,
4249 MemOpChains.push_back(Load.getValue(1));
4250 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4252 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4253 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4254 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4255 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4256 MachinePointerInfo(),
4257 false, false, false, 0);
4258 MemOpChains.push_back(Load.getValue(1));
4259 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4262 // If we have any FPRs remaining, we may also have GPRs remaining.
4263 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4265 if (GPR_idx != NumGPRs)
4267 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4268 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4272 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4273 isPPC64, isTailCall, false, MemOpChains,
4274 TailCallArguments, dl);
4278 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4285 // These go aligned on the stack, or in the corresponding R registers
4286 // when within range. The Darwin PPC ABI doc claims they also go in
4287 // V registers; in fact gcc does this only for arguments that are
4288 // prototyped, not for those that match the ... We do it for all
4289 // arguments, seems to work.
4290 while (ArgOffset % 16 !=0) {
4291 ArgOffset += PtrByteSize;
4292 if (GPR_idx != NumGPRs)
4295 // We could elide this store in the case where the object fits
4296 // entirely in R registers. Maybe later.
4297 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4298 DAG.getConstant(ArgOffset, PtrVT));
4299 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4300 MachinePointerInfo(), false, false, 0);
4301 MemOpChains.push_back(Store);
4302 if (VR_idx != NumVRs) {
4303 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4304 MachinePointerInfo(),
4305 false, false, false, 0);
4306 MemOpChains.push_back(Load.getValue(1));
4307 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4310 for (unsigned i=0; i<16; i+=PtrByteSize) {
4311 if (GPR_idx == NumGPRs)
4313 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4314 DAG.getConstant(i, PtrVT));
4315 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4316 false, false, false, 0);
4317 MemOpChains.push_back(Load.getValue(1));
4318 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4323 // Non-varargs Altivec params generally go in registers, but have
4324 // stack space allocated at the end.
4325 if (VR_idx != NumVRs) {
4326 // Doesn't have GPR space allocated.
4327 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4328 } else if (nAltivecParamsAtEnd==0) {
4329 // We are emitting Altivec params in order.
4330 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4331 isPPC64, isTailCall, true, MemOpChains,
4332 TailCallArguments, dl);
4338 // If all Altivec parameters fit in registers, as they usually do,
4339 // they get stack space following the non-Altivec parameters. We
4340 // don't track this here because nobody below needs it.
4341 // If there are more Altivec parameters than fit in registers emit
4343 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4345 // Offset is aligned; skip 1st 12 params which go in V registers.
4346 ArgOffset = ((ArgOffset+15)/16)*16;
4348 for (unsigned i = 0; i != NumOps; ++i) {
4349 SDValue Arg = OutVals[i];
4350 EVT ArgType = Outs[i].VT;
4351 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4352 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4355 // We are emitting Altivec params in order.
4356 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4357 isPPC64, isTailCall, true, MemOpChains,
4358 TailCallArguments, dl);
4365 if (!MemOpChains.empty())
4366 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4367 &MemOpChains[0], MemOpChains.size());
4369 // On Darwin, R12 must contain the address of an indirect callee. This does
4370 // not mean the MTCTR instruction must use R12; it's easier to model this as
4371 // an extra parameter, so do that.
4373 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4374 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4375 !isBLACompatibleAddress(Callee, DAG))
4376 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4377 PPC::R12), Callee));
4379 // Build a sequence of copy-to-reg nodes chained together with token chain
4380 // and flag operands which copy the outgoing args into the appropriate regs.
4382 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4383 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4384 RegsToPass[i].second, InFlag);
4385 InFlag = Chain.getValue(1);
4389 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4390 FPOp, true, TailCallArguments);
4392 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4393 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4398 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4399 MachineFunction &MF, bool isVarArg,
4400 const SmallVectorImpl<ISD::OutputArg> &Outs,
4401 LLVMContext &Context) const {
4402 SmallVector<CCValAssign, 16> RVLocs;
4403 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4405 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4409 PPCTargetLowering::LowerReturn(SDValue Chain,
4410 CallingConv::ID CallConv, bool isVarArg,
4411 const SmallVectorImpl<ISD::OutputArg> &Outs,
4412 const SmallVectorImpl<SDValue> &OutVals,
4413 DebugLoc dl, SelectionDAG &DAG) const {
4415 SmallVector<CCValAssign, 16> RVLocs;
4416 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4417 getTargetMachine(), RVLocs, *DAG.getContext());
4418 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4420 // If this is the first return lowered for this function, add the regs to the
4421 // liveout set for the function.
4422 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
4423 for (unsigned i = 0; i != RVLocs.size(); ++i)
4424 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
4429 // Copy the result values into the output registers.
4430 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4431 CCValAssign &VA = RVLocs[i];
4432 assert(VA.isRegLoc() && "Can only return in registers!");
4434 SDValue Arg = OutVals[i];
4436 switch (VA.getLocInfo()) {
4437 default: llvm_unreachable("Unknown loc info!");
4438 case CCValAssign::Full: break;
4439 case CCValAssign::AExt:
4440 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4442 case CCValAssign::ZExt:
4443 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4445 case CCValAssign::SExt:
4446 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4450 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4451 Flag = Chain.getValue(1);
4455 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
4457 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, Chain);
4460 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4461 const PPCSubtarget &Subtarget) const {
4462 // When we pop the dynamic allocation we need to restore the SP link.
4463 DebugLoc dl = Op.getDebugLoc();
4465 // Get the corect type for pointers.
4466 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4468 // Construct the stack pointer operand.
4469 bool isPPC64 = Subtarget.isPPC64();
4470 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4471 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4473 // Get the operands for the STACKRESTORE.
4474 SDValue Chain = Op.getOperand(0);
4475 SDValue SaveSP = Op.getOperand(1);
4477 // Load the old link SP.
4478 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4479 MachinePointerInfo(),
4480 false, false, false, 0);
4482 // Restore the stack pointer.
4483 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4485 // Store the old link SP.
4486 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4493 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4494 MachineFunction &MF = DAG.getMachineFunction();
4495 bool isPPC64 = PPCSubTarget.isPPC64();
4496 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4497 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4499 // Get current frame pointer save index. The users of this index will be
4500 // primarily DYNALLOC instructions.
4501 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4502 int RASI = FI->getReturnAddrSaveIndex();
4504 // If the frame pointer save index hasn't been defined yet.
4506 // Find out what the fix offset of the frame pointer save area.
4507 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4508 // Allocate the frame index for frame pointer save area.
4509 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4511 FI->setReturnAddrSaveIndex(RASI);
4513 return DAG.getFrameIndex(RASI, PtrVT);
4517 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4518 MachineFunction &MF = DAG.getMachineFunction();
4519 bool isPPC64 = PPCSubTarget.isPPC64();
4520 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4521 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4523 // Get current frame pointer save index. The users of this index will be
4524 // primarily DYNALLOC instructions.
4525 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4526 int FPSI = FI->getFramePointerSaveIndex();
4528 // If the frame pointer save index hasn't been defined yet.
4530 // Find out what the fix offset of the frame pointer save area.
4531 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4534 // Allocate the frame index for frame pointer save area.
4535 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4537 FI->setFramePointerSaveIndex(FPSI);
4539 return DAG.getFrameIndex(FPSI, PtrVT);
4542 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4544 const PPCSubtarget &Subtarget) const {
4546 SDValue Chain = Op.getOperand(0);
4547 SDValue Size = Op.getOperand(1);
4548 DebugLoc dl = Op.getDebugLoc();
4550 // Get the corect type for pointers.
4551 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4553 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4554 DAG.getConstant(0, PtrVT), Size);
4555 // Construct a node for the frame pointer save index.
4556 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4557 // Build a DYNALLOC node.
4558 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4559 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4560 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4563 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4565 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4566 // Not FP? Not a fsel.
4567 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4568 !Op.getOperand(2).getValueType().isFloatingPoint())
4571 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4573 // Cannot handle SETEQ/SETNE.
4574 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4576 EVT ResVT = Op.getValueType();
4577 EVT CmpVT = Op.getOperand(0).getValueType();
4578 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4579 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4580 DebugLoc dl = Op.getDebugLoc();
4582 // If the RHS of the comparison is a 0.0, we don't need to do the
4583 // subtraction at all.
4584 if (isFloatingPointZero(RHS))
4586 default: break; // SETUO etc aren't handled by fsel.
4589 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4592 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4593 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4594 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4597 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4600 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4601 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4602 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4603 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4608 default: break; // SETUO etc aren't handled by fsel.
4611 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4612 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4613 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4614 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4617 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4618 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4619 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4620 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4623 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4624 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4625 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4626 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4629 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4630 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4631 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4632 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4637 // FIXME: Split this code up when LegalizeDAGTypes lands.
4638 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4639 DebugLoc dl) const {
4640 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4641 SDValue Src = Op.getOperand(0);
4642 if (Src.getValueType() == MVT::f32)
4643 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4646 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4647 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4649 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4654 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4658 // Convert the FP value to an int value through memory.
4659 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4661 // Emit a store to the stack slot.
4662 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4663 MachinePointerInfo(), false, false, 0);
4665 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4667 if (Op.getValueType() == MVT::i32)
4668 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4669 DAG.getConstant(4, FIPtr.getValueType()));
4670 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4671 false, false, false, 0);
4674 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4675 SelectionDAG &DAG) const {
4676 DebugLoc dl = Op.getDebugLoc();
4677 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4678 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4681 if (Op.getOperand(0).getValueType() == MVT::i64) {
4682 SDValue SINT = Op.getOperand(0);
4683 // When converting to single-precision, we actually need to convert
4684 // to double-precision first and then round to single-precision.
4685 // To avoid double-rounding effects during that operation, we have
4686 // to prepare the input operand. Bits that might be truncated when
4687 // converting to double-precision are replaced by a bit that won't
4688 // be lost at this stage, but is below the single-precision rounding
4691 // However, if -enable-unsafe-fp-math is in effect, accept double
4692 // rounding to avoid the extra overhead.
4693 if (Op.getValueType() == MVT::f32 &&
4694 !DAG.getTarget().Options.UnsafeFPMath) {
4696 // Twiddle input to make sure the low 11 bits are zero. (If this
4697 // is the case, we are guaranteed the value will fit into the 53 bit
4698 // mantissa of an IEEE double-precision value without rounding.)
4699 // If any of those low 11 bits were not zero originally, make sure
4700 // bit 12 (value 2048) is set instead, so that the final rounding
4701 // to single-precision gets the correct result.
4702 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4703 SINT, DAG.getConstant(2047, MVT::i64));
4704 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4705 Round, DAG.getConstant(2047, MVT::i64));
4706 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4707 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4708 Round, DAG.getConstant(-2048, MVT::i64));
4710 // However, we cannot use that value unconditionally: if the magnitude
4711 // of the input value is small, the bit-twiddling we did above might
4712 // end up visibly changing the output. Fortunately, in that case, we
4713 // don't need to twiddle bits since the original input will convert
4714 // exactly to double-precision floating-point already. Therefore,
4715 // construct a conditional to use the original value if the top 11
4716 // bits are all sign-bit copies, and use the rounded value computed
4718 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4719 SINT, DAG.getConstant(53, MVT::i32));
4720 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4721 Cond, DAG.getConstant(1, MVT::i64));
4722 Cond = DAG.getSetCC(dl, MVT::i32,
4723 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4725 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4727 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4728 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4729 if (Op.getValueType() == MVT::f32)
4730 FP = DAG.getNode(ISD::FP_ROUND, dl,
4731 MVT::f32, FP, DAG.getIntPtrConstant(0));
4735 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4736 "Unhandled SINT_TO_FP type in custom expander!");
4737 // Since we only generate this in 64-bit mode, we can take advantage of
4738 // 64-bit registers. In particular, sign extend the input value into the
4739 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4740 // then lfd it and fcfid it.
4741 MachineFunction &MF = DAG.getMachineFunction();
4742 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4743 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4744 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4745 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4747 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4750 // STD the extended value into the stack slot.
4751 MachineMemOperand *MMO =
4752 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4753 MachineMemOperand::MOStore, 8, 8);
4754 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4756 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4757 Ops, 4, MVT::i64, MMO);
4758 // Load the value as a double.
4759 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4760 false, false, false, 0);
4762 // FCFID it and return it.
4763 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4764 if (Op.getValueType() == MVT::f32)
4765 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4769 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4770 SelectionDAG &DAG) const {
4771 DebugLoc dl = Op.getDebugLoc();
4773 The rounding mode is in bits 30:31 of FPSR, and has the following
4780 FLT_ROUNDS, on the other hand, expects the following:
4787 To perform the conversion, we do:
4788 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4791 MachineFunction &MF = DAG.getMachineFunction();
4792 EVT VT = Op.getValueType();
4793 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4794 std::vector<EVT> NodeTys;
4795 SDValue MFFSreg, InFlag;
4797 // Save FP Control Word to register
4798 NodeTys.push_back(MVT::f64); // return register
4799 NodeTys.push_back(MVT::Glue); // unused in this context
4800 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4802 // Save FP register to stack slot
4803 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4804 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4805 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4806 StackSlot, MachinePointerInfo(), false, false,0);
4808 // Load FP Control Word from low 32 bits of stack slot.
4809 SDValue Four = DAG.getConstant(4, PtrVT);
4810 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4811 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4812 false, false, false, 0);
4814 // Transform as necessary
4816 DAG.getNode(ISD::AND, dl, MVT::i32,
4817 CWD, DAG.getConstant(3, MVT::i32));
4819 DAG.getNode(ISD::SRL, dl, MVT::i32,
4820 DAG.getNode(ISD::AND, dl, MVT::i32,
4821 DAG.getNode(ISD::XOR, dl, MVT::i32,
4822 CWD, DAG.getConstant(3, MVT::i32)),
4823 DAG.getConstant(3, MVT::i32)),
4824 DAG.getConstant(1, MVT::i32));
4827 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4829 return DAG.getNode((VT.getSizeInBits() < 16 ?
4830 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4833 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4834 EVT VT = Op.getValueType();
4835 unsigned BitWidth = VT.getSizeInBits();
4836 DebugLoc dl = Op.getDebugLoc();
4837 assert(Op.getNumOperands() == 3 &&
4838 VT == Op.getOperand(1).getValueType() &&
4841 // Expand into a bunch of logical ops. Note that these ops
4842 // depend on the PPC behavior for oversized shift amounts.
4843 SDValue Lo = Op.getOperand(0);
4844 SDValue Hi = Op.getOperand(1);
4845 SDValue Amt = Op.getOperand(2);
4846 EVT AmtVT = Amt.getValueType();
4848 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4849 DAG.getConstant(BitWidth, AmtVT), Amt);
4850 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4851 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4852 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4853 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4854 DAG.getConstant(-BitWidth, AmtVT));
4855 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4856 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4857 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4858 SDValue OutOps[] = { OutLo, OutHi };
4859 return DAG.getMergeValues(OutOps, 2, dl);
4862 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4863 EVT VT = Op.getValueType();
4864 DebugLoc dl = Op.getDebugLoc();
4865 unsigned BitWidth = VT.getSizeInBits();
4866 assert(Op.getNumOperands() == 3 &&
4867 VT == Op.getOperand(1).getValueType() &&
4870 // Expand into a bunch of logical ops. Note that these ops
4871 // depend on the PPC behavior for oversized shift amounts.
4872 SDValue Lo = Op.getOperand(0);
4873 SDValue Hi = Op.getOperand(1);
4874 SDValue Amt = Op.getOperand(2);
4875 EVT AmtVT = Amt.getValueType();
4877 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4878 DAG.getConstant(BitWidth, AmtVT), Amt);
4879 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4880 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4881 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4882 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4883 DAG.getConstant(-BitWidth, AmtVT));
4884 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4885 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4886 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4887 SDValue OutOps[] = { OutLo, OutHi };
4888 return DAG.getMergeValues(OutOps, 2, dl);
4891 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4892 DebugLoc dl = Op.getDebugLoc();
4893 EVT VT = Op.getValueType();
4894 unsigned BitWidth = VT.getSizeInBits();
4895 assert(Op.getNumOperands() == 3 &&
4896 VT == Op.getOperand(1).getValueType() &&
4899 // Expand into a bunch of logical ops, followed by a select_cc.
4900 SDValue Lo = Op.getOperand(0);
4901 SDValue Hi = Op.getOperand(1);
4902 SDValue Amt = Op.getOperand(2);
4903 EVT AmtVT = Amt.getValueType();
4905 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4906 DAG.getConstant(BitWidth, AmtVT), Amt);
4907 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4908 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4909 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4910 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4911 DAG.getConstant(-BitWidth, AmtVT));
4912 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4913 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4914 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4915 Tmp4, Tmp6, ISD::SETLE);
4916 SDValue OutOps[] = { OutLo, OutHi };
4917 return DAG.getMergeValues(OutOps, 2, dl);
4920 //===----------------------------------------------------------------------===//
4921 // Vector related lowering.
4924 /// BuildSplatI - Build a canonical splati of Val with an element size of
4925 /// SplatSize. Cast the result to VT.
4926 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4927 SelectionDAG &DAG, DebugLoc dl) {
4928 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4930 static const EVT VTys[] = { // canonical VT to use for each size.
4931 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4934 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4936 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4940 EVT CanonicalVT = VTys[SplatSize-1];
4942 // Build a canonical splat for this value.
4943 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4944 SmallVector<SDValue, 8> Ops;
4945 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4946 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4947 &Ops[0], Ops.size());
4948 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
4951 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
4952 /// specified intrinsic ID.
4953 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
4954 SelectionDAG &DAG, DebugLoc dl,
4955 EVT DestVT = MVT::Other) {
4956 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
4957 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4958 DAG.getConstant(IID, MVT::i32), LHS, RHS);
4961 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
4962 /// specified intrinsic ID.
4963 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
4964 SDValue Op2, SelectionDAG &DAG,
4965 DebugLoc dl, EVT DestVT = MVT::Other) {
4966 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
4967 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4968 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
4972 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
4973 /// amount. The result has the specified value type.
4974 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
4975 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
4976 // Force LHS/RHS to be the right type.
4977 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
4978 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
4981 for (unsigned i = 0; i != 16; ++i)
4983 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
4984 return DAG.getNode(ISD::BITCAST, dl, VT, T);
4987 // If this is a case we can't handle, return null and let the default
4988 // expansion code take care of it. If we CAN select this case, and if it
4989 // selects to a single instruction, return Op. Otherwise, if we can codegen
4990 // this case more efficiently than a constant pool load, lower it to the
4991 // sequence of ops that should be used.
4992 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
4993 SelectionDAG &DAG) const {
4994 DebugLoc dl = Op.getDebugLoc();
4995 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
4996 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
4998 // Check if this is a splat of a constant value.
4999 APInt APSplatBits, APSplatUndef;
5000 unsigned SplatBitSize;
5002 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5003 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5006 unsigned SplatBits = APSplatBits.getZExtValue();
5007 unsigned SplatUndef = APSplatUndef.getZExtValue();
5008 unsigned SplatSize = SplatBitSize / 8;
5010 // First, handle single instruction cases.
5013 if (SplatBits == 0) {
5014 // Canonicalize all zero vectors to be v4i32.
5015 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5016 SDValue Z = DAG.getConstant(0, MVT::i32);
5017 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5018 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5023 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5024 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5026 if (SextVal >= -16 && SextVal <= 15)
5027 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5030 // Two instruction sequences.
5032 // If this value is in the range [-32,30] and is even, use:
5033 // tmp = VSPLTI[bhw], result = add tmp, tmp
5034 if (SextVal >= -32 && SextVal <= 30 && (SextVal & 1) == 0) {
5035 SDValue Res = BuildSplatI(SextVal >> 1, SplatSize, MVT::Other, DAG, dl);
5036 Res = DAG.getNode(ISD::ADD, dl, Res.getValueType(), Res, Res);
5037 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5040 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5041 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5043 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5044 // Make -1 and vspltisw -1:
5045 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5047 // Make the VSLW intrinsic, computing 0x8000_0000.
5048 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5051 // xor by OnesV to invert it.
5052 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5053 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5056 // Check to see if this is a wide variety of vsplti*, binop self cases.
5057 static const signed char SplatCsts[] = {
5058 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5059 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5062 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5063 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5064 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5065 int i = SplatCsts[idx];
5067 // Figure out what shift amount will be used by altivec if shifted by i in
5069 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5071 // vsplti + shl self.
5072 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5073 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5074 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5075 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5076 Intrinsic::ppc_altivec_vslw
5078 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5079 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5082 // vsplti + srl self.
5083 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5084 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5085 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5086 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5087 Intrinsic::ppc_altivec_vsrw
5089 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5090 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5093 // vsplti + sra self.
5094 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5095 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5096 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5097 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5098 Intrinsic::ppc_altivec_vsraw
5100 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5101 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5104 // vsplti + rol self.
5105 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5106 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5107 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5108 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5109 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5110 Intrinsic::ppc_altivec_vrlw
5112 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5113 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5116 // t = vsplti c, result = vsldoi t, t, 1
5117 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5118 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5119 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5121 // t = vsplti c, result = vsldoi t, t, 2
5122 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5123 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5124 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5126 // t = vsplti c, result = vsldoi t, t, 3
5127 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5128 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5129 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5133 // Three instruction sequences.
5135 // Odd, in range [17,31]: (vsplti C)-(vsplti -16).
5136 if (SextVal >= 0 && SextVal <= 31) {
5137 SDValue LHS = BuildSplatI(SextVal-16, SplatSize, MVT::Other, DAG, dl);
5138 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5139 LHS = DAG.getNode(ISD::SUB, dl, LHS.getValueType(), LHS, RHS);
5140 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5142 // Odd, in range [-31,-17]: (vsplti C)+(vsplti -16).
5143 if (SextVal >= -31 && SextVal <= 0) {
5144 SDValue LHS = BuildSplatI(SextVal+16, SplatSize, MVT::Other, DAG, dl);
5145 SDValue RHS = BuildSplatI(-16, SplatSize, MVT::Other, DAG, dl);
5146 LHS = DAG.getNode(ISD::ADD, dl, LHS.getValueType(), LHS, RHS);
5147 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), LHS);
5153 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5154 /// the specified operations to build the shuffle.
5155 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5156 SDValue RHS, SelectionDAG &DAG,
5158 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5159 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5160 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5163 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5175 if (OpNum == OP_COPY) {
5176 if (LHSID == (1*9+2)*9+3) return LHS;
5177 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5181 SDValue OpLHS, OpRHS;
5182 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5183 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5187 default: llvm_unreachable("Unknown i32 permute!");
5189 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5190 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5191 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5192 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5195 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5196 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5197 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5198 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5201 for (unsigned i = 0; i != 16; ++i)
5202 ShufIdxs[i] = (i&3)+0;
5205 for (unsigned i = 0; i != 16; ++i)
5206 ShufIdxs[i] = (i&3)+4;
5209 for (unsigned i = 0; i != 16; ++i)
5210 ShufIdxs[i] = (i&3)+8;
5213 for (unsigned i = 0; i != 16; ++i)
5214 ShufIdxs[i] = (i&3)+12;
5217 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5219 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5221 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5223 EVT VT = OpLHS.getValueType();
5224 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5225 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5226 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5227 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5230 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5231 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5232 /// return the code it can be lowered into. Worst case, it can always be
5233 /// lowered into a vperm.
5234 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5235 SelectionDAG &DAG) const {
5236 DebugLoc dl = Op.getDebugLoc();
5237 SDValue V1 = Op.getOperand(0);
5238 SDValue V2 = Op.getOperand(1);
5239 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5240 EVT VT = Op.getValueType();
5242 // Cases that are handled by instructions that take permute immediates
5243 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5244 // selected by the instruction selector.
5245 if (V2.getOpcode() == ISD::UNDEF) {
5246 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5247 PPC::isSplatShuffleMask(SVOp, 2) ||
5248 PPC::isSplatShuffleMask(SVOp, 4) ||
5249 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5250 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5251 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5252 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5253 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5254 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5255 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5256 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5257 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5262 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5263 // and produce a fixed permutation. If any of these match, do not lower to
5265 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5266 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5267 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5268 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5269 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5270 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5271 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5272 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5273 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5276 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5277 // perfect shuffle table to emit an optimal matching sequence.
5278 ArrayRef<int> PermMask = SVOp->getMask();
5280 unsigned PFIndexes[4];
5281 bool isFourElementShuffle = true;
5282 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5283 unsigned EltNo = 8; // Start out undef.
5284 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5285 if (PermMask[i*4+j] < 0)
5286 continue; // Undef, ignore it.
5288 unsigned ByteSource = PermMask[i*4+j];
5289 if ((ByteSource & 3) != j) {
5290 isFourElementShuffle = false;
5295 EltNo = ByteSource/4;
5296 } else if (EltNo != ByteSource/4) {
5297 isFourElementShuffle = false;
5301 PFIndexes[i] = EltNo;
5304 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5305 // perfect shuffle vector to determine if it is cost effective to do this as
5306 // discrete instructions, or whether we should use a vperm.
5307 if (isFourElementShuffle) {
5308 // Compute the index in the perfect shuffle table.
5309 unsigned PFTableIndex =
5310 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5312 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5313 unsigned Cost = (PFEntry >> 30);
5315 // Determining when to avoid vperm is tricky. Many things affect the cost
5316 // of vperm, particularly how many times the perm mask needs to be computed.
5317 // For example, if the perm mask can be hoisted out of a loop or is already
5318 // used (perhaps because there are multiple permutes with the same shuffle
5319 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5320 // the loop requires an extra register.
5322 // As a compromise, we only emit discrete instructions if the shuffle can be
5323 // generated in 3 or fewer operations. When we have loop information
5324 // available, if this block is within a loop, we should avoid using vperm
5325 // for 3-operation perms and use a constant pool load instead.
5327 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5330 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5331 // vector that will get spilled to the constant pool.
5332 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5334 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5335 // that it is in input element units, not in bytes. Convert now.
5336 EVT EltVT = V1.getValueType().getVectorElementType();
5337 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5339 SmallVector<SDValue, 16> ResultMask;
5340 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5341 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5343 for (unsigned j = 0; j != BytesPerElement; ++j)
5344 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5348 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5349 &ResultMask[0], ResultMask.size());
5350 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5353 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5354 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5355 /// information about the intrinsic.
5356 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5358 unsigned IntrinsicID =
5359 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5362 switch (IntrinsicID) {
5363 default: return false;
5364 // Comparison predicates.
5365 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5366 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5367 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5368 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5369 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5370 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5371 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5372 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5373 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5374 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5375 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5376 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5377 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5379 // Normal Comparisons.
5380 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5381 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5382 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5383 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5384 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5385 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5386 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5387 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5388 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5389 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5390 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5391 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5392 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5397 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5398 /// lower, do it, otherwise return null.
5399 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5400 SelectionDAG &DAG) const {
5401 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5402 // opcode number of the comparison.
5403 DebugLoc dl = Op.getDebugLoc();
5406 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5407 return SDValue(); // Don't custom lower most intrinsics.
5409 // If this is a non-dot comparison, make the VCMP node and we are done.
5411 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5412 Op.getOperand(1), Op.getOperand(2),
5413 DAG.getConstant(CompareOpc, MVT::i32));
5414 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5417 // Create the PPCISD altivec 'dot' comparison node.
5419 Op.getOperand(2), // LHS
5420 Op.getOperand(3), // RHS
5421 DAG.getConstant(CompareOpc, MVT::i32)
5423 std::vector<EVT> VTs;
5424 VTs.push_back(Op.getOperand(2).getValueType());
5425 VTs.push_back(MVT::Glue);
5426 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5428 // Now that we have the comparison, emit a copy from the CR to a GPR.
5429 // This is flagged to the above dot comparison.
5430 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5431 DAG.getRegister(PPC::CR6, MVT::i32),
5432 CompNode.getValue(1));
5434 // Unpack the result based on how the target uses it.
5435 unsigned BitNo; // Bit # of CR6.
5436 bool InvertBit; // Invert result?
5437 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5438 default: // Can't happen, don't crash on invalid number though.
5439 case 0: // Return the value of the EQ bit of CR6.
5440 BitNo = 0; InvertBit = false;
5442 case 1: // Return the inverted value of the EQ bit of CR6.
5443 BitNo = 0; InvertBit = true;
5445 case 2: // Return the value of the LT bit of CR6.
5446 BitNo = 2; InvertBit = false;
5448 case 3: // Return the inverted value of the LT bit of CR6.
5449 BitNo = 2; InvertBit = true;
5453 // Shift the bit into the low position.
5454 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5455 DAG.getConstant(8-(3-BitNo), MVT::i32));
5457 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5458 DAG.getConstant(1, MVT::i32));
5460 // If we are supposed to, toggle the bit.
5462 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5463 DAG.getConstant(1, MVT::i32));
5467 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5468 SelectionDAG &DAG) const {
5469 DebugLoc dl = Op.getDebugLoc();
5470 // Create a stack slot that is 16-byte aligned.
5471 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5472 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5473 EVT PtrVT = getPointerTy();
5474 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5476 // Store the input value into Value#0 of the stack slot.
5477 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5478 Op.getOperand(0), FIdx, MachinePointerInfo(),
5481 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5482 false, false, false, 0);
5485 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5486 DebugLoc dl = Op.getDebugLoc();
5487 if (Op.getValueType() == MVT::v4i32) {
5488 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5490 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5491 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5493 SDValue RHSSwap = // = vrlw RHS, 16
5494 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5496 // Shrinkify inputs to v8i16.
5497 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5498 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5499 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5501 // Low parts multiplied together, generating 32-bit results (we ignore the
5503 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5504 LHS, RHS, DAG, dl, MVT::v4i32);
5506 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5507 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5508 // Shift the high parts up 16 bits.
5509 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5511 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5512 } else if (Op.getValueType() == MVT::v8i16) {
5513 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5515 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5517 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5518 LHS, RHS, Zero, DAG, dl);
5519 } else if (Op.getValueType() == MVT::v16i8) {
5520 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5522 // Multiply the even 8-bit parts, producing 16-bit sums.
5523 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5524 LHS, RHS, DAG, dl, MVT::v8i16);
5525 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5527 // Multiply the odd 8-bit parts, producing 16-bit sums.
5528 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5529 LHS, RHS, DAG, dl, MVT::v8i16);
5530 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5532 // Merge the results together.
5534 for (unsigned i = 0; i != 8; ++i) {
5536 Ops[i*2+1] = 2*i+1+16;
5538 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5540 llvm_unreachable("Unknown mul to lower!");
5544 /// LowerOperation - Provide custom lowering hooks for some operations.
5546 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5547 switch (Op.getOpcode()) {
5548 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5549 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5550 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5551 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5552 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5553 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5554 case ISD::SETCC: return LowerSETCC(Op, DAG);
5555 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5556 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5558 return LowerVASTART(Op, DAG, PPCSubTarget);
5561 return LowerVAARG(Op, DAG, PPCSubTarget);
5563 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5564 case ISD::DYNAMIC_STACKALLOC:
5565 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5567 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5568 case ISD::FP_TO_UINT:
5569 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5571 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5572 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5574 // Lower 64-bit shifts.
5575 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5576 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5577 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5579 // Vector-related lowering.
5580 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5581 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5582 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5583 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5584 case ISD::MUL: return LowerMUL(Op, DAG);
5586 // Frame & Return address.
5587 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5588 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5592 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5593 SmallVectorImpl<SDValue>&Results,
5594 SelectionDAG &DAG) const {
5595 const TargetMachine &TM = getTargetMachine();
5596 DebugLoc dl = N->getDebugLoc();
5597 switch (N->getOpcode()) {
5599 llvm_unreachable("Do not know how to custom type legalize this operation!");
5601 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5602 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5605 EVT VT = N->getValueType(0);
5607 if (VT == MVT::i64) {
5608 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5610 Results.push_back(NewNode);
5611 Results.push_back(NewNode.getValue(1));
5615 case ISD::FP_ROUND_INREG: {
5616 assert(N->getValueType(0) == MVT::ppcf128);
5617 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5618 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5619 MVT::f64, N->getOperand(0),
5620 DAG.getIntPtrConstant(0));
5621 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5622 MVT::f64, N->getOperand(0),
5623 DAG.getIntPtrConstant(1));
5625 // This sequence changes FPSCR to do round-to-zero, adds the two halves
5626 // of the long double, and puts FPSCR back the way it was. We do not
5627 // actually model FPSCR.
5628 std::vector<EVT> NodeTys;
5629 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
5631 NodeTys.push_back(MVT::f64); // Return register
5632 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
5633 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5634 MFFSreg = Result.getValue(0);
5635 InFlag = Result.getValue(1);
5638 NodeTys.push_back(MVT::Glue); // Returns a flag
5639 Ops[0] = DAG.getConstant(31, MVT::i32);
5641 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
5642 InFlag = Result.getValue(0);
5645 NodeTys.push_back(MVT::Glue); // Returns a flag
5646 Ops[0] = DAG.getConstant(30, MVT::i32);
5648 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
5649 InFlag = Result.getValue(0);
5652 NodeTys.push_back(MVT::f64); // result of add
5653 NodeTys.push_back(MVT::Glue); // Returns a flag
5657 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
5658 FPreg = Result.getValue(0);
5659 InFlag = Result.getValue(1);
5662 NodeTys.push_back(MVT::f64);
5663 Ops[0] = DAG.getConstant(1, MVT::i32);
5667 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
5668 FPreg = Result.getValue(0);
5670 // We know the low half is about to be thrown away, so just use something
5672 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5676 case ISD::FP_TO_SINT:
5677 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5683 //===----------------------------------------------------------------------===//
5684 // Other Lowering Code
5685 //===----------------------------------------------------------------------===//
5688 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5689 bool is64bit, unsigned BinOpcode) const {
5690 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5691 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5693 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5694 MachineFunction *F = BB->getParent();
5695 MachineFunction::iterator It = BB;
5698 unsigned dest = MI->getOperand(0).getReg();
5699 unsigned ptrA = MI->getOperand(1).getReg();
5700 unsigned ptrB = MI->getOperand(2).getReg();
5701 unsigned incr = MI->getOperand(3).getReg();
5702 DebugLoc dl = MI->getDebugLoc();
5704 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5705 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5706 F->insert(It, loopMBB);
5707 F->insert(It, exitMBB);
5708 exitMBB->splice(exitMBB->begin(), BB,
5709 llvm::next(MachineBasicBlock::iterator(MI)),
5711 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5713 MachineRegisterInfo &RegInfo = F->getRegInfo();
5714 unsigned TmpReg = (!BinOpcode) ? incr :
5715 RegInfo.createVirtualRegister(
5716 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5717 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5721 // fallthrough --> loopMBB
5722 BB->addSuccessor(loopMBB);
5725 // l[wd]arx dest, ptr
5726 // add r0, dest, incr
5727 // st[wd]cx. r0, ptr
5729 // fallthrough --> exitMBB
5731 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5732 .addReg(ptrA).addReg(ptrB);
5734 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5735 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5736 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5737 BuildMI(BB, dl, TII->get(PPC::BCC))
5738 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5739 BB->addSuccessor(loopMBB);
5740 BB->addSuccessor(exitMBB);
5749 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5750 MachineBasicBlock *BB,
5751 bool is8bit, // operation
5752 unsigned BinOpcode) const {
5753 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5754 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5755 // In 64 bit mode we have to use 64 bits for addresses, even though the
5756 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5757 // registers without caring whether they're 32 or 64, but here we're
5758 // doing actual arithmetic on the addresses.
5759 bool is64bit = PPCSubTarget.isPPC64();
5760 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
5762 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5763 MachineFunction *F = BB->getParent();
5764 MachineFunction::iterator It = BB;
5767 unsigned dest = MI->getOperand(0).getReg();
5768 unsigned ptrA = MI->getOperand(1).getReg();
5769 unsigned ptrB = MI->getOperand(2).getReg();
5770 unsigned incr = MI->getOperand(3).getReg();
5771 DebugLoc dl = MI->getDebugLoc();
5773 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5774 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5775 F->insert(It, loopMBB);
5776 F->insert(It, exitMBB);
5777 exitMBB->splice(exitMBB->begin(), BB,
5778 llvm::next(MachineBasicBlock::iterator(MI)),
5780 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5782 MachineRegisterInfo &RegInfo = F->getRegInfo();
5783 const TargetRegisterClass *RC =
5784 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5785 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5786 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5787 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5788 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5789 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5790 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5791 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5792 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5793 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5794 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5795 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5796 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5798 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5802 // fallthrough --> loopMBB
5803 BB->addSuccessor(loopMBB);
5805 // The 4-byte load must be aligned, while a char or short may be
5806 // anywhere in the word. Hence all this nasty bookkeeping code.
5807 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5808 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5809 // xori shift, shift1, 24 [16]
5810 // rlwinm ptr, ptr1, 0, 0, 29
5811 // slw incr2, incr, shift
5812 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5813 // slw mask, mask2, shift
5815 // lwarx tmpDest, ptr
5816 // add tmp, tmpDest, incr2
5817 // andc tmp2, tmpDest, mask
5818 // and tmp3, tmp, mask
5819 // or tmp4, tmp3, tmp2
5822 // fallthrough --> exitMBB
5823 // srw dest, tmpDest, shift
5824 if (ptrA != ZeroReg) {
5825 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5826 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5827 .addReg(ptrA).addReg(ptrB);
5831 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5832 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5833 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5834 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5836 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5837 .addReg(Ptr1Reg).addImm(0).addImm(61);
5839 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5840 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5841 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5842 .addReg(incr).addReg(ShiftReg);
5844 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5846 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5847 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5849 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5850 .addReg(Mask2Reg).addReg(ShiftReg);
5853 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5854 .addReg(ZeroReg).addReg(PtrReg);
5856 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5857 .addReg(Incr2Reg).addReg(TmpDestReg);
5858 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5859 .addReg(TmpDestReg).addReg(MaskReg);
5860 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5861 .addReg(TmpReg).addReg(MaskReg);
5862 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5863 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5864 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5865 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5866 BuildMI(BB, dl, TII->get(PPC::BCC))
5867 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5868 BB->addSuccessor(loopMBB);
5869 BB->addSuccessor(exitMBB);
5874 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5880 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5881 MachineBasicBlock *BB) const {
5882 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5884 // To "insert" these instructions we actually have to insert their
5885 // control-flow patterns.
5886 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5887 MachineFunction::iterator It = BB;
5890 MachineFunction *F = BB->getParent();
5892 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5893 MI->getOpcode() == PPC::SELECT_CC_I8)) {
5894 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
5895 PPC::ISEL8 : PPC::ISEL;
5896 unsigned SelectPred = MI->getOperand(4).getImm();
5897 DebugLoc dl = MI->getDebugLoc();
5899 // The SelectPred is ((BI << 5) | BO) for a BCC
5900 unsigned BO = SelectPred & 0xF;
5901 assert((BO == 12 || BO == 4) && "invalid predicate BO field for isel");
5903 unsigned TrueOpNo, FalseOpNo;
5910 SelectPred = PPC::InvertPredicate((PPC::Predicate)SelectPred);
5913 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
5914 .addReg(MI->getOperand(TrueOpNo).getReg())
5915 .addReg(MI->getOperand(FalseOpNo).getReg())
5916 .addImm(SelectPred).addReg(MI->getOperand(1).getReg());
5917 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
5918 MI->getOpcode() == PPC::SELECT_CC_I8 ||
5919 MI->getOpcode() == PPC::SELECT_CC_F4 ||
5920 MI->getOpcode() == PPC::SELECT_CC_F8 ||
5921 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
5924 // The incoming instruction knows the destination vreg to set, the
5925 // condition code register to branch on, the true/false values to
5926 // select between, and a branch opcode to use.
5931 // cmpTY ccX, r1, r2
5933 // fallthrough --> copy0MBB
5934 MachineBasicBlock *thisMBB = BB;
5935 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
5936 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
5937 unsigned SelectPred = MI->getOperand(4).getImm();
5938 DebugLoc dl = MI->getDebugLoc();
5939 F->insert(It, copy0MBB);
5940 F->insert(It, sinkMBB);
5942 // Transfer the remainder of BB and its successor edges to sinkMBB.
5943 sinkMBB->splice(sinkMBB->begin(), BB,
5944 llvm::next(MachineBasicBlock::iterator(MI)),
5946 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
5948 // Next, add the true and fallthrough blocks as its successors.
5949 BB->addSuccessor(copy0MBB);
5950 BB->addSuccessor(sinkMBB);
5952 BuildMI(BB, dl, TII->get(PPC::BCC))
5953 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
5956 // %FalseValue = ...
5957 // # fallthrough to sinkMBB
5960 // Update machine-CFG edges
5961 BB->addSuccessor(sinkMBB);
5964 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5967 BuildMI(*BB, BB->begin(), dl,
5968 TII->get(PPC::PHI), MI->getOperand(0).getReg())
5969 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
5970 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5972 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
5973 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
5974 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
5975 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
5976 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
5977 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
5978 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
5979 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
5981 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
5982 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
5983 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
5984 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
5985 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
5986 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
5987 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
5988 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
5990 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
5991 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
5992 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
5993 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
5994 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
5995 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
5996 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
5997 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
5999 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6000 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6001 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6002 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6003 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6004 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6005 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6006 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6008 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6009 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6010 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6011 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6012 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6013 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6014 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6015 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6017 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6018 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6019 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6020 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6021 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6022 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6023 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6024 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6026 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6027 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6028 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6029 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6030 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6031 BB = EmitAtomicBinary(MI, BB, false, 0);
6032 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6033 BB = EmitAtomicBinary(MI, BB, true, 0);
6035 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6036 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6037 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6039 unsigned dest = MI->getOperand(0).getReg();
6040 unsigned ptrA = MI->getOperand(1).getReg();
6041 unsigned ptrB = MI->getOperand(2).getReg();
6042 unsigned oldval = MI->getOperand(3).getReg();
6043 unsigned newval = MI->getOperand(4).getReg();
6044 DebugLoc dl = MI->getDebugLoc();
6046 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6047 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6048 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6049 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6050 F->insert(It, loop1MBB);
6051 F->insert(It, loop2MBB);
6052 F->insert(It, midMBB);
6053 F->insert(It, exitMBB);
6054 exitMBB->splice(exitMBB->begin(), BB,
6055 llvm::next(MachineBasicBlock::iterator(MI)),
6057 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6061 // fallthrough --> loopMBB
6062 BB->addSuccessor(loop1MBB);
6065 // l[wd]arx dest, ptr
6066 // cmp[wd] dest, oldval
6069 // st[wd]cx. newval, ptr
6073 // st[wd]cx. dest, ptr
6076 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6077 .addReg(ptrA).addReg(ptrB);
6078 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6079 .addReg(oldval).addReg(dest);
6080 BuildMI(BB, dl, TII->get(PPC::BCC))
6081 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6082 BB->addSuccessor(loop2MBB);
6083 BB->addSuccessor(midMBB);
6086 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6087 .addReg(newval).addReg(ptrA).addReg(ptrB);
6088 BuildMI(BB, dl, TII->get(PPC::BCC))
6089 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6090 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6091 BB->addSuccessor(loop1MBB);
6092 BB->addSuccessor(exitMBB);
6095 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6096 .addReg(dest).addReg(ptrA).addReg(ptrB);
6097 BB->addSuccessor(exitMBB);
6102 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6103 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6104 // We must use 64-bit registers for addresses when targeting 64-bit,
6105 // since we're actually doing arithmetic on them. Other registers
6107 bool is64bit = PPCSubTarget.isPPC64();
6108 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6110 unsigned dest = MI->getOperand(0).getReg();
6111 unsigned ptrA = MI->getOperand(1).getReg();
6112 unsigned ptrB = MI->getOperand(2).getReg();
6113 unsigned oldval = MI->getOperand(3).getReg();
6114 unsigned newval = MI->getOperand(4).getReg();
6115 DebugLoc dl = MI->getDebugLoc();
6117 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6118 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6119 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6120 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6121 F->insert(It, loop1MBB);
6122 F->insert(It, loop2MBB);
6123 F->insert(It, midMBB);
6124 F->insert(It, exitMBB);
6125 exitMBB->splice(exitMBB->begin(), BB,
6126 llvm::next(MachineBasicBlock::iterator(MI)),
6128 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6130 MachineRegisterInfo &RegInfo = F->getRegInfo();
6131 const TargetRegisterClass *RC =
6132 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6133 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6134 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6135 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6136 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6137 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6138 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6139 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6140 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6141 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6142 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6143 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6144 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6145 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6146 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6148 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6149 unsigned ZeroReg = is64bit ? PPC::X0 : PPC::R0;
6152 // fallthrough --> loopMBB
6153 BB->addSuccessor(loop1MBB);
6155 // The 4-byte load must be aligned, while a char or short may be
6156 // anywhere in the word. Hence all this nasty bookkeeping code.
6157 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6158 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6159 // xori shift, shift1, 24 [16]
6160 // rlwinm ptr, ptr1, 0, 0, 29
6161 // slw newval2, newval, shift
6162 // slw oldval2, oldval,shift
6163 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6164 // slw mask, mask2, shift
6165 // and newval3, newval2, mask
6166 // and oldval3, oldval2, mask
6168 // lwarx tmpDest, ptr
6169 // and tmp, tmpDest, mask
6170 // cmpw tmp, oldval3
6173 // andc tmp2, tmpDest, mask
6174 // or tmp4, tmp2, newval3
6179 // stwcx. tmpDest, ptr
6181 // srw dest, tmpDest, shift
6182 if (ptrA != ZeroReg) {
6183 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6184 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6185 .addReg(ptrA).addReg(ptrB);
6189 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6190 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6191 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6192 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6194 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6195 .addReg(Ptr1Reg).addImm(0).addImm(61);
6197 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6198 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6199 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6200 .addReg(newval).addReg(ShiftReg);
6201 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6202 .addReg(oldval).addReg(ShiftReg);
6204 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6206 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6207 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6208 .addReg(Mask3Reg).addImm(65535);
6210 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6211 .addReg(Mask2Reg).addReg(ShiftReg);
6212 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6213 .addReg(NewVal2Reg).addReg(MaskReg);
6214 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6215 .addReg(OldVal2Reg).addReg(MaskReg);
6218 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6219 .addReg(ZeroReg).addReg(PtrReg);
6220 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6221 .addReg(TmpDestReg).addReg(MaskReg);
6222 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6223 .addReg(TmpReg).addReg(OldVal3Reg);
6224 BuildMI(BB, dl, TII->get(PPC::BCC))
6225 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6226 BB->addSuccessor(loop2MBB);
6227 BB->addSuccessor(midMBB);
6230 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6231 .addReg(TmpDestReg).addReg(MaskReg);
6232 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6233 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6234 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6235 .addReg(ZeroReg).addReg(PtrReg);
6236 BuildMI(BB, dl, TII->get(PPC::BCC))
6237 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6238 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6239 BB->addSuccessor(loop1MBB);
6240 BB->addSuccessor(exitMBB);
6243 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6244 .addReg(ZeroReg).addReg(PtrReg);
6245 BB->addSuccessor(exitMBB);
6250 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6253 llvm_unreachable("Unexpected instr type to insert");
6256 MI->eraseFromParent(); // The pseudo instruction is gone now.
6260 //===----------------------------------------------------------------------===//
6261 // Target Optimization Hooks
6262 //===----------------------------------------------------------------------===//
6264 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6265 DAGCombinerInfo &DCI) const {
6266 const TargetMachine &TM = getTargetMachine();
6267 SelectionDAG &DAG = DCI.DAG;
6268 DebugLoc dl = N->getDebugLoc();
6269 switch (N->getOpcode()) {
6272 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6273 if (C->isNullValue()) // 0 << V -> 0.
6274 return N->getOperand(0);
6278 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6279 if (C->isNullValue()) // 0 >>u V -> 0.
6280 return N->getOperand(0);
6284 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6285 if (C->isNullValue() || // 0 >>s V -> 0.
6286 C->isAllOnesValue()) // -1 >>s V -> -1.
6287 return N->getOperand(0);
6291 case ISD::SINT_TO_FP:
6292 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6293 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6294 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6295 // We allow the src/dst to be either f32/f64, but the intermediate
6296 // type must be i64.
6297 if (N->getOperand(0).getValueType() == MVT::i64 &&
6298 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6299 SDValue Val = N->getOperand(0).getOperand(0);
6300 if (Val.getValueType() == MVT::f32) {
6301 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6302 DCI.AddToWorklist(Val.getNode());
6305 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6306 DCI.AddToWorklist(Val.getNode());
6307 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6308 DCI.AddToWorklist(Val.getNode());
6309 if (N->getValueType(0) == MVT::f32) {
6310 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6311 DAG.getIntPtrConstant(0));
6312 DCI.AddToWorklist(Val.getNode());
6315 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6316 // If the intermediate type is i32, we can avoid the load/store here
6323 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6324 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6325 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6326 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6327 N->getOperand(1).getValueType() == MVT::i32 &&
6328 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6329 SDValue Val = N->getOperand(1).getOperand(0);
6330 if (Val.getValueType() == MVT::f32) {
6331 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6332 DCI.AddToWorklist(Val.getNode());
6334 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6335 DCI.AddToWorklist(Val.getNode());
6337 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6338 N->getOperand(2), N->getOperand(3));
6339 DCI.AddToWorklist(Val.getNode());
6343 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6344 if (cast<StoreSDNode>(N)->isUnindexed() &&
6345 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6346 N->getOperand(1).getNode()->hasOneUse() &&
6347 (N->getOperand(1).getValueType() == MVT::i32 ||
6348 N->getOperand(1).getValueType() == MVT::i16)) {
6349 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6350 // Do an any-extend to 32-bits if this is a half-word input.
6351 if (BSwapOp.getValueType() == MVT::i16)
6352 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6355 N->getOperand(0), BSwapOp, N->getOperand(2),
6356 DAG.getValueType(N->getOperand(1).getValueType())
6359 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6360 Ops, array_lengthof(Ops),
6361 cast<StoreSDNode>(N)->getMemoryVT(),
6362 cast<StoreSDNode>(N)->getMemOperand());
6366 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6367 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6368 N->getOperand(0).hasOneUse() &&
6369 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6370 SDValue Load = N->getOperand(0);
6371 LoadSDNode *LD = cast<LoadSDNode>(Load);
6372 // Create the byte-swapping load.
6374 LD->getChain(), // Chain
6375 LD->getBasePtr(), // Ptr
6376 DAG.getValueType(N->getValueType(0)) // VT
6379 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6380 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6381 LD->getMemoryVT(), LD->getMemOperand());
6383 // If this is an i16 load, insert the truncate.
6384 SDValue ResVal = BSLoad;
6385 if (N->getValueType(0) == MVT::i16)
6386 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6388 // First, combine the bswap away. This makes the value produced by the
6390 DCI.CombineTo(N, ResVal);
6392 // Next, combine the load away, we give it a bogus result value but a real
6393 // chain result. The result value is dead because the bswap is dead.
6394 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6396 // Return N so it doesn't get rechecked!
6397 return SDValue(N, 0);
6401 case PPCISD::VCMP: {
6402 // If a VCMPo node already exists with exactly the same operands as this
6403 // node, use its result instead of this node (VCMPo computes both a CR6 and
6404 // a normal output).
6406 if (!N->getOperand(0).hasOneUse() &&
6407 !N->getOperand(1).hasOneUse() &&
6408 !N->getOperand(2).hasOneUse()) {
6410 // Scan all of the users of the LHS, looking for VCMPo's that match.
6411 SDNode *VCMPoNode = 0;
6413 SDNode *LHSN = N->getOperand(0).getNode();
6414 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6416 if (UI->getOpcode() == PPCISD::VCMPo &&
6417 UI->getOperand(1) == N->getOperand(1) &&
6418 UI->getOperand(2) == N->getOperand(2) &&
6419 UI->getOperand(0) == N->getOperand(0)) {
6424 // If there is no VCMPo node, or if the flag value has a single use, don't
6426 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6429 // Look at the (necessarily single) use of the flag value. If it has a
6430 // chain, this transformation is more complex. Note that multiple things
6431 // could use the value result, which we should ignore.
6432 SDNode *FlagUser = 0;
6433 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6434 FlagUser == 0; ++UI) {
6435 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6437 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6438 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6445 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6446 // give up for right now.
6447 if (FlagUser->getOpcode() == PPCISD::MFCR)
6448 return SDValue(VCMPoNode, 0);
6453 // If this is a branch on an altivec predicate comparison, lower this so
6454 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6455 // lowering is done pre-legalize, because the legalizer lowers the predicate
6456 // compare down to code that is difficult to reassemble.
6457 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6458 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6462 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6463 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6464 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6465 assert(isDot && "Can't compare against a vector result!");
6467 // If this is a comparison against something other than 0/1, then we know
6468 // that the condition is never/always true.
6469 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6470 if (Val != 0 && Val != 1) {
6471 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6472 return N->getOperand(0);
6473 // Always !=, turn it into an unconditional branch.
6474 return DAG.getNode(ISD::BR, dl, MVT::Other,
6475 N->getOperand(0), N->getOperand(4));
6478 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6480 // Create the PPCISD altivec 'dot' comparison node.
6481 std::vector<EVT> VTs;
6483 LHS.getOperand(2), // LHS of compare
6484 LHS.getOperand(3), // RHS of compare
6485 DAG.getConstant(CompareOpc, MVT::i32)
6487 VTs.push_back(LHS.getOperand(2).getValueType());
6488 VTs.push_back(MVT::Glue);
6489 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6491 // Unpack the result based on how the target uses it.
6492 PPC::Predicate CompOpc;
6493 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6494 default: // Can't happen, don't crash on invalid number though.
6495 case 0: // Branch on the value of the EQ bit of CR6.
6496 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6498 case 1: // Branch on the inverted value of the EQ bit of CR6.
6499 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6501 case 2: // Branch on the value of the LT bit of CR6.
6502 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6504 case 3: // Branch on the inverted value of the LT bit of CR6.
6505 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6509 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6510 DAG.getConstant(CompOpc, MVT::i32),
6511 DAG.getRegister(PPC::CR6, MVT::i32),
6512 N->getOperand(4), CompNode.getValue(1));
6521 //===----------------------------------------------------------------------===//
6522 // Inline Assembly Support
6523 //===----------------------------------------------------------------------===//
6525 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6528 const SelectionDAG &DAG,
6529 unsigned Depth) const {
6530 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6531 switch (Op.getOpcode()) {
6533 case PPCISD::LBRX: {
6534 // lhbrx is known to have the top bits cleared out.
6535 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6536 KnownZero = 0xFFFF0000;
6539 case ISD::INTRINSIC_WO_CHAIN: {
6540 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6542 case Intrinsic::ppc_altivec_vcmpbfp_p:
6543 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6544 case Intrinsic::ppc_altivec_vcmpequb_p:
6545 case Intrinsic::ppc_altivec_vcmpequh_p:
6546 case Intrinsic::ppc_altivec_vcmpequw_p:
6547 case Intrinsic::ppc_altivec_vcmpgefp_p:
6548 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6549 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6550 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6551 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6552 case Intrinsic::ppc_altivec_vcmpgtub_p:
6553 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6554 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6555 KnownZero = ~1U; // All bits but the low one are known to be zero.
6563 /// getConstraintType - Given a constraint, return the type of
6564 /// constraint it is for this target.
6565 PPCTargetLowering::ConstraintType
6566 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6567 if (Constraint.size() == 1) {
6568 switch (Constraint[0]) {
6575 return C_RegisterClass;
6577 // FIXME: While Z does indicate a memory constraint, it specifically
6578 // indicates an r+r address (used in conjunction with the 'y' modifier
6579 // in the replacement string). Currently, we're forcing the base
6580 // register to be r0 in the asm printer (which is interpreted as zero)
6581 // and forming the complete address in the second register. This is
6586 return TargetLowering::getConstraintType(Constraint);
6589 /// Examine constraint type and operand type and determine a weight value.
6590 /// This object must already have been set up with the operand type
6591 /// and the current alternative constraint selected.
6592 TargetLowering::ConstraintWeight
6593 PPCTargetLowering::getSingleConstraintMatchWeight(
6594 AsmOperandInfo &info, const char *constraint) const {
6595 ConstraintWeight weight = CW_Invalid;
6596 Value *CallOperandVal = info.CallOperandVal;
6597 // If we don't have a value, we can't do a match,
6598 // but allow it at the lowest weight.
6599 if (CallOperandVal == NULL)
6601 Type *type = CallOperandVal->getType();
6602 // Look at the constraint type.
6603 switch (*constraint) {
6605 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6608 if (type->isIntegerTy())
6609 weight = CW_Register;
6612 if (type->isFloatTy())
6613 weight = CW_Register;
6616 if (type->isDoubleTy())
6617 weight = CW_Register;
6620 if (type->isVectorTy())
6621 weight = CW_Register;
6624 weight = CW_Register;
6633 std::pair<unsigned, const TargetRegisterClass*>
6634 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6636 if (Constraint.size() == 1) {
6637 // GCC RS6000 Constraint Letters
6638 switch (Constraint[0]) {
6641 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6642 return std::make_pair(0U, &PPC::G8RCRegClass);
6643 return std::make_pair(0U, &PPC::GPRCRegClass);
6645 if (VT == MVT::f32 || VT == MVT::i32)
6646 return std::make_pair(0U, &PPC::F4RCRegClass);
6647 if (VT == MVT::f64 || VT == MVT::i64)
6648 return std::make_pair(0U, &PPC::F8RCRegClass);
6651 return std::make_pair(0U, &PPC::VRRCRegClass);
6653 return std::make_pair(0U, &PPC::CRRCRegClass);
6657 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6661 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6662 /// vector. If it is invalid, don't add anything to Ops.
6663 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6664 std::string &Constraint,
6665 std::vector<SDValue>&Ops,
6666 SelectionDAG &DAG) const {
6667 SDValue Result(0,0);
6669 // Only support length 1 constraints.
6670 if (Constraint.length() > 1) return;
6672 char Letter = Constraint[0];
6683 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6684 if (!CST) return; // Must be an immediate to match.
6685 unsigned Value = CST->getZExtValue();
6687 default: llvm_unreachable("Unknown constraint letter!");
6688 case 'I': // "I" is a signed 16-bit constant.
6689 if ((short)Value == (int)Value)
6690 Result = DAG.getTargetConstant(Value, Op.getValueType());
6692 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6693 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6694 if ((short)Value == 0)
6695 Result = DAG.getTargetConstant(Value, Op.getValueType());
6697 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6698 if ((Value >> 16) == 0)
6699 Result = DAG.getTargetConstant(Value, Op.getValueType());
6701 case 'M': // "M" is a constant that is greater than 31.
6703 Result = DAG.getTargetConstant(Value, Op.getValueType());
6705 case 'N': // "N" is a positive constant that is an exact power of two.
6706 if ((int)Value > 0 && isPowerOf2_32(Value))
6707 Result = DAG.getTargetConstant(Value, Op.getValueType());
6709 case 'O': // "O" is the constant zero.
6711 Result = DAG.getTargetConstant(Value, Op.getValueType());
6713 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6714 if ((short)-Value == (int)-Value)
6715 Result = DAG.getTargetConstant(Value, Op.getValueType());
6722 if (Result.getNode()) {
6723 Ops.push_back(Result);
6727 // Handle standard constraint letters.
6728 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6731 // isLegalAddressingMode - Return true if the addressing mode represented
6732 // by AM is legal for this target, for a load/store of the specified type.
6733 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
6735 // FIXME: PPC does not allow r+i addressing modes for vectors!
6737 // PPC allows a sign-extended 16-bit immediate field.
6738 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
6741 // No global is ever allowed as a base.
6745 // PPC only support r+r,
6747 case 0: // "r+i" or just "i", depending on HasBaseReg.
6750 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
6752 // Otherwise we have r+r or r+i.
6755 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
6757 // Allow 2*r as r+r.
6760 // No other scales are supported.
6767 /// isLegalAddressImmediate - Return true if the integer value can be used
6768 /// as the offset of the target addressing mode for load / store of the
6770 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
6771 // PPC allows a sign-extended 16-bit immediate field.
6772 return (V > -(1 << 16) && V < (1 << 16)-1);
6775 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
6779 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
6780 SelectionDAG &DAG) const {
6781 MachineFunction &MF = DAG.getMachineFunction();
6782 MachineFrameInfo *MFI = MF.getFrameInfo();
6783 MFI->setReturnAddressIsTaken(true);
6785 DebugLoc dl = Op.getDebugLoc();
6786 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6788 // Make sure the function does not optimize away the store of the RA to
6790 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
6791 FuncInfo->setLRStoreRequired();
6792 bool isPPC64 = PPCSubTarget.isPPC64();
6793 bool isDarwinABI = PPCSubTarget.isDarwinABI();
6796 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6799 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
6800 isPPC64? MVT::i64 : MVT::i32);
6801 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6802 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6804 MachinePointerInfo(), false, false, false, 0);
6807 // Just load the return address off the stack.
6808 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
6809 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6810 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
6813 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
6814 SelectionDAG &DAG) const {
6815 DebugLoc dl = Op.getDebugLoc();
6816 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6818 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
6819 bool isPPC64 = PtrVT == MVT::i64;
6821 MachineFunction &MF = DAG.getMachineFunction();
6822 MachineFrameInfo *MFI = MF.getFrameInfo();
6823 MFI->setFrameAddressIsTaken(true);
6824 bool is31 = (getTargetMachine().Options.DisableFramePointerElim(MF) ||
6825 MFI->hasVarSizedObjects()) &&
6826 MFI->getStackSize() &&
6827 !MF.getFunction()->getAttributes().
6828 hasAttribute(AttributeSet::FunctionIndex, Attribute::Naked);
6829 unsigned FrameReg = isPPC64 ? (is31 ? PPC::X31 : PPC::X1) :
6830 (is31 ? PPC::R31 : PPC::R1);
6831 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
6834 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
6835 FrameAddr, MachinePointerInfo(), false, false,
6841 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
6842 // The PowerPC target isn't yet aware of offsets.
6846 /// getOptimalMemOpType - Returns the target specific optimal type for load
6847 /// and store operations as a result of memset, memcpy, and memmove
6848 /// lowering. If DstAlign is zero that means it's safe to destination
6849 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
6850 /// means there isn't a need to check it against alignment requirement,
6851 /// probably because the source does not need to be loaded. If 'IsMemset' is
6852 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
6853 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
6854 /// source is constant so it does not need to be loaded.
6855 /// It returns EVT::Other if the type should be determined using generic
6856 /// target-independent logic.
6857 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
6858 unsigned DstAlign, unsigned SrcAlign,
6859 bool IsMemset, bool ZeroMemset,
6861 MachineFunction &MF) const {
6862 if (this->PPCSubTarget.isPPC64()) {
6869 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
6870 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
6871 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
6872 /// is expanded to mul + add.
6873 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
6877 switch (VT.getSimpleVT().SimpleTy) {
6889 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
6891 return TargetLowering::getSchedulingPreference(N);