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_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
40 CCValAssign::LocInfo &LocInfo,
41 ISD::ArgFlagsTy &ArgFlags,
43 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
45 CCValAssign::LocInfo &LocInfo,
46 ISD::ArgFlagsTy &ArgFlags,
48 static bool CC_PPC32_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 cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
61 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
63 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
64 if (TM.getSubtargetImpl()->isDarwin())
65 return new TargetLoweringObjectFileMachO();
67 return new TargetLoweringObjectFileELF();
70 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
71 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
72 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
73 PPCRegInfo = TM.getRegisterInfo();
77 // Use _setjmp/_longjmp instead of setjmp/longjmp.
78 setUseUnderscoreSetJmp(true);
79 setUseUnderscoreLongJmp(true);
81 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
82 // arguments are at least 4/8 bytes aligned.
83 bool isPPC64 = Subtarget->isPPC64();
84 setMinStackArgumentAlignment(isPPC64 ? 8:4);
86 // Set up the register classes.
87 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
88 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
89 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
91 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
92 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
95 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
97 // PowerPC has pre-inc load and store's.
98 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
99 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
100 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
101 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
102 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
103 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
104 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
105 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
106 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
107 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
109 // This is used in the ppcf128->int sequence. Note it has different semantics
110 // from FP_ROUND: that rounds to nearest, this rounds to zero.
111 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
113 // We do not currently implement these libm ops for PowerPC.
114 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
115 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
116 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
117 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
118 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
120 // PowerPC has no SREM/UREM instructions
121 setOperationAction(ISD::SREM, MVT::i32, Expand);
122 setOperationAction(ISD::UREM, MVT::i32, Expand);
123 setOperationAction(ISD::SREM, MVT::i64, Expand);
124 setOperationAction(ISD::UREM, MVT::i64, Expand);
126 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
127 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
128 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
129 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
130 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
131 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
132 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
133 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
134 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
136 // We don't support sin/cos/sqrt/fmod/pow
137 setOperationAction(ISD::FSIN , MVT::f64, Expand);
138 setOperationAction(ISD::FCOS , MVT::f64, Expand);
139 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
140 setOperationAction(ISD::FREM , MVT::f64, Expand);
141 setOperationAction(ISD::FPOW , MVT::f64, Expand);
142 setOperationAction(ISD::FMA , MVT::f64, Legal);
143 setOperationAction(ISD::FSIN , MVT::f32, Expand);
144 setOperationAction(ISD::FCOS , MVT::f32, Expand);
145 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
146 setOperationAction(ISD::FREM , MVT::f32, Expand);
147 setOperationAction(ISD::FPOW , MVT::f32, Expand);
148 setOperationAction(ISD::FMA , MVT::f32, Legal);
150 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
152 // If we're enabling GP optimizations, use hardware square root
153 if (!Subtarget->hasFSQRT()) {
154 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
155 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
158 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
159 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
161 // PowerPC does not have BSWAP, CTPOP or CTTZ
162 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
163 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
164 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
165 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
166 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
167 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
168 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
169 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
170 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
171 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
173 // PowerPC does not have ROTR
174 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
175 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
177 // PowerPC does not have Select
178 setOperationAction(ISD::SELECT, MVT::i32, Expand);
179 setOperationAction(ISD::SELECT, MVT::i64, Expand);
180 setOperationAction(ISD::SELECT, MVT::f32, Expand);
181 setOperationAction(ISD::SELECT, MVT::f64, Expand);
183 // PowerPC wants to turn select_cc of FP into fsel when possible.
184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
187 // PowerPC wants to optimize integer setcc a bit
188 setOperationAction(ISD::SETCC, MVT::i32, Custom);
190 // PowerPC does not have BRCOND which requires SetCC
191 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
193 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
195 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
196 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
198 // PowerPC does not have [U|S]INT_TO_FP
199 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
200 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
202 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
203 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
204 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
205 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
207 // We cannot sextinreg(i1). Expand to shifts.
208 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
210 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
211 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
212 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
213 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
215 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intened to support
216 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
217 // support continuation, user-level threading, and etc.. As a result, no
218 // other SjLj exception interfaces are implemented and please don't build
219 // your own exception handling based on them.
220 // LLVM/Clang supports zero-cost DWARF exception handling.
221 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
222 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
224 // We want to legalize GlobalAddress and ConstantPool nodes into the
225 // appropriate instructions to materialize the address.
226 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
227 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
228 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
229 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
230 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
231 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
234 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
238 setOperationAction(ISD::TRAP, MVT::Other, Legal);
240 // TRAMPOLINE is custom lowered.
241 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
242 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
244 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
245 setOperationAction(ISD::VASTART , MVT::Other, Custom);
247 if (Subtarget->isSVR4ABI()) {
249 // VAARG always uses double-word chunks, so promote anything smaller.
250 setOperationAction(ISD::VAARG, MVT::i1, Promote);
251 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
252 setOperationAction(ISD::VAARG, MVT::i8, Promote);
253 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
254 setOperationAction(ISD::VAARG, MVT::i16, Promote);
255 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
256 setOperationAction(ISD::VAARG, MVT::i32, Promote);
257 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
258 setOperationAction(ISD::VAARG, MVT::Other, Expand);
260 // VAARG is custom lowered with the 32-bit SVR4 ABI.
261 setOperationAction(ISD::VAARG, MVT::Other, Custom);
262 setOperationAction(ISD::VAARG, MVT::i64, Custom);
265 setOperationAction(ISD::VAARG, MVT::Other, Expand);
267 // Use the default implementation.
268 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
269 setOperationAction(ISD::VAEND , MVT::Other, Expand);
270 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
271 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
272 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
273 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
275 // We want to custom lower some of our intrinsics.
276 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
278 // Comparisons that require checking two conditions.
279 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
280 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
281 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
282 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
283 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
284 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
285 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
286 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
287 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
288 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
289 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
290 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
292 if (Subtarget->has64BitSupport()) {
293 // They also have instructions for converting between i64 and fp.
294 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
297 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
298 // This is just the low 32 bits of a (signed) fp->i64 conversion.
299 // We cannot do this with Promote because i64 is not a legal type.
300 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
302 // FIXME: disable this lowered code. This generates 64-bit register values,
303 // and we don't model the fact that the top part is clobbered by calls. We
304 // need to flag these together so that the value isn't live across a call.
305 //setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
307 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
308 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
311 if (Subtarget->use64BitRegs()) {
312 // 64-bit PowerPC implementations can support i64 types directly
313 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
314 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
315 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
316 // 64-bit PowerPC wants to expand i128 shifts itself.
317 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
318 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
319 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
321 // 32-bit PowerPC wants to expand i64 shifts itself.
322 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
323 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
324 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
327 if (Subtarget->hasAltivec()) {
328 // First set operation action for all vector types to expand. Then we
329 // will selectively turn on ones that can be effectively codegen'd.
330 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
331 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
332 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
334 // add/sub are legal for all supported vector VT's.
335 setOperationAction(ISD::ADD , VT, Legal);
336 setOperationAction(ISD::SUB , VT, Legal);
338 // We promote all shuffles to v16i8.
339 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
340 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
342 // We promote all non-typed operations to v4i32.
343 setOperationAction(ISD::AND , VT, Promote);
344 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
345 setOperationAction(ISD::OR , VT, Promote);
346 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
347 setOperationAction(ISD::XOR , VT, Promote);
348 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
349 setOperationAction(ISD::LOAD , VT, Promote);
350 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
351 setOperationAction(ISD::SELECT, VT, Promote);
352 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
353 setOperationAction(ISD::STORE, VT, Promote);
354 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
356 // No other operations are legal.
357 setOperationAction(ISD::MUL , VT, Expand);
358 setOperationAction(ISD::SDIV, VT, Expand);
359 setOperationAction(ISD::SREM, VT, Expand);
360 setOperationAction(ISD::UDIV, VT, Expand);
361 setOperationAction(ISD::UREM, VT, Expand);
362 setOperationAction(ISD::FDIV, VT, Expand);
363 setOperationAction(ISD::FNEG, VT, Expand);
364 setOperationAction(ISD::FSQRT, VT, Expand);
365 setOperationAction(ISD::FLOG, VT, Expand);
366 setOperationAction(ISD::FLOG10, VT, Expand);
367 setOperationAction(ISD::FLOG2, VT, Expand);
368 setOperationAction(ISD::FEXP, VT, Expand);
369 setOperationAction(ISD::FEXP2, VT, Expand);
370 setOperationAction(ISD::FSIN, VT, Expand);
371 setOperationAction(ISD::FCOS, VT, Expand);
372 setOperationAction(ISD::FABS, VT, Expand);
373 setOperationAction(ISD::FPOWI, VT, Expand);
374 setOperationAction(ISD::FFLOOR, VT, Expand);
375 setOperationAction(ISD::FCEIL, VT, Expand);
376 setOperationAction(ISD::FTRUNC, VT, Expand);
377 setOperationAction(ISD::FRINT, VT, Expand);
378 setOperationAction(ISD::FNEARBYINT, VT, Expand);
379 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
380 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
381 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
382 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
383 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
384 setOperationAction(ISD::UDIVREM, VT, Expand);
385 setOperationAction(ISD::SDIVREM, VT, Expand);
386 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
387 setOperationAction(ISD::FPOW, VT, Expand);
388 setOperationAction(ISD::CTPOP, VT, Expand);
389 setOperationAction(ISD::CTLZ, VT, Expand);
390 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
391 setOperationAction(ISD::CTTZ, VT, Expand);
392 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
393 setOperationAction(ISD::VSELECT, VT, Expand);
394 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
396 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
397 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
398 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
399 setTruncStoreAction(VT, InnerVT, Expand);
401 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
402 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
403 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
406 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
407 // with merges, splats, etc.
408 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
410 setOperationAction(ISD::AND , MVT::v4i32, Legal);
411 setOperationAction(ISD::OR , MVT::v4i32, Legal);
412 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
413 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
414 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
415 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
416 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
417 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
418 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
419 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
420 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
421 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
422 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
423 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
425 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
426 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
427 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
428 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
430 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
431 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
432 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
433 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
434 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
436 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
437 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
439 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
440 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
441 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
442 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
444 // Altivec does not contain unordered floating-point compare instructions
445 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
446 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
447 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
448 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
449 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
450 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
453 if (Subtarget->has64BitSupport()) {
454 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
458 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
459 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
460 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
461 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
463 setBooleanContents(ZeroOrOneBooleanContent);
464 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
467 setStackPointerRegisterToSaveRestore(PPC::X1);
468 setExceptionPointerRegister(PPC::X3);
469 setExceptionSelectorRegister(PPC::X4);
471 setStackPointerRegisterToSaveRestore(PPC::R1);
472 setExceptionPointerRegister(PPC::R3);
473 setExceptionSelectorRegister(PPC::R4);
476 // We have target-specific dag combine patterns for the following nodes:
477 setTargetDAGCombine(ISD::SINT_TO_FP);
478 setTargetDAGCombine(ISD::STORE);
479 setTargetDAGCombine(ISD::BR_CC);
480 setTargetDAGCombine(ISD::BSWAP);
482 // Darwin long double math library functions have $LDBL128 appended.
483 if (Subtarget->isDarwin()) {
484 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
485 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
486 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
487 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
488 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
489 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
490 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
491 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
492 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
493 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
496 setMinFunctionAlignment(2);
497 if (PPCSubTarget.isDarwin())
498 setPrefFunctionAlignment(4);
500 if (isPPC64 && Subtarget->isJITCodeModel())
501 // Temporary workaround for the inability of PPC64 JIT to handle jump
503 setSupportJumpTables(false);
505 setInsertFencesForAtomic(true);
507 setSchedulingPreference(Sched::Hybrid);
509 computeRegisterProperties();
511 // The Freescale cores does better with aggressive inlining of memcpy and
512 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
513 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
514 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
515 MaxStoresPerMemset = 32;
516 MaxStoresPerMemsetOptSize = 16;
517 MaxStoresPerMemcpy = 32;
518 MaxStoresPerMemcpyOptSize = 8;
519 MaxStoresPerMemmove = 32;
520 MaxStoresPerMemmoveOptSize = 8;
522 setPrefFunctionAlignment(4);
523 BenefitFromCodePlacementOpt = true;
527 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
528 /// function arguments in the caller parameter area.
529 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
530 const TargetMachine &TM = getTargetMachine();
531 // Darwin passes everything on 4 byte boundary.
532 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
535 // 16byte and wider vectors are passed on 16byte boundary.
536 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
537 if (VTy->getBitWidth() >= 128)
540 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
541 if (PPCSubTarget.isPPC64())
547 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
550 case PPCISD::FSEL: return "PPCISD::FSEL";
551 case PPCISD::FCFID: return "PPCISD::FCFID";
552 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
553 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
554 case PPCISD::STFIWX: return "PPCISD::STFIWX";
555 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
556 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
557 case PPCISD::VPERM: return "PPCISD::VPERM";
558 case PPCISD::Hi: return "PPCISD::Hi";
559 case PPCISD::Lo: return "PPCISD::Lo";
560 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
561 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
562 case PPCISD::LOAD: return "PPCISD::LOAD";
563 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
564 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
565 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
566 case PPCISD::SRL: return "PPCISD::SRL";
567 case PPCISD::SRA: return "PPCISD::SRA";
568 case PPCISD::SHL: return "PPCISD::SHL";
569 case PPCISD::EXTSW_32: return "PPCISD::EXTSW_32";
570 case PPCISD::STD_32: return "PPCISD::STD_32";
571 case PPCISD::CALL: return "PPCISD::CALL";
572 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
573 case PPCISD::MTCTR: return "PPCISD::MTCTR";
574 case PPCISD::BCTRL: return "PPCISD::BCTRL";
575 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
576 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
577 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
578 case PPCISD::MFCR: return "PPCISD::MFCR";
579 case PPCISD::VCMP: return "PPCISD::VCMP";
580 case PPCISD::VCMPo: return "PPCISD::VCMPo";
581 case PPCISD::LBRX: return "PPCISD::LBRX";
582 case PPCISD::STBRX: return "PPCISD::STBRX";
583 case PPCISD::LARX: return "PPCISD::LARX";
584 case PPCISD::STCX: return "PPCISD::STCX";
585 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
586 case PPCISD::MFFS: return "PPCISD::MFFS";
587 case PPCISD::MTFSB0: return "PPCISD::MTFSB0";
588 case PPCISD::MTFSB1: return "PPCISD::MTFSB1";
589 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
590 case PPCISD::MTFSF: return "PPCISD::MTFSF";
591 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
592 case PPCISD::CR6SET: return "PPCISD::CR6SET";
593 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
594 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
595 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
596 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
597 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
598 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
599 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
600 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
601 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
602 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
603 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
604 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
605 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
606 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
607 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
608 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
612 EVT PPCTargetLowering::getSetCCResultType(EVT VT) const {
615 return VT.changeVectorElementTypeToInteger();
618 //===----------------------------------------------------------------------===//
619 // Node matching predicates, for use by the tblgen matching code.
620 //===----------------------------------------------------------------------===//
622 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
623 static bool isFloatingPointZero(SDValue Op) {
624 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
625 return CFP->getValueAPF().isZero();
626 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
627 // Maybe this has already been legalized into the constant pool?
628 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
629 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
630 return CFP->getValueAPF().isZero();
635 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
636 /// true if Op is undef or if it matches the specified value.
637 static bool isConstantOrUndef(int Op, int Val) {
638 return Op < 0 || Op == Val;
641 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
642 /// VPKUHUM instruction.
643 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
645 for (unsigned i = 0; i != 16; ++i)
646 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
649 for (unsigned i = 0; i != 8; ++i)
650 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
651 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
657 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
658 /// VPKUWUM instruction.
659 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
661 for (unsigned i = 0; i != 16; i += 2)
662 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
663 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
666 for (unsigned i = 0; i != 8; i += 2)
667 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
668 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
669 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
670 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
676 /// isVMerge - Common function, used to match vmrg* shuffles.
678 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
679 unsigned LHSStart, unsigned RHSStart) {
680 assert(N->getValueType(0) == MVT::v16i8 &&
681 "PPC only supports shuffles by bytes!");
682 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
683 "Unsupported merge size!");
685 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
686 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
687 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
688 LHSStart+j+i*UnitSize) ||
689 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
690 RHSStart+j+i*UnitSize))
696 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
697 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
698 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
701 return isVMerge(N, UnitSize, 8, 24);
702 return isVMerge(N, UnitSize, 8, 8);
705 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
706 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
707 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
710 return isVMerge(N, UnitSize, 0, 16);
711 return isVMerge(N, UnitSize, 0, 0);
715 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
716 /// amount, otherwise return -1.
717 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
718 assert(N->getValueType(0) == MVT::v16i8 &&
719 "PPC only supports shuffles by bytes!");
721 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
723 // Find the first non-undef value in the shuffle mask.
725 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
728 if (i == 16) return -1; // all undef.
730 // Otherwise, check to see if the rest of the elements are consecutively
731 // numbered from this value.
732 unsigned ShiftAmt = SVOp->getMaskElt(i);
733 if (ShiftAmt < i) return -1;
737 // Check the rest of the elements to see if they are consecutive.
738 for (++i; i != 16; ++i)
739 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
742 // Check the rest of the elements to see if they are consecutive.
743 for (++i; i != 16; ++i)
744 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
750 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
751 /// specifies a splat of a single element that is suitable for input to
752 /// VSPLTB/VSPLTH/VSPLTW.
753 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
754 assert(N->getValueType(0) == MVT::v16i8 &&
755 (EltSize == 1 || EltSize == 2 || EltSize == 4));
757 // This is a splat operation if each element of the permute is the same, and
758 // if the value doesn't reference the second vector.
759 unsigned ElementBase = N->getMaskElt(0);
761 // FIXME: Handle UNDEF elements too!
762 if (ElementBase >= 16)
765 // Check that the indices are consecutive, in the case of a multi-byte element
766 // splatted with a v16i8 mask.
767 for (unsigned i = 1; i != EltSize; ++i)
768 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
771 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
772 if (N->getMaskElt(i) < 0) continue;
773 for (unsigned j = 0; j != EltSize; ++j)
774 if (N->getMaskElt(i+j) != N->getMaskElt(j))
780 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
782 bool PPC::isAllNegativeZeroVector(SDNode *N) {
783 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
785 APInt APVal, APUndef;
789 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
790 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
791 return CFP->getValueAPF().isNegZero();
796 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
797 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
798 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
799 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
800 assert(isSplatShuffleMask(SVOp, EltSize));
801 return SVOp->getMaskElt(0) / EltSize;
804 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
805 /// by using a vspltis[bhw] instruction of the specified element size, return
806 /// the constant being splatted. The ByteSize field indicates the number of
807 /// bytes of each element [124] -> [bhw].
808 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
811 // If ByteSize of the splat is bigger than the element size of the
812 // build_vector, then we have a case where we are checking for a splat where
813 // multiple elements of the buildvector are folded together into a single
814 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
815 unsigned EltSize = 16/N->getNumOperands();
816 if (EltSize < ByteSize) {
817 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
818 SDValue UniquedVals[4];
819 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
821 // See if all of the elements in the buildvector agree across.
822 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
823 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
824 // If the element isn't a constant, bail fully out.
825 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
828 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
829 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
830 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
831 return SDValue(); // no match.
834 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
835 // either constant or undef values that are identical for each chunk. See
836 // if these chunks can form into a larger vspltis*.
838 // Check to see if all of the leading entries are either 0 or -1. If
839 // neither, then this won't fit into the immediate field.
840 bool LeadingZero = true;
841 bool LeadingOnes = true;
842 for (unsigned i = 0; i != Multiple-1; ++i) {
843 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
845 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
846 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
848 // Finally, check the least significant entry.
850 if (UniquedVals[Multiple-1].getNode() == 0)
851 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
852 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
854 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
857 if (UniquedVals[Multiple-1].getNode() == 0)
858 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
859 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
860 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
861 return DAG.getTargetConstant(Val, MVT::i32);
867 // Check to see if this buildvec has a single non-undef value in its elements.
868 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
869 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
870 if (OpVal.getNode() == 0)
871 OpVal = N->getOperand(i);
872 else if (OpVal != N->getOperand(i))
876 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
878 unsigned ValSizeInBytes = EltSize;
880 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
881 Value = CN->getZExtValue();
882 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
883 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
884 Value = FloatToBits(CN->getValueAPF().convertToFloat());
887 // If the splat value is larger than the element value, then we can never do
888 // this splat. The only case that we could fit the replicated bits into our
889 // immediate field for would be zero, and we prefer to use vxor for it.
890 if (ValSizeInBytes < ByteSize) return SDValue();
892 // If the element value is larger than the splat value, cut it in half and
893 // check to see if the two halves are equal. Continue doing this until we
894 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
895 while (ValSizeInBytes > ByteSize) {
896 ValSizeInBytes >>= 1;
898 // If the top half equals the bottom half, we're still ok.
899 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
900 (Value & ((1 << (8*ValSizeInBytes))-1)))
904 // Properly sign extend the value.
905 int MaskVal = SignExtend32(Value, ByteSize * 8);
907 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
908 if (MaskVal == 0) return SDValue();
910 // Finally, if this value fits in a 5 bit sext field, return it
911 if (SignExtend32<5>(MaskVal) == MaskVal)
912 return DAG.getTargetConstant(MaskVal, MVT::i32);
916 //===----------------------------------------------------------------------===//
917 // Addressing Mode Selection
918 //===----------------------------------------------------------------------===//
920 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
921 /// or 64-bit immediate, and if the value can be accurately represented as a
922 /// sign extension from a 16-bit value. If so, this returns true and the
924 static bool isIntS16Immediate(SDNode *N, short &Imm) {
925 if (N->getOpcode() != ISD::Constant)
928 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
929 if (N->getValueType(0) == MVT::i32)
930 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
932 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
934 static bool isIntS16Immediate(SDValue Op, short &Imm) {
935 return isIntS16Immediate(Op.getNode(), Imm);
939 /// SelectAddressRegReg - Given the specified addressed, check to see if it
940 /// can be represented as an indexed [r+r] operation. Returns false if it
941 /// can be more efficiently represented with [r+imm].
942 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
944 SelectionDAG &DAG) const {
946 if (N.getOpcode() == ISD::ADD) {
947 if (isIntS16Immediate(N.getOperand(1), imm))
949 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
952 Base = N.getOperand(0);
953 Index = N.getOperand(1);
955 } else if (N.getOpcode() == ISD::OR) {
956 if (isIntS16Immediate(N.getOperand(1), imm))
957 return false; // r+i can fold it if we can.
959 // If this is an or of disjoint bitfields, we can codegen this as an add
960 // (for better address arithmetic) if the LHS and RHS of the OR are provably
962 APInt LHSKnownZero, LHSKnownOne;
963 APInt RHSKnownZero, RHSKnownOne;
964 DAG.ComputeMaskedBits(N.getOperand(0),
965 LHSKnownZero, LHSKnownOne);
967 if (LHSKnownZero.getBoolValue()) {
968 DAG.ComputeMaskedBits(N.getOperand(1),
969 RHSKnownZero, RHSKnownOne);
970 // If all of the bits are known zero on the LHS or RHS, the add won't
972 if (~(LHSKnownZero | RHSKnownZero) == 0) {
973 Base = N.getOperand(0);
974 Index = N.getOperand(1);
983 /// Returns true if the address N can be represented by a base register plus
984 /// a signed 16-bit displacement [r+imm], and if it is not better
985 /// represented as reg+reg.
986 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
988 SelectionDAG &DAG) const {
989 // FIXME dl should come from parent load or store, not from address
990 DebugLoc dl = N.getDebugLoc();
991 // If this can be more profitably realized as r+r, fail.
992 if (SelectAddressRegReg(N, Disp, Base, DAG))
995 if (N.getOpcode() == ISD::ADD) {
997 if (isIntS16Immediate(N.getOperand(1), imm)) {
998 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
999 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1000 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1002 Base = N.getOperand(0);
1004 return true; // [r+i]
1005 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1006 // Match LOAD (ADD (X, Lo(G))).
1007 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1008 && "Cannot handle constant offsets yet!");
1009 Disp = N.getOperand(1).getOperand(0); // The global address.
1010 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1011 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1012 Disp.getOpcode() == ISD::TargetConstantPool ||
1013 Disp.getOpcode() == ISD::TargetJumpTable);
1014 Base = N.getOperand(0);
1015 return true; // [&g+r]
1017 } else if (N.getOpcode() == ISD::OR) {
1019 if (isIntS16Immediate(N.getOperand(1), imm)) {
1020 // If this is an or of disjoint bitfields, we can codegen this as an add
1021 // (for better address arithmetic) if the LHS and RHS of the OR are
1022 // provably disjoint.
1023 APInt LHSKnownZero, LHSKnownOne;
1024 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1026 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1027 // If all of the bits are known zero on the LHS or RHS, the add won't
1029 Base = N.getOperand(0);
1030 Disp = DAG.getTargetConstant((int)imm & 0xFFFF, MVT::i32);
1034 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1035 // Loading from a constant address.
1037 // If this address fits entirely in a 16-bit sext immediate field, codegen
1040 if (isIntS16Immediate(CN, Imm)) {
1041 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1042 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1043 CN->getValueType(0));
1047 // Handle 32-bit sext immediates with LIS + addr mode.
1048 if (CN->getValueType(0) == MVT::i32 ||
1049 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1050 int Addr = (int)CN->getZExtValue();
1052 // Otherwise, break this down into an LIS + disp.
1053 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1055 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1056 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1057 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1062 Disp = DAG.getTargetConstant(0, getPointerTy());
1063 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1064 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1067 return true; // [r+0]
1070 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1071 /// represented as an indexed [r+r] operation.
1072 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1074 SelectionDAG &DAG) const {
1075 // Check to see if we can easily represent this as an [r+r] address. This
1076 // will fail if it thinks that the address is more profitably represented as
1077 // reg+imm, e.g. where imm = 0.
1078 if (SelectAddressRegReg(N, Base, Index, DAG))
1081 // If the operand is an addition, always emit this as [r+r], since this is
1082 // better (for code size, and execution, as the memop does the add for free)
1083 // than emitting an explicit add.
1084 if (N.getOpcode() == ISD::ADD) {
1085 Base = N.getOperand(0);
1086 Index = N.getOperand(1);
1090 // Otherwise, do it the hard way, using R0 as the base register.
1091 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1097 /// SelectAddressRegImmShift - Returns true if the address N can be
1098 /// represented by a base register plus a signed 14-bit displacement
1099 /// [r+imm*4]. Suitable for use by STD and friends.
1100 bool PPCTargetLowering::SelectAddressRegImmShift(SDValue N, SDValue &Disp,
1102 SelectionDAG &DAG) const {
1103 // FIXME dl should come from the parent load or store, not the address
1104 DebugLoc dl = N.getDebugLoc();
1105 // If this can be more profitably realized as r+r, fail.
1106 if (SelectAddressRegReg(N, Disp, Base, DAG))
1109 if (N.getOpcode() == ISD::ADD) {
1111 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1112 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1113 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1114 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1116 Base = N.getOperand(0);
1118 return true; // [r+i]
1119 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1120 // Match LOAD (ADD (X, Lo(G))).
1121 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1122 && "Cannot handle constant offsets yet!");
1123 Disp = N.getOperand(1).getOperand(0); // The global address.
1124 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1125 Disp.getOpcode() == ISD::TargetConstantPool ||
1126 Disp.getOpcode() == ISD::TargetJumpTable);
1127 Base = N.getOperand(0);
1128 return true; // [&g+r]
1130 } else if (N.getOpcode() == ISD::OR) {
1132 if (isIntS16Immediate(N.getOperand(1), imm) && (imm & 3) == 0) {
1133 // If this is an or of disjoint bitfields, we can codegen this as an add
1134 // (for better address arithmetic) if the LHS and RHS of the OR are
1135 // provably disjoint.
1136 APInt LHSKnownZero, LHSKnownOne;
1137 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1138 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1139 // If all of the bits are known zero on the LHS or RHS, the add won't
1141 Base = N.getOperand(0);
1142 Disp = DAG.getTargetConstant(((int)imm & 0xFFFF) >> 2, MVT::i32);
1146 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1147 // Loading from a constant address. Verify low two bits are clear.
1148 if ((CN->getZExtValue() & 3) == 0) {
1149 // If this address fits entirely in a 14-bit sext immediate field, codegen
1152 if (isIntS16Immediate(CN, Imm)) {
1153 Disp = DAG.getTargetConstant((unsigned short)Imm >> 2, getPointerTy());
1154 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1155 CN->getValueType(0));
1159 // Fold the low-part of 32-bit absolute addresses into addr mode.
1160 if (CN->getValueType(0) == MVT::i32 ||
1161 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) {
1162 int Addr = (int)CN->getZExtValue();
1164 // Otherwise, break this down into an LIS + disp.
1165 Disp = DAG.getTargetConstant((short)Addr >> 2, MVT::i32);
1166 Base = DAG.getTargetConstant((Addr-(signed short)Addr) >> 16, MVT::i32);
1167 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1168 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base),0);
1174 Disp = DAG.getTargetConstant(0, getPointerTy());
1175 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1176 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1179 return true; // [r+0]
1183 /// getPreIndexedAddressParts - returns true by value, base pointer and
1184 /// offset pointer and addressing mode by reference if the node's address
1185 /// can be legally represented as pre-indexed load / store address.
1186 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1188 ISD::MemIndexedMode &AM,
1189 SelectionDAG &DAG) const {
1190 if (DisablePPCPreinc) return false;
1196 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1197 Ptr = LD->getBasePtr();
1198 VT = LD->getMemoryVT();
1199 Alignment = LD->getAlignment();
1200 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1201 Ptr = ST->getBasePtr();
1202 VT = ST->getMemoryVT();
1203 Alignment = ST->getAlignment();
1208 // PowerPC doesn't have preinc load/store instructions for vectors.
1212 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1214 // Common code will reject creating a pre-inc form if the base pointer
1215 // is a frame index, or if N is a store and the base pointer is either
1216 // the same as or a predecessor of the value being stored. Check for
1217 // those situations here, and try with swapped Base/Offset instead.
1220 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1223 SDValue Val = cast<StoreSDNode>(N)->getValue();
1224 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1229 std::swap(Base, Offset);
1235 // LDU/STU use reg+imm*4, others use reg+imm.
1236 if (VT != MVT::i64) {
1238 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG))
1241 // LDU/STU need an address with at least 4-byte alignment.
1246 if (!SelectAddressRegImmShift(Ptr, Offset, Base, DAG))
1250 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1251 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1252 // sext i32 to i64 when addr mode is r+i.
1253 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1254 LD->getExtensionType() == ISD::SEXTLOAD &&
1255 isa<ConstantSDNode>(Offset))
1263 //===----------------------------------------------------------------------===//
1264 // LowerOperation implementation
1265 //===----------------------------------------------------------------------===//
1267 /// GetLabelAccessInfo - Return true if we should reference labels using a
1268 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1269 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1270 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1271 HiOpFlags = PPCII::MO_HA16;
1272 LoOpFlags = PPCII::MO_LO16;
1274 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1275 // non-darwin platform. We don't support PIC on other platforms yet.
1276 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1277 TM.getSubtarget<PPCSubtarget>().isDarwin();
1279 HiOpFlags |= PPCII::MO_PIC_FLAG;
1280 LoOpFlags |= PPCII::MO_PIC_FLAG;
1283 // If this is a reference to a global value that requires a non-lazy-ptr, make
1284 // sure that instruction lowering adds it.
1285 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1286 HiOpFlags |= PPCII::MO_NLP_FLAG;
1287 LoOpFlags |= PPCII::MO_NLP_FLAG;
1289 if (GV->hasHiddenVisibility()) {
1290 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1291 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1298 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1299 SelectionDAG &DAG) {
1300 EVT PtrVT = HiPart.getValueType();
1301 SDValue Zero = DAG.getConstant(0, PtrVT);
1302 DebugLoc DL = HiPart.getDebugLoc();
1304 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1305 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1307 // With PIC, the first instruction is actually "GR+hi(&G)".
1309 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1310 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1312 // Generate non-pic code that has direct accesses to the constant pool.
1313 // The address of the global is just (hi(&g)+lo(&g)).
1314 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1317 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1318 SelectionDAG &DAG) const {
1319 EVT PtrVT = Op.getValueType();
1320 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1321 const Constant *C = CP->getConstVal();
1323 // 64-bit SVR4 ABI code is always position-independent.
1324 // The actual address of the GlobalValue is stored in the TOC.
1325 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1326 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1327 return DAG.getNode(PPCISD::TOC_ENTRY, CP->getDebugLoc(), MVT::i64, GA,
1328 DAG.getRegister(PPC::X2, MVT::i64));
1331 unsigned MOHiFlag, MOLoFlag;
1332 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1334 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1336 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1337 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1340 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1341 EVT PtrVT = Op.getValueType();
1342 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1344 // 64-bit SVR4 ABI code is always position-independent.
1345 // The actual address of the GlobalValue is stored in the TOC.
1346 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1347 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1348 return DAG.getNode(PPCISD::TOC_ENTRY, JT->getDebugLoc(), MVT::i64, GA,
1349 DAG.getRegister(PPC::X2, MVT::i64));
1352 unsigned MOHiFlag, MOLoFlag;
1353 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1354 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1355 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1356 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1359 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1360 SelectionDAG &DAG) const {
1361 EVT PtrVT = Op.getValueType();
1363 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1365 unsigned MOHiFlag, MOLoFlag;
1366 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1367 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1368 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1369 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1372 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1373 SelectionDAG &DAG) const {
1375 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1376 DebugLoc dl = GA->getDebugLoc();
1377 const GlobalValue *GV = GA->getGlobal();
1378 EVT PtrVT = getPointerTy();
1379 bool is64bit = PPCSubTarget.isPPC64();
1381 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1383 if (Model == TLSModel::LocalExec) {
1384 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1385 PPCII::MO_TPREL16_HA);
1386 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1387 PPCII::MO_TPREL16_LO);
1388 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1389 is64bit ? MVT::i64 : MVT::i32);
1390 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1391 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1395 llvm_unreachable("only local-exec is currently supported for ppc32");
1397 if (Model == TLSModel::InitialExec) {
1398 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1399 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1400 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1401 PtrVT, GOTReg, TGA);
1402 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1403 PtrVT, TGA, TPOffsetHi);
1404 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGA);
1407 if (Model == TLSModel::GeneralDynamic) {
1408 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1409 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1410 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1412 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1415 // We need a chain node, and don't have one handy. The underlying
1416 // call has no side effects, so using the function entry node
1418 SDValue Chain = DAG.getEntryNode();
1419 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1420 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1421 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1422 PtrVT, ParmReg, TGA);
1423 // The return value from GET_TLS_ADDR really is in X3 already, but
1424 // some hacks are needed here to tie everything together. The extra
1425 // copies dissolve during subsequent transforms.
1426 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1427 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1430 if (Model == TLSModel::LocalDynamic) {
1431 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1432 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1433 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1435 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1438 // We need a chain node, and don't have one handy. The underlying
1439 // call has no side effects, so using the function entry node
1441 SDValue Chain = DAG.getEntryNode();
1442 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1443 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1444 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1445 PtrVT, ParmReg, TGA);
1446 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1447 // some hacks are needed here to tie everything together. The extra
1448 // copies dissolve during subsequent transforms.
1449 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1450 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1451 Chain, ParmReg, TGA);
1452 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1455 llvm_unreachable("Unknown TLS model!");
1458 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1459 SelectionDAG &DAG) const {
1460 EVT PtrVT = Op.getValueType();
1461 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1462 DebugLoc DL = GSDN->getDebugLoc();
1463 const GlobalValue *GV = GSDN->getGlobal();
1465 // 64-bit SVR4 ABI code is always position-independent.
1466 // The actual address of the GlobalValue is stored in the TOC.
1467 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1468 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1469 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1470 DAG.getRegister(PPC::X2, MVT::i64));
1473 unsigned MOHiFlag, MOLoFlag;
1474 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1477 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1479 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1481 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1483 // If the global reference is actually to a non-lazy-pointer, we have to do an
1484 // extra load to get the address of the global.
1485 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1486 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1487 false, false, false, 0);
1491 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1492 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1493 DebugLoc dl = Op.getDebugLoc();
1495 // If we're comparing for equality to zero, expose the fact that this is
1496 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1497 // fold the new nodes.
1498 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1499 if (C->isNullValue() && CC == ISD::SETEQ) {
1500 EVT VT = Op.getOperand(0).getValueType();
1501 SDValue Zext = Op.getOperand(0);
1502 if (VT.bitsLT(MVT::i32)) {
1504 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1506 unsigned Log2b = Log2_32(VT.getSizeInBits());
1507 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1508 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1509 DAG.getConstant(Log2b, MVT::i32));
1510 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1512 // Leave comparisons against 0 and -1 alone for now, since they're usually
1513 // optimized. FIXME: revisit this when we can custom lower all setcc
1515 if (C->isAllOnesValue() || C->isNullValue())
1519 // If we have an integer seteq/setne, turn it into a compare against zero
1520 // by xor'ing the rhs with the lhs, which is faster than setting a
1521 // condition register, reading it back out, and masking the correct bit. The
1522 // normal approach here uses sub to do this instead of xor. Using xor exposes
1523 // the result to other bit-twiddling opportunities.
1524 EVT LHSVT = Op.getOperand(0).getValueType();
1525 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1526 EVT VT = Op.getValueType();
1527 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1529 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1534 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1535 const PPCSubtarget &Subtarget) const {
1536 SDNode *Node = Op.getNode();
1537 EVT VT = Node->getValueType(0);
1538 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1539 SDValue InChain = Node->getOperand(0);
1540 SDValue VAListPtr = Node->getOperand(1);
1541 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1542 DebugLoc dl = Node->getDebugLoc();
1544 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1547 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1548 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1550 InChain = GprIndex.getValue(1);
1552 if (VT == MVT::i64) {
1553 // Check if GprIndex is even
1554 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1555 DAG.getConstant(1, MVT::i32));
1556 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1557 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1558 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1559 DAG.getConstant(1, MVT::i32));
1560 // Align GprIndex to be even if it isn't
1561 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1565 // fpr index is 1 byte after gpr
1566 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1567 DAG.getConstant(1, MVT::i32));
1570 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1571 FprPtr, MachinePointerInfo(SV), MVT::i8,
1573 InChain = FprIndex.getValue(1);
1575 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1576 DAG.getConstant(8, MVT::i32));
1578 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1579 DAG.getConstant(4, MVT::i32));
1582 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1583 MachinePointerInfo(), false, false,
1585 InChain = OverflowArea.getValue(1);
1587 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1588 MachinePointerInfo(), false, false,
1590 InChain = RegSaveArea.getValue(1);
1592 // select overflow_area if index > 8
1593 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1594 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1596 // adjustment constant gpr_index * 4/8
1597 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1598 VT.isInteger() ? GprIndex : FprIndex,
1599 DAG.getConstant(VT.isInteger() ? 4 : 8,
1602 // OurReg = RegSaveArea + RegConstant
1603 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1606 // Floating types are 32 bytes into RegSaveArea
1607 if (VT.isFloatingPoint())
1608 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1609 DAG.getConstant(32, MVT::i32));
1611 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1612 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1613 VT.isInteger() ? GprIndex : FprIndex,
1614 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1617 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1618 VT.isInteger() ? VAListPtr : FprPtr,
1619 MachinePointerInfo(SV),
1620 MVT::i8, false, false, 0);
1622 // determine if we should load from reg_save_area or overflow_area
1623 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1625 // increase overflow_area by 4/8 if gpr/fpr > 8
1626 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1627 DAG.getConstant(VT.isInteger() ? 4 : 8,
1630 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1633 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1635 MachinePointerInfo(),
1636 MVT::i32, false, false, 0);
1638 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1639 false, false, false, 0);
1642 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1643 SelectionDAG &DAG) const {
1644 return Op.getOperand(0);
1647 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1648 SelectionDAG &DAG) const {
1649 SDValue Chain = Op.getOperand(0);
1650 SDValue Trmp = Op.getOperand(1); // trampoline
1651 SDValue FPtr = Op.getOperand(2); // nested function
1652 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1653 DebugLoc dl = Op.getDebugLoc();
1655 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1656 bool isPPC64 = (PtrVT == MVT::i64);
1658 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1661 TargetLowering::ArgListTy Args;
1662 TargetLowering::ArgListEntry Entry;
1664 Entry.Ty = IntPtrTy;
1665 Entry.Node = Trmp; Args.push_back(Entry);
1667 // TrampSize == (isPPC64 ? 48 : 40);
1668 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1669 isPPC64 ? MVT::i64 : MVT::i32);
1670 Args.push_back(Entry);
1672 Entry.Node = FPtr; Args.push_back(Entry);
1673 Entry.Node = Nest; Args.push_back(Entry);
1675 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1676 TargetLowering::CallLoweringInfo CLI(Chain,
1677 Type::getVoidTy(*DAG.getContext()),
1678 false, false, false, false, 0,
1680 /*isTailCall=*/false,
1681 /*doesNotRet=*/false,
1682 /*isReturnValueUsed=*/true,
1683 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1685 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1687 return CallResult.second;
1690 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1691 const PPCSubtarget &Subtarget) const {
1692 MachineFunction &MF = DAG.getMachineFunction();
1693 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1695 DebugLoc dl = Op.getDebugLoc();
1697 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1698 // vastart just stores the address of the VarArgsFrameIndex slot into the
1699 // memory location argument.
1700 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1701 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1702 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1703 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1704 MachinePointerInfo(SV),
1708 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1709 // We suppose the given va_list is already allocated.
1712 // char gpr; /* index into the array of 8 GPRs
1713 // * stored in the register save area
1714 // * gpr=0 corresponds to r3,
1715 // * gpr=1 to r4, etc.
1717 // char fpr; /* index into the array of 8 FPRs
1718 // * stored in the register save area
1719 // * fpr=0 corresponds to f1,
1720 // * fpr=1 to f2, etc.
1722 // char *overflow_arg_area;
1723 // /* location on stack that holds
1724 // * the next overflow argument
1726 // char *reg_save_area;
1727 // /* where r3:r10 and f1:f8 (if saved)
1733 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1734 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1737 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1739 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1741 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1744 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1745 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1747 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1748 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1750 uint64_t FPROffset = 1;
1751 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1753 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1755 // Store first byte : number of int regs
1756 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1758 MachinePointerInfo(SV),
1759 MVT::i8, false, false, 0);
1760 uint64_t nextOffset = FPROffset;
1761 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1764 // Store second byte : number of float regs
1765 SDValue secondStore =
1766 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1767 MachinePointerInfo(SV, nextOffset), MVT::i8,
1769 nextOffset += StackOffset;
1770 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1772 // Store second word : arguments given on stack
1773 SDValue thirdStore =
1774 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1775 MachinePointerInfo(SV, nextOffset),
1777 nextOffset += FrameOffset;
1778 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1780 // Store third word : arguments given in registers
1781 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1782 MachinePointerInfo(SV, nextOffset),
1787 #include "PPCGenCallingConv.inc"
1789 static bool CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1790 CCValAssign::LocInfo &LocInfo,
1791 ISD::ArgFlagsTy &ArgFlags,
1796 static bool CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1798 CCValAssign::LocInfo &LocInfo,
1799 ISD::ArgFlagsTy &ArgFlags,
1801 static const uint16_t ArgRegs[] = {
1802 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1803 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1805 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1807 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1809 // Skip one register if the first unallocated register has an even register
1810 // number and there are still argument registers available which have not been
1811 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1812 // need to skip a register if RegNum is odd.
1813 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1814 State.AllocateReg(ArgRegs[RegNum]);
1817 // Always return false here, as this function only makes sure that the first
1818 // unallocated register has an odd register number and does not actually
1819 // allocate a register for the current argument.
1823 static bool CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1825 CCValAssign::LocInfo &LocInfo,
1826 ISD::ArgFlagsTy &ArgFlags,
1828 static const uint16_t ArgRegs[] = {
1829 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1833 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1835 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1837 // If there is only one Floating-point register left we need to put both f64
1838 // values of a split ppc_fp128 value on the stack.
1839 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1840 State.AllocateReg(ArgRegs[RegNum]);
1843 // Always return false here, as this function only makes sure that the two f64
1844 // values a ppc_fp128 value is split into are both passed in registers or both
1845 // passed on the stack and does not actually allocate a register for the
1846 // current argument.
1850 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1852 static const uint16_t *GetFPR() {
1853 static const uint16_t FPR[] = {
1854 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1855 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1861 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1863 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1864 unsigned PtrByteSize) {
1865 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1866 if (Flags.isByVal())
1867 ArgSize = Flags.getByValSize();
1868 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1874 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1875 CallingConv::ID CallConv, bool isVarArg,
1876 const SmallVectorImpl<ISD::InputArg>
1878 DebugLoc dl, SelectionDAG &DAG,
1879 SmallVectorImpl<SDValue> &InVals)
1881 if (PPCSubTarget.isSVR4ABI()) {
1882 if (PPCSubTarget.isPPC64())
1883 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1886 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1889 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1895 PPCTargetLowering::LowerFormalArguments_32SVR4(
1897 CallingConv::ID CallConv, bool isVarArg,
1898 const SmallVectorImpl<ISD::InputArg>
1900 DebugLoc dl, SelectionDAG &DAG,
1901 SmallVectorImpl<SDValue> &InVals) const {
1903 // 32-bit SVR4 ABI Stack Frame Layout:
1904 // +-----------------------------------+
1905 // +--> | Back chain |
1906 // | +-----------------------------------+
1907 // | | Floating-point register save area |
1908 // | +-----------------------------------+
1909 // | | General register save area |
1910 // | +-----------------------------------+
1911 // | | CR save word |
1912 // | +-----------------------------------+
1913 // | | VRSAVE save word |
1914 // | +-----------------------------------+
1915 // | | Alignment padding |
1916 // | +-----------------------------------+
1917 // | | Vector register save area |
1918 // | +-----------------------------------+
1919 // | | Local variable space |
1920 // | +-----------------------------------+
1921 // | | Parameter list area |
1922 // | +-----------------------------------+
1923 // | | LR save word |
1924 // | +-----------------------------------+
1925 // SP--> +--- | Back chain |
1926 // +-----------------------------------+
1929 // System V Application Binary Interface PowerPC Processor Supplement
1930 // AltiVec Technology Programming Interface Manual
1932 MachineFunction &MF = DAG.getMachineFunction();
1933 MachineFrameInfo *MFI = MF.getFrameInfo();
1934 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1936 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1937 // Potential tail calls could cause overwriting of argument stack slots.
1938 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1939 (CallConv == CallingConv::Fast));
1940 unsigned PtrByteSize = 4;
1942 // Assign locations to all of the incoming arguments.
1943 SmallVector<CCValAssign, 16> ArgLocs;
1944 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1945 getTargetMachine(), ArgLocs, *DAG.getContext());
1947 // Reserve space for the linkage area on the stack.
1948 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1950 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
1952 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1953 CCValAssign &VA = ArgLocs[i];
1955 // Arguments stored in registers.
1956 if (VA.isRegLoc()) {
1957 const TargetRegisterClass *RC;
1958 EVT ValVT = VA.getValVT();
1960 switch (ValVT.getSimpleVT().SimpleTy) {
1962 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1964 RC = &PPC::GPRCRegClass;
1967 RC = &PPC::F4RCRegClass;
1970 RC = &PPC::F8RCRegClass;
1976 RC = &PPC::VRRCRegClass;
1980 // Transform the arguments stored in physical registers into virtual ones.
1981 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1982 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1984 InVals.push_back(ArgValue);
1986 // Argument stored in memory.
1987 assert(VA.isMemLoc());
1989 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1990 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1993 // Create load nodes to retrieve arguments from the stack.
1994 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1995 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1996 MachinePointerInfo(),
1997 false, false, false, 0));
2001 // Assign locations to all of the incoming aggregate by value arguments.
2002 // Aggregates passed by value are stored in the local variable space of the
2003 // caller's stack frame, right above the parameter list area.
2004 SmallVector<CCValAssign, 16> ByValArgLocs;
2005 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2006 getTargetMachine(), ByValArgLocs, *DAG.getContext());
2008 // Reserve stack space for the allocations in CCInfo.
2009 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2011 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2013 // Area that is at least reserved in the caller of this function.
2014 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2016 // Set the size that is at least reserved in caller of this function. Tail
2017 // call optimized function's reserved stack space needs to be aligned so that
2018 // taking the difference between two stack areas will result in an aligned
2020 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2023 std::max(MinReservedArea,
2024 PPCFrameLowering::getMinCallFrameSize(false, false));
2026 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
2027 getStackAlignment();
2028 unsigned AlignMask = TargetAlign-1;
2029 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2031 FI->setMinReservedArea(MinReservedArea);
2033 SmallVector<SDValue, 8> MemOps;
2035 // If the function takes variable number of arguments, make a frame index for
2036 // the start of the first vararg value... for expansion of llvm.va_start.
2038 static const uint16_t GPArgRegs[] = {
2039 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2040 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2042 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2044 static const uint16_t FPArgRegs[] = {
2045 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2048 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2050 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2052 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2055 // Make room for NumGPArgRegs and NumFPArgRegs.
2056 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2057 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2059 FuncInfo->setVarArgsStackOffset(
2060 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2061 CCInfo.getNextStackOffset(), true));
2063 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2064 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2066 // The fixed integer arguments of a variadic function are stored to the
2067 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2068 // the result of va_next.
2069 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2070 // Get an existing live-in vreg, or add a new one.
2071 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2073 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2075 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2076 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2077 MachinePointerInfo(), false, false, 0);
2078 MemOps.push_back(Store);
2079 // Increment the address by four for the next argument to store
2080 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2081 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2084 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2086 // The double arguments are stored to the VarArgsFrameIndex
2088 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2089 // Get an existing live-in vreg, or add a new one.
2090 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2092 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2094 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2095 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2096 MachinePointerInfo(), false, false, 0);
2097 MemOps.push_back(Store);
2098 // Increment the address by eight for the next argument to store
2099 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2101 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2105 if (!MemOps.empty())
2106 Chain = DAG.getNode(ISD::TokenFactor, dl,
2107 MVT::Other, &MemOps[0], MemOps.size());
2112 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2113 // value to MVT::i64 and then truncate to the correct register size.
2115 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2116 SelectionDAG &DAG, SDValue ArgVal,
2117 DebugLoc dl) const {
2119 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2120 DAG.getValueType(ObjectVT));
2121 else if (Flags.isZExt())
2122 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2123 DAG.getValueType(ObjectVT));
2125 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2128 // Set the size that is at least reserved in caller of this function. Tail
2129 // call optimized functions' reserved stack space needs to be aligned so that
2130 // taking the difference between two stack areas will result in an aligned
2133 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2134 unsigned nAltivecParamsAtEnd,
2135 unsigned MinReservedArea,
2136 bool isPPC64) const {
2137 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2138 // Add the Altivec parameters at the end, if needed.
2139 if (nAltivecParamsAtEnd) {
2140 MinReservedArea = ((MinReservedArea+15)/16)*16;
2141 MinReservedArea += 16*nAltivecParamsAtEnd;
2144 std::max(MinReservedArea,
2145 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2146 unsigned TargetAlign
2147 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2148 getStackAlignment();
2149 unsigned AlignMask = TargetAlign-1;
2150 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2151 FI->setMinReservedArea(MinReservedArea);
2155 PPCTargetLowering::LowerFormalArguments_64SVR4(
2157 CallingConv::ID CallConv, bool isVarArg,
2158 const SmallVectorImpl<ISD::InputArg>
2160 DebugLoc dl, SelectionDAG &DAG,
2161 SmallVectorImpl<SDValue> &InVals) const {
2162 // TODO: add description of PPC stack frame format, or at least some docs.
2164 MachineFunction &MF = DAG.getMachineFunction();
2165 MachineFrameInfo *MFI = MF.getFrameInfo();
2166 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2168 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2169 // Potential tail calls could cause overwriting of argument stack slots.
2170 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2171 (CallConv == CallingConv::Fast));
2172 unsigned PtrByteSize = 8;
2174 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2175 // Area that is at least reserved in caller of this function.
2176 unsigned MinReservedArea = ArgOffset;
2178 static const uint16_t GPR[] = {
2179 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2180 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2183 static const uint16_t *FPR = GetFPR();
2185 static const uint16_t VR[] = {
2186 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2187 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2190 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2191 const unsigned Num_FPR_Regs = 13;
2192 const unsigned Num_VR_Regs = array_lengthof(VR);
2194 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2196 // Add DAG nodes to load the arguments or copy them out of registers. On
2197 // entry to a function on PPC, the arguments start after the linkage area,
2198 // although the first ones are often in registers.
2200 SmallVector<SDValue, 8> MemOps;
2201 unsigned nAltivecParamsAtEnd = 0;
2202 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2203 unsigned CurArgIdx = 0;
2204 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2206 bool needsLoad = false;
2207 EVT ObjectVT = Ins[ArgNo].VT;
2208 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2209 unsigned ArgSize = ObjSize;
2210 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2211 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2212 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2214 unsigned CurArgOffset = ArgOffset;
2216 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2217 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2218 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2220 MinReservedArea = ((MinReservedArea+15)/16)*16;
2221 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2225 nAltivecParamsAtEnd++;
2227 // Calculate min reserved area.
2228 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2232 // FIXME the codegen can be much improved in some cases.
2233 // We do not have to keep everything in memory.
2234 if (Flags.isByVal()) {
2235 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2236 ObjSize = Flags.getByValSize();
2237 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2238 // Empty aggregate parameters do not take up registers. Examples:
2242 // etc. However, we have to provide a place-holder in InVals, so
2243 // pretend we have an 8-byte item at the current address for that
2246 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2247 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2248 InVals.push_back(FIN);
2251 // All aggregates smaller than 8 bytes must be passed right-justified.
2252 if (ObjSize < PtrByteSize)
2253 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2254 // The value of the object is its address.
2255 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2256 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2257 InVals.push_back(FIN);
2260 if (GPR_idx != Num_GPR_Regs) {
2261 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2262 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2265 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2266 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2267 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2268 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2269 MachinePointerInfo(FuncArg, CurArgOffset),
2270 ObjType, false, false, 0);
2272 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2273 // store the whole register as-is to the parameter save area
2274 // slot. The address of the parameter was already calculated
2275 // above (InVals.push_back(FIN)) to be the right-justified
2276 // offset within the slot. For this store, we need a new
2277 // frame index that points at the beginning of the slot.
2278 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2279 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2280 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2281 MachinePointerInfo(FuncArg, ArgOffset),
2285 MemOps.push_back(Store);
2288 // Whether we copied from a register or not, advance the offset
2289 // into the parameter save area by a full doubleword.
2290 ArgOffset += PtrByteSize;
2294 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2295 // Store whatever pieces of the object are in registers
2296 // to memory. ArgOffset will be the address of the beginning
2298 if (GPR_idx != Num_GPR_Regs) {
2300 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2301 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2302 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2303 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2304 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2305 MachinePointerInfo(FuncArg, ArgOffset),
2307 MemOps.push_back(Store);
2309 ArgOffset += PtrByteSize;
2311 ArgOffset += ArgSize - j;
2318 switch (ObjectVT.getSimpleVT().SimpleTy) {
2319 default: llvm_unreachable("Unhandled argument type!");
2322 if (GPR_idx != Num_GPR_Regs) {
2323 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2324 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2326 if (ObjectVT == MVT::i32)
2327 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2328 // value to MVT::i64 and then truncate to the correct register size.
2329 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2334 ArgSize = PtrByteSize;
2341 // Every 8 bytes of argument space consumes one of the GPRs available for
2342 // argument passing.
2343 if (GPR_idx != Num_GPR_Regs) {
2346 if (FPR_idx != Num_FPR_Regs) {
2349 if (ObjectVT == MVT::f32)
2350 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2352 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2354 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2358 ArgSize = PtrByteSize;
2367 // Note that vector arguments in registers don't reserve stack space,
2368 // except in varargs functions.
2369 if (VR_idx != Num_VR_Regs) {
2370 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2371 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2373 while ((ArgOffset % 16) != 0) {
2374 ArgOffset += PtrByteSize;
2375 if (GPR_idx != Num_GPR_Regs)
2379 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2383 // Vectors are aligned.
2384 ArgOffset = ((ArgOffset+15)/16)*16;
2385 CurArgOffset = ArgOffset;
2392 // We need to load the argument to a virtual register if we determined
2393 // above that we ran out of physical registers of the appropriate type.
2395 int FI = MFI->CreateFixedObject(ObjSize,
2396 CurArgOffset + (ArgSize - ObjSize),
2398 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2399 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2400 false, false, false, 0);
2403 InVals.push_back(ArgVal);
2406 // Set the size that is at least reserved in caller of this function. Tail
2407 // call optimized functions' reserved stack space needs to be aligned so that
2408 // taking the difference between two stack areas will result in an aligned
2410 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2412 // If the function takes variable number of arguments, make a frame index for
2413 // the start of the first vararg value... for expansion of llvm.va_start.
2415 int Depth = ArgOffset;
2417 FuncInfo->setVarArgsFrameIndex(
2418 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2419 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2421 // If this function is vararg, store any remaining integer argument regs
2422 // to their spots on the stack so that they may be loaded by deferencing the
2423 // result of va_next.
2424 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2425 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2426 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2427 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2428 MachinePointerInfo(), false, false, 0);
2429 MemOps.push_back(Store);
2430 // Increment the address by four for the next argument to store
2431 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2432 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2436 if (!MemOps.empty())
2437 Chain = DAG.getNode(ISD::TokenFactor, dl,
2438 MVT::Other, &MemOps[0], MemOps.size());
2444 PPCTargetLowering::LowerFormalArguments_Darwin(
2446 CallingConv::ID CallConv, bool isVarArg,
2447 const SmallVectorImpl<ISD::InputArg>
2449 DebugLoc dl, SelectionDAG &DAG,
2450 SmallVectorImpl<SDValue> &InVals) const {
2451 // TODO: add description of PPC stack frame format, or at least some docs.
2453 MachineFunction &MF = DAG.getMachineFunction();
2454 MachineFrameInfo *MFI = MF.getFrameInfo();
2455 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2457 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2458 bool isPPC64 = PtrVT == MVT::i64;
2459 // Potential tail calls could cause overwriting of argument stack slots.
2460 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2461 (CallConv == CallingConv::Fast));
2462 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2464 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2465 // Area that is at least reserved in caller of this function.
2466 unsigned MinReservedArea = ArgOffset;
2468 static const uint16_t GPR_32[] = { // 32-bit registers.
2469 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2470 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2472 static const uint16_t GPR_64[] = { // 64-bit registers.
2473 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2474 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2477 static const uint16_t *FPR = GetFPR();
2479 static const uint16_t VR[] = {
2480 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2481 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2484 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2485 const unsigned Num_FPR_Regs = 13;
2486 const unsigned Num_VR_Regs = array_lengthof( VR);
2488 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2490 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2492 // In 32-bit non-varargs functions, the stack space for vectors is after the
2493 // stack space for non-vectors. We do not use this space unless we have
2494 // too many vectors to fit in registers, something that only occurs in
2495 // constructed examples:), but we have to walk the arglist to figure
2496 // that out...for the pathological case, compute VecArgOffset as the
2497 // start of the vector parameter area. Computing VecArgOffset is the
2498 // entire point of the following loop.
2499 unsigned VecArgOffset = ArgOffset;
2500 if (!isVarArg && !isPPC64) {
2501 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2503 EVT ObjectVT = Ins[ArgNo].VT;
2504 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2506 if (Flags.isByVal()) {
2507 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2508 unsigned ObjSize = Flags.getByValSize();
2510 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2511 VecArgOffset += ArgSize;
2515 switch(ObjectVT.getSimpleVT().SimpleTy) {
2516 default: llvm_unreachable("Unhandled argument type!");
2521 case MVT::i64: // PPC64
2523 // FIXME: We are guaranteed to be !isPPC64 at this point.
2524 // Does MVT::i64 apply?
2531 // Nothing to do, we're only looking at Nonvector args here.
2536 // We've found where the vector parameter area in memory is. Skip the
2537 // first 12 parameters; these don't use that memory.
2538 VecArgOffset = ((VecArgOffset+15)/16)*16;
2539 VecArgOffset += 12*16;
2541 // Add DAG nodes to load the arguments or copy them out of registers. On
2542 // entry to a function on PPC, the arguments start after the linkage area,
2543 // although the first ones are often in registers.
2545 SmallVector<SDValue, 8> MemOps;
2546 unsigned nAltivecParamsAtEnd = 0;
2547 // FIXME: FuncArg and Ins[ArgNo] must reference the same argument.
2548 // When passing anonymous aggregates, this is currently not true.
2549 // See LowerFormalArguments_64SVR4 for a fix.
2550 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2551 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo, ++FuncArg) {
2553 bool needsLoad = false;
2554 EVT ObjectVT = Ins[ArgNo].VT;
2555 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2556 unsigned ArgSize = ObjSize;
2557 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2559 unsigned CurArgOffset = ArgOffset;
2561 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2562 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2563 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2564 if (isVarArg || isPPC64) {
2565 MinReservedArea = ((MinReservedArea+15)/16)*16;
2566 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2569 } else nAltivecParamsAtEnd++;
2571 // Calculate min reserved area.
2572 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2576 // FIXME the codegen can be much improved in some cases.
2577 // We do not have to keep everything in memory.
2578 if (Flags.isByVal()) {
2579 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2580 ObjSize = Flags.getByValSize();
2581 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2582 // Objects of size 1 and 2 are right justified, everything else is
2583 // left justified. This means the memory address is adjusted forwards.
2584 if (ObjSize==1 || ObjSize==2) {
2585 CurArgOffset = CurArgOffset + (4 - ObjSize);
2587 // The value of the object is its address.
2588 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2589 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2590 InVals.push_back(FIN);
2591 if (ObjSize==1 || ObjSize==2) {
2592 if (GPR_idx != Num_GPR_Regs) {
2595 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2597 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2598 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2599 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2600 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2601 MachinePointerInfo(FuncArg,
2603 ObjType, false, false, 0);
2604 MemOps.push_back(Store);
2608 ArgOffset += PtrByteSize;
2612 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2613 // Store whatever pieces of the object are in registers
2614 // to memory. ArgOffset will be the address of the beginning
2616 if (GPR_idx != Num_GPR_Regs) {
2619 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2621 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2622 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2623 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2624 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2625 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2626 MachinePointerInfo(FuncArg, ArgOffset),
2628 MemOps.push_back(Store);
2630 ArgOffset += PtrByteSize;
2632 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2639 switch (ObjectVT.getSimpleVT().SimpleTy) {
2640 default: llvm_unreachable("Unhandled argument type!");
2643 if (GPR_idx != Num_GPR_Regs) {
2644 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2645 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2649 ArgSize = PtrByteSize;
2651 // All int arguments reserve stack space in the Darwin ABI.
2652 ArgOffset += PtrByteSize;
2656 case MVT::i64: // PPC64
2657 if (GPR_idx != Num_GPR_Regs) {
2658 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2659 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2661 if (ObjectVT == MVT::i32)
2662 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2663 // value to MVT::i64 and then truncate to the correct register size.
2664 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2669 ArgSize = PtrByteSize;
2671 // All int arguments reserve stack space in the Darwin ABI.
2677 // Every 4 bytes of argument space consumes one of the GPRs available for
2678 // argument passing.
2679 if (GPR_idx != Num_GPR_Regs) {
2681 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2684 if (FPR_idx != Num_FPR_Regs) {
2687 if (ObjectVT == MVT::f32)
2688 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2690 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2692 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2698 // All FP arguments reserve stack space in the Darwin ABI.
2699 ArgOffset += isPPC64 ? 8 : ObjSize;
2705 // Note that vector arguments in registers don't reserve stack space,
2706 // except in varargs functions.
2707 if (VR_idx != Num_VR_Regs) {
2708 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2709 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2711 while ((ArgOffset % 16) != 0) {
2712 ArgOffset += PtrByteSize;
2713 if (GPR_idx != Num_GPR_Regs)
2717 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2721 if (!isVarArg && !isPPC64) {
2722 // Vectors go after all the nonvectors.
2723 CurArgOffset = VecArgOffset;
2726 // Vectors are aligned.
2727 ArgOffset = ((ArgOffset+15)/16)*16;
2728 CurArgOffset = ArgOffset;
2736 // We need to load the argument to a virtual register if we determined above
2737 // that we ran out of physical registers of the appropriate type.
2739 int FI = MFI->CreateFixedObject(ObjSize,
2740 CurArgOffset + (ArgSize - ObjSize),
2742 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2743 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2744 false, false, false, 0);
2747 InVals.push_back(ArgVal);
2750 // Set the size that is at least reserved in caller of this function. Tail
2751 // call optimized functions' reserved stack space needs to be aligned so that
2752 // taking the difference between two stack areas will result in an aligned
2754 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2756 // If the function takes variable number of arguments, make a frame index for
2757 // the start of the first vararg value... for expansion of llvm.va_start.
2759 int Depth = ArgOffset;
2761 FuncInfo->setVarArgsFrameIndex(
2762 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2764 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2766 // If this function is vararg, store any remaining integer argument regs
2767 // to their spots on the stack so that they may be loaded by deferencing the
2768 // result of va_next.
2769 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2773 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2775 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2777 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2778 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2779 MachinePointerInfo(), false, false, 0);
2780 MemOps.push_back(Store);
2781 // Increment the address by four for the next argument to store
2782 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2783 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2787 if (!MemOps.empty())
2788 Chain = DAG.getNode(ISD::TokenFactor, dl,
2789 MVT::Other, &MemOps[0], MemOps.size());
2794 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2795 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2797 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2801 const SmallVectorImpl<ISD::OutputArg>
2803 const SmallVectorImpl<SDValue> &OutVals,
2804 unsigned &nAltivecParamsAtEnd) {
2805 // Count how many bytes are to be pushed on the stack, including the linkage
2806 // area, and parameter passing area. We start with 24/48 bytes, which is
2807 // prereserved space for [SP][CR][LR][3 x unused].
2808 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2809 unsigned NumOps = Outs.size();
2810 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2812 // Add up all the space actually used.
2813 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2814 // they all go in registers, but we must reserve stack space for them for
2815 // possible use by the caller. In varargs or 64-bit calls, parameters are
2816 // assigned stack space in order, with padding so Altivec parameters are
2818 nAltivecParamsAtEnd = 0;
2819 for (unsigned i = 0; i != NumOps; ++i) {
2820 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2821 EVT ArgVT = Outs[i].VT;
2822 // Varargs Altivec parameters are padded to a 16 byte boundary.
2823 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2824 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2825 if (!isVarArg && !isPPC64) {
2826 // Non-varargs Altivec parameters go after all the non-Altivec
2827 // parameters; handle those later so we know how much padding we need.
2828 nAltivecParamsAtEnd++;
2831 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2832 NumBytes = ((NumBytes+15)/16)*16;
2834 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2837 // Allow for Altivec parameters at the end, if needed.
2838 if (nAltivecParamsAtEnd) {
2839 NumBytes = ((NumBytes+15)/16)*16;
2840 NumBytes += 16*nAltivecParamsAtEnd;
2843 // The prolog code of the callee may store up to 8 GPR argument registers to
2844 // the stack, allowing va_start to index over them in memory if its varargs.
2845 // Because we cannot tell if this is needed on the caller side, we have to
2846 // conservatively assume that it is needed. As such, make sure we have at
2847 // least enough stack space for the caller to store the 8 GPRs.
2848 NumBytes = std::max(NumBytes,
2849 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2851 // Tail call needs the stack to be aligned.
2852 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2853 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2854 getFrameLowering()->getStackAlignment();
2855 unsigned AlignMask = TargetAlign-1;
2856 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2862 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2863 /// adjusted to accommodate the arguments for the tailcall.
2864 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2865 unsigned ParamSize) {
2867 if (!isTailCall) return 0;
2869 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2870 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2871 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2872 // Remember only if the new adjustement is bigger.
2873 if (SPDiff < FI->getTailCallSPDelta())
2874 FI->setTailCallSPDelta(SPDiff);
2879 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2880 /// for tail call optimization. Targets which want to do tail call
2881 /// optimization should implement this function.
2883 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2884 CallingConv::ID CalleeCC,
2886 const SmallVectorImpl<ISD::InputArg> &Ins,
2887 SelectionDAG& DAG) const {
2888 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2891 // Variable argument functions are not supported.
2895 MachineFunction &MF = DAG.getMachineFunction();
2896 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2897 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2898 // Functions containing by val parameters are not supported.
2899 for (unsigned i = 0; i != Ins.size(); i++) {
2900 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2901 if (Flags.isByVal()) return false;
2904 // Non PIC/GOT tail calls are supported.
2905 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2908 // At the moment we can only do local tail calls (in same module, hidden
2909 // or protected) if we are generating PIC.
2910 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2911 return G->getGlobal()->hasHiddenVisibility()
2912 || G->getGlobal()->hasProtectedVisibility();
2918 /// isCallCompatibleAddress - Return the immediate to use if the specified
2919 /// 32-bit value is representable in the immediate field of a BxA instruction.
2920 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2921 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2924 int Addr = C->getZExtValue();
2925 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2926 SignExtend32<26>(Addr) != Addr)
2927 return 0; // Top 6 bits have to be sext of immediate.
2929 return DAG.getConstant((int)C->getZExtValue() >> 2,
2930 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2935 struct TailCallArgumentInfo {
2940 TailCallArgumentInfo() : FrameIdx(0) {}
2945 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2947 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2949 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2950 SmallVector<SDValue, 8> &MemOpChains,
2952 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2953 SDValue Arg = TailCallArgs[i].Arg;
2954 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2955 int FI = TailCallArgs[i].FrameIdx;
2956 // Store relative to framepointer.
2957 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2958 MachinePointerInfo::getFixedStack(FI),
2963 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2964 /// the appropriate stack slot for the tail call optimized function call.
2965 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2966 MachineFunction &MF,
2975 // Calculate the new stack slot for the return address.
2976 int SlotSize = isPPC64 ? 8 : 4;
2977 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2979 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2980 NewRetAddrLoc, true);
2981 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2982 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2983 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2984 MachinePointerInfo::getFixedStack(NewRetAddr),
2987 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2988 // slot as the FP is never overwritten.
2991 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2992 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2994 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2995 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2996 MachinePointerInfo::getFixedStack(NewFPIdx),
3003 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3004 /// the position of the argument.
3006 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3007 SDValue Arg, int SPDiff, unsigned ArgOffset,
3008 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
3009 int Offset = ArgOffset + SPDiff;
3010 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3011 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3012 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3013 SDValue FIN = DAG.getFrameIndex(FI, VT);
3014 TailCallArgumentInfo Info;
3016 Info.FrameIdxOp = FIN;
3018 TailCallArguments.push_back(Info);
3021 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3022 /// stack slot. Returns the chain as result and the loaded frame pointers in
3023 /// LROpOut/FPOpout. Used when tail calling.
3024 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3030 DebugLoc dl) const {
3032 // Load the LR and FP stack slot for later adjusting.
3033 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3034 LROpOut = getReturnAddrFrameIndex(DAG);
3035 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3036 false, false, false, 0);
3037 Chain = SDValue(LROpOut.getNode(), 1);
3039 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3040 // slot as the FP is never overwritten.
3042 FPOpOut = getFramePointerFrameIndex(DAG);
3043 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3044 false, false, false, 0);
3045 Chain = SDValue(FPOpOut.getNode(), 1);
3051 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3052 /// by "Src" to address "Dst" of size "Size". Alignment information is
3053 /// specified by the specific parameter attribute. The copy will be passed as
3054 /// a byval function parameter.
3055 /// Sometimes what we are copying is the end of a larger object, the part that
3056 /// does not fit in registers.
3058 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3059 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3061 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3062 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3063 false, false, MachinePointerInfo(0),
3064 MachinePointerInfo(0));
3067 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3070 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3071 SDValue Arg, SDValue PtrOff, int SPDiff,
3072 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3073 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3074 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3076 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3081 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3083 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3084 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3085 DAG.getConstant(ArgOffset, PtrVT));
3087 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3088 MachinePointerInfo(), false, false, 0));
3089 // Calculate and remember argument location.
3090 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3095 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3096 DebugLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3097 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3098 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3099 MachineFunction &MF = DAG.getMachineFunction();
3101 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3102 // might overwrite each other in case of tail call optimization.
3103 SmallVector<SDValue, 8> MemOpChains2;
3104 // Do not flag preceding copytoreg stuff together with the following stuff.
3106 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3108 if (!MemOpChains2.empty())
3109 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3110 &MemOpChains2[0], MemOpChains2.size());
3112 // Store the return address to the appropriate stack slot.
3113 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3114 isPPC64, isDarwinABI, dl);
3116 // Emit callseq_end just before tailcall node.
3117 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3118 DAG.getIntPtrConstant(0, true), InFlag);
3119 InFlag = Chain.getValue(1);
3123 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3124 SDValue &Chain, DebugLoc dl, int SPDiff, bool isTailCall,
3125 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3126 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3127 const PPCSubtarget &PPCSubTarget) {
3129 bool isPPC64 = PPCSubTarget.isPPC64();
3130 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3132 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3133 NodeTys.push_back(MVT::Other); // Returns a chain
3134 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3136 unsigned CallOpc = PPCISD::CALL;
3138 bool needIndirectCall = true;
3139 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3140 // If this is an absolute destination address, use the munged value.
3141 Callee = SDValue(Dest, 0);
3142 needIndirectCall = false;
3145 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3146 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3147 // Use indirect calls for ALL functions calls in JIT mode, since the
3148 // far-call stubs may be outside relocation limits for a BL instruction.
3149 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3150 unsigned OpFlags = 0;
3151 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3152 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3153 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3154 (G->getGlobal()->isDeclaration() ||
3155 G->getGlobal()->isWeakForLinker())) {
3156 // PC-relative references to external symbols should go through $stub,
3157 // unless we're building with the leopard linker or later, which
3158 // automatically synthesizes these stubs.
3159 OpFlags = PPCII::MO_DARWIN_STUB;
3162 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3163 // every direct call is) turn it into a TargetGlobalAddress /
3164 // TargetExternalSymbol node so that legalize doesn't hack it.
3165 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3166 Callee.getValueType(),
3168 needIndirectCall = false;
3172 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3173 unsigned char OpFlags = 0;
3175 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3176 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3177 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3178 // PC-relative references to external symbols should go through $stub,
3179 // unless we're building with the leopard linker or later, which
3180 // automatically synthesizes these stubs.
3181 OpFlags = PPCII::MO_DARWIN_STUB;
3184 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3186 needIndirectCall = false;
3189 if (needIndirectCall) {
3190 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3191 // to do the call, we can't use PPCISD::CALL.
3192 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3194 if (isSVR4ABI && isPPC64) {
3195 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3196 // entry point, but to the function descriptor (the function entry point
3197 // address is part of the function descriptor though).
3198 // The function descriptor is a three doubleword structure with the
3199 // following fields: function entry point, TOC base address and
3200 // environment pointer.
3201 // Thus for a call through a function pointer, the following actions need
3203 // 1. Save the TOC of the caller in the TOC save area of its stack
3204 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3205 // 2. Load the address of the function entry point from the function
3207 // 3. Load the TOC of the callee from the function descriptor into r2.
3208 // 4. Load the environment pointer from the function descriptor into
3210 // 5. Branch to the function entry point address.
3211 // 6. On return of the callee, the TOC of the caller needs to be
3212 // restored (this is done in FinishCall()).
3214 // All those operations are flagged together to ensure that no other
3215 // operations can be scheduled in between. E.g. without flagging the
3216 // operations together, a TOC access in the caller could be scheduled
3217 // between the load of the callee TOC and the branch to the callee, which
3218 // results in the TOC access going through the TOC of the callee instead
3219 // of going through the TOC of the caller, which leads to incorrect code.
3221 // Load the address of the function entry point from the function
3223 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3224 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3225 InFlag.getNode() ? 3 : 2);
3226 Chain = LoadFuncPtr.getValue(1);
3227 InFlag = LoadFuncPtr.getValue(2);
3229 // Load environment pointer into r11.
3230 // Offset of the environment pointer within the function descriptor.
3231 SDValue PtrOff = DAG.getIntPtrConstant(16);
3233 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3234 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3236 Chain = LoadEnvPtr.getValue(1);
3237 InFlag = LoadEnvPtr.getValue(2);
3239 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3241 Chain = EnvVal.getValue(0);
3242 InFlag = EnvVal.getValue(1);
3244 // Load TOC of the callee into r2. We are using a target-specific load
3245 // with r2 hard coded, because the result of a target-independent load
3246 // would never go directly into r2, since r2 is a reserved register (which
3247 // prevents the register allocator from allocating it), resulting in an
3248 // additional register being allocated and an unnecessary move instruction
3250 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3251 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3253 Chain = LoadTOCPtr.getValue(0);
3254 InFlag = LoadTOCPtr.getValue(1);
3256 MTCTROps[0] = Chain;
3257 MTCTROps[1] = LoadFuncPtr;
3258 MTCTROps[2] = InFlag;
3261 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3262 2 + (InFlag.getNode() != 0));
3263 InFlag = Chain.getValue(1);
3266 NodeTys.push_back(MVT::Other);
3267 NodeTys.push_back(MVT::Glue);
3268 Ops.push_back(Chain);
3269 CallOpc = PPCISD::BCTRL;
3271 // Add use of X11 (holding environment pointer)
3272 if (isSVR4ABI && isPPC64)
3273 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3274 // Add CTR register as callee so a bctr can be emitted later.
3276 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3279 // If this is a direct call, pass the chain and the callee.
3280 if (Callee.getNode()) {
3281 Ops.push_back(Chain);
3282 Ops.push_back(Callee);
3284 // If this is a tail call add stack pointer delta.
3286 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3288 // Add argument registers to the end of the list so that they are known live
3290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3291 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3292 RegsToPass[i].second.getValueType()));
3298 bool isLocalCall(const SDValue &Callee)
3300 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3301 return !G->getGlobal()->isDeclaration() &&
3302 !G->getGlobal()->isWeakForLinker();
3307 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3308 CallingConv::ID CallConv, bool isVarArg,
3309 const SmallVectorImpl<ISD::InputArg> &Ins,
3310 DebugLoc dl, SelectionDAG &DAG,
3311 SmallVectorImpl<SDValue> &InVals) const {
3313 SmallVector<CCValAssign, 16> RVLocs;
3314 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3315 getTargetMachine(), RVLocs, *DAG.getContext());
3316 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3318 // Copy all of the result registers out of their specified physreg.
3319 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3320 CCValAssign &VA = RVLocs[i];
3321 assert(VA.isRegLoc() && "Can only return in registers!");
3323 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3324 VA.getLocReg(), VA.getLocVT(), InFlag);
3325 Chain = Val.getValue(1);
3326 InFlag = Val.getValue(2);
3328 switch (VA.getLocInfo()) {
3329 default: llvm_unreachable("Unknown loc info!");
3330 case CCValAssign::Full: break;
3331 case CCValAssign::AExt:
3332 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3334 case CCValAssign::ZExt:
3335 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3336 DAG.getValueType(VA.getValVT()));
3337 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3339 case CCValAssign::SExt:
3340 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3341 DAG.getValueType(VA.getValVT()));
3342 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3346 InVals.push_back(Val);
3353 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, DebugLoc dl,
3354 bool isTailCall, bool isVarArg,
3356 SmallVector<std::pair<unsigned, SDValue>, 8>
3358 SDValue InFlag, SDValue Chain,
3360 int SPDiff, unsigned NumBytes,
3361 const SmallVectorImpl<ISD::InputArg> &Ins,
3362 SmallVectorImpl<SDValue> &InVals) const {
3363 std::vector<EVT> NodeTys;
3364 SmallVector<SDValue, 8> Ops;
3365 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3366 isTailCall, RegsToPass, Ops, NodeTys,
3369 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3370 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3371 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3373 // When performing tail call optimization the callee pops its arguments off
3374 // the stack. Account for this here so these bytes can be pushed back on in
3375 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3376 int BytesCalleePops =
3377 (CallConv == CallingConv::Fast &&
3378 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3380 // Add a register mask operand representing the call-preserved registers.
3381 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3382 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3383 assert(Mask && "Missing call preserved mask for calling convention");
3384 Ops.push_back(DAG.getRegisterMask(Mask));
3386 if (InFlag.getNode())
3387 Ops.push_back(InFlag);
3391 assert(((Callee.getOpcode() == ISD::Register &&
3392 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3393 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3394 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3395 isa<ConstantSDNode>(Callee)) &&
3396 "Expecting an global address, external symbol, absolute value or register");
3398 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3401 // Add a NOP immediately after the branch instruction when using the 64-bit
3402 // SVR4 ABI. At link time, if caller and callee are in a different module and
3403 // thus have a different TOC, the call will be replaced with a call to a stub
3404 // function which saves the current TOC, loads the TOC of the callee and
3405 // branches to the callee. The NOP will be replaced with a load instruction
3406 // which restores the TOC of the caller from the TOC save slot of the current
3407 // stack frame. If caller and callee belong to the same module (and have the
3408 // same TOC), the NOP will remain unchanged.
3410 bool needsTOCRestore = false;
3411 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3412 if (CallOpc == PPCISD::BCTRL) {
3413 // This is a call through a function pointer.
3414 // Restore the caller TOC from the save area into R2.
3415 // See PrepareCall() for more information about calls through function
3416 // pointers in the 64-bit SVR4 ABI.
3417 // We are using a target-specific load with r2 hard coded, because the
3418 // result of a target-independent load would never go directly into r2,
3419 // since r2 is a reserved register (which prevents the register allocator
3420 // from allocating it), resulting in an additional register being
3421 // allocated and an unnecessary move instruction being generated.
3422 needsTOCRestore = true;
3423 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3424 // Otherwise insert NOP for non-local calls.
3425 CallOpc = PPCISD::CALL_NOP;
3429 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3430 InFlag = Chain.getValue(1);
3432 if (needsTOCRestore) {
3433 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3434 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3435 InFlag = Chain.getValue(1);
3438 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3439 DAG.getIntPtrConstant(BytesCalleePops, true),
3442 InFlag = Chain.getValue(1);
3444 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3445 Ins, dl, DAG, InVals);
3449 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3450 SmallVectorImpl<SDValue> &InVals) const {
3451 SelectionDAG &DAG = CLI.DAG;
3452 DebugLoc &dl = CLI.DL;
3453 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3454 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3455 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3456 SDValue Chain = CLI.Chain;
3457 SDValue Callee = CLI.Callee;
3458 bool &isTailCall = CLI.IsTailCall;
3459 CallingConv::ID CallConv = CLI.CallConv;
3460 bool isVarArg = CLI.IsVarArg;
3463 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3466 if (PPCSubTarget.isSVR4ABI()) {
3467 if (PPCSubTarget.isPPC64())
3468 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3469 isTailCall, Outs, OutVals, Ins,
3472 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3473 isTailCall, Outs, OutVals, Ins,
3477 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3478 isTailCall, Outs, OutVals, Ins,
3483 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3484 CallingConv::ID CallConv, bool isVarArg,
3486 const SmallVectorImpl<ISD::OutputArg> &Outs,
3487 const SmallVectorImpl<SDValue> &OutVals,
3488 const SmallVectorImpl<ISD::InputArg> &Ins,
3489 DebugLoc dl, SelectionDAG &DAG,
3490 SmallVectorImpl<SDValue> &InVals) const {
3491 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3492 // of the 32-bit SVR4 ABI stack frame layout.
3494 assert((CallConv == CallingConv::C ||
3495 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3497 unsigned PtrByteSize = 4;
3499 MachineFunction &MF = DAG.getMachineFunction();
3501 // Mark this function as potentially containing a function that contains a
3502 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3503 // and restoring the callers stack pointer in this functions epilog. This is
3504 // done because by tail calling the called function might overwrite the value
3505 // in this function's (MF) stack pointer stack slot 0(SP).
3506 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3507 CallConv == CallingConv::Fast)
3508 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3510 // Count how many bytes are to be pushed on the stack, including the linkage
3511 // area, parameter list area and the part of the local variable space which
3512 // contains copies of aggregates which are passed by value.
3514 // Assign locations to all of the outgoing arguments.
3515 SmallVector<CCValAssign, 16> ArgLocs;
3516 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3517 getTargetMachine(), ArgLocs, *DAG.getContext());
3519 // Reserve space for the linkage area on the stack.
3520 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3523 // Handle fixed and variable vector arguments differently.
3524 // Fixed vector arguments go into registers as long as registers are
3525 // available. Variable vector arguments always go into memory.
3526 unsigned NumArgs = Outs.size();
3528 for (unsigned i = 0; i != NumArgs; ++i) {
3529 MVT ArgVT = Outs[i].VT;
3530 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3533 if (Outs[i].IsFixed) {
3534 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3537 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3543 errs() << "Call operand #" << i << " has unhandled type "
3544 << EVT(ArgVT).getEVTString() << "\n";
3546 llvm_unreachable(0);
3550 // All arguments are treated the same.
3551 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3554 // Assign locations to all of the outgoing aggregate by value arguments.
3555 SmallVector<CCValAssign, 16> ByValArgLocs;
3556 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3557 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3559 // Reserve stack space for the allocations in CCInfo.
3560 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3562 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3564 // Size of the linkage area, parameter list area and the part of the local
3565 // space variable where copies of aggregates which are passed by value are
3567 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3569 // Calculate by how many bytes the stack has to be adjusted in case of tail
3570 // call optimization.
3571 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3573 // Adjust the stack pointer for the new arguments...
3574 // These operations are automatically eliminated by the prolog/epilog pass
3575 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3576 SDValue CallSeqStart = Chain;
3578 // Load the return address and frame pointer so it can be moved somewhere else
3581 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3584 // Set up a copy of the stack pointer for use loading and storing any
3585 // arguments that may not fit in the registers available for argument
3587 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3589 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3590 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3591 SmallVector<SDValue, 8> MemOpChains;
3593 bool seenFloatArg = false;
3594 // Walk the register/memloc assignments, inserting copies/loads.
3595 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3598 CCValAssign &VA = ArgLocs[i];
3599 SDValue Arg = OutVals[i];
3600 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3602 if (Flags.isByVal()) {
3603 // Argument is an aggregate which is passed by value, thus we need to
3604 // create a copy of it in the local variable space of the current stack
3605 // frame (which is the stack frame of the caller) and pass the address of
3606 // this copy to the callee.
3607 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3608 CCValAssign &ByValVA = ByValArgLocs[j++];
3609 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3611 // Memory reserved in the local variable space of the callers stack frame.
3612 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3614 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3615 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3617 // Create a copy of the argument in the local area of the current
3619 SDValue MemcpyCall =
3620 CreateCopyOfByValArgument(Arg, PtrOff,
3621 CallSeqStart.getNode()->getOperand(0),
3624 // This must go outside the CALLSEQ_START..END.
3625 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3626 CallSeqStart.getNode()->getOperand(1));
3627 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3628 NewCallSeqStart.getNode());
3629 Chain = CallSeqStart = NewCallSeqStart;
3631 // Pass the address of the aggregate copy on the stack either in a
3632 // physical register or in the parameter list area of the current stack
3633 // frame to the callee.
3637 if (VA.isRegLoc()) {
3638 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3639 // Put argument in a physical register.
3640 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3642 // Put argument in the parameter list area of the current stack frame.
3643 assert(VA.isMemLoc());
3644 unsigned LocMemOffset = VA.getLocMemOffset();
3647 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3648 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3650 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3651 MachinePointerInfo(),
3654 // Calculate and remember argument location.
3655 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3661 if (!MemOpChains.empty())
3662 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3663 &MemOpChains[0], MemOpChains.size());
3665 // Build a sequence of copy-to-reg nodes chained together with token chain
3666 // and flag operands which copy the outgoing args into the appropriate regs.
3668 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3669 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3670 RegsToPass[i].second, InFlag);
3671 InFlag = Chain.getValue(1);
3674 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3677 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3678 SDValue Ops[] = { Chain, InFlag };
3680 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3681 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3683 InFlag = Chain.getValue(1);
3687 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3688 false, TailCallArguments);
3690 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3691 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3695 // Copy an argument into memory, being careful to do this outside the
3696 // call sequence for the call to which the argument belongs.
3698 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3699 SDValue CallSeqStart,
3700 ISD::ArgFlagsTy Flags,
3702 DebugLoc dl) const {
3703 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3704 CallSeqStart.getNode()->getOperand(0),
3706 // The MEMCPY must go outside the CALLSEQ_START..END.
3707 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3708 CallSeqStart.getNode()->getOperand(1));
3709 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3710 NewCallSeqStart.getNode());
3711 return NewCallSeqStart;
3715 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3716 CallingConv::ID CallConv, bool isVarArg,
3718 const SmallVectorImpl<ISD::OutputArg> &Outs,
3719 const SmallVectorImpl<SDValue> &OutVals,
3720 const SmallVectorImpl<ISD::InputArg> &Ins,
3721 DebugLoc dl, SelectionDAG &DAG,
3722 SmallVectorImpl<SDValue> &InVals) const {
3724 unsigned NumOps = Outs.size();
3726 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3727 unsigned PtrByteSize = 8;
3729 MachineFunction &MF = DAG.getMachineFunction();
3731 // Mark this function as potentially containing a function that contains a
3732 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3733 // and restoring the callers stack pointer in this functions epilog. This is
3734 // done because by tail calling the called function might overwrite the value
3735 // in this function's (MF) stack pointer stack slot 0(SP).
3736 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3737 CallConv == CallingConv::Fast)
3738 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3740 unsigned nAltivecParamsAtEnd = 0;
3742 // Count how many bytes are to be pushed on the stack, including the linkage
3743 // area, and parameter passing area. We start with at least 48 bytes, which
3744 // is reserved space for [SP][CR][LR][3 x unused].
3745 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3748 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3749 Outs, OutVals, nAltivecParamsAtEnd);
3751 // Calculate by how many bytes the stack has to be adjusted in case of tail
3752 // call optimization.
3753 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3755 // To protect arguments on the stack from being clobbered in a tail call,
3756 // force all the loads to happen before doing any other lowering.
3758 Chain = DAG.getStackArgumentTokenFactor(Chain);
3760 // Adjust the stack pointer for the new arguments...
3761 // These operations are automatically eliminated by the prolog/epilog pass
3762 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
3763 SDValue CallSeqStart = Chain;
3765 // Load the return address and frame pointer so it can be move somewhere else
3768 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3771 // Set up a copy of the stack pointer for use loading and storing any
3772 // arguments that may not fit in the registers available for argument
3774 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3776 // Figure out which arguments are going to go in registers, and which in
3777 // memory. Also, if this is a vararg function, floating point operations
3778 // must be stored to our stack, and loaded into integer regs as well, if
3779 // any integer regs are available for argument passing.
3780 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3781 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3783 static const uint16_t GPR[] = {
3784 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3785 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3787 static const uint16_t *FPR = GetFPR();
3789 static const uint16_t VR[] = {
3790 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3791 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3793 const unsigned NumGPRs = array_lengthof(GPR);
3794 const unsigned NumFPRs = 13;
3795 const unsigned NumVRs = array_lengthof(VR);
3797 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3798 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3800 SmallVector<SDValue, 8> MemOpChains;
3801 for (unsigned i = 0; i != NumOps; ++i) {
3802 SDValue Arg = OutVals[i];
3803 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3805 // PtrOff will be used to store the current argument to the stack if a
3806 // register cannot be found for it.
3809 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3811 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3813 // Promote integers to 64-bit values.
3814 if (Arg.getValueType() == MVT::i32) {
3815 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3816 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3817 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3820 // FIXME memcpy is used way more than necessary. Correctness first.
3821 // Note: "by value" is code for passing a structure by value, not
3823 if (Flags.isByVal()) {
3824 // Note: Size includes alignment padding, so
3825 // struct x { short a; char b; }
3826 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3827 // These are the proper values we need for right-justifying the
3828 // aggregate in a parameter register.
3829 unsigned Size = Flags.getByValSize();
3831 // An empty aggregate parameter takes up no storage and no
3836 // All aggregates smaller than 8 bytes must be passed right-justified.
3837 if (Size==1 || Size==2 || Size==4) {
3838 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3839 if (GPR_idx != NumGPRs) {
3840 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3841 MachinePointerInfo(), VT,
3843 MemOpChains.push_back(Load.getValue(1));
3844 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3846 ArgOffset += PtrByteSize;
3851 if (GPR_idx == NumGPRs && Size < 8) {
3852 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3853 PtrOff.getValueType());
3854 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3855 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3858 ArgOffset += PtrByteSize;
3861 // Copy entire object into memory. There are cases where gcc-generated
3862 // code assumes it is there, even if it could be put entirely into
3863 // registers. (This is not what the doc says.)
3865 // FIXME: The above statement is likely due to a misunderstanding of the
3866 // documents. All arguments must be copied into the parameter area BY
3867 // THE CALLEE in the event that the callee takes the address of any
3868 // formal argument. That has not yet been implemented. However, it is
3869 // reasonable to use the stack area as a staging area for the register
3872 // Skip this for small aggregates, as we will use the same slot for a
3873 // right-justified copy, below.
3875 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3879 // When a register is available, pass a small aggregate right-justified.
3880 if (Size < 8 && GPR_idx != NumGPRs) {
3881 // The easiest way to get this right-justified in a register
3882 // is to copy the structure into the rightmost portion of a
3883 // local variable slot, then load the whole slot into the
3885 // FIXME: The memcpy seems to produce pretty awful code for
3886 // small aggregates, particularly for packed ones.
3887 // FIXME: It would be preferable to use the slot in the
3888 // parameter save area instead of a new local variable.
3889 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3890 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3891 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3895 // Load the slot into the register.
3896 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3897 MachinePointerInfo(),
3898 false, false, false, 0);
3899 MemOpChains.push_back(Load.getValue(1));
3900 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3902 // Done with this argument.
3903 ArgOffset += PtrByteSize;
3907 // For aggregates larger than PtrByteSize, copy the pieces of the
3908 // object that fit into registers from the parameter save area.
3909 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3910 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3911 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3912 if (GPR_idx != NumGPRs) {
3913 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3914 MachinePointerInfo(),
3915 false, false, false, 0);
3916 MemOpChains.push_back(Load.getValue(1));
3917 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3918 ArgOffset += PtrByteSize;
3920 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3927 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3928 default: llvm_unreachable("Unexpected ValueType for argument!");
3931 if (GPR_idx != NumGPRs) {
3932 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3934 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3935 true, isTailCall, false, MemOpChains,
3936 TailCallArguments, dl);
3938 ArgOffset += PtrByteSize;
3942 if (FPR_idx != NumFPRs) {
3943 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3946 // A single float or an aggregate containing only a single float
3947 // must be passed right-justified in the stack doubleword, and
3948 // in the GPR, if one is available.
3950 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3951 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3952 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3956 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3957 MachinePointerInfo(), false, false, 0);
3958 MemOpChains.push_back(Store);
3960 // Float varargs are always shadowed in available integer registers
3961 if (GPR_idx != NumGPRs) {
3962 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3963 MachinePointerInfo(), false, false,
3965 MemOpChains.push_back(Load.getValue(1));
3966 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3968 } else if (GPR_idx != NumGPRs)
3969 // If we have any FPRs remaining, we may also have GPRs remaining.
3972 // Single-precision floating-point values are mapped to the
3973 // second (rightmost) word of the stack doubleword.
3974 if (Arg.getValueType() == MVT::f32) {
3975 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3976 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3979 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3980 true, isTailCall, false, MemOpChains,
3981 TailCallArguments, dl);
3990 // These go aligned on the stack, or in the corresponding R registers
3991 // when within range. The Darwin PPC ABI doc claims they also go in
3992 // V registers; in fact gcc does this only for arguments that are
3993 // prototyped, not for those that match the ... We do it for all
3994 // arguments, seems to work.
3995 while (ArgOffset % 16 !=0) {
3996 ArgOffset += PtrByteSize;
3997 if (GPR_idx != NumGPRs)
4000 // We could elide this store in the case where the object fits
4001 // entirely in R registers. Maybe later.
4002 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4003 DAG.getConstant(ArgOffset, PtrVT));
4004 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4005 MachinePointerInfo(), false, false, 0);
4006 MemOpChains.push_back(Store);
4007 if (VR_idx != NumVRs) {
4008 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4009 MachinePointerInfo(),
4010 false, false, false, 0);
4011 MemOpChains.push_back(Load.getValue(1));
4012 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4015 for (unsigned i=0; i<16; i+=PtrByteSize) {
4016 if (GPR_idx == NumGPRs)
4018 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4019 DAG.getConstant(i, PtrVT));
4020 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4021 false, false, false, 0);
4022 MemOpChains.push_back(Load.getValue(1));
4023 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4028 // Non-varargs Altivec params generally go in registers, but have
4029 // stack space allocated at the end.
4030 if (VR_idx != NumVRs) {
4031 // Doesn't have GPR space allocated.
4032 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4034 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4035 true, isTailCall, true, MemOpChains,
4036 TailCallArguments, dl);
4043 if (!MemOpChains.empty())
4044 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4045 &MemOpChains[0], MemOpChains.size());
4047 // Check if this is an indirect call (MTCTR/BCTRL).
4048 // See PrepareCall() for more information about calls through function
4049 // pointers in the 64-bit SVR4 ABI.
4051 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4052 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4053 !isBLACompatibleAddress(Callee, DAG)) {
4054 // Load r2 into a virtual register and store it to the TOC save area.
4055 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4056 // TOC save area offset.
4057 SDValue PtrOff = DAG.getIntPtrConstant(40);
4058 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4059 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4061 // R12 must contain the address of an indirect callee. This does not
4062 // mean the MTCTR instruction must use R12; it's easier to model this
4063 // as an extra parameter, so do that.
4064 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4067 // Build a sequence of copy-to-reg nodes chained together with token chain
4068 // and flag operands which copy the outgoing args into the appropriate regs.
4070 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4071 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4072 RegsToPass[i].second, InFlag);
4073 InFlag = Chain.getValue(1);
4077 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4078 FPOp, true, TailCallArguments);
4080 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4081 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4086 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4087 CallingConv::ID CallConv, bool isVarArg,
4089 const SmallVectorImpl<ISD::OutputArg> &Outs,
4090 const SmallVectorImpl<SDValue> &OutVals,
4091 const SmallVectorImpl<ISD::InputArg> &Ins,
4092 DebugLoc dl, SelectionDAG &DAG,
4093 SmallVectorImpl<SDValue> &InVals) const {
4095 unsigned NumOps = Outs.size();
4097 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4098 bool isPPC64 = PtrVT == MVT::i64;
4099 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4101 MachineFunction &MF = DAG.getMachineFunction();
4103 // Mark this function as potentially containing a function that contains a
4104 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4105 // and restoring the callers stack pointer in this functions epilog. This is
4106 // done because by tail calling the called function might overwrite the value
4107 // in this function's (MF) stack pointer stack slot 0(SP).
4108 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4109 CallConv == CallingConv::Fast)
4110 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4112 unsigned nAltivecParamsAtEnd = 0;
4114 // Count how many bytes are to be pushed on the stack, including the linkage
4115 // area, and parameter passing area. We start with 24/48 bytes, which is
4116 // prereserved space for [SP][CR][LR][3 x unused].
4118 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4120 nAltivecParamsAtEnd);
4122 // Calculate by how many bytes the stack has to be adjusted in case of tail
4123 // call optimization.
4124 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4126 // To protect arguments on the stack from being clobbered in a tail call,
4127 // force all the loads to happen before doing any other lowering.
4129 Chain = DAG.getStackArgumentTokenFactor(Chain);
4131 // Adjust the stack pointer for the new arguments...
4132 // These operations are automatically eliminated by the prolog/epilog pass
4133 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
4134 SDValue CallSeqStart = Chain;
4136 // Load the return address and frame pointer so it can be move somewhere else
4139 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4142 // Set up a copy of the stack pointer for use loading and storing any
4143 // arguments that may not fit in the registers available for argument
4147 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4149 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4151 // Figure out which arguments are going to go in registers, and which in
4152 // memory. Also, if this is a vararg function, floating point operations
4153 // must be stored to our stack, and loaded into integer regs as well, if
4154 // any integer regs are available for argument passing.
4155 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4156 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4158 static const uint16_t GPR_32[] = { // 32-bit registers.
4159 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4160 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4162 static const uint16_t GPR_64[] = { // 64-bit registers.
4163 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4164 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4166 static const uint16_t *FPR = GetFPR();
4168 static const uint16_t VR[] = {
4169 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4170 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4172 const unsigned NumGPRs = array_lengthof(GPR_32);
4173 const unsigned NumFPRs = 13;
4174 const unsigned NumVRs = array_lengthof(VR);
4176 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4178 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4179 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4181 SmallVector<SDValue, 8> MemOpChains;
4182 for (unsigned i = 0; i != NumOps; ++i) {
4183 SDValue Arg = OutVals[i];
4184 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4186 // PtrOff will be used to store the current argument to the stack if a
4187 // register cannot be found for it.
4190 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4192 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4194 // On PPC64, promote integers to 64-bit values.
4195 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4196 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4197 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4198 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4201 // FIXME memcpy is used way more than necessary. Correctness first.
4202 // Note: "by value" is code for passing a structure by value, not
4204 if (Flags.isByVal()) {
4205 unsigned Size = Flags.getByValSize();
4206 // Very small objects are passed right-justified. Everything else is
4207 // passed left-justified.
4208 if (Size==1 || Size==2) {
4209 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4210 if (GPR_idx != NumGPRs) {
4211 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4212 MachinePointerInfo(), VT,
4214 MemOpChains.push_back(Load.getValue(1));
4215 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4217 ArgOffset += PtrByteSize;
4219 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4220 PtrOff.getValueType());
4221 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4222 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4225 ArgOffset += PtrByteSize;
4229 // Copy entire object into memory. There are cases where gcc-generated
4230 // code assumes it is there, even if it could be put entirely into
4231 // registers. (This is not what the doc says.)
4232 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4236 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4237 // copy the pieces of the object that fit into registers from the
4238 // parameter save area.
4239 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4240 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4241 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4242 if (GPR_idx != NumGPRs) {
4243 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4244 MachinePointerInfo(),
4245 false, false, false, 0);
4246 MemOpChains.push_back(Load.getValue(1));
4247 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4248 ArgOffset += PtrByteSize;
4250 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4257 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4258 default: llvm_unreachable("Unexpected ValueType for argument!");
4261 if (GPR_idx != NumGPRs) {
4262 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4264 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4265 isPPC64, isTailCall, false, MemOpChains,
4266 TailCallArguments, dl);
4268 ArgOffset += PtrByteSize;
4272 if (FPR_idx != NumFPRs) {
4273 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4276 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4277 MachinePointerInfo(), false, false, 0);
4278 MemOpChains.push_back(Store);
4280 // Float varargs are always shadowed in available integer registers
4281 if (GPR_idx != NumGPRs) {
4282 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4283 MachinePointerInfo(), false, false,
4285 MemOpChains.push_back(Load.getValue(1));
4286 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4288 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4289 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4290 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4291 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4292 MachinePointerInfo(),
4293 false, false, false, 0);
4294 MemOpChains.push_back(Load.getValue(1));
4295 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4298 // If we have any FPRs remaining, we may also have GPRs remaining.
4299 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4301 if (GPR_idx != NumGPRs)
4303 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4304 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4308 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4309 isPPC64, isTailCall, false, MemOpChains,
4310 TailCallArguments, dl);
4314 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4321 // These go aligned on the stack, or in the corresponding R registers
4322 // when within range. The Darwin PPC ABI doc claims they also go in
4323 // V registers; in fact gcc does this only for arguments that are
4324 // prototyped, not for those that match the ... We do it for all
4325 // arguments, seems to work.
4326 while (ArgOffset % 16 !=0) {
4327 ArgOffset += PtrByteSize;
4328 if (GPR_idx != NumGPRs)
4331 // We could elide this store in the case where the object fits
4332 // entirely in R registers. Maybe later.
4333 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4334 DAG.getConstant(ArgOffset, PtrVT));
4335 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4336 MachinePointerInfo(), false, false, 0);
4337 MemOpChains.push_back(Store);
4338 if (VR_idx != NumVRs) {
4339 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4340 MachinePointerInfo(),
4341 false, false, false, 0);
4342 MemOpChains.push_back(Load.getValue(1));
4343 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4346 for (unsigned i=0; i<16; i+=PtrByteSize) {
4347 if (GPR_idx == NumGPRs)
4349 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4350 DAG.getConstant(i, PtrVT));
4351 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4352 false, false, false, 0);
4353 MemOpChains.push_back(Load.getValue(1));
4354 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4359 // Non-varargs Altivec params generally go in registers, but have
4360 // stack space allocated at the end.
4361 if (VR_idx != NumVRs) {
4362 // Doesn't have GPR space allocated.
4363 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4364 } else if (nAltivecParamsAtEnd==0) {
4365 // We are emitting Altivec params in order.
4366 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4367 isPPC64, isTailCall, true, MemOpChains,
4368 TailCallArguments, dl);
4374 // If all Altivec parameters fit in registers, as they usually do,
4375 // they get stack space following the non-Altivec parameters. We
4376 // don't track this here because nobody below needs it.
4377 // If there are more Altivec parameters than fit in registers emit
4379 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4381 // Offset is aligned; skip 1st 12 params which go in V registers.
4382 ArgOffset = ((ArgOffset+15)/16)*16;
4384 for (unsigned i = 0; i != NumOps; ++i) {
4385 SDValue Arg = OutVals[i];
4386 EVT ArgType = Outs[i].VT;
4387 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4388 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
4391 // We are emitting Altivec params in order.
4392 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4393 isPPC64, isTailCall, true, MemOpChains,
4394 TailCallArguments, dl);
4401 if (!MemOpChains.empty())
4402 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4403 &MemOpChains[0], MemOpChains.size());
4405 // On Darwin, R12 must contain the address of an indirect callee. This does
4406 // not mean the MTCTR instruction must use R12; it's easier to model this as
4407 // an extra parameter, so do that.
4409 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4410 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4411 !isBLACompatibleAddress(Callee, DAG))
4412 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4413 PPC::R12), Callee));
4415 // Build a sequence of copy-to-reg nodes chained together with token chain
4416 // and flag operands which copy the outgoing args into the appropriate regs.
4418 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4419 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4420 RegsToPass[i].second, InFlag);
4421 InFlag = Chain.getValue(1);
4425 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4426 FPOp, true, TailCallArguments);
4428 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4429 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4434 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4435 MachineFunction &MF, bool isVarArg,
4436 const SmallVectorImpl<ISD::OutputArg> &Outs,
4437 LLVMContext &Context) const {
4438 SmallVector<CCValAssign, 16> RVLocs;
4439 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4441 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4445 PPCTargetLowering::LowerReturn(SDValue Chain,
4446 CallingConv::ID CallConv, bool isVarArg,
4447 const SmallVectorImpl<ISD::OutputArg> &Outs,
4448 const SmallVectorImpl<SDValue> &OutVals,
4449 DebugLoc dl, SelectionDAG &DAG) const {
4451 SmallVector<CCValAssign, 16> RVLocs;
4452 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4453 getTargetMachine(), RVLocs, *DAG.getContext());
4454 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4457 SmallVector<SDValue, 4> RetOps(1, Chain);
4459 // Copy the result values into the output registers.
4460 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4461 CCValAssign &VA = RVLocs[i];
4462 assert(VA.isRegLoc() && "Can only return in registers!");
4464 SDValue Arg = OutVals[i];
4466 switch (VA.getLocInfo()) {
4467 default: llvm_unreachable("Unknown loc info!");
4468 case CCValAssign::Full: break;
4469 case CCValAssign::AExt:
4470 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4472 case CCValAssign::ZExt:
4473 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4475 case CCValAssign::SExt:
4476 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4480 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4481 Flag = Chain.getValue(1);
4482 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4485 RetOps[0] = Chain; // Update chain.
4487 // Add the flag if we have it.
4489 RetOps.push_back(Flag);
4491 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4492 &RetOps[0], RetOps.size());
4495 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4496 const PPCSubtarget &Subtarget) const {
4497 // When we pop the dynamic allocation we need to restore the SP link.
4498 DebugLoc dl = Op.getDebugLoc();
4500 // Get the corect type for pointers.
4501 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4503 // Construct the stack pointer operand.
4504 bool isPPC64 = Subtarget.isPPC64();
4505 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4506 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4508 // Get the operands for the STACKRESTORE.
4509 SDValue Chain = Op.getOperand(0);
4510 SDValue SaveSP = Op.getOperand(1);
4512 // Load the old link SP.
4513 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4514 MachinePointerInfo(),
4515 false, false, false, 0);
4517 // Restore the stack pointer.
4518 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4520 // Store the old link SP.
4521 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4528 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4529 MachineFunction &MF = DAG.getMachineFunction();
4530 bool isPPC64 = PPCSubTarget.isPPC64();
4531 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4532 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4534 // Get current frame pointer save index. The users of this index will be
4535 // primarily DYNALLOC instructions.
4536 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4537 int RASI = FI->getReturnAddrSaveIndex();
4539 // If the frame pointer save index hasn't been defined yet.
4541 // Find out what the fix offset of the frame pointer save area.
4542 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4543 // Allocate the frame index for frame pointer save area.
4544 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4546 FI->setReturnAddrSaveIndex(RASI);
4548 return DAG.getFrameIndex(RASI, PtrVT);
4552 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4553 MachineFunction &MF = DAG.getMachineFunction();
4554 bool isPPC64 = PPCSubTarget.isPPC64();
4555 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4556 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4558 // Get current frame pointer save index. The users of this index will be
4559 // primarily DYNALLOC instructions.
4560 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4561 int FPSI = FI->getFramePointerSaveIndex();
4563 // If the frame pointer save index hasn't been defined yet.
4565 // Find out what the fix offset of the frame pointer save area.
4566 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4569 // Allocate the frame index for frame pointer save area.
4570 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4572 FI->setFramePointerSaveIndex(FPSI);
4574 return DAG.getFrameIndex(FPSI, PtrVT);
4577 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4579 const PPCSubtarget &Subtarget) const {
4581 SDValue Chain = Op.getOperand(0);
4582 SDValue Size = Op.getOperand(1);
4583 DebugLoc dl = Op.getDebugLoc();
4585 // Get the corect type for pointers.
4586 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4588 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4589 DAG.getConstant(0, PtrVT), Size);
4590 // Construct a node for the frame pointer save index.
4591 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4592 // Build a DYNALLOC node.
4593 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4594 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4595 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4598 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4599 SelectionDAG &DAG) const {
4600 DebugLoc DL = Op.getDebugLoc();
4601 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4602 DAG.getVTList(MVT::i32, MVT::Other),
4603 Op.getOperand(0), Op.getOperand(1));
4606 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4607 SelectionDAG &DAG) const {
4608 DebugLoc DL = Op.getDebugLoc();
4609 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4610 Op.getOperand(0), Op.getOperand(1));
4613 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4615 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4616 // Not FP? Not a fsel.
4617 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4618 !Op.getOperand(2).getValueType().isFloatingPoint())
4621 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4623 // Cannot handle SETEQ/SETNE.
4624 if (CC == ISD::SETEQ || CC == ISD::SETNE) return Op;
4626 EVT ResVT = Op.getValueType();
4627 EVT CmpVT = Op.getOperand(0).getValueType();
4628 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4629 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4630 DebugLoc dl = Op.getDebugLoc();
4632 // If the RHS of the comparison is a 0.0, we don't need to do the
4633 // subtraction at all.
4634 if (isFloatingPointZero(RHS))
4636 default: break; // SETUO etc aren't handled by fsel.
4639 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4642 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4643 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4644 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4647 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4650 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4651 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4652 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4653 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4658 default: break; // SETUO etc aren't handled by fsel.
4661 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4662 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4663 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4664 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4667 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4668 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4669 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4670 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4673 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4674 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4675 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4676 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
4679 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
4680 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4681 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4682 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4687 // FIXME: Split this code up when LegalizeDAGTypes lands.
4688 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
4689 DebugLoc dl) const {
4690 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4691 SDValue Src = Op.getOperand(0);
4692 if (Src.getValueType() == MVT::f32)
4693 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4696 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4697 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4699 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4704 Tmp = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Src);
4708 // Convert the FP value to an int value through memory.
4709 SDValue FIPtr = DAG.CreateStackTemporary(MVT::f64);
4711 // Emit a store to the stack slot.
4712 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4713 MachinePointerInfo(), false, false, 0);
4715 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4717 if (Op.getValueType() == MVT::i32)
4718 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4719 DAG.getConstant(4, FIPtr.getValueType()));
4720 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MachinePointerInfo(),
4721 false, false, false, 0);
4724 SDValue PPCTargetLowering::LowerSINT_TO_FP(SDValue Op,
4725 SelectionDAG &DAG) const {
4726 DebugLoc dl = Op.getDebugLoc();
4727 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4728 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4731 if (Op.getOperand(0).getValueType() == MVT::i64) {
4732 SDValue SINT = Op.getOperand(0);
4733 // When converting to single-precision, we actually need to convert
4734 // to double-precision first and then round to single-precision.
4735 // To avoid double-rounding effects during that operation, we have
4736 // to prepare the input operand. Bits that might be truncated when
4737 // converting to double-precision are replaced by a bit that won't
4738 // be lost at this stage, but is below the single-precision rounding
4741 // However, if -enable-unsafe-fp-math is in effect, accept double
4742 // rounding to avoid the extra overhead.
4743 if (Op.getValueType() == MVT::f32 &&
4744 !DAG.getTarget().Options.UnsafeFPMath) {
4746 // Twiddle input to make sure the low 11 bits are zero. (If this
4747 // is the case, we are guaranteed the value will fit into the 53 bit
4748 // mantissa of an IEEE double-precision value without rounding.)
4749 // If any of those low 11 bits were not zero originally, make sure
4750 // bit 12 (value 2048) is set instead, so that the final rounding
4751 // to single-precision gets the correct result.
4752 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4753 SINT, DAG.getConstant(2047, MVT::i64));
4754 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4755 Round, DAG.getConstant(2047, MVT::i64));
4756 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4757 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4758 Round, DAG.getConstant(-2048, MVT::i64));
4760 // However, we cannot use that value unconditionally: if the magnitude
4761 // of the input value is small, the bit-twiddling we did above might
4762 // end up visibly changing the output. Fortunately, in that case, we
4763 // don't need to twiddle bits since the original input will convert
4764 // exactly to double-precision floating-point already. Therefore,
4765 // construct a conditional to use the original value if the top 11
4766 // bits are all sign-bit copies, and use the rounded value computed
4768 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4769 SINT, DAG.getConstant(53, MVT::i32));
4770 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4771 Cond, DAG.getConstant(1, MVT::i64));
4772 Cond = DAG.getSetCC(dl, MVT::i32,
4773 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4775 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4777 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4778 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Bits);
4779 if (Op.getValueType() == MVT::f32)
4780 FP = DAG.getNode(ISD::FP_ROUND, dl,
4781 MVT::f32, FP, DAG.getIntPtrConstant(0));
4785 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4786 "Unhandled SINT_TO_FP type in custom expander!");
4787 // Since we only generate this in 64-bit mode, we can take advantage of
4788 // 64-bit registers. In particular, sign extend the input value into the
4789 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4790 // then lfd it and fcfid it.
4791 MachineFunction &MF = DAG.getMachineFunction();
4792 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4793 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4794 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4795 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4797 SDValue Ext64 = DAG.getNode(PPCISD::EXTSW_32, dl, MVT::i32,
4800 // STD the extended value into the stack slot.
4801 MachineMemOperand *MMO =
4802 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4803 MachineMemOperand::MOStore, 8, 8);
4804 SDValue Ops[] = { DAG.getEntryNode(), Ext64, FIdx };
4806 DAG.getMemIntrinsicNode(PPCISD::STD_32, dl, DAG.getVTList(MVT::Other),
4807 Ops, 4, MVT::i64, MMO);
4808 // Load the value as a double.
4809 SDValue Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx, MachinePointerInfo(),
4810 false, false, false, 0);
4812 // FCFID it and return it.
4813 SDValue FP = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Ld);
4814 if (Op.getValueType() == MVT::f32)
4815 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4819 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4820 SelectionDAG &DAG) const {
4821 DebugLoc dl = Op.getDebugLoc();
4823 The rounding mode is in bits 30:31 of FPSR, and has the following
4830 FLT_ROUNDS, on the other hand, expects the following:
4837 To perform the conversion, we do:
4838 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4841 MachineFunction &MF = DAG.getMachineFunction();
4842 EVT VT = Op.getValueType();
4843 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4844 SDValue MFFSreg, InFlag;
4846 // Save FP Control Word to register
4848 MVT::f64, // return register
4849 MVT::Glue // unused in this context
4851 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4853 // Save FP register to stack slot
4854 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4855 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4856 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4857 StackSlot, MachinePointerInfo(), false, false,0);
4859 // Load FP Control Word from low 32 bits of stack slot.
4860 SDValue Four = DAG.getConstant(4, PtrVT);
4861 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4862 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4863 false, false, false, 0);
4865 // Transform as necessary
4867 DAG.getNode(ISD::AND, dl, MVT::i32,
4868 CWD, DAG.getConstant(3, MVT::i32));
4870 DAG.getNode(ISD::SRL, dl, MVT::i32,
4871 DAG.getNode(ISD::AND, dl, MVT::i32,
4872 DAG.getNode(ISD::XOR, dl, MVT::i32,
4873 CWD, DAG.getConstant(3, MVT::i32)),
4874 DAG.getConstant(3, MVT::i32)),
4875 DAG.getConstant(1, MVT::i32));
4878 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4880 return DAG.getNode((VT.getSizeInBits() < 16 ?
4881 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4884 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4885 EVT VT = Op.getValueType();
4886 unsigned BitWidth = VT.getSizeInBits();
4887 DebugLoc dl = Op.getDebugLoc();
4888 assert(Op.getNumOperands() == 3 &&
4889 VT == Op.getOperand(1).getValueType() &&
4892 // Expand into a bunch of logical ops. Note that these ops
4893 // depend on the PPC behavior for oversized shift amounts.
4894 SDValue Lo = Op.getOperand(0);
4895 SDValue Hi = Op.getOperand(1);
4896 SDValue Amt = Op.getOperand(2);
4897 EVT AmtVT = Amt.getValueType();
4899 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4900 DAG.getConstant(BitWidth, AmtVT), Amt);
4901 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4902 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4903 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4904 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4905 DAG.getConstant(-BitWidth, AmtVT));
4906 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4907 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4908 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4909 SDValue OutOps[] = { OutLo, OutHi };
4910 return DAG.getMergeValues(OutOps, 2, dl);
4913 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4914 EVT VT = Op.getValueType();
4915 DebugLoc dl = Op.getDebugLoc();
4916 unsigned BitWidth = VT.getSizeInBits();
4917 assert(Op.getNumOperands() == 3 &&
4918 VT == Op.getOperand(1).getValueType() &&
4921 // Expand into a bunch of logical ops. Note that these ops
4922 // depend on the PPC behavior for oversized shift amounts.
4923 SDValue Lo = Op.getOperand(0);
4924 SDValue Hi = Op.getOperand(1);
4925 SDValue Amt = Op.getOperand(2);
4926 EVT AmtVT = Amt.getValueType();
4928 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4929 DAG.getConstant(BitWidth, AmtVT), Amt);
4930 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4931 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4932 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4933 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4934 DAG.getConstant(-BitWidth, AmtVT));
4935 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
4936 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4937 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
4938 SDValue OutOps[] = { OutLo, OutHi };
4939 return DAG.getMergeValues(OutOps, 2, dl);
4942 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
4943 DebugLoc dl = Op.getDebugLoc();
4944 EVT VT = Op.getValueType();
4945 unsigned BitWidth = VT.getSizeInBits();
4946 assert(Op.getNumOperands() == 3 &&
4947 VT == Op.getOperand(1).getValueType() &&
4950 // Expand into a bunch of logical ops, followed by a select_cc.
4951 SDValue Lo = Op.getOperand(0);
4952 SDValue Hi = Op.getOperand(1);
4953 SDValue Amt = Op.getOperand(2);
4954 EVT AmtVT = Amt.getValueType();
4956 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4957 DAG.getConstant(BitWidth, AmtVT), Amt);
4958 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
4959 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
4960 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
4961 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4962 DAG.getConstant(-BitWidth, AmtVT));
4963 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
4964 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
4965 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
4966 Tmp4, Tmp6, ISD::SETLE);
4967 SDValue OutOps[] = { OutLo, OutHi };
4968 return DAG.getMergeValues(OutOps, 2, dl);
4971 //===----------------------------------------------------------------------===//
4972 // Vector related lowering.
4975 /// BuildSplatI - Build a canonical splati of Val with an element size of
4976 /// SplatSize. Cast the result to VT.
4977 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
4978 SelectionDAG &DAG, DebugLoc dl) {
4979 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
4981 static const EVT VTys[] = { // canonical VT to use for each size.
4982 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
4985 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
4987 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
4991 EVT CanonicalVT = VTys[SplatSize-1];
4993 // Build a canonical splat for this value.
4994 SDValue Elt = DAG.getConstant(Val, MVT::i32);
4995 SmallVector<SDValue, 8> Ops;
4996 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
4997 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
4998 &Ops[0], Ops.size());
4999 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5002 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5003 /// specified intrinsic ID.
5004 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5005 SelectionDAG &DAG, DebugLoc dl,
5006 EVT DestVT = MVT::Other) {
5007 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5008 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5009 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5012 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5013 /// specified intrinsic ID.
5014 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5015 SDValue Op2, SelectionDAG &DAG,
5016 DebugLoc dl, EVT DestVT = MVT::Other) {
5017 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5018 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5019 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5023 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5024 /// amount. The result has the specified value type.
5025 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5026 EVT VT, SelectionDAG &DAG, DebugLoc dl) {
5027 // Force LHS/RHS to be the right type.
5028 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5029 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5032 for (unsigned i = 0; i != 16; ++i)
5034 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5035 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5038 // If this is a case we can't handle, return null and let the default
5039 // expansion code take care of it. If we CAN select this case, and if it
5040 // selects to a single instruction, return Op. Otherwise, if we can codegen
5041 // this case more efficiently than a constant pool load, lower it to the
5042 // sequence of ops that should be used.
5043 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5044 SelectionDAG &DAG) const {
5045 DebugLoc dl = Op.getDebugLoc();
5046 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5047 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5049 // Check if this is a splat of a constant value.
5050 APInt APSplatBits, APSplatUndef;
5051 unsigned SplatBitSize;
5053 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5054 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5057 unsigned SplatBits = APSplatBits.getZExtValue();
5058 unsigned SplatUndef = APSplatUndef.getZExtValue();
5059 unsigned SplatSize = SplatBitSize / 8;
5061 // First, handle single instruction cases.
5064 if (SplatBits == 0) {
5065 // Canonicalize all zero vectors to be v4i32.
5066 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5067 SDValue Z = DAG.getConstant(0, MVT::i32);
5068 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5069 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5074 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5075 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5077 if (SextVal >= -16 && SextVal <= 15)
5078 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5081 // Two instruction sequences.
5083 // If this value is in the range [-32,30] and is even, use:
5084 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5085 // If this value is in the range [17,31] and is odd, use:
5086 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5087 // If this value is in the range [-31,-17] and is odd, use:
5088 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5089 // Note the last two are three-instruction sequences.
5090 if (SextVal >= -32 && SextVal <= 31) {
5091 // To avoid having these optimizations undone by constant folding,
5092 // we convert to a pseudo that will be expanded later into one of
5094 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5095 EVT VT = Op.getValueType();
5096 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5097 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5098 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5101 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5102 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5104 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5105 // Make -1 and vspltisw -1:
5106 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5108 // Make the VSLW intrinsic, computing 0x8000_0000.
5109 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5112 // xor by OnesV to invert it.
5113 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5114 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5117 // Check to see if this is a wide variety of vsplti*, binop self cases.
5118 static const signed char SplatCsts[] = {
5119 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5120 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5123 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5124 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5125 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5126 int i = SplatCsts[idx];
5128 // Figure out what shift amount will be used by altivec if shifted by i in
5130 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5132 // vsplti + shl self.
5133 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5134 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5135 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5136 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5137 Intrinsic::ppc_altivec_vslw
5139 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5140 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5143 // vsplti + srl self.
5144 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5145 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5146 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5147 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5148 Intrinsic::ppc_altivec_vsrw
5150 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5151 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5154 // vsplti + sra self.
5155 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5156 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5157 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5158 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5159 Intrinsic::ppc_altivec_vsraw
5161 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5162 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5165 // vsplti + rol self.
5166 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5167 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5168 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5169 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5170 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5171 Intrinsic::ppc_altivec_vrlw
5173 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5174 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5177 // t = vsplti c, result = vsldoi t, t, 1
5178 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5179 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5180 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5182 // t = vsplti c, result = vsldoi t, t, 2
5183 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5184 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5185 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5187 // t = vsplti c, result = vsldoi t, t, 3
5188 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5189 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5190 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5197 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5198 /// the specified operations to build the shuffle.
5199 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5200 SDValue RHS, SelectionDAG &DAG,
5202 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5203 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5204 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5207 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5219 if (OpNum == OP_COPY) {
5220 if (LHSID == (1*9+2)*9+3) return LHS;
5221 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5225 SDValue OpLHS, OpRHS;
5226 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5227 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5231 default: llvm_unreachable("Unknown i32 permute!");
5233 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5234 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5235 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5236 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5239 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5240 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5241 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5242 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5245 for (unsigned i = 0; i != 16; ++i)
5246 ShufIdxs[i] = (i&3)+0;
5249 for (unsigned i = 0; i != 16; ++i)
5250 ShufIdxs[i] = (i&3)+4;
5253 for (unsigned i = 0; i != 16; ++i)
5254 ShufIdxs[i] = (i&3)+8;
5257 for (unsigned i = 0; i != 16; ++i)
5258 ShufIdxs[i] = (i&3)+12;
5261 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5263 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5265 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5267 EVT VT = OpLHS.getValueType();
5268 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5269 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5270 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5271 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5274 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5275 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5276 /// return the code it can be lowered into. Worst case, it can always be
5277 /// lowered into a vperm.
5278 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5279 SelectionDAG &DAG) const {
5280 DebugLoc dl = Op.getDebugLoc();
5281 SDValue V1 = Op.getOperand(0);
5282 SDValue V2 = Op.getOperand(1);
5283 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5284 EVT VT = Op.getValueType();
5286 // Cases that are handled by instructions that take permute immediates
5287 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5288 // selected by the instruction selector.
5289 if (V2.getOpcode() == ISD::UNDEF) {
5290 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5291 PPC::isSplatShuffleMask(SVOp, 2) ||
5292 PPC::isSplatShuffleMask(SVOp, 4) ||
5293 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5294 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5295 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5296 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5297 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5298 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5299 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5300 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5301 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5306 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5307 // and produce a fixed permutation. If any of these match, do not lower to
5309 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5310 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5311 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5312 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5313 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5314 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5315 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5316 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5317 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5320 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5321 // perfect shuffle table to emit an optimal matching sequence.
5322 ArrayRef<int> PermMask = SVOp->getMask();
5324 unsigned PFIndexes[4];
5325 bool isFourElementShuffle = true;
5326 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5327 unsigned EltNo = 8; // Start out undef.
5328 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5329 if (PermMask[i*4+j] < 0)
5330 continue; // Undef, ignore it.
5332 unsigned ByteSource = PermMask[i*4+j];
5333 if ((ByteSource & 3) != j) {
5334 isFourElementShuffle = false;
5339 EltNo = ByteSource/4;
5340 } else if (EltNo != ByteSource/4) {
5341 isFourElementShuffle = false;
5345 PFIndexes[i] = EltNo;
5348 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5349 // perfect shuffle vector to determine if it is cost effective to do this as
5350 // discrete instructions, or whether we should use a vperm.
5351 if (isFourElementShuffle) {
5352 // Compute the index in the perfect shuffle table.
5353 unsigned PFTableIndex =
5354 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5356 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5357 unsigned Cost = (PFEntry >> 30);
5359 // Determining when to avoid vperm is tricky. Many things affect the cost
5360 // of vperm, particularly how many times the perm mask needs to be computed.
5361 // For example, if the perm mask can be hoisted out of a loop or is already
5362 // used (perhaps because there are multiple permutes with the same shuffle
5363 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5364 // the loop requires an extra register.
5366 // As a compromise, we only emit discrete instructions if the shuffle can be
5367 // generated in 3 or fewer operations. When we have loop information
5368 // available, if this block is within a loop, we should avoid using vperm
5369 // for 3-operation perms and use a constant pool load instead.
5371 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5374 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5375 // vector that will get spilled to the constant pool.
5376 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5378 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5379 // that it is in input element units, not in bytes. Convert now.
5380 EVT EltVT = V1.getValueType().getVectorElementType();
5381 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5383 SmallVector<SDValue, 16> ResultMask;
5384 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5385 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5387 for (unsigned j = 0; j != BytesPerElement; ++j)
5388 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5392 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5393 &ResultMask[0], ResultMask.size());
5394 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5397 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5398 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5399 /// information about the intrinsic.
5400 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5402 unsigned IntrinsicID =
5403 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5406 switch (IntrinsicID) {
5407 default: return false;
5408 // Comparison predicates.
5409 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5410 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5411 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5412 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5413 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5414 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5415 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5416 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5417 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5418 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5419 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5420 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5421 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5423 // Normal Comparisons.
5424 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5425 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5426 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5427 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5428 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5429 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5430 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5431 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5432 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5433 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5434 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5435 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5436 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5441 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5442 /// lower, do it, otherwise return null.
5443 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5444 SelectionDAG &DAG) const {
5445 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5446 // opcode number of the comparison.
5447 DebugLoc dl = Op.getDebugLoc();
5450 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5451 return SDValue(); // Don't custom lower most intrinsics.
5453 // If this is a non-dot comparison, make the VCMP node and we are done.
5455 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5456 Op.getOperand(1), Op.getOperand(2),
5457 DAG.getConstant(CompareOpc, MVT::i32));
5458 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5461 // Create the PPCISD altivec 'dot' comparison node.
5463 Op.getOperand(2), // LHS
5464 Op.getOperand(3), // RHS
5465 DAG.getConstant(CompareOpc, MVT::i32)
5467 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5468 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5470 // Now that we have the comparison, emit a copy from the CR to a GPR.
5471 // This is flagged to the above dot comparison.
5472 SDValue Flags = DAG.getNode(PPCISD::MFCR, dl, MVT::i32,
5473 DAG.getRegister(PPC::CR6, MVT::i32),
5474 CompNode.getValue(1));
5476 // Unpack the result based on how the target uses it.
5477 unsigned BitNo; // Bit # of CR6.
5478 bool InvertBit; // Invert result?
5479 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5480 default: // Can't happen, don't crash on invalid number though.
5481 case 0: // Return the value of the EQ bit of CR6.
5482 BitNo = 0; InvertBit = false;
5484 case 1: // Return the inverted value of the EQ bit of CR6.
5485 BitNo = 0; InvertBit = true;
5487 case 2: // Return the value of the LT bit of CR6.
5488 BitNo = 2; InvertBit = false;
5490 case 3: // Return the inverted value of the LT bit of CR6.
5491 BitNo = 2; InvertBit = true;
5495 // Shift the bit into the low position.
5496 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5497 DAG.getConstant(8-(3-BitNo), MVT::i32));
5499 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5500 DAG.getConstant(1, MVT::i32));
5502 // If we are supposed to, toggle the bit.
5504 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5505 DAG.getConstant(1, MVT::i32));
5509 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5510 SelectionDAG &DAG) const {
5511 DebugLoc dl = Op.getDebugLoc();
5512 // Create a stack slot that is 16-byte aligned.
5513 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5514 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5515 EVT PtrVT = getPointerTy();
5516 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5518 // Store the input value into Value#0 of the stack slot.
5519 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5520 Op.getOperand(0), FIdx, MachinePointerInfo(),
5523 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5524 false, false, false, 0);
5527 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5528 DebugLoc dl = Op.getDebugLoc();
5529 if (Op.getValueType() == MVT::v4i32) {
5530 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5532 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5533 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5535 SDValue RHSSwap = // = vrlw RHS, 16
5536 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5538 // Shrinkify inputs to v8i16.
5539 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5540 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5541 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5543 // Low parts multiplied together, generating 32-bit results (we ignore the
5545 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5546 LHS, RHS, DAG, dl, MVT::v4i32);
5548 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5549 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5550 // Shift the high parts up 16 bits.
5551 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5553 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5554 } else if (Op.getValueType() == MVT::v8i16) {
5555 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5557 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5559 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5560 LHS, RHS, Zero, DAG, dl);
5561 } else if (Op.getValueType() == MVT::v16i8) {
5562 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5564 // Multiply the even 8-bit parts, producing 16-bit sums.
5565 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5566 LHS, RHS, DAG, dl, MVT::v8i16);
5567 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5569 // Multiply the odd 8-bit parts, producing 16-bit sums.
5570 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5571 LHS, RHS, DAG, dl, MVT::v8i16);
5572 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5574 // Merge the results together.
5576 for (unsigned i = 0; i != 8; ++i) {
5578 Ops[i*2+1] = 2*i+1+16;
5580 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5582 llvm_unreachable("Unknown mul to lower!");
5586 /// LowerOperation - Provide custom lowering hooks for some operations.
5588 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5589 switch (Op.getOpcode()) {
5590 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5591 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5592 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5593 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5594 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5595 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5596 case ISD::SETCC: return LowerSETCC(Op, DAG);
5597 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5598 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5600 return LowerVASTART(Op, DAG, PPCSubTarget);
5603 return LowerVAARG(Op, DAG, PPCSubTarget);
5605 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5606 case ISD::DYNAMIC_STACKALLOC:
5607 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5609 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5610 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5612 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5613 case ISD::FP_TO_UINT:
5614 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5616 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5617 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5619 // Lower 64-bit shifts.
5620 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5621 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5622 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5624 // Vector-related lowering.
5625 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5626 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5627 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5628 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5629 case ISD::MUL: return LowerMUL(Op, DAG);
5631 // Frame & Return address.
5632 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5633 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5637 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5638 SmallVectorImpl<SDValue>&Results,
5639 SelectionDAG &DAG) const {
5640 const TargetMachine &TM = getTargetMachine();
5641 DebugLoc dl = N->getDebugLoc();
5642 switch (N->getOpcode()) {
5644 llvm_unreachable("Do not know how to custom type legalize this operation!");
5646 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5647 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5650 EVT VT = N->getValueType(0);
5652 if (VT == MVT::i64) {
5653 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5655 Results.push_back(NewNode);
5656 Results.push_back(NewNode.getValue(1));
5660 case ISD::FP_ROUND_INREG: {
5661 assert(N->getValueType(0) == MVT::ppcf128);
5662 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5663 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5664 MVT::f64, N->getOperand(0),
5665 DAG.getIntPtrConstant(0));
5666 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5667 MVT::f64, N->getOperand(0),
5668 DAG.getIntPtrConstant(1));
5670 // This sequence changes FPSCR to do round-to-zero, adds the two halves
5671 // of the long double, and puts FPSCR back the way it was. We do not
5672 // actually model FPSCR.
5673 std::vector<EVT> NodeTys;
5674 SDValue Ops[4], Result, MFFSreg, InFlag, FPreg;
5676 NodeTys.push_back(MVT::f64); // Return register
5677 NodeTys.push_back(MVT::Glue); // Returns a flag for later insns
5678 Result = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
5679 MFFSreg = Result.getValue(0);
5680 InFlag = Result.getValue(1);
5683 NodeTys.push_back(MVT::Glue); // Returns a flag
5684 Ops[0] = DAG.getConstant(31, MVT::i32);
5686 Result = DAG.getNode(PPCISD::MTFSB1, dl, NodeTys, Ops, 2);
5687 InFlag = Result.getValue(0);
5690 NodeTys.push_back(MVT::Glue); // Returns a flag
5691 Ops[0] = DAG.getConstant(30, MVT::i32);
5693 Result = DAG.getNode(PPCISD::MTFSB0, dl, NodeTys, Ops, 2);
5694 InFlag = Result.getValue(0);
5697 NodeTys.push_back(MVT::f64); // result of add
5698 NodeTys.push_back(MVT::Glue); // Returns a flag
5702 Result = DAG.getNode(PPCISD::FADDRTZ, dl, NodeTys, Ops, 3);
5703 FPreg = Result.getValue(0);
5704 InFlag = Result.getValue(1);
5707 NodeTys.push_back(MVT::f64);
5708 Ops[0] = DAG.getConstant(1, MVT::i32);
5712 Result = DAG.getNode(PPCISD::MTFSF, dl, NodeTys, Ops, 4);
5713 FPreg = Result.getValue(0);
5715 // We know the low half is about to be thrown away, so just use something
5717 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5721 case ISD::FP_TO_SINT:
5722 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5728 //===----------------------------------------------------------------------===//
5729 // Other Lowering Code
5730 //===----------------------------------------------------------------------===//
5733 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5734 bool is64bit, unsigned BinOpcode) const {
5735 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5736 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5738 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5739 MachineFunction *F = BB->getParent();
5740 MachineFunction::iterator It = BB;
5743 unsigned dest = MI->getOperand(0).getReg();
5744 unsigned ptrA = MI->getOperand(1).getReg();
5745 unsigned ptrB = MI->getOperand(2).getReg();
5746 unsigned incr = MI->getOperand(3).getReg();
5747 DebugLoc dl = MI->getDebugLoc();
5749 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5750 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5751 F->insert(It, loopMBB);
5752 F->insert(It, exitMBB);
5753 exitMBB->splice(exitMBB->begin(), BB,
5754 llvm::next(MachineBasicBlock::iterator(MI)),
5756 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5758 MachineRegisterInfo &RegInfo = F->getRegInfo();
5759 unsigned TmpReg = (!BinOpcode) ? incr :
5760 RegInfo.createVirtualRegister(
5761 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5762 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5766 // fallthrough --> loopMBB
5767 BB->addSuccessor(loopMBB);
5770 // l[wd]arx dest, ptr
5771 // add r0, dest, incr
5772 // st[wd]cx. r0, ptr
5774 // fallthrough --> exitMBB
5776 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5777 .addReg(ptrA).addReg(ptrB);
5779 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5780 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5781 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5782 BuildMI(BB, dl, TII->get(PPC::BCC))
5783 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5784 BB->addSuccessor(loopMBB);
5785 BB->addSuccessor(exitMBB);
5794 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5795 MachineBasicBlock *BB,
5796 bool is8bit, // operation
5797 unsigned BinOpcode) const {
5798 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5799 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5800 // In 64 bit mode we have to use 64 bits for addresses, even though the
5801 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5802 // registers without caring whether they're 32 or 64, but here we're
5803 // doing actual arithmetic on the addresses.
5804 bool is64bit = PPCSubTarget.isPPC64();
5805 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5807 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5808 MachineFunction *F = BB->getParent();
5809 MachineFunction::iterator It = BB;
5812 unsigned dest = MI->getOperand(0).getReg();
5813 unsigned ptrA = MI->getOperand(1).getReg();
5814 unsigned ptrB = MI->getOperand(2).getReg();
5815 unsigned incr = MI->getOperand(3).getReg();
5816 DebugLoc dl = MI->getDebugLoc();
5818 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5819 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5820 F->insert(It, loopMBB);
5821 F->insert(It, exitMBB);
5822 exitMBB->splice(exitMBB->begin(), BB,
5823 llvm::next(MachineBasicBlock::iterator(MI)),
5825 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5827 MachineRegisterInfo &RegInfo = F->getRegInfo();
5828 const TargetRegisterClass *RC =
5829 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5830 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5831 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5832 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5833 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5834 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5835 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5836 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5837 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5838 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5839 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5840 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5841 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5843 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5847 // fallthrough --> loopMBB
5848 BB->addSuccessor(loopMBB);
5850 // The 4-byte load must be aligned, while a char or short may be
5851 // anywhere in the word. Hence all this nasty bookkeeping code.
5852 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5853 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5854 // xori shift, shift1, 24 [16]
5855 // rlwinm ptr, ptr1, 0, 0, 29
5856 // slw incr2, incr, shift
5857 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5858 // slw mask, mask2, shift
5860 // lwarx tmpDest, ptr
5861 // add tmp, tmpDest, incr2
5862 // andc tmp2, tmpDest, mask
5863 // and tmp3, tmp, mask
5864 // or tmp4, tmp3, tmp2
5867 // fallthrough --> exitMBB
5868 // srw dest, tmpDest, shift
5869 if (ptrA != ZeroReg) {
5870 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5871 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5872 .addReg(ptrA).addReg(ptrB);
5876 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5877 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5878 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5879 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5881 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5882 .addReg(Ptr1Reg).addImm(0).addImm(61);
5884 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5885 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5886 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5887 .addReg(incr).addReg(ShiftReg);
5889 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5891 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5892 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5894 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5895 .addReg(Mask2Reg).addReg(ShiftReg);
5898 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5899 .addReg(ZeroReg).addReg(PtrReg);
5901 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5902 .addReg(Incr2Reg).addReg(TmpDestReg);
5903 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5904 .addReg(TmpDestReg).addReg(MaskReg);
5905 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5906 .addReg(TmpReg).addReg(MaskReg);
5907 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5908 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5909 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5910 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5911 BuildMI(BB, dl, TII->get(PPC::BCC))
5912 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5913 BB->addSuccessor(loopMBB);
5914 BB->addSuccessor(exitMBB);
5919 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5924 llvm::MachineBasicBlock*
5925 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
5926 MachineBasicBlock *MBB) const {
5927 DebugLoc DL = MI->getDebugLoc();
5928 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5930 MachineFunction *MF = MBB->getParent();
5931 MachineRegisterInfo &MRI = MF->getRegInfo();
5933 const BasicBlock *BB = MBB->getBasicBlock();
5934 MachineFunction::iterator I = MBB;
5938 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
5939 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
5941 unsigned DstReg = MI->getOperand(0).getReg();
5942 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
5943 assert(RC->hasType(MVT::i32) && "Invalid destination!");
5944 unsigned mainDstReg = MRI.createVirtualRegister(RC);
5945 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
5947 MVT PVT = getPointerTy();
5948 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
5949 "Invalid Pointer Size!");
5950 // For v = setjmp(buf), we generate
5953 // SjLjSetup mainMBB
5959 // buf[LabelOffset] = LR
5963 // v = phi(main, restore)
5966 MachineBasicBlock *thisMBB = MBB;
5967 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
5968 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
5969 MF->insert(I, mainMBB);
5970 MF->insert(I, sinkMBB);
5972 MachineInstrBuilder MIB;
5974 // Transfer the remainder of BB and its successor edges to sinkMBB.
5975 sinkMBB->splice(sinkMBB->begin(), MBB,
5976 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
5977 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
5979 // Note that the structure of the jmp_buf used here is not compatible
5980 // with that used by libc, and is not designed to be. Specifically, it
5981 // stores only those 'reserved' registers that LLVM does not otherwise
5982 // understand how to spill. Also, by convention, by the time this
5983 // intrinsic is called, Clang has already stored the frame address in the
5984 // first slot of the buffer and stack address in the third. Following the
5985 // X86 target code, we'll store the jump address in the second slot. We also
5986 // need to save the TOC pointer (R2) to handle jumps between shared
5987 // libraries, and that will be stored in the fourth slot. The thread
5988 // identifier (R13) is not affected.
5991 const int64_t LabelOffset = 1 * PVT.getStoreSize();
5992 const int64_t TOCOffset = 3 * PVT.getStoreSize();
5994 // Prepare IP either in reg.
5995 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
5996 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
5997 unsigned BufReg = MI->getOperand(1).getReg();
5999 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6000 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6002 .addImm(TOCOffset / 4)
6005 MIB.setMemRefs(MMOBegin, MMOEnd);
6009 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCL)).addMBB(mainMBB);
6010 MIB.addRegMask(PPCRegInfo->getNoPreservedMask());
6012 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6014 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6016 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6018 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6019 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6023 MIB = BuildMI(mainMBB, DL,
6024 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6027 if (PPCSubTarget.isPPC64()) {
6028 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6030 .addImm(LabelOffset / 4)
6033 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6035 .addImm(LabelOffset)
6039 MIB.setMemRefs(MMOBegin, MMOEnd);
6041 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6042 mainMBB->addSuccessor(sinkMBB);
6045 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6046 TII->get(PPC::PHI), DstReg)
6047 .addReg(mainDstReg).addMBB(mainMBB)
6048 .addReg(restoreDstReg).addMBB(thisMBB);
6050 MI->eraseFromParent();
6055 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6056 MachineBasicBlock *MBB) const {
6057 DebugLoc DL = MI->getDebugLoc();
6058 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6060 MachineFunction *MF = MBB->getParent();
6061 MachineRegisterInfo &MRI = MF->getRegInfo();
6064 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6065 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6067 MVT PVT = getPointerTy();
6068 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6069 "Invalid Pointer Size!");
6071 const TargetRegisterClass *RC =
6072 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6073 unsigned Tmp = MRI.createVirtualRegister(RC);
6074 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6075 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6076 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6078 MachineInstrBuilder MIB;
6080 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6081 const int64_t SPOffset = 2 * PVT.getStoreSize();
6082 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6084 unsigned BufReg = MI->getOperand(0).getReg();
6086 // Reload FP (the jumped-to function may not have had a
6087 // frame pointer, and if so, then its r31 will be restored
6089 if (PVT == MVT::i64) {
6090 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6094 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6098 MIB.setMemRefs(MMOBegin, MMOEnd);
6101 if (PVT == MVT::i64) {
6102 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6103 .addImm(LabelOffset / 4)
6106 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6107 .addImm(LabelOffset)
6110 MIB.setMemRefs(MMOBegin, MMOEnd);
6113 if (PVT == MVT::i64) {
6114 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6115 .addImm(SPOffset / 4)
6118 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6122 MIB.setMemRefs(MMOBegin, MMOEnd);
6124 // FIXME: When we also support base pointers, that register must also be
6128 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6129 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6130 .addImm(TOCOffset / 4)
6133 MIB.setMemRefs(MMOBegin, MMOEnd);
6137 BuildMI(*MBB, MI, DL,
6138 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6139 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6141 MI->eraseFromParent();
6146 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6147 MachineBasicBlock *BB) const {
6148 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6149 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6150 return emitEHSjLjSetJmp(MI, BB);
6151 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6152 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6153 return emitEHSjLjLongJmp(MI, BB);
6156 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6158 // To "insert" these instructions we actually have to insert their
6159 // control-flow patterns.
6160 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6161 MachineFunction::iterator It = BB;
6164 MachineFunction *F = BB->getParent();
6166 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6167 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6168 unsigned OpCode = MI->getOpcode() == PPC::SELECT_CC_I8 ?
6169 PPC::ISEL8 : PPC::ISEL;
6170 unsigned SelectPred = MI->getOperand(4).getImm();
6171 DebugLoc dl = MI->getDebugLoc();
6175 switch (SelectPred) {
6176 default: llvm_unreachable("invalid predicate for isel");
6177 case PPC::PRED_EQ: SubIdx = PPC::sub_eq; SwapOps = false; break;
6178 case PPC::PRED_NE: SubIdx = PPC::sub_eq; SwapOps = true; break;
6179 case PPC::PRED_LT: SubIdx = PPC::sub_lt; SwapOps = false; break;
6180 case PPC::PRED_GE: SubIdx = PPC::sub_lt; SwapOps = true; break;
6181 case PPC::PRED_GT: SubIdx = PPC::sub_gt; SwapOps = false; break;
6182 case PPC::PRED_LE: SubIdx = PPC::sub_gt; SwapOps = true; break;
6183 case PPC::PRED_UN: SubIdx = PPC::sub_un; SwapOps = false; break;
6184 case PPC::PRED_NU: SubIdx = PPC::sub_un; SwapOps = true; break;
6187 BuildMI(*BB, MI, dl, TII->get(OpCode), MI->getOperand(0).getReg())
6188 .addReg(MI->getOperand(SwapOps? 3 : 2).getReg())
6189 .addReg(MI->getOperand(SwapOps? 2 : 3).getReg())
6190 .addReg(MI->getOperand(1).getReg(), 0, SubIdx);
6191 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6192 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6193 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6194 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6195 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6198 // The incoming instruction knows the destination vreg to set, the
6199 // condition code register to branch on, the true/false values to
6200 // select between, and a branch opcode to use.
6205 // cmpTY ccX, r1, r2
6207 // fallthrough --> copy0MBB
6208 MachineBasicBlock *thisMBB = BB;
6209 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6210 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6211 unsigned SelectPred = MI->getOperand(4).getImm();
6212 DebugLoc dl = MI->getDebugLoc();
6213 F->insert(It, copy0MBB);
6214 F->insert(It, sinkMBB);
6216 // Transfer the remainder of BB and its successor edges to sinkMBB.
6217 sinkMBB->splice(sinkMBB->begin(), BB,
6218 llvm::next(MachineBasicBlock::iterator(MI)),
6220 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6222 // Next, add the true and fallthrough blocks as its successors.
6223 BB->addSuccessor(copy0MBB);
6224 BB->addSuccessor(sinkMBB);
6226 BuildMI(BB, dl, TII->get(PPC::BCC))
6227 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6230 // %FalseValue = ...
6231 // # fallthrough to sinkMBB
6234 // Update machine-CFG edges
6235 BB->addSuccessor(sinkMBB);
6238 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6241 BuildMI(*BB, BB->begin(), dl,
6242 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6243 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6244 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6246 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6247 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6248 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6249 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6250 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6251 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6252 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6253 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6255 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6256 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6257 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6258 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6259 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6260 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6261 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6262 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6264 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6265 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6266 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6267 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6268 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6269 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6270 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6271 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6273 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6274 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6275 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6276 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6277 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6278 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6279 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6280 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6282 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6283 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6284 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6285 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6286 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6287 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6288 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6289 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6291 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6292 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6293 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6294 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6295 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6296 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6297 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6298 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6300 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6301 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6302 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6303 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6304 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6305 BB = EmitAtomicBinary(MI, BB, false, 0);
6306 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6307 BB = EmitAtomicBinary(MI, BB, true, 0);
6309 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6310 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6311 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6313 unsigned dest = MI->getOperand(0).getReg();
6314 unsigned ptrA = MI->getOperand(1).getReg();
6315 unsigned ptrB = MI->getOperand(2).getReg();
6316 unsigned oldval = MI->getOperand(3).getReg();
6317 unsigned newval = MI->getOperand(4).getReg();
6318 DebugLoc dl = MI->getDebugLoc();
6320 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6321 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6322 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6323 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6324 F->insert(It, loop1MBB);
6325 F->insert(It, loop2MBB);
6326 F->insert(It, midMBB);
6327 F->insert(It, exitMBB);
6328 exitMBB->splice(exitMBB->begin(), BB,
6329 llvm::next(MachineBasicBlock::iterator(MI)),
6331 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6335 // fallthrough --> loopMBB
6336 BB->addSuccessor(loop1MBB);
6339 // l[wd]arx dest, ptr
6340 // cmp[wd] dest, oldval
6343 // st[wd]cx. newval, ptr
6347 // st[wd]cx. dest, ptr
6350 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6351 .addReg(ptrA).addReg(ptrB);
6352 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6353 .addReg(oldval).addReg(dest);
6354 BuildMI(BB, dl, TII->get(PPC::BCC))
6355 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6356 BB->addSuccessor(loop2MBB);
6357 BB->addSuccessor(midMBB);
6360 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6361 .addReg(newval).addReg(ptrA).addReg(ptrB);
6362 BuildMI(BB, dl, TII->get(PPC::BCC))
6363 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6364 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6365 BB->addSuccessor(loop1MBB);
6366 BB->addSuccessor(exitMBB);
6369 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6370 .addReg(dest).addReg(ptrA).addReg(ptrB);
6371 BB->addSuccessor(exitMBB);
6376 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6377 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6378 // We must use 64-bit registers for addresses when targeting 64-bit,
6379 // since we're actually doing arithmetic on them. Other registers
6381 bool is64bit = PPCSubTarget.isPPC64();
6382 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6384 unsigned dest = MI->getOperand(0).getReg();
6385 unsigned ptrA = MI->getOperand(1).getReg();
6386 unsigned ptrB = MI->getOperand(2).getReg();
6387 unsigned oldval = MI->getOperand(3).getReg();
6388 unsigned newval = MI->getOperand(4).getReg();
6389 DebugLoc dl = MI->getDebugLoc();
6391 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6392 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6393 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6394 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6395 F->insert(It, loop1MBB);
6396 F->insert(It, loop2MBB);
6397 F->insert(It, midMBB);
6398 F->insert(It, exitMBB);
6399 exitMBB->splice(exitMBB->begin(), BB,
6400 llvm::next(MachineBasicBlock::iterator(MI)),
6402 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6404 MachineRegisterInfo &RegInfo = F->getRegInfo();
6405 const TargetRegisterClass *RC =
6406 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6407 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6408 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6409 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6410 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6411 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6412 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6413 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6414 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6415 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6416 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6417 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6418 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6419 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6420 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6422 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6423 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6426 // fallthrough --> loopMBB
6427 BB->addSuccessor(loop1MBB);
6429 // The 4-byte load must be aligned, while a char or short may be
6430 // anywhere in the word. Hence all this nasty bookkeeping code.
6431 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6432 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6433 // xori shift, shift1, 24 [16]
6434 // rlwinm ptr, ptr1, 0, 0, 29
6435 // slw newval2, newval, shift
6436 // slw oldval2, oldval,shift
6437 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6438 // slw mask, mask2, shift
6439 // and newval3, newval2, mask
6440 // and oldval3, oldval2, mask
6442 // lwarx tmpDest, ptr
6443 // and tmp, tmpDest, mask
6444 // cmpw tmp, oldval3
6447 // andc tmp2, tmpDest, mask
6448 // or tmp4, tmp2, newval3
6453 // stwcx. tmpDest, ptr
6455 // srw dest, tmpDest, shift
6456 if (ptrA != ZeroReg) {
6457 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6458 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6459 .addReg(ptrA).addReg(ptrB);
6463 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6464 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6465 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6466 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6468 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6469 .addReg(Ptr1Reg).addImm(0).addImm(61);
6471 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6472 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6473 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6474 .addReg(newval).addReg(ShiftReg);
6475 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6476 .addReg(oldval).addReg(ShiftReg);
6478 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6480 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6481 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6482 .addReg(Mask3Reg).addImm(65535);
6484 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6485 .addReg(Mask2Reg).addReg(ShiftReg);
6486 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6487 .addReg(NewVal2Reg).addReg(MaskReg);
6488 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6489 .addReg(OldVal2Reg).addReg(MaskReg);
6492 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6493 .addReg(ZeroReg).addReg(PtrReg);
6494 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6495 .addReg(TmpDestReg).addReg(MaskReg);
6496 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6497 .addReg(TmpReg).addReg(OldVal3Reg);
6498 BuildMI(BB, dl, TII->get(PPC::BCC))
6499 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6500 BB->addSuccessor(loop2MBB);
6501 BB->addSuccessor(midMBB);
6504 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6505 .addReg(TmpDestReg).addReg(MaskReg);
6506 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6507 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6508 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6509 .addReg(ZeroReg).addReg(PtrReg);
6510 BuildMI(BB, dl, TII->get(PPC::BCC))
6511 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6512 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6513 BB->addSuccessor(loop1MBB);
6514 BB->addSuccessor(exitMBB);
6517 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6518 .addReg(ZeroReg).addReg(PtrReg);
6519 BB->addSuccessor(exitMBB);
6524 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6527 llvm_unreachable("Unexpected instr type to insert");
6530 MI->eraseFromParent(); // The pseudo instruction is gone now.
6534 //===----------------------------------------------------------------------===//
6535 // Target Optimization Hooks
6536 //===----------------------------------------------------------------------===//
6538 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6539 DAGCombinerInfo &DCI) const {
6540 const TargetMachine &TM = getTargetMachine();
6541 SelectionDAG &DAG = DCI.DAG;
6542 DebugLoc dl = N->getDebugLoc();
6543 switch (N->getOpcode()) {
6546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6547 if (C->isNullValue()) // 0 << V -> 0.
6548 return N->getOperand(0);
6552 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6553 if (C->isNullValue()) // 0 >>u V -> 0.
6554 return N->getOperand(0);
6558 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6559 if (C->isNullValue() || // 0 >>s V -> 0.
6560 C->isAllOnesValue()) // -1 >>s V -> -1.
6561 return N->getOperand(0);
6565 case ISD::SINT_TO_FP:
6566 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6567 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6568 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6569 // We allow the src/dst to be either f32/f64, but the intermediate
6570 // type must be i64.
6571 if (N->getOperand(0).getValueType() == MVT::i64 &&
6572 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6573 SDValue Val = N->getOperand(0).getOperand(0);
6574 if (Val.getValueType() == MVT::f32) {
6575 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6576 DCI.AddToWorklist(Val.getNode());
6579 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
6580 DCI.AddToWorklist(Val.getNode());
6581 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
6582 DCI.AddToWorklist(Val.getNode());
6583 if (N->getValueType(0) == MVT::f32) {
6584 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
6585 DAG.getIntPtrConstant(0));
6586 DCI.AddToWorklist(Val.getNode());
6589 } else if (N->getOperand(0).getValueType() == MVT::i32) {
6590 // If the intermediate type is i32, we can avoid the load/store here
6597 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
6598 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
6599 !cast<StoreSDNode>(N)->isTruncatingStore() &&
6600 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
6601 N->getOperand(1).getValueType() == MVT::i32 &&
6602 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
6603 SDValue Val = N->getOperand(1).getOperand(0);
6604 if (Val.getValueType() == MVT::f32) {
6605 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6606 DCI.AddToWorklist(Val.getNode());
6608 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
6609 DCI.AddToWorklist(Val.getNode());
6611 Val = DAG.getNode(PPCISD::STFIWX, dl, MVT::Other, N->getOperand(0), Val,
6612 N->getOperand(2), N->getOperand(3));
6613 DCI.AddToWorklist(Val.getNode());
6617 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
6618 if (cast<StoreSDNode>(N)->isUnindexed() &&
6619 N->getOperand(1).getOpcode() == ISD::BSWAP &&
6620 N->getOperand(1).getNode()->hasOneUse() &&
6621 (N->getOperand(1).getValueType() == MVT::i32 ||
6622 N->getOperand(1).getValueType() == MVT::i16)) {
6623 SDValue BSwapOp = N->getOperand(1).getOperand(0);
6624 // Do an any-extend to 32-bits if this is a half-word input.
6625 if (BSwapOp.getValueType() == MVT::i16)
6626 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
6629 N->getOperand(0), BSwapOp, N->getOperand(2),
6630 DAG.getValueType(N->getOperand(1).getValueType())
6633 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
6634 Ops, array_lengthof(Ops),
6635 cast<StoreSDNode>(N)->getMemoryVT(),
6636 cast<StoreSDNode>(N)->getMemOperand());
6640 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
6641 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
6642 N->getOperand(0).hasOneUse() &&
6643 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16)) {
6644 SDValue Load = N->getOperand(0);
6645 LoadSDNode *LD = cast<LoadSDNode>(Load);
6646 // Create the byte-swapping load.
6648 LD->getChain(), // Chain
6649 LD->getBasePtr(), // Ptr
6650 DAG.getValueType(N->getValueType(0)) // VT
6653 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
6654 DAG.getVTList(MVT::i32, MVT::Other), Ops, 3,
6655 LD->getMemoryVT(), LD->getMemOperand());
6657 // If this is an i16 load, insert the truncate.
6658 SDValue ResVal = BSLoad;
6659 if (N->getValueType(0) == MVT::i16)
6660 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
6662 // First, combine the bswap away. This makes the value produced by the
6664 DCI.CombineTo(N, ResVal);
6666 // Next, combine the load away, we give it a bogus result value but a real
6667 // chain result. The result value is dead because the bswap is dead.
6668 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
6670 // Return N so it doesn't get rechecked!
6671 return SDValue(N, 0);
6675 case PPCISD::VCMP: {
6676 // If a VCMPo node already exists with exactly the same operands as this
6677 // node, use its result instead of this node (VCMPo computes both a CR6 and
6678 // a normal output).
6680 if (!N->getOperand(0).hasOneUse() &&
6681 !N->getOperand(1).hasOneUse() &&
6682 !N->getOperand(2).hasOneUse()) {
6684 // Scan all of the users of the LHS, looking for VCMPo's that match.
6685 SDNode *VCMPoNode = 0;
6687 SDNode *LHSN = N->getOperand(0).getNode();
6688 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
6690 if (UI->getOpcode() == PPCISD::VCMPo &&
6691 UI->getOperand(1) == N->getOperand(1) &&
6692 UI->getOperand(2) == N->getOperand(2) &&
6693 UI->getOperand(0) == N->getOperand(0)) {
6698 // If there is no VCMPo node, or if the flag value has a single use, don't
6700 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
6703 // Look at the (necessarily single) use of the flag value. If it has a
6704 // chain, this transformation is more complex. Note that multiple things
6705 // could use the value result, which we should ignore.
6706 SDNode *FlagUser = 0;
6707 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
6708 FlagUser == 0; ++UI) {
6709 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
6711 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
6712 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
6719 // If the user is a MFCR instruction, we know this is safe. Otherwise we
6720 // give up for right now.
6721 if (FlagUser->getOpcode() == PPCISD::MFCR)
6722 return SDValue(VCMPoNode, 0);
6727 // If this is a branch on an altivec predicate comparison, lower this so
6728 // that we don't have to do a MFCR: instead, branch directly on CR6. This
6729 // lowering is done pre-legalize, because the legalizer lowers the predicate
6730 // compare down to code that is difficult to reassemble.
6731 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
6732 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
6736 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
6737 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
6738 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
6739 assert(isDot && "Can't compare against a vector result!");
6741 // If this is a comparison against something other than 0/1, then we know
6742 // that the condition is never/always true.
6743 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
6744 if (Val != 0 && Val != 1) {
6745 if (CC == ISD::SETEQ) // Cond never true, remove branch.
6746 return N->getOperand(0);
6747 // Always !=, turn it into an unconditional branch.
6748 return DAG.getNode(ISD::BR, dl, MVT::Other,
6749 N->getOperand(0), N->getOperand(4));
6752 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
6754 // Create the PPCISD altivec 'dot' comparison node.
6756 LHS.getOperand(2), // LHS of compare
6757 LHS.getOperand(3), // RHS of compare
6758 DAG.getConstant(CompareOpc, MVT::i32)
6760 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
6761 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
6763 // Unpack the result based on how the target uses it.
6764 PPC::Predicate CompOpc;
6765 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
6766 default: // Can't happen, don't crash on invalid number though.
6767 case 0: // Branch on the value of the EQ bit of CR6.
6768 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
6770 case 1: // Branch on the inverted value of the EQ bit of CR6.
6771 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
6773 case 2: // Branch on the value of the LT bit of CR6.
6774 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
6776 case 3: // Branch on the inverted value of the LT bit of CR6.
6777 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
6781 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
6782 DAG.getConstant(CompOpc, MVT::i32),
6783 DAG.getRegister(PPC::CR6, MVT::i32),
6784 N->getOperand(4), CompNode.getValue(1));
6793 //===----------------------------------------------------------------------===//
6794 // Inline Assembly Support
6795 //===----------------------------------------------------------------------===//
6797 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
6800 const SelectionDAG &DAG,
6801 unsigned Depth) const {
6802 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
6803 switch (Op.getOpcode()) {
6805 case PPCISD::LBRX: {
6806 // lhbrx is known to have the top bits cleared out.
6807 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
6808 KnownZero = 0xFFFF0000;
6811 case ISD::INTRINSIC_WO_CHAIN: {
6812 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
6814 case Intrinsic::ppc_altivec_vcmpbfp_p:
6815 case Intrinsic::ppc_altivec_vcmpeqfp_p:
6816 case Intrinsic::ppc_altivec_vcmpequb_p:
6817 case Intrinsic::ppc_altivec_vcmpequh_p:
6818 case Intrinsic::ppc_altivec_vcmpequw_p:
6819 case Intrinsic::ppc_altivec_vcmpgefp_p:
6820 case Intrinsic::ppc_altivec_vcmpgtfp_p:
6821 case Intrinsic::ppc_altivec_vcmpgtsb_p:
6822 case Intrinsic::ppc_altivec_vcmpgtsh_p:
6823 case Intrinsic::ppc_altivec_vcmpgtsw_p:
6824 case Intrinsic::ppc_altivec_vcmpgtub_p:
6825 case Intrinsic::ppc_altivec_vcmpgtuh_p:
6826 case Intrinsic::ppc_altivec_vcmpgtuw_p:
6827 KnownZero = ~1U; // All bits but the low one are known to be zero.
6835 /// getConstraintType - Given a constraint, return the type of
6836 /// constraint it is for this target.
6837 PPCTargetLowering::ConstraintType
6838 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
6839 if (Constraint.size() == 1) {
6840 switch (Constraint[0]) {
6847 return C_RegisterClass;
6849 // FIXME: While Z does indicate a memory constraint, it specifically
6850 // indicates an r+r address (used in conjunction with the 'y' modifier
6851 // in the replacement string). Currently, we're forcing the base
6852 // register to be r0 in the asm printer (which is interpreted as zero)
6853 // and forming the complete address in the second register. This is
6858 return TargetLowering::getConstraintType(Constraint);
6861 /// Examine constraint type and operand type and determine a weight value.
6862 /// This object must already have been set up with the operand type
6863 /// and the current alternative constraint selected.
6864 TargetLowering::ConstraintWeight
6865 PPCTargetLowering::getSingleConstraintMatchWeight(
6866 AsmOperandInfo &info, const char *constraint) const {
6867 ConstraintWeight weight = CW_Invalid;
6868 Value *CallOperandVal = info.CallOperandVal;
6869 // If we don't have a value, we can't do a match,
6870 // but allow it at the lowest weight.
6871 if (CallOperandVal == NULL)
6873 Type *type = CallOperandVal->getType();
6874 // Look at the constraint type.
6875 switch (*constraint) {
6877 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
6880 if (type->isIntegerTy())
6881 weight = CW_Register;
6884 if (type->isFloatTy())
6885 weight = CW_Register;
6888 if (type->isDoubleTy())
6889 weight = CW_Register;
6892 if (type->isVectorTy())
6893 weight = CW_Register;
6896 weight = CW_Register;
6905 std::pair<unsigned, const TargetRegisterClass*>
6906 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6908 if (Constraint.size() == 1) {
6909 // GCC RS6000 Constraint Letters
6910 switch (Constraint[0]) {
6912 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6913 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
6914 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
6916 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
6917 return std::make_pair(0U, &PPC::G8RCRegClass);
6918 return std::make_pair(0U, &PPC::GPRCRegClass);
6920 if (VT == MVT::f32 || VT == MVT::i32)
6921 return std::make_pair(0U, &PPC::F4RCRegClass);
6922 if (VT == MVT::f64 || VT == MVT::i64)
6923 return std::make_pair(0U, &PPC::F8RCRegClass);
6926 return std::make_pair(0U, &PPC::VRRCRegClass);
6928 return std::make_pair(0U, &PPC::CRRCRegClass);
6932 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6936 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6937 /// vector. If it is invalid, don't add anything to Ops.
6938 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
6939 std::string &Constraint,
6940 std::vector<SDValue>&Ops,
6941 SelectionDAG &DAG) const {
6942 SDValue Result(0,0);
6944 // Only support length 1 constraints.
6945 if (Constraint.length() > 1) return;
6947 char Letter = Constraint[0];
6958 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
6959 if (!CST) return; // Must be an immediate to match.
6960 unsigned Value = CST->getZExtValue();
6962 default: llvm_unreachable("Unknown constraint letter!");
6963 case 'I': // "I" is a signed 16-bit constant.
6964 if ((short)Value == (int)Value)
6965 Result = DAG.getTargetConstant(Value, Op.getValueType());
6967 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
6968 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
6969 if ((short)Value == 0)
6970 Result = DAG.getTargetConstant(Value, Op.getValueType());
6972 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
6973 if ((Value >> 16) == 0)
6974 Result = DAG.getTargetConstant(Value, Op.getValueType());
6976 case 'M': // "M" is a constant that is greater than 31.
6978 Result = DAG.getTargetConstant(Value, Op.getValueType());
6980 case 'N': // "N" is a positive constant that is an exact power of two.
6981 if ((int)Value > 0 && isPowerOf2_32(Value))
6982 Result = DAG.getTargetConstant(Value, Op.getValueType());
6984 case 'O': // "O" is the constant zero.
6986 Result = DAG.getTargetConstant(Value, Op.getValueType());
6988 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
6989 if ((short)-Value == (int)-Value)
6990 Result = DAG.getTargetConstant(Value, Op.getValueType());
6997 if (Result.getNode()) {
6998 Ops.push_back(Result);
7002 // Handle standard constraint letters.
7003 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7006 // isLegalAddressingMode - Return true if the addressing mode represented
7007 // by AM is legal for this target, for a load/store of the specified type.
7008 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7010 // FIXME: PPC does not allow r+i addressing modes for vectors!
7012 // PPC allows a sign-extended 16-bit immediate field.
7013 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
7016 // No global is ever allowed as a base.
7020 // PPC only support r+r,
7022 case 0: // "r+i" or just "i", depending on HasBaseReg.
7025 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7027 // Otherwise we have r+r or r+i.
7030 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7032 // Allow 2*r as r+r.
7035 // No other scales are supported.
7042 /// isLegalAddressImmediate - Return true if the integer value can be used
7043 /// as the offset of the target addressing mode for load / store of the
7045 bool PPCTargetLowering::isLegalAddressImmediate(int64_t V,Type *Ty) const{
7046 // PPC allows a sign-extended 16-bit immediate field.
7047 return (V > -(1 << 16) && V < (1 << 16)-1);
7050 bool PPCTargetLowering::isLegalAddressImmediate(GlobalValue* GV) const {
7054 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7055 SelectionDAG &DAG) const {
7056 MachineFunction &MF = DAG.getMachineFunction();
7057 MachineFrameInfo *MFI = MF.getFrameInfo();
7058 MFI->setReturnAddressIsTaken(true);
7060 DebugLoc dl = Op.getDebugLoc();
7061 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7063 // Make sure the function does not optimize away the store of the RA to
7065 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7066 FuncInfo->setLRStoreRequired();
7067 bool isPPC64 = PPCSubTarget.isPPC64();
7068 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7071 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7074 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7075 isPPC64? MVT::i64 : MVT::i32);
7076 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7077 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7079 MachinePointerInfo(), false, false, false, 0);
7082 // Just load the return address off the stack.
7083 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7084 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7085 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7088 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7089 SelectionDAG &DAG) const {
7090 DebugLoc dl = Op.getDebugLoc();
7091 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7093 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7094 bool isPPC64 = PtrVT == MVT::i64;
7096 MachineFunction &MF = DAG.getMachineFunction();
7097 MachineFrameInfo *MFI = MF.getFrameInfo();
7098 MFI->setFrameAddressIsTaken(true);
7100 // Naked functions never have a frame pointer, and so we use r1. For all
7101 // other functions, this decision must be delayed until during PEI.
7103 if (MF.getFunction()->getAttributes().hasAttribute(
7104 AttributeSet::FunctionIndex, Attribute::Naked))
7105 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7107 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7109 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7112 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7113 FrameAddr, MachinePointerInfo(), false, false,
7119 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7120 // The PowerPC target isn't yet aware of offsets.
7124 /// getOptimalMemOpType - Returns the target specific optimal type for load
7125 /// and store operations as a result of memset, memcpy, and memmove
7126 /// lowering. If DstAlign is zero that means it's safe to destination
7127 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7128 /// means there isn't a need to check it against alignment requirement,
7129 /// probably because the source does not need to be loaded. If 'IsMemset' is
7130 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7131 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7132 /// source is constant so it does not need to be loaded.
7133 /// It returns EVT::Other if the type should be determined using generic
7134 /// target-independent logic.
7135 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7136 unsigned DstAlign, unsigned SrcAlign,
7137 bool IsMemset, bool ZeroMemset,
7139 MachineFunction &MF) const {
7140 if (this->PPCSubTarget.isPPC64()) {
7147 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7149 if (DisablePPCUnaligned)
7152 // PowerPC supports unaligned memory access for simple non-vector types.
7153 // Although accessing unaligned addresses is not as efficient as accessing
7154 // aligned addresses, it is generally more efficient than manual expansion,
7155 // and generally only traps for software emulation when crossing page
7161 if (VT.getSimpleVT().isVector())
7164 if (VT == MVT::ppcf128)
7173 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7174 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7175 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7176 /// is expanded to mul + add.
7177 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7181 switch (VT.getSimpleVT().SimpleTy) {
7193 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7195 return TargetLowering::getSchedulingPreference(N);