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 "PPCTargetObjectFile.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/SelectionDAG.h"
27 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/Constants.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetOptions.h"
40 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
41 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
43 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
44 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
46 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
47 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
49 static TargetLoweringObjectFile *CreateTLOF(const PPCTargetMachine &TM) {
50 if (TM.getSubtargetImpl()->isDarwin())
51 return new TargetLoweringObjectFileMachO();
53 if (TM.getSubtargetImpl()->isSVR4ABI())
54 return new PPC64LinuxTargetObjectFile();
56 return new TargetLoweringObjectFileELF();
59 PPCTargetLowering::PPCTargetLowering(PPCTargetMachine &TM)
60 : TargetLowering(TM, CreateTLOF(TM)), PPCSubTarget(*TM.getSubtargetImpl()) {
61 const PPCSubtarget *Subtarget = &TM.getSubtarget<PPCSubtarget>();
65 // Use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(true);
67 setUseUnderscoreLongJmp(true);
69 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
70 // arguments are at least 4/8 bytes aligned.
71 bool isPPC64 = Subtarget->isPPC64();
72 setMinStackArgumentAlignment(isPPC64 ? 8:4);
74 // Set up the register classes.
75 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
76 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
77 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
79 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
80 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
81 setLoadExtAction(ISD::SEXTLOAD, MVT::i8, Expand);
83 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
85 // PowerPC has pre-inc load and store's.
86 setIndexedLoadAction(ISD::PRE_INC, MVT::i1, Legal);
87 setIndexedLoadAction(ISD::PRE_INC, MVT::i8, Legal);
88 setIndexedLoadAction(ISD::PRE_INC, MVT::i16, Legal);
89 setIndexedLoadAction(ISD::PRE_INC, MVT::i32, Legal);
90 setIndexedLoadAction(ISD::PRE_INC, MVT::i64, Legal);
91 setIndexedStoreAction(ISD::PRE_INC, MVT::i1, Legal);
92 setIndexedStoreAction(ISD::PRE_INC, MVT::i8, Legal);
93 setIndexedStoreAction(ISD::PRE_INC, MVT::i16, Legal);
94 setIndexedStoreAction(ISD::PRE_INC, MVT::i32, Legal);
95 setIndexedStoreAction(ISD::PRE_INC, MVT::i64, Legal);
97 // This is used in the ppcf128->int sequence. Note it has different semantics
98 // from FP_ROUND: that rounds to nearest, this rounds to zero.
99 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
101 // We do not currently implement these libm ops for PowerPC.
102 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
103 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
104 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
105 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
106 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
107 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
109 // PowerPC has no SREM/UREM instructions
110 setOperationAction(ISD::SREM, MVT::i32, Expand);
111 setOperationAction(ISD::UREM, MVT::i32, Expand);
112 setOperationAction(ISD::SREM, MVT::i64, Expand);
113 setOperationAction(ISD::UREM, MVT::i64, Expand);
115 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
116 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
117 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
118 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
119 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
120 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
121 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
122 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
123 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
125 // We don't support sin/cos/sqrt/fmod/pow
126 setOperationAction(ISD::FSIN , MVT::f64, Expand);
127 setOperationAction(ISD::FCOS , MVT::f64, Expand);
128 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
129 setOperationAction(ISD::FREM , MVT::f64, Expand);
130 setOperationAction(ISD::FPOW , MVT::f64, Expand);
131 setOperationAction(ISD::FMA , MVT::f64, Legal);
132 setOperationAction(ISD::FSIN , MVT::f32, Expand);
133 setOperationAction(ISD::FCOS , MVT::f32, Expand);
134 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
135 setOperationAction(ISD::FREM , MVT::f32, Expand);
136 setOperationAction(ISD::FPOW , MVT::f32, Expand);
137 setOperationAction(ISD::FMA , MVT::f32, Legal);
139 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
141 // If we're enabling GP optimizations, use hardware square root
142 if (!Subtarget->hasFSQRT() &&
143 !(TM.Options.UnsafeFPMath &&
144 Subtarget->hasFRSQRTE() && Subtarget->hasFRE()))
145 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
147 if (!Subtarget->hasFSQRT() &&
148 !(TM.Options.UnsafeFPMath &&
149 Subtarget->hasFRSQRTES() && Subtarget->hasFRES()))
150 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
152 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
153 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
155 if (Subtarget->hasFPRND()) {
156 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
157 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
158 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
160 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
161 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
162 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
164 // frin does not implement "ties to even." Thus, this is safe only in
166 if (TM.Options.UnsafeFPMath) {
167 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
168 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
170 // These need to set FE_INEXACT, and use a custom inserter.
171 setOperationAction(ISD::FRINT, MVT::f64, Legal);
172 setOperationAction(ISD::FRINT, MVT::f32, Legal);
176 // PowerPC does not have BSWAP, CTPOP or CTTZ
177 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
178 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
179 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
180 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
181 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
182 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
183 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
184 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
186 if (Subtarget->hasPOPCNTD()) {
187 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
188 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
190 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
191 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
194 // PowerPC does not have ROTR
195 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
196 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
198 // PowerPC does not have Select
199 setOperationAction(ISD::SELECT, MVT::i32, Expand);
200 setOperationAction(ISD::SELECT, MVT::i64, Expand);
201 setOperationAction(ISD::SELECT, MVT::f32, Expand);
202 setOperationAction(ISD::SELECT, MVT::f64, Expand);
204 // PowerPC wants to turn select_cc of FP into fsel when possible.
205 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
206 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
208 // PowerPC wants to optimize integer setcc a bit
209 setOperationAction(ISD::SETCC, MVT::i32, Custom);
211 // PowerPC does not have BRCOND which requires SetCC
212 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
214 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
216 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
217 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
219 // PowerPC does not have [U|S]INT_TO_FP
220 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
221 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
223 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
224 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
225 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
226 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
228 // We cannot sextinreg(i1). Expand to shifts.
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
231 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
232 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
233 // support continuation, user-level threading, and etc.. As a result, no
234 // other SjLj exception interfaces are implemented and please don't build
235 // your own exception handling based on them.
236 // LLVM/Clang supports zero-cost DWARF exception handling.
237 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
238 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
240 // We want to legalize GlobalAddress and ConstantPool nodes into the
241 // appropriate instructions to materialize the address.
242 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
243 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
244 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
245 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
246 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
247 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
248 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
249 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
250 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
251 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
254 setOperationAction(ISD::TRAP, MVT::Other, Legal);
256 // TRAMPOLINE is custom lowered.
257 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
258 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
260 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
261 setOperationAction(ISD::VASTART , MVT::Other, Custom);
263 if (Subtarget->isSVR4ABI()) {
265 // VAARG always uses double-word chunks, so promote anything smaller.
266 setOperationAction(ISD::VAARG, MVT::i1, Promote);
267 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
268 setOperationAction(ISD::VAARG, MVT::i8, Promote);
269 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
270 setOperationAction(ISD::VAARG, MVT::i16, Promote);
271 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
272 setOperationAction(ISD::VAARG, MVT::i32, Promote);
273 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
274 setOperationAction(ISD::VAARG, MVT::Other, Expand);
276 // VAARG is custom lowered with the 32-bit SVR4 ABI.
277 setOperationAction(ISD::VAARG, MVT::Other, Custom);
278 setOperationAction(ISD::VAARG, MVT::i64, Custom);
281 setOperationAction(ISD::VAARG, MVT::Other, Expand);
283 // Use the default implementation.
284 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
285 setOperationAction(ISD::VAEND , MVT::Other, Expand);
286 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
287 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
288 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
289 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
291 // We want to custom lower some of our intrinsics.
292 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
294 // To handle counter-based loop conditions.
295 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
297 // Comparisons that require checking two conditions.
298 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
299 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
300 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
301 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
302 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
303 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
304 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
305 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
306 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
307 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
308 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
309 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
311 if (Subtarget->has64BitSupport()) {
312 // They also have instructions for converting between i64 and fp.
313 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
314 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
315 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
316 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
317 // This is just the low 32 bits of a (signed) fp->i64 conversion.
318 // We cannot do this with Promote because i64 is not a legal type.
319 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
321 if (PPCSubTarget.hasLFIWAX() || Subtarget->isPPC64())
322 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
324 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
325 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
328 // With the instructions enabled under FPCVT, we can do everything.
329 if (PPCSubTarget.hasFPCVT()) {
330 if (Subtarget->has64BitSupport()) {
331 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
332 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
333 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
334 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
337 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
338 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
339 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
340 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
343 if (Subtarget->use64BitRegs()) {
344 // 64-bit PowerPC implementations can support i64 types directly
345 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
346 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
347 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
348 // 64-bit PowerPC wants to expand i128 shifts itself.
349 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
350 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
351 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
353 // 32-bit PowerPC wants to expand i64 shifts itself.
354 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
355 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
356 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
359 if (Subtarget->hasAltivec()) {
360 // First set operation action for all vector types to expand. Then we
361 // will selectively turn on ones that can be effectively codegen'd.
362 for (unsigned i = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
363 i <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++i) {
364 MVT::SimpleValueType VT = (MVT::SimpleValueType)i;
366 // add/sub are legal for all supported vector VT's.
367 setOperationAction(ISD::ADD , VT, Legal);
368 setOperationAction(ISD::SUB , VT, Legal);
370 // We promote all shuffles to v16i8.
371 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
372 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
374 // We promote all non-typed operations to v4i32.
375 setOperationAction(ISD::AND , VT, Promote);
376 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
377 setOperationAction(ISD::OR , VT, Promote);
378 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
379 setOperationAction(ISD::XOR , VT, Promote);
380 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
381 setOperationAction(ISD::LOAD , VT, Promote);
382 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
383 setOperationAction(ISD::SELECT, VT, Promote);
384 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
385 setOperationAction(ISD::STORE, VT, Promote);
386 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
388 // No other operations are legal.
389 setOperationAction(ISD::MUL , VT, Expand);
390 setOperationAction(ISD::SDIV, VT, Expand);
391 setOperationAction(ISD::SREM, VT, Expand);
392 setOperationAction(ISD::UDIV, VT, Expand);
393 setOperationAction(ISD::UREM, VT, Expand);
394 setOperationAction(ISD::FDIV, VT, Expand);
395 setOperationAction(ISD::FREM, VT, Expand);
396 setOperationAction(ISD::FNEG, VT, Expand);
397 setOperationAction(ISD::FSQRT, VT, Expand);
398 setOperationAction(ISD::FLOG, VT, Expand);
399 setOperationAction(ISD::FLOG10, VT, Expand);
400 setOperationAction(ISD::FLOG2, VT, Expand);
401 setOperationAction(ISD::FEXP, VT, Expand);
402 setOperationAction(ISD::FEXP2, VT, Expand);
403 setOperationAction(ISD::FSIN, VT, Expand);
404 setOperationAction(ISD::FCOS, VT, Expand);
405 setOperationAction(ISD::FABS, VT, Expand);
406 setOperationAction(ISD::FPOWI, VT, Expand);
407 setOperationAction(ISD::FFLOOR, VT, Expand);
408 setOperationAction(ISD::FCEIL, VT, Expand);
409 setOperationAction(ISD::FTRUNC, VT, Expand);
410 setOperationAction(ISD::FRINT, VT, Expand);
411 setOperationAction(ISD::FNEARBYINT, VT, Expand);
412 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
413 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
414 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
415 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
416 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
417 setOperationAction(ISD::UDIVREM, VT, Expand);
418 setOperationAction(ISD::SDIVREM, VT, Expand);
419 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
420 setOperationAction(ISD::FPOW, VT, Expand);
421 setOperationAction(ISD::CTPOP, VT, Expand);
422 setOperationAction(ISD::CTLZ, VT, Expand);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
424 setOperationAction(ISD::CTTZ, VT, Expand);
425 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
426 setOperationAction(ISD::VSELECT, VT, Expand);
427 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
429 for (unsigned j = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
430 j <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++j) {
431 MVT::SimpleValueType InnerVT = (MVT::SimpleValueType)j;
432 setTruncStoreAction(VT, InnerVT, Expand);
434 setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
435 setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
436 setLoadExtAction(ISD::EXTLOAD, VT, Expand);
439 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
440 // with merges, splats, etc.
441 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
443 setOperationAction(ISD::AND , MVT::v4i32, Legal);
444 setOperationAction(ISD::OR , MVT::v4i32, Legal);
445 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
446 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
447 setOperationAction(ISD::SELECT, MVT::v4i32, Expand);
448 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
449 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
450 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
451 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
452 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
453 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
454 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
455 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
456 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
458 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
459 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
460 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
461 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
463 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
464 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
466 if (TM.Options.UnsafeFPMath) {
467 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
468 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
471 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
472 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
473 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
475 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
476 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
478 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
479 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
480 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
481 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
483 // Altivec does not contain unordered floating-point compare instructions
484 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
485 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
486 setCondCodeAction(ISD::SETUGT, MVT::v4f32, Expand);
487 setCondCodeAction(ISD::SETUGE, MVT::v4f32, Expand);
488 setCondCodeAction(ISD::SETULT, MVT::v4f32, Expand);
489 setCondCodeAction(ISD::SETULE, MVT::v4f32, Expand);
491 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
492 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
495 if (Subtarget->has64BitSupport()) {
496 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
497 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
500 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
501 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
502 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
503 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
505 setBooleanContents(ZeroOrOneBooleanContent);
506 // Altivec instructions set fields to all zeros or all ones.
507 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
510 setStackPointerRegisterToSaveRestore(PPC::X1);
511 setExceptionPointerRegister(PPC::X3);
512 setExceptionSelectorRegister(PPC::X4);
514 setStackPointerRegisterToSaveRestore(PPC::R1);
515 setExceptionPointerRegister(PPC::R3);
516 setExceptionSelectorRegister(PPC::R4);
519 // We have target-specific dag combine patterns for the following nodes:
520 setTargetDAGCombine(ISD::SINT_TO_FP);
521 setTargetDAGCombine(ISD::LOAD);
522 setTargetDAGCombine(ISD::STORE);
523 setTargetDAGCombine(ISD::BR_CC);
524 setTargetDAGCombine(ISD::BSWAP);
525 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
527 // Use reciprocal estimates.
528 if (TM.Options.UnsafeFPMath) {
529 setTargetDAGCombine(ISD::FDIV);
530 setTargetDAGCombine(ISD::FSQRT);
533 // Darwin long double math library functions have $LDBL128 appended.
534 if (Subtarget->isDarwin()) {
535 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
536 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
537 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
538 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
539 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
540 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
541 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
542 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
543 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
544 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
547 setMinFunctionAlignment(2);
548 if (PPCSubTarget.isDarwin())
549 setPrefFunctionAlignment(4);
551 if (isPPC64 && Subtarget->isJITCodeModel())
552 // Temporary workaround for the inability of PPC64 JIT to handle jump
554 setSupportJumpTables(false);
556 setInsertFencesForAtomic(true);
558 setSchedulingPreference(Sched::Hybrid);
560 computeRegisterProperties();
562 // The Freescale cores does better with aggressive inlining of memcpy and
563 // friends. Gcc uses same threshold of 128 bytes (= 32 word stores).
564 if (Subtarget->getDarwinDirective() == PPC::DIR_E500mc ||
565 Subtarget->getDarwinDirective() == PPC::DIR_E5500) {
566 MaxStoresPerMemset = 32;
567 MaxStoresPerMemsetOptSize = 16;
568 MaxStoresPerMemcpy = 32;
569 MaxStoresPerMemcpyOptSize = 8;
570 MaxStoresPerMemmove = 32;
571 MaxStoresPerMemmoveOptSize = 8;
573 setPrefFunctionAlignment(4);
577 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
578 /// function arguments in the caller parameter area.
579 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
580 const TargetMachine &TM = getTargetMachine();
581 // Darwin passes everything on 4 byte boundary.
582 if (TM.getSubtarget<PPCSubtarget>().isDarwin())
585 // 16byte and wider vectors are passed on 16byte boundary.
586 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
587 if (VTy->getBitWidth() >= 128)
590 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
591 if (PPCSubTarget.isPPC64())
597 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
600 case PPCISD::FSEL: return "PPCISD::FSEL";
601 case PPCISD::FCFID: return "PPCISD::FCFID";
602 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
603 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
604 case PPCISD::FRE: return "PPCISD::FRE";
605 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
606 case PPCISD::STFIWX: return "PPCISD::STFIWX";
607 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
608 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
609 case PPCISD::VPERM: return "PPCISD::VPERM";
610 case PPCISD::Hi: return "PPCISD::Hi";
611 case PPCISD::Lo: return "PPCISD::Lo";
612 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
613 case PPCISD::TOC_RESTORE: return "PPCISD::TOC_RESTORE";
614 case PPCISD::LOAD: return "PPCISD::LOAD";
615 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
616 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
617 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
618 case PPCISD::SRL: return "PPCISD::SRL";
619 case PPCISD::SRA: return "PPCISD::SRA";
620 case PPCISD::SHL: return "PPCISD::SHL";
621 case PPCISD::CALL: return "PPCISD::CALL";
622 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
623 case PPCISD::MTCTR: return "PPCISD::MTCTR";
624 case PPCISD::BCTRL: return "PPCISD::BCTRL";
625 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
626 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
627 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
628 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
629 case PPCISD::VCMP: return "PPCISD::VCMP";
630 case PPCISD::VCMPo: return "PPCISD::VCMPo";
631 case PPCISD::LBRX: return "PPCISD::LBRX";
632 case PPCISD::STBRX: return "PPCISD::STBRX";
633 case PPCISD::LARX: return "PPCISD::LARX";
634 case PPCISD::STCX: return "PPCISD::STCX";
635 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
636 case PPCISD::BDNZ: return "PPCISD::BDNZ";
637 case PPCISD::BDZ: return "PPCISD::BDZ";
638 case PPCISD::MFFS: return "PPCISD::MFFS";
639 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
640 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
641 case PPCISD::CR6SET: return "PPCISD::CR6SET";
642 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
643 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
644 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
645 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
646 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
647 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
648 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
649 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
650 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
651 case PPCISD::GET_TLS_ADDR: return "PPCISD::GET_TLS_ADDR";
652 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
653 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
654 case PPCISD::GET_TLSLD_ADDR: return "PPCISD::GET_TLSLD_ADDR";
655 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
656 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
657 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
658 case PPCISD::SC: return "PPCISD::SC";
662 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
665 return VT.changeVectorElementTypeToInteger();
668 //===----------------------------------------------------------------------===//
669 // Node matching predicates, for use by the tblgen matching code.
670 //===----------------------------------------------------------------------===//
672 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
673 static bool isFloatingPointZero(SDValue Op) {
674 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
675 return CFP->getValueAPF().isZero();
676 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
677 // Maybe this has already been legalized into the constant pool?
678 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
679 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
680 return CFP->getValueAPF().isZero();
685 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
686 /// true if Op is undef or if it matches the specified value.
687 static bool isConstantOrUndef(int Op, int Val) {
688 return Op < 0 || Op == Val;
691 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
692 /// VPKUHUM instruction.
693 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
695 for (unsigned i = 0; i != 16; ++i)
696 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
699 for (unsigned i = 0; i != 8; ++i)
700 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1) ||
701 !isConstantOrUndef(N->getMaskElt(i+8), i*2+1))
707 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
708 /// VPKUWUM instruction.
709 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, bool isUnary) {
711 for (unsigned i = 0; i != 16; i += 2)
712 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
713 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
716 for (unsigned i = 0; i != 8; i += 2)
717 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
718 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3) ||
719 !isConstantOrUndef(N->getMaskElt(i+8), i*2+2) ||
720 !isConstantOrUndef(N->getMaskElt(i+9), i*2+3))
726 /// isVMerge - Common function, used to match vmrg* shuffles.
728 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
729 unsigned LHSStart, unsigned RHSStart) {
730 assert(N->getValueType(0) == MVT::v16i8 &&
731 "PPC only supports shuffles by bytes!");
732 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
733 "Unsupported merge size!");
735 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
736 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
737 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
738 LHSStart+j+i*UnitSize) ||
739 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
740 RHSStart+j+i*UnitSize))
746 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
747 /// a VRGL* instruction with the specified unit size (1,2 or 4 bytes).
748 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
751 return isVMerge(N, UnitSize, 8, 24);
752 return isVMerge(N, UnitSize, 8, 8);
755 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
756 /// a VRGH* instruction with the specified unit size (1,2 or 4 bytes).
757 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
760 return isVMerge(N, UnitSize, 0, 16);
761 return isVMerge(N, UnitSize, 0, 0);
765 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
766 /// amount, otherwise return -1.
767 int PPC::isVSLDOIShuffleMask(SDNode *N, bool isUnary) {
768 assert(N->getValueType(0) == MVT::v16i8 &&
769 "PPC only supports shuffles by bytes!");
771 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
773 // Find the first non-undef value in the shuffle mask.
775 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
778 if (i == 16) return -1; // all undef.
780 // Otherwise, check to see if the rest of the elements are consecutively
781 // numbered from this value.
782 unsigned ShiftAmt = SVOp->getMaskElt(i);
783 if (ShiftAmt < i) return -1;
787 // Check the rest of the elements to see if they are consecutive.
788 for (++i; i != 16; ++i)
789 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
792 // Check the rest of the elements to see if they are consecutive.
793 for (++i; i != 16; ++i)
794 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
800 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
801 /// specifies a splat of a single element that is suitable for input to
802 /// VSPLTB/VSPLTH/VSPLTW.
803 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
804 assert(N->getValueType(0) == MVT::v16i8 &&
805 (EltSize == 1 || EltSize == 2 || EltSize == 4));
807 // This is a splat operation if each element of the permute is the same, and
808 // if the value doesn't reference the second vector.
809 unsigned ElementBase = N->getMaskElt(0);
811 // FIXME: Handle UNDEF elements too!
812 if (ElementBase >= 16)
815 // Check that the indices are consecutive, in the case of a multi-byte element
816 // splatted with a v16i8 mask.
817 for (unsigned i = 1; i != EltSize; ++i)
818 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
821 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
822 if (N->getMaskElt(i) < 0) continue;
823 for (unsigned j = 0; j != EltSize; ++j)
824 if (N->getMaskElt(i+j) != N->getMaskElt(j))
830 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
832 bool PPC::isAllNegativeZeroVector(SDNode *N) {
833 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
835 APInt APVal, APUndef;
839 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
840 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
841 return CFP->getValueAPF().isNegZero();
846 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
847 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
848 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize) {
849 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
850 assert(isSplatShuffleMask(SVOp, EltSize));
851 return SVOp->getMaskElt(0) / EltSize;
854 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
855 /// by using a vspltis[bhw] instruction of the specified element size, return
856 /// the constant being splatted. The ByteSize field indicates the number of
857 /// bytes of each element [124] -> [bhw].
858 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
861 // If ByteSize of the splat is bigger than the element size of the
862 // build_vector, then we have a case where we are checking for a splat where
863 // multiple elements of the buildvector are folded together into a single
864 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
865 unsigned EltSize = 16/N->getNumOperands();
866 if (EltSize < ByteSize) {
867 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
868 SDValue UniquedVals[4];
869 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
871 // See if all of the elements in the buildvector agree across.
872 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
873 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
874 // If the element isn't a constant, bail fully out.
875 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
878 if (UniquedVals[i&(Multiple-1)].getNode() == 0)
879 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
880 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
881 return SDValue(); // no match.
884 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
885 // either constant or undef values that are identical for each chunk. See
886 // if these chunks can form into a larger vspltis*.
888 // Check to see if all of the leading entries are either 0 or -1. If
889 // neither, then this won't fit into the immediate field.
890 bool LeadingZero = true;
891 bool LeadingOnes = true;
892 for (unsigned i = 0; i != Multiple-1; ++i) {
893 if (UniquedVals[i].getNode() == 0) continue; // Must have been undefs.
895 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
896 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
898 // Finally, check the least significant entry.
900 if (UniquedVals[Multiple-1].getNode() == 0)
901 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
902 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
904 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
907 if (UniquedVals[Multiple-1].getNode() == 0)
908 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
909 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
910 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
911 return DAG.getTargetConstant(Val, MVT::i32);
917 // Check to see if this buildvec has a single non-undef value in its elements.
918 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
919 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
920 if (OpVal.getNode() == 0)
921 OpVal = N->getOperand(i);
922 else if (OpVal != N->getOperand(i))
926 if (OpVal.getNode() == 0) return SDValue(); // All UNDEF: use implicit def.
928 unsigned ValSizeInBytes = EltSize;
930 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
931 Value = CN->getZExtValue();
932 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
933 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
934 Value = FloatToBits(CN->getValueAPF().convertToFloat());
937 // If the splat value is larger than the element value, then we can never do
938 // this splat. The only case that we could fit the replicated bits into our
939 // immediate field for would be zero, and we prefer to use vxor for it.
940 if (ValSizeInBytes < ByteSize) return SDValue();
942 // If the element value is larger than the splat value, cut it in half and
943 // check to see if the two halves are equal. Continue doing this until we
944 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
945 while (ValSizeInBytes > ByteSize) {
946 ValSizeInBytes >>= 1;
948 // If the top half equals the bottom half, we're still ok.
949 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
950 (Value & ((1 << (8*ValSizeInBytes))-1)))
954 // Properly sign extend the value.
955 int MaskVal = SignExtend32(Value, ByteSize * 8);
957 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
958 if (MaskVal == 0) return SDValue();
960 // Finally, if this value fits in a 5 bit sext field, return it
961 if (SignExtend32<5>(MaskVal) == MaskVal)
962 return DAG.getTargetConstant(MaskVal, MVT::i32);
966 //===----------------------------------------------------------------------===//
967 // Addressing Mode Selection
968 //===----------------------------------------------------------------------===//
970 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
971 /// or 64-bit immediate, and if the value can be accurately represented as a
972 /// sign extension from a 16-bit value. If so, this returns true and the
974 static bool isIntS16Immediate(SDNode *N, short &Imm) {
975 if (N->getOpcode() != ISD::Constant)
978 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
979 if (N->getValueType(0) == MVT::i32)
980 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
982 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
984 static bool isIntS16Immediate(SDValue Op, short &Imm) {
985 return isIntS16Immediate(Op.getNode(), Imm);
989 /// SelectAddressRegReg - Given the specified addressed, check to see if it
990 /// can be represented as an indexed [r+r] operation. Returns false if it
991 /// can be more efficiently represented with [r+imm].
992 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
994 SelectionDAG &DAG) const {
996 if (N.getOpcode() == ISD::ADD) {
997 if (isIntS16Immediate(N.getOperand(1), imm))
999 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1000 return false; // r+i
1002 Base = N.getOperand(0);
1003 Index = N.getOperand(1);
1005 } else if (N.getOpcode() == ISD::OR) {
1006 if (isIntS16Immediate(N.getOperand(1), imm))
1007 return false; // r+i can fold it if we can.
1009 // If this is an or of disjoint bitfields, we can codegen this as an add
1010 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1012 APInt LHSKnownZero, LHSKnownOne;
1013 APInt RHSKnownZero, RHSKnownOne;
1014 DAG.ComputeMaskedBits(N.getOperand(0),
1015 LHSKnownZero, LHSKnownOne);
1017 if (LHSKnownZero.getBoolValue()) {
1018 DAG.ComputeMaskedBits(N.getOperand(1),
1019 RHSKnownZero, RHSKnownOne);
1020 // If all of the bits are known zero on the LHS or RHS, the add won't
1022 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1023 Base = N.getOperand(0);
1024 Index = N.getOperand(1);
1033 /// Returns true if the address N can be represented by a base register plus
1034 /// a signed 16-bit displacement [r+imm], and if it is not better
1035 /// represented as reg+reg. If Aligned is true, only accept displacements
1036 /// suitable for STD and friends, i.e. multiples of 4.
1037 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1040 bool Aligned) const {
1041 // FIXME dl should come from parent load or store, not from address
1043 // If this can be more profitably realized as r+r, fail.
1044 if (SelectAddressRegReg(N, Disp, Base, DAG))
1047 if (N.getOpcode() == ISD::ADD) {
1049 if (isIntS16Immediate(N.getOperand(1), imm) &&
1050 (!Aligned || (imm & 3) == 0)) {
1051 Disp = DAG.getTargetConstant(imm, N.getValueType());
1052 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1053 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1055 Base = N.getOperand(0);
1057 return true; // [r+i]
1058 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1059 // Match LOAD (ADD (X, Lo(G))).
1060 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1061 && "Cannot handle constant offsets yet!");
1062 Disp = N.getOperand(1).getOperand(0); // The global address.
1063 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1064 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1065 Disp.getOpcode() == ISD::TargetConstantPool ||
1066 Disp.getOpcode() == ISD::TargetJumpTable);
1067 Base = N.getOperand(0);
1068 return true; // [&g+r]
1070 } else if (N.getOpcode() == ISD::OR) {
1072 if (isIntS16Immediate(N.getOperand(1), imm) &&
1073 (!Aligned || (imm & 3) == 0)) {
1074 // If this is an or of disjoint bitfields, we can codegen this as an add
1075 // (for better address arithmetic) if the LHS and RHS of the OR are
1076 // provably disjoint.
1077 APInt LHSKnownZero, LHSKnownOne;
1078 DAG.ComputeMaskedBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1080 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1081 // If all of the bits are known zero on the LHS or RHS, the add won't
1083 Base = N.getOperand(0);
1084 Disp = DAG.getTargetConstant(imm, N.getValueType());
1088 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1089 // Loading from a constant address.
1091 // If this address fits entirely in a 16-bit sext immediate field, codegen
1094 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1095 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1096 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1097 CN->getValueType(0));
1101 // Handle 32-bit sext immediates with LIS + addr mode.
1102 if ((CN->getValueType(0) == MVT::i32 ||
1103 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1104 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1105 int Addr = (int)CN->getZExtValue();
1107 // Otherwise, break this down into an LIS + disp.
1108 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1110 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1111 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1112 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1117 Disp = DAG.getTargetConstant(0, getPointerTy());
1118 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
1119 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1122 return true; // [r+0]
1125 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1126 /// represented as an indexed [r+r] operation.
1127 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1129 SelectionDAG &DAG) const {
1130 // Check to see if we can easily represent this as an [r+r] address. This
1131 // will fail if it thinks that the address is more profitably represented as
1132 // reg+imm, e.g. where imm = 0.
1133 if (SelectAddressRegReg(N, Base, Index, DAG))
1136 // If the operand is an addition, always emit this as [r+r], since this is
1137 // better (for code size, and execution, as the memop does the add for free)
1138 // than emitting an explicit add.
1139 if (N.getOpcode() == ISD::ADD) {
1140 Base = N.getOperand(0);
1141 Index = N.getOperand(1);
1145 // Otherwise, do it the hard way, using R0 as the base register.
1146 Base = DAG.getRegister(PPCSubTarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1152 /// getPreIndexedAddressParts - returns true by value, base pointer and
1153 /// offset pointer and addressing mode by reference if the node's address
1154 /// can be legally represented as pre-indexed load / store address.
1155 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1157 ISD::MemIndexedMode &AM,
1158 SelectionDAG &DAG) const {
1159 if (DisablePPCPreinc) return false;
1165 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1166 Ptr = LD->getBasePtr();
1167 VT = LD->getMemoryVT();
1168 Alignment = LD->getAlignment();
1169 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1170 Ptr = ST->getBasePtr();
1171 VT = ST->getMemoryVT();
1172 Alignment = ST->getAlignment();
1177 // PowerPC doesn't have preinc load/store instructions for vectors.
1181 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1183 // Common code will reject creating a pre-inc form if the base pointer
1184 // is a frame index, or if N is a store and the base pointer is either
1185 // the same as or a predecessor of the value being stored. Check for
1186 // those situations here, and try with swapped Base/Offset instead.
1189 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1192 SDValue Val = cast<StoreSDNode>(N)->getValue();
1193 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1198 std::swap(Base, Offset);
1204 // LDU/STU can only handle immediates that are a multiple of 4.
1205 if (VT != MVT::i64) {
1206 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1209 // LDU/STU need an address with at least 4-byte alignment.
1213 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1217 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1218 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1219 // sext i32 to i64 when addr mode is r+i.
1220 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1221 LD->getExtensionType() == ISD::SEXTLOAD &&
1222 isa<ConstantSDNode>(Offset))
1230 //===----------------------------------------------------------------------===//
1231 // LowerOperation implementation
1232 //===----------------------------------------------------------------------===//
1234 /// GetLabelAccessInfo - Return true if we should reference labels using a
1235 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1236 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1237 unsigned &LoOpFlags, const GlobalValue *GV = 0) {
1238 HiOpFlags = PPCII::MO_HA;
1239 LoOpFlags = PPCII::MO_LO;
1241 // Don't use the pic base if not in PIC relocation model. Or if we are on a
1242 // non-darwin platform. We don't support PIC on other platforms yet.
1243 bool isPIC = TM.getRelocationModel() == Reloc::PIC_ &&
1244 TM.getSubtarget<PPCSubtarget>().isDarwin();
1246 HiOpFlags |= PPCII::MO_PIC_FLAG;
1247 LoOpFlags |= PPCII::MO_PIC_FLAG;
1250 // If this is a reference to a global value that requires a non-lazy-ptr, make
1251 // sure that instruction lowering adds it.
1252 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1253 HiOpFlags |= PPCII::MO_NLP_FLAG;
1254 LoOpFlags |= PPCII::MO_NLP_FLAG;
1256 if (GV->hasHiddenVisibility()) {
1257 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1258 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1265 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1266 SelectionDAG &DAG) {
1267 EVT PtrVT = HiPart.getValueType();
1268 SDValue Zero = DAG.getConstant(0, PtrVT);
1271 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1272 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1274 // With PIC, the first instruction is actually "GR+hi(&G)".
1276 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1277 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1279 // Generate non-pic code that has direct accesses to the constant pool.
1280 // The address of the global is just (hi(&g)+lo(&g)).
1281 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1284 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1285 SelectionDAG &DAG) const {
1286 EVT PtrVT = Op.getValueType();
1287 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1288 const Constant *C = CP->getConstVal();
1290 // 64-bit SVR4 ABI code is always position-independent.
1291 // The actual address of the GlobalValue is stored in the TOC.
1292 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1293 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1294 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1295 DAG.getRegister(PPC::X2, MVT::i64));
1298 unsigned MOHiFlag, MOLoFlag;
1299 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1301 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1303 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1304 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1307 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1308 EVT PtrVT = Op.getValueType();
1309 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1311 // 64-bit SVR4 ABI code is always position-independent.
1312 // The actual address of the GlobalValue is stored in the TOC.
1313 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1314 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1315 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1316 DAG.getRegister(PPC::X2, MVT::i64));
1319 unsigned MOHiFlag, MOLoFlag;
1320 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1321 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1322 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1323 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1326 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1327 SelectionDAG &DAG) const {
1328 EVT PtrVT = Op.getValueType();
1330 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1332 unsigned MOHiFlag, MOLoFlag;
1333 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1334 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1335 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1336 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1339 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1340 SelectionDAG &DAG) const {
1342 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1344 const GlobalValue *GV = GA->getGlobal();
1345 EVT PtrVT = getPointerTy();
1346 bool is64bit = PPCSubTarget.isPPC64();
1348 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1350 if (Model == TLSModel::LocalExec) {
1351 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1352 PPCII::MO_TPREL_HA);
1353 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1354 PPCII::MO_TPREL_LO);
1355 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1356 is64bit ? MVT::i64 : MVT::i32);
1357 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1358 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1362 llvm_unreachable("only local-exec is currently supported for ppc32");
1364 if (Model == TLSModel::InitialExec) {
1365 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1366 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1368 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1369 SDValue TPOffsetHi = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1370 PtrVT, GOTReg, TGA);
1371 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1372 PtrVT, TGA, TPOffsetHi);
1373 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1376 if (Model == TLSModel::GeneralDynamic) {
1377 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1378 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1379 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1381 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1384 // We need a chain node, and don't have one handy. The underlying
1385 // call has no side effects, so using the function entry node
1387 SDValue Chain = DAG.getEntryNode();
1388 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1389 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1390 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLS_ADDR, dl,
1391 PtrVT, ParmReg, TGA);
1392 // The return value from GET_TLS_ADDR really is in X3 already, but
1393 // some hacks are needed here to tie everything together. The extra
1394 // copies dissolve during subsequent transforms.
1395 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1396 return DAG.getCopyFromReg(Chain, dl, PPC::X3, PtrVT);
1399 if (Model == TLSModel::LocalDynamic) {
1400 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1401 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1402 SDValue GOTEntryHi = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1404 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1407 // We need a chain node, and don't have one handy. The underlying
1408 // call has no side effects, so using the function entry node
1410 SDValue Chain = DAG.getEntryNode();
1411 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, GOTEntry);
1412 SDValue ParmReg = DAG.getRegister(PPC::X3, MVT::i64);
1413 SDValue TLSAddr = DAG.getNode(PPCISD::GET_TLSLD_ADDR, dl,
1414 PtrVT, ParmReg, TGA);
1415 // The return value from GET_TLSLD_ADDR really is in X3 already, but
1416 // some hacks are needed here to tie everything together. The extra
1417 // copies dissolve during subsequent transforms.
1418 Chain = DAG.getCopyToReg(Chain, dl, PPC::X3, TLSAddr);
1419 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1420 Chain, ParmReg, TGA);
1421 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1424 llvm_unreachable("Unknown TLS model!");
1427 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1428 SelectionDAG &DAG) const {
1429 EVT PtrVT = Op.getValueType();
1430 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1432 const GlobalValue *GV = GSDN->getGlobal();
1434 // 64-bit SVR4 ABI code is always position-independent.
1435 // The actual address of the GlobalValue is stored in the TOC.
1436 if (PPCSubTarget.isSVR4ABI() && PPCSubTarget.isPPC64()) {
1437 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1438 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1439 DAG.getRegister(PPC::X2, MVT::i64));
1442 unsigned MOHiFlag, MOLoFlag;
1443 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1446 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1448 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1450 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1452 // If the global reference is actually to a non-lazy-pointer, we have to do an
1453 // extra load to get the address of the global.
1454 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1455 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1456 false, false, false, 0);
1460 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1461 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1464 // If we're comparing for equality to zero, expose the fact that this is
1465 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1466 // fold the new nodes.
1467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1468 if (C->isNullValue() && CC == ISD::SETEQ) {
1469 EVT VT = Op.getOperand(0).getValueType();
1470 SDValue Zext = Op.getOperand(0);
1471 if (VT.bitsLT(MVT::i32)) {
1473 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1475 unsigned Log2b = Log2_32(VT.getSizeInBits());
1476 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1477 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1478 DAG.getConstant(Log2b, MVT::i32));
1479 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1481 // Leave comparisons against 0 and -1 alone for now, since they're usually
1482 // optimized. FIXME: revisit this when we can custom lower all setcc
1484 if (C->isAllOnesValue() || C->isNullValue())
1488 // If we have an integer seteq/setne, turn it into a compare against zero
1489 // by xor'ing the rhs with the lhs, which is faster than setting a
1490 // condition register, reading it back out, and masking the correct bit. The
1491 // normal approach here uses sub to do this instead of xor. Using xor exposes
1492 // the result to other bit-twiddling opportunities.
1493 EVT LHSVT = Op.getOperand(0).getValueType();
1494 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1495 EVT VT = Op.getValueType();
1496 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1498 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1503 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1504 const PPCSubtarget &Subtarget) const {
1505 SDNode *Node = Op.getNode();
1506 EVT VT = Node->getValueType(0);
1507 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1508 SDValue InChain = Node->getOperand(0);
1509 SDValue VAListPtr = Node->getOperand(1);
1510 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1513 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1516 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1517 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1519 InChain = GprIndex.getValue(1);
1521 if (VT == MVT::i64) {
1522 // Check if GprIndex is even
1523 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1524 DAG.getConstant(1, MVT::i32));
1525 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1526 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1527 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1528 DAG.getConstant(1, MVT::i32));
1529 // Align GprIndex to be even if it isn't
1530 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1534 // fpr index is 1 byte after gpr
1535 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1536 DAG.getConstant(1, MVT::i32));
1539 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1540 FprPtr, MachinePointerInfo(SV), MVT::i8,
1542 InChain = FprIndex.getValue(1);
1544 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1545 DAG.getConstant(8, MVT::i32));
1547 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1548 DAG.getConstant(4, MVT::i32));
1551 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1552 MachinePointerInfo(), false, false,
1554 InChain = OverflowArea.getValue(1);
1556 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1557 MachinePointerInfo(), false, false,
1559 InChain = RegSaveArea.getValue(1);
1561 // select overflow_area if index > 8
1562 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1563 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1565 // adjustment constant gpr_index * 4/8
1566 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1567 VT.isInteger() ? GprIndex : FprIndex,
1568 DAG.getConstant(VT.isInteger() ? 4 : 8,
1571 // OurReg = RegSaveArea + RegConstant
1572 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1575 // Floating types are 32 bytes into RegSaveArea
1576 if (VT.isFloatingPoint())
1577 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1578 DAG.getConstant(32, MVT::i32));
1580 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1581 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1582 VT.isInteger() ? GprIndex : FprIndex,
1583 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1586 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1587 VT.isInteger() ? VAListPtr : FprPtr,
1588 MachinePointerInfo(SV),
1589 MVT::i8, false, false, 0);
1591 // determine if we should load from reg_save_area or overflow_area
1592 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1594 // increase overflow_area by 4/8 if gpr/fpr > 8
1595 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1596 DAG.getConstant(VT.isInteger() ? 4 : 8,
1599 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1602 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1604 MachinePointerInfo(),
1605 MVT::i32, false, false, 0);
1607 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1608 false, false, false, 0);
1611 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
1612 SelectionDAG &DAG) const {
1613 return Op.getOperand(0);
1616 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
1617 SelectionDAG &DAG) const {
1618 SDValue Chain = Op.getOperand(0);
1619 SDValue Trmp = Op.getOperand(1); // trampoline
1620 SDValue FPtr = Op.getOperand(2); // nested function
1621 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
1624 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1625 bool isPPC64 = (PtrVT == MVT::i64);
1627 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
1630 TargetLowering::ArgListTy Args;
1631 TargetLowering::ArgListEntry Entry;
1633 Entry.Ty = IntPtrTy;
1634 Entry.Node = Trmp; Args.push_back(Entry);
1636 // TrampSize == (isPPC64 ? 48 : 40);
1637 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
1638 isPPC64 ? MVT::i64 : MVT::i32);
1639 Args.push_back(Entry);
1641 Entry.Node = FPtr; Args.push_back(Entry);
1642 Entry.Node = Nest; Args.push_back(Entry);
1644 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
1645 TargetLowering::CallLoweringInfo CLI(Chain,
1646 Type::getVoidTy(*DAG.getContext()),
1647 false, false, false, false, 0,
1649 /*isTailCall=*/false,
1650 /*doesNotRet=*/false,
1651 /*isReturnValueUsed=*/true,
1652 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
1654 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1656 return CallResult.second;
1659 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
1660 const PPCSubtarget &Subtarget) const {
1661 MachineFunction &MF = DAG.getMachineFunction();
1662 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1666 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
1667 // vastart just stores the address of the VarArgsFrameIndex slot into the
1668 // memory location argument.
1669 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1670 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
1671 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1672 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
1673 MachinePointerInfo(SV),
1677 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
1678 // We suppose the given va_list is already allocated.
1681 // char gpr; /* index into the array of 8 GPRs
1682 // * stored in the register save area
1683 // * gpr=0 corresponds to r3,
1684 // * gpr=1 to r4, etc.
1686 // char fpr; /* index into the array of 8 FPRs
1687 // * stored in the register save area
1688 // * fpr=0 corresponds to f1,
1689 // * fpr=1 to f2, etc.
1691 // char *overflow_arg_area;
1692 // /* location on stack that holds
1693 // * the next overflow argument
1695 // char *reg_save_area;
1696 // /* where r3:r10 and f1:f8 (if saved)
1702 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
1703 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
1706 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1708 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
1710 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1713 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
1714 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
1716 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
1717 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
1719 uint64_t FPROffset = 1;
1720 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
1722 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1724 // Store first byte : number of int regs
1725 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
1727 MachinePointerInfo(SV),
1728 MVT::i8, false, false, 0);
1729 uint64_t nextOffset = FPROffset;
1730 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
1733 // Store second byte : number of float regs
1734 SDValue secondStore =
1735 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
1736 MachinePointerInfo(SV, nextOffset), MVT::i8,
1738 nextOffset += StackOffset;
1739 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
1741 // Store second word : arguments given on stack
1742 SDValue thirdStore =
1743 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
1744 MachinePointerInfo(SV, nextOffset),
1746 nextOffset += FrameOffset;
1747 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
1749 // Store third word : arguments given in registers
1750 return DAG.getStore(thirdStore, dl, FR, nextPtr,
1751 MachinePointerInfo(SV, nextOffset),
1756 #include "PPCGenCallingConv.inc"
1758 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
1759 CCValAssign::LocInfo &LocInfo,
1760 ISD::ArgFlagsTy &ArgFlags,
1765 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
1767 CCValAssign::LocInfo &LocInfo,
1768 ISD::ArgFlagsTy &ArgFlags,
1770 static const uint16_t ArgRegs[] = {
1771 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1772 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1774 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1776 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1778 // Skip one register if the first unallocated register has an even register
1779 // number and there are still argument registers available which have not been
1780 // allocated yet. RegNum is actually an index into ArgRegs, which means we
1781 // need to skip a register if RegNum is odd.
1782 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
1783 State.AllocateReg(ArgRegs[RegNum]);
1786 // Always return false here, as this function only makes sure that the first
1787 // unallocated register has an odd register number and does not actually
1788 // allocate a register for the current argument.
1792 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
1794 CCValAssign::LocInfo &LocInfo,
1795 ISD::ArgFlagsTy &ArgFlags,
1797 static const uint16_t ArgRegs[] = {
1798 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1802 const unsigned NumArgRegs = array_lengthof(ArgRegs);
1804 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
1806 // If there is only one Floating-point register left we need to put both f64
1807 // values of a split ppc_fp128 value on the stack.
1808 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
1809 State.AllocateReg(ArgRegs[RegNum]);
1812 // Always return false here, as this function only makes sure that the two f64
1813 // values a ppc_fp128 value is split into are both passed in registers or both
1814 // passed on the stack and does not actually allocate a register for the
1815 // current argument.
1819 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
1821 static const uint16_t *GetFPR() {
1822 static const uint16_t FPR[] = {
1823 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1824 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1830 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
1832 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
1833 unsigned PtrByteSize) {
1834 unsigned ArgSize = ArgVT.getSizeInBits()/8;
1835 if (Flags.isByVal())
1836 ArgSize = Flags.getByValSize();
1837 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
1843 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
1844 CallingConv::ID CallConv, bool isVarArg,
1845 const SmallVectorImpl<ISD::InputArg>
1847 SDLoc dl, SelectionDAG &DAG,
1848 SmallVectorImpl<SDValue> &InVals)
1850 if (PPCSubTarget.isSVR4ABI()) {
1851 if (PPCSubTarget.isPPC64())
1852 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
1855 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
1858 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
1864 PPCTargetLowering::LowerFormalArguments_32SVR4(
1866 CallingConv::ID CallConv, bool isVarArg,
1867 const SmallVectorImpl<ISD::InputArg>
1869 SDLoc dl, SelectionDAG &DAG,
1870 SmallVectorImpl<SDValue> &InVals) const {
1872 // 32-bit SVR4 ABI Stack Frame Layout:
1873 // +-----------------------------------+
1874 // +--> | Back chain |
1875 // | +-----------------------------------+
1876 // | | Floating-point register save area |
1877 // | +-----------------------------------+
1878 // | | General register save area |
1879 // | +-----------------------------------+
1880 // | | CR save word |
1881 // | +-----------------------------------+
1882 // | | VRSAVE save word |
1883 // | +-----------------------------------+
1884 // | | Alignment padding |
1885 // | +-----------------------------------+
1886 // | | Vector register save area |
1887 // | +-----------------------------------+
1888 // | | Local variable space |
1889 // | +-----------------------------------+
1890 // | | Parameter list area |
1891 // | +-----------------------------------+
1892 // | | LR save word |
1893 // | +-----------------------------------+
1894 // SP--> +--- | Back chain |
1895 // +-----------------------------------+
1898 // System V Application Binary Interface PowerPC Processor Supplement
1899 // AltiVec Technology Programming Interface Manual
1901 MachineFunction &MF = DAG.getMachineFunction();
1902 MachineFrameInfo *MFI = MF.getFrameInfo();
1903 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1905 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1906 // Potential tail calls could cause overwriting of argument stack slots.
1907 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
1908 (CallConv == CallingConv::Fast));
1909 unsigned PtrByteSize = 4;
1911 // Assign locations to all of the incoming arguments.
1912 SmallVector<CCValAssign, 16> ArgLocs;
1913 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1914 getTargetMachine(), ArgLocs, *DAG.getContext());
1916 // Reserve space for the linkage area on the stack.
1917 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
1919 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
1921 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1922 CCValAssign &VA = ArgLocs[i];
1924 // Arguments stored in registers.
1925 if (VA.isRegLoc()) {
1926 const TargetRegisterClass *RC;
1927 EVT ValVT = VA.getValVT();
1929 switch (ValVT.getSimpleVT().SimpleTy) {
1931 llvm_unreachable("ValVT not supported by formal arguments Lowering");
1933 RC = &PPC::GPRCRegClass;
1936 RC = &PPC::F4RCRegClass;
1939 RC = &PPC::F8RCRegClass;
1945 RC = &PPC::VRRCRegClass;
1949 // Transform the arguments stored in physical registers into virtual ones.
1950 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1951 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, ValVT);
1953 InVals.push_back(ArgValue);
1955 // Argument stored in memory.
1956 assert(VA.isMemLoc());
1958 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1959 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
1962 // Create load nodes to retrieve arguments from the stack.
1963 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
1964 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
1965 MachinePointerInfo(),
1966 false, false, false, 0));
1970 // Assign locations to all of the incoming aggregate by value arguments.
1971 // Aggregates passed by value are stored in the local variable space of the
1972 // caller's stack frame, right above the parameter list area.
1973 SmallVector<CCValAssign, 16> ByValArgLocs;
1974 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1975 getTargetMachine(), ByValArgLocs, *DAG.getContext());
1977 // Reserve stack space for the allocations in CCInfo.
1978 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
1980 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
1982 // Area that is at least reserved in the caller of this function.
1983 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
1985 // Set the size that is at least reserved in caller of this function. Tail
1986 // call optimized function's reserved stack space needs to be aligned so that
1987 // taking the difference between two stack areas will result in an aligned
1989 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
1992 std::max(MinReservedArea,
1993 PPCFrameLowering::getMinCallFrameSize(false, false));
1995 unsigned TargetAlign = DAG.getMachineFunction().getTarget().getFrameLowering()->
1996 getStackAlignment();
1997 unsigned AlignMask = TargetAlign-1;
1998 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2000 FI->setMinReservedArea(MinReservedArea);
2002 SmallVector<SDValue, 8> MemOps;
2004 // If the function takes variable number of arguments, make a frame index for
2005 // the start of the first vararg value... for expansion of llvm.va_start.
2007 static const uint16_t GPArgRegs[] = {
2008 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2009 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2011 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2013 static const uint16_t FPArgRegs[] = {
2014 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2017 const unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2019 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2021 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2024 // Make room for NumGPArgRegs and NumFPArgRegs.
2025 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2026 NumFPArgRegs * EVT(MVT::f64).getSizeInBits()/8;
2028 FuncInfo->setVarArgsStackOffset(
2029 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2030 CCInfo.getNextStackOffset(), true));
2032 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2033 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2035 // The fixed integer arguments of a variadic function are stored to the
2036 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2037 // the result of va_next.
2038 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2039 // Get an existing live-in vreg, or add a new one.
2040 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2042 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2044 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2045 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2046 MachinePointerInfo(), false, false, 0);
2047 MemOps.push_back(Store);
2048 // Increment the address by four for the next argument to store
2049 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2050 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2053 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2055 // The double arguments are stored to the VarArgsFrameIndex
2057 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2058 // Get an existing live-in vreg, or add a new one.
2059 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2061 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2063 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2064 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2065 MachinePointerInfo(), false, false, 0);
2066 MemOps.push_back(Store);
2067 // Increment the address by eight for the next argument to store
2068 SDValue PtrOff = DAG.getConstant(EVT(MVT::f64).getSizeInBits()/8,
2070 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2074 if (!MemOps.empty())
2075 Chain = DAG.getNode(ISD::TokenFactor, dl,
2076 MVT::Other, &MemOps[0], MemOps.size());
2081 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2082 // value to MVT::i64 and then truncate to the correct register size.
2084 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2085 SelectionDAG &DAG, SDValue ArgVal,
2088 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2089 DAG.getValueType(ObjectVT));
2090 else if (Flags.isZExt())
2091 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2092 DAG.getValueType(ObjectVT));
2094 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2097 // Set the size that is at least reserved in caller of this function. Tail
2098 // call optimized functions' reserved stack space needs to be aligned so that
2099 // taking the difference between two stack areas will result in an aligned
2102 PPCTargetLowering::setMinReservedArea(MachineFunction &MF, SelectionDAG &DAG,
2103 unsigned nAltivecParamsAtEnd,
2104 unsigned MinReservedArea,
2105 bool isPPC64) const {
2106 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
2107 // Add the Altivec parameters at the end, if needed.
2108 if (nAltivecParamsAtEnd) {
2109 MinReservedArea = ((MinReservedArea+15)/16)*16;
2110 MinReservedArea += 16*nAltivecParamsAtEnd;
2113 std::max(MinReservedArea,
2114 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2115 unsigned TargetAlign
2116 = DAG.getMachineFunction().getTarget().getFrameLowering()->
2117 getStackAlignment();
2118 unsigned AlignMask = TargetAlign-1;
2119 MinReservedArea = (MinReservedArea + AlignMask) & ~AlignMask;
2120 FI->setMinReservedArea(MinReservedArea);
2124 PPCTargetLowering::LowerFormalArguments_64SVR4(
2126 CallingConv::ID CallConv, bool isVarArg,
2127 const SmallVectorImpl<ISD::InputArg>
2129 SDLoc dl, SelectionDAG &DAG,
2130 SmallVectorImpl<SDValue> &InVals) const {
2131 // TODO: add description of PPC stack frame format, or at least some docs.
2133 MachineFunction &MF = DAG.getMachineFunction();
2134 MachineFrameInfo *MFI = MF.getFrameInfo();
2135 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2137 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2138 // Potential tail calls could cause overwriting of argument stack slots.
2139 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2140 (CallConv == CallingConv::Fast));
2141 unsigned PtrByteSize = 8;
2143 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
2144 // Area that is at least reserved in caller of this function.
2145 unsigned MinReservedArea = ArgOffset;
2147 static const uint16_t GPR[] = {
2148 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2149 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2152 static const uint16_t *FPR = GetFPR();
2154 static const uint16_t VR[] = {
2155 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2156 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2159 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2160 const unsigned Num_FPR_Regs = 13;
2161 const unsigned Num_VR_Regs = array_lengthof(VR);
2163 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2165 // Add DAG nodes to load the arguments or copy them out of registers. On
2166 // entry to a function on PPC, the arguments start after the linkage area,
2167 // although the first ones are often in registers.
2169 SmallVector<SDValue, 8> MemOps;
2170 unsigned nAltivecParamsAtEnd = 0;
2171 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2172 unsigned CurArgIdx = 0;
2173 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2175 bool needsLoad = false;
2176 EVT ObjectVT = Ins[ArgNo].VT;
2177 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2178 unsigned ArgSize = ObjSize;
2179 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2180 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2181 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2183 unsigned CurArgOffset = ArgOffset;
2185 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2186 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2187 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2189 MinReservedArea = ((MinReservedArea+15)/16)*16;
2190 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2194 nAltivecParamsAtEnd++;
2196 // Calculate min reserved area.
2197 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2201 // FIXME the codegen can be much improved in some cases.
2202 // We do not have to keep everything in memory.
2203 if (Flags.isByVal()) {
2204 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2205 ObjSize = Flags.getByValSize();
2206 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2207 // Empty aggregate parameters do not take up registers. Examples:
2211 // etc. However, we have to provide a place-holder in InVals, so
2212 // pretend we have an 8-byte item at the current address for that
2215 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2216 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2217 InVals.push_back(FIN);
2220 // All aggregates smaller than 8 bytes must be passed right-justified.
2221 if (ObjSize < PtrByteSize)
2222 CurArgOffset = CurArgOffset + (PtrByteSize - ObjSize);
2223 // The value of the object is its address.
2224 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2225 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2226 InVals.push_back(FIN);
2229 if (GPR_idx != Num_GPR_Regs) {
2230 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2231 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2234 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2235 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2236 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2237 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2238 MachinePointerInfo(FuncArg, CurArgOffset),
2239 ObjType, false, false, 0);
2241 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2242 // store the whole register as-is to the parameter save area
2243 // slot. The address of the parameter was already calculated
2244 // above (InVals.push_back(FIN)) to be the right-justified
2245 // offset within the slot. For this store, we need a new
2246 // frame index that points at the beginning of the slot.
2247 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2248 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2249 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2250 MachinePointerInfo(FuncArg, ArgOffset),
2254 MemOps.push_back(Store);
2257 // Whether we copied from a register or not, advance the offset
2258 // into the parameter save area by a full doubleword.
2259 ArgOffset += PtrByteSize;
2263 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2264 // Store whatever pieces of the object are in registers
2265 // to memory. ArgOffset will be the address of the beginning
2267 if (GPR_idx != Num_GPR_Regs) {
2269 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2270 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2271 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2272 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2273 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2274 MachinePointerInfo(FuncArg, ArgOffset),
2276 MemOps.push_back(Store);
2278 ArgOffset += PtrByteSize;
2280 ArgOffset += ArgSize - j;
2287 switch (ObjectVT.getSimpleVT().SimpleTy) {
2288 default: llvm_unreachable("Unhandled argument type!");
2291 if (GPR_idx != Num_GPR_Regs) {
2292 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2293 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2295 if (ObjectVT == MVT::i32)
2296 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2297 // value to MVT::i64 and then truncate to the correct register size.
2298 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2303 ArgSize = PtrByteSize;
2310 // Every 8 bytes of argument space consumes one of the GPRs available for
2311 // argument passing.
2312 if (GPR_idx != Num_GPR_Regs) {
2315 if (FPR_idx != Num_FPR_Regs) {
2318 if (ObjectVT == MVT::f32)
2319 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2321 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2323 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2327 ArgSize = PtrByteSize;
2336 // Note that vector arguments in registers don't reserve stack space,
2337 // except in varargs functions.
2338 if (VR_idx != Num_VR_Regs) {
2339 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2340 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2342 while ((ArgOffset % 16) != 0) {
2343 ArgOffset += PtrByteSize;
2344 if (GPR_idx != Num_GPR_Regs)
2348 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2352 // Vectors are aligned.
2353 ArgOffset = ((ArgOffset+15)/16)*16;
2354 CurArgOffset = ArgOffset;
2361 // We need to load the argument to a virtual register if we determined
2362 // above that we ran out of physical registers of the appropriate type.
2364 int FI = MFI->CreateFixedObject(ObjSize,
2365 CurArgOffset + (ArgSize - ObjSize),
2367 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2368 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2369 false, false, false, 0);
2372 InVals.push_back(ArgVal);
2375 // Set the size that is at least reserved in caller of this function. Tail
2376 // call optimized functions' reserved stack space needs to be aligned so that
2377 // taking the difference between two stack areas will result in an aligned
2379 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, true);
2381 // If the function takes variable number of arguments, make a frame index for
2382 // the start of the first vararg value... for expansion of llvm.va_start.
2384 int Depth = ArgOffset;
2386 FuncInfo->setVarArgsFrameIndex(
2387 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2388 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2390 // If this function is vararg, store any remaining integer argument regs
2391 // to their spots on the stack so that they may be loaded by deferencing the
2392 // result of va_next.
2393 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2394 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2395 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2396 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2397 MachinePointerInfo(), false, false, 0);
2398 MemOps.push_back(Store);
2399 // Increment the address by four for the next argument to store
2400 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2401 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2405 if (!MemOps.empty())
2406 Chain = DAG.getNode(ISD::TokenFactor, dl,
2407 MVT::Other, &MemOps[0], MemOps.size());
2413 PPCTargetLowering::LowerFormalArguments_Darwin(
2415 CallingConv::ID CallConv, bool isVarArg,
2416 const SmallVectorImpl<ISD::InputArg>
2418 SDLoc dl, SelectionDAG &DAG,
2419 SmallVectorImpl<SDValue> &InVals) const {
2420 // TODO: add description of PPC stack frame format, or at least some docs.
2422 MachineFunction &MF = DAG.getMachineFunction();
2423 MachineFrameInfo *MFI = MF.getFrameInfo();
2424 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2426 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2427 bool isPPC64 = PtrVT == MVT::i64;
2428 // Potential tail calls could cause overwriting of argument stack slots.
2429 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2430 (CallConv == CallingConv::Fast));
2431 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2433 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
2434 // Area that is at least reserved in caller of this function.
2435 unsigned MinReservedArea = ArgOffset;
2437 static const uint16_t GPR_32[] = { // 32-bit registers.
2438 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2439 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2441 static const uint16_t GPR_64[] = { // 64-bit registers.
2442 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2443 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2446 static const uint16_t *FPR = GetFPR();
2448 static const uint16_t VR[] = {
2449 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2450 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2453 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2454 const unsigned Num_FPR_Regs = 13;
2455 const unsigned Num_VR_Regs = array_lengthof( VR);
2457 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
2459 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
2461 // In 32-bit non-varargs functions, the stack space for vectors is after the
2462 // stack space for non-vectors. We do not use this space unless we have
2463 // too many vectors to fit in registers, something that only occurs in
2464 // constructed examples:), but we have to walk the arglist to figure
2465 // that out...for the pathological case, compute VecArgOffset as the
2466 // start of the vector parameter area. Computing VecArgOffset is the
2467 // entire point of the following loop.
2468 unsigned VecArgOffset = ArgOffset;
2469 if (!isVarArg && !isPPC64) {
2470 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
2472 EVT ObjectVT = Ins[ArgNo].VT;
2473 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2475 if (Flags.isByVal()) {
2476 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
2477 unsigned ObjSize = Flags.getByValSize();
2479 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2480 VecArgOffset += ArgSize;
2484 switch(ObjectVT.getSimpleVT().SimpleTy) {
2485 default: llvm_unreachable("Unhandled argument type!");
2490 case MVT::i64: // PPC64
2492 // FIXME: We are guaranteed to be !isPPC64 at this point.
2493 // Does MVT::i64 apply?
2500 // Nothing to do, we're only looking at Nonvector args here.
2505 // We've found where the vector parameter area in memory is. Skip the
2506 // first 12 parameters; these don't use that memory.
2507 VecArgOffset = ((VecArgOffset+15)/16)*16;
2508 VecArgOffset += 12*16;
2510 // Add DAG nodes to load the arguments or copy them out of registers. On
2511 // entry to a function on PPC, the arguments start after the linkage area,
2512 // although the first ones are often in registers.
2514 SmallVector<SDValue, 8> MemOps;
2515 unsigned nAltivecParamsAtEnd = 0;
2516 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2517 unsigned CurArgIdx = 0;
2518 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2520 bool needsLoad = false;
2521 EVT ObjectVT = Ins[ArgNo].VT;
2522 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
2523 unsigned ArgSize = ObjSize;
2524 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2525 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2526 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2528 unsigned CurArgOffset = ArgOffset;
2530 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
2531 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
2532 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
2533 if (isVarArg || isPPC64) {
2534 MinReservedArea = ((MinReservedArea+15)/16)*16;
2535 MinReservedArea += CalculateStackSlotSize(ObjectVT,
2538 } else nAltivecParamsAtEnd++;
2540 // Calculate min reserved area.
2541 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
2545 // FIXME the codegen can be much improved in some cases.
2546 // We do not have to keep everything in memory.
2547 if (Flags.isByVal()) {
2548 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2549 ObjSize = Flags.getByValSize();
2550 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2551 // Objects of size 1 and 2 are right justified, everything else is
2552 // left justified. This means the memory address is adjusted forwards.
2553 if (ObjSize==1 || ObjSize==2) {
2554 CurArgOffset = CurArgOffset + (4 - ObjSize);
2556 // The value of the object is its address.
2557 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, true);
2558 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2559 InVals.push_back(FIN);
2560 if (ObjSize==1 || ObjSize==2) {
2561 if (GPR_idx != Num_GPR_Regs) {
2564 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2566 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2567 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2568 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
2569 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
2570 MachinePointerInfo(FuncArg,
2572 ObjType, false, false, 0);
2573 MemOps.push_back(Store);
2577 ArgOffset += PtrByteSize;
2581 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2582 // Store whatever pieces of the object are in registers
2583 // to memory. ArgOffset will be the address of the beginning
2585 if (GPR_idx != Num_GPR_Regs) {
2588 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2590 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2591 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2592 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2593 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2594 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2595 MachinePointerInfo(FuncArg, ArgOffset),
2597 MemOps.push_back(Store);
2599 ArgOffset += PtrByteSize;
2601 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
2608 switch (ObjectVT.getSimpleVT().SimpleTy) {
2609 default: llvm_unreachable("Unhandled argument type!");
2612 if (GPR_idx != Num_GPR_Regs) {
2613 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2614 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
2618 ArgSize = PtrByteSize;
2620 // All int arguments reserve stack space in the Darwin ABI.
2621 ArgOffset += PtrByteSize;
2625 case MVT::i64: // PPC64
2626 if (GPR_idx != Num_GPR_Regs) {
2627 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2628 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2630 if (ObjectVT == MVT::i32)
2631 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2632 // value to MVT::i64 and then truncate to the correct register size.
2633 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2638 ArgSize = PtrByteSize;
2640 // All int arguments reserve stack space in the Darwin ABI.
2646 // Every 4 bytes of argument space consumes one of the GPRs available for
2647 // argument passing.
2648 if (GPR_idx != Num_GPR_Regs) {
2650 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
2653 if (FPR_idx != Num_FPR_Regs) {
2656 if (ObjectVT == MVT::f32)
2657 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2659 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
2661 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2667 // All FP arguments reserve stack space in the Darwin ABI.
2668 ArgOffset += isPPC64 ? 8 : ObjSize;
2674 // Note that vector arguments in registers don't reserve stack space,
2675 // except in varargs functions.
2676 if (VR_idx != Num_VR_Regs) {
2677 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2678 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2680 while ((ArgOffset % 16) != 0) {
2681 ArgOffset += PtrByteSize;
2682 if (GPR_idx != Num_GPR_Regs)
2686 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
2690 if (!isVarArg && !isPPC64) {
2691 // Vectors go after all the nonvectors.
2692 CurArgOffset = VecArgOffset;
2695 // Vectors are aligned.
2696 ArgOffset = ((ArgOffset+15)/16)*16;
2697 CurArgOffset = ArgOffset;
2705 // We need to load the argument to a virtual register if we determined above
2706 // that we ran out of physical registers of the appropriate type.
2708 int FI = MFI->CreateFixedObject(ObjSize,
2709 CurArgOffset + (ArgSize - ObjSize),
2711 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2712 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2713 false, false, false, 0);
2716 InVals.push_back(ArgVal);
2719 // Set the size that is at least reserved in caller of this function. Tail
2720 // call optimized functions' reserved stack space needs to be aligned so that
2721 // taking the difference between two stack areas will result in an aligned
2723 setMinReservedArea(MF, DAG, nAltivecParamsAtEnd, MinReservedArea, isPPC64);
2725 // If the function takes variable number of arguments, make a frame index for
2726 // the start of the first vararg value... for expansion of llvm.va_start.
2728 int Depth = ArgOffset;
2730 FuncInfo->setVarArgsFrameIndex(
2731 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2733 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2735 // If this function is vararg, store any remaining integer argument regs
2736 // to their spots on the stack so that they may be loaded by deferencing the
2737 // result of va_next.
2738 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
2742 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2744 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
2746 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2747 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2748 MachinePointerInfo(), false, false, 0);
2749 MemOps.push_back(Store);
2750 // Increment the address by four for the next argument to store
2751 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2752 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2756 if (!MemOps.empty())
2757 Chain = DAG.getNode(ISD::TokenFactor, dl,
2758 MVT::Other, &MemOps[0], MemOps.size());
2763 /// CalculateParameterAndLinkageAreaSize - Get the size of the parameter plus
2764 /// linkage area for the Darwin ABI, or the 64-bit SVR4 ABI.
2766 CalculateParameterAndLinkageAreaSize(SelectionDAG &DAG,
2770 const SmallVectorImpl<ISD::OutputArg>
2772 const SmallVectorImpl<SDValue> &OutVals,
2773 unsigned &nAltivecParamsAtEnd) {
2774 // Count how many bytes are to be pushed on the stack, including the linkage
2775 // area, and parameter passing area. We start with 24/48 bytes, which is
2776 // prereserved space for [SP][CR][LR][3 x unused].
2777 unsigned NumBytes = PPCFrameLowering::getLinkageSize(isPPC64, true);
2778 unsigned NumOps = Outs.size();
2779 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2781 // Add up all the space actually used.
2782 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
2783 // they all go in registers, but we must reserve stack space for them for
2784 // possible use by the caller. In varargs or 64-bit calls, parameters are
2785 // assigned stack space in order, with padding so Altivec parameters are
2787 nAltivecParamsAtEnd = 0;
2788 for (unsigned i = 0; i != NumOps; ++i) {
2789 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2790 EVT ArgVT = Outs[i].VT;
2791 // Varargs Altivec parameters are padded to a 16 byte boundary.
2792 if (ArgVT==MVT::v4f32 || ArgVT==MVT::v4i32 ||
2793 ArgVT==MVT::v8i16 || ArgVT==MVT::v16i8) {
2794 if (!isVarArg && !isPPC64) {
2795 // Non-varargs Altivec parameters go after all the non-Altivec
2796 // parameters; handle those later so we know how much padding we need.
2797 nAltivecParamsAtEnd++;
2800 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
2801 NumBytes = ((NumBytes+15)/16)*16;
2803 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2806 // Allow for Altivec parameters at the end, if needed.
2807 if (nAltivecParamsAtEnd) {
2808 NumBytes = ((NumBytes+15)/16)*16;
2809 NumBytes += 16*nAltivecParamsAtEnd;
2812 // The prolog code of the callee may store up to 8 GPR argument registers to
2813 // the stack, allowing va_start to index over them in memory if its varargs.
2814 // Because we cannot tell if this is needed on the caller side, we have to
2815 // conservatively assume that it is needed. As such, make sure we have at
2816 // least enough stack space for the caller to store the 8 GPRs.
2817 NumBytes = std::max(NumBytes,
2818 PPCFrameLowering::getMinCallFrameSize(isPPC64, true));
2820 // Tail call needs the stack to be aligned.
2821 if (CC == CallingConv::Fast && DAG.getTarget().Options.GuaranteedTailCallOpt){
2822 unsigned TargetAlign = DAG.getMachineFunction().getTarget().
2823 getFrameLowering()->getStackAlignment();
2824 unsigned AlignMask = TargetAlign-1;
2825 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2831 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
2832 /// adjusted to accommodate the arguments for the tailcall.
2833 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
2834 unsigned ParamSize) {
2836 if (!isTailCall) return 0;
2838 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
2839 unsigned CallerMinReservedArea = FI->getMinReservedArea();
2840 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
2841 // Remember only if the new adjustement is bigger.
2842 if (SPDiff < FI->getTailCallSPDelta())
2843 FI->setTailCallSPDelta(SPDiff);
2848 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2849 /// for tail call optimization. Targets which want to do tail call
2850 /// optimization should implement this function.
2852 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2853 CallingConv::ID CalleeCC,
2855 const SmallVectorImpl<ISD::InputArg> &Ins,
2856 SelectionDAG& DAG) const {
2857 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
2860 // Variable argument functions are not supported.
2864 MachineFunction &MF = DAG.getMachineFunction();
2865 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2866 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2867 // Functions containing by val parameters are not supported.
2868 for (unsigned i = 0; i != Ins.size(); i++) {
2869 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2870 if (Flags.isByVal()) return false;
2873 // Non PIC/GOT tail calls are supported.
2874 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
2877 // At the moment we can only do local tail calls (in same module, hidden
2878 // or protected) if we are generating PIC.
2879 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2880 return G->getGlobal()->hasHiddenVisibility()
2881 || G->getGlobal()->hasProtectedVisibility();
2887 /// isCallCompatibleAddress - Return the immediate to use if the specified
2888 /// 32-bit value is representable in the immediate field of a BxA instruction.
2889 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
2890 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2893 int Addr = C->getZExtValue();
2894 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
2895 SignExtend32<26>(Addr) != Addr)
2896 return 0; // Top 6 bits have to be sext of immediate.
2898 return DAG.getConstant((int)C->getZExtValue() >> 2,
2899 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
2904 struct TailCallArgumentInfo {
2909 TailCallArgumentInfo() : FrameIdx(0) {}
2914 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
2916 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
2918 const SmallVector<TailCallArgumentInfo, 8> &TailCallArgs,
2919 SmallVector<SDValue, 8> &MemOpChains,
2921 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
2922 SDValue Arg = TailCallArgs[i].Arg;
2923 SDValue FIN = TailCallArgs[i].FrameIdxOp;
2924 int FI = TailCallArgs[i].FrameIdx;
2925 // Store relative to framepointer.
2926 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
2927 MachinePointerInfo::getFixedStack(FI),
2932 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
2933 /// the appropriate stack slot for the tail call optimized function call.
2934 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
2935 MachineFunction &MF,
2944 // Calculate the new stack slot for the return address.
2945 int SlotSize = isPPC64 ? 8 : 4;
2946 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
2948 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
2949 NewRetAddrLoc, true);
2950 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2951 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
2952 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
2953 MachinePointerInfo::getFixedStack(NewRetAddr),
2956 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
2957 // slot as the FP is never overwritten.
2960 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
2961 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
2963 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
2964 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
2965 MachinePointerInfo::getFixedStack(NewFPIdx),
2972 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
2973 /// the position of the argument.
2975 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
2976 SDValue Arg, int SPDiff, unsigned ArgOffset,
2977 SmallVector<TailCallArgumentInfo, 8>& TailCallArguments) {
2978 int Offset = ArgOffset + SPDiff;
2979 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
2980 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2981 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
2982 SDValue FIN = DAG.getFrameIndex(FI, VT);
2983 TailCallArgumentInfo Info;
2985 Info.FrameIdxOp = FIN;
2987 TailCallArguments.push_back(Info);
2990 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
2991 /// stack slot. Returns the chain as result and the loaded frame pointers in
2992 /// LROpOut/FPOpout. Used when tail calling.
2993 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3001 // Load the LR and FP stack slot for later adjusting.
3002 EVT VT = PPCSubTarget.isPPC64() ? MVT::i64 : MVT::i32;
3003 LROpOut = getReturnAddrFrameIndex(DAG);
3004 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3005 false, false, false, 0);
3006 Chain = SDValue(LROpOut.getNode(), 1);
3008 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3009 // slot as the FP is never overwritten.
3011 FPOpOut = getFramePointerFrameIndex(DAG);
3012 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3013 false, false, false, 0);
3014 Chain = SDValue(FPOpOut.getNode(), 1);
3020 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3021 /// by "Src" to address "Dst" of size "Size". Alignment information is
3022 /// specified by the specific parameter attribute. The copy will be passed as
3023 /// a byval function parameter.
3024 /// Sometimes what we are copying is the end of a larger object, the part that
3025 /// does not fit in registers.
3027 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3028 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3030 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3031 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3032 false, false, MachinePointerInfo(0),
3033 MachinePointerInfo(0));
3036 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3039 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3040 SDValue Arg, SDValue PtrOff, int SPDiff,
3041 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3042 bool isVector, SmallVector<SDValue, 8> &MemOpChains,
3043 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments,
3045 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3050 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3052 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3053 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3054 DAG.getConstant(ArgOffset, PtrVT));
3056 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3057 MachinePointerInfo(), false, false, 0));
3058 // Calculate and remember argument location.
3059 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3064 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3065 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3066 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3067 SmallVector<TailCallArgumentInfo, 8> &TailCallArguments) {
3068 MachineFunction &MF = DAG.getMachineFunction();
3070 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3071 // might overwrite each other in case of tail call optimization.
3072 SmallVector<SDValue, 8> MemOpChains2;
3073 // Do not flag preceding copytoreg stuff together with the following stuff.
3075 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3077 if (!MemOpChains2.empty())
3078 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3079 &MemOpChains2[0], MemOpChains2.size());
3081 // Store the return address to the appropriate stack slot.
3082 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3083 isPPC64, isDarwinABI, dl);
3085 // Emit callseq_end just before tailcall node.
3086 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3087 DAG.getIntPtrConstant(0, true), InFlag, dl);
3088 InFlag = Chain.getValue(1);
3092 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3093 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3094 SmallVector<std::pair<unsigned, SDValue>, 8> &RegsToPass,
3095 SmallVector<SDValue, 8> &Ops, std::vector<EVT> &NodeTys,
3096 const PPCSubtarget &PPCSubTarget) {
3098 bool isPPC64 = PPCSubTarget.isPPC64();
3099 bool isSVR4ABI = PPCSubTarget.isSVR4ABI();
3101 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3102 NodeTys.push_back(MVT::Other); // Returns a chain
3103 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3105 unsigned CallOpc = PPCISD::CALL;
3107 bool needIndirectCall = true;
3108 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3109 // If this is an absolute destination address, use the munged value.
3110 Callee = SDValue(Dest, 0);
3111 needIndirectCall = false;
3114 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3115 // XXX Work around for http://llvm.org/bugs/show_bug.cgi?id=5201
3116 // Use indirect calls for ALL functions calls in JIT mode, since the
3117 // far-call stubs may be outside relocation limits for a BL instruction.
3118 if (!DAG.getTarget().getSubtarget<PPCSubtarget>().isJITCodeModel()) {
3119 unsigned OpFlags = 0;
3120 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3121 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3122 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3123 (G->getGlobal()->isDeclaration() ||
3124 G->getGlobal()->isWeakForLinker())) {
3125 // PC-relative references to external symbols should go through $stub,
3126 // unless we're building with the leopard linker or later, which
3127 // automatically synthesizes these stubs.
3128 OpFlags = PPCII::MO_DARWIN_STUB;
3131 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3132 // every direct call is) turn it into a TargetGlobalAddress /
3133 // TargetExternalSymbol node so that legalize doesn't hack it.
3134 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3135 Callee.getValueType(),
3137 needIndirectCall = false;
3141 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3142 unsigned char OpFlags = 0;
3144 if (DAG.getTarget().getRelocationModel() != Reloc::Static &&
3145 (PPCSubTarget.getTargetTriple().isMacOSX() &&
3146 PPCSubTarget.getTargetTriple().isMacOSXVersionLT(10, 5))) {
3147 // PC-relative references to external symbols should go through $stub,
3148 // unless we're building with the leopard linker or later, which
3149 // automatically synthesizes these stubs.
3150 OpFlags = PPCII::MO_DARWIN_STUB;
3153 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3155 needIndirectCall = false;
3158 if (needIndirectCall) {
3159 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3160 // to do the call, we can't use PPCISD::CALL.
3161 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3163 if (isSVR4ABI && isPPC64) {
3164 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3165 // entry point, but to the function descriptor (the function entry point
3166 // address is part of the function descriptor though).
3167 // The function descriptor is a three doubleword structure with the
3168 // following fields: function entry point, TOC base address and
3169 // environment pointer.
3170 // Thus for a call through a function pointer, the following actions need
3172 // 1. Save the TOC of the caller in the TOC save area of its stack
3173 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3174 // 2. Load the address of the function entry point from the function
3176 // 3. Load the TOC of the callee from the function descriptor into r2.
3177 // 4. Load the environment pointer from the function descriptor into
3179 // 5. Branch to the function entry point address.
3180 // 6. On return of the callee, the TOC of the caller needs to be
3181 // restored (this is done in FinishCall()).
3183 // All those operations are flagged together to ensure that no other
3184 // operations can be scheduled in between. E.g. without flagging the
3185 // operations together, a TOC access in the caller could be scheduled
3186 // between the load of the callee TOC and the branch to the callee, which
3187 // results in the TOC access going through the TOC of the callee instead
3188 // of going through the TOC of the caller, which leads to incorrect code.
3190 // Load the address of the function entry point from the function
3192 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3193 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, MTCTROps,
3194 InFlag.getNode() ? 3 : 2);
3195 Chain = LoadFuncPtr.getValue(1);
3196 InFlag = LoadFuncPtr.getValue(2);
3198 // Load environment pointer into r11.
3199 // Offset of the environment pointer within the function descriptor.
3200 SDValue PtrOff = DAG.getIntPtrConstant(16);
3202 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3203 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3205 Chain = LoadEnvPtr.getValue(1);
3206 InFlag = LoadEnvPtr.getValue(2);
3208 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3210 Chain = EnvVal.getValue(0);
3211 InFlag = EnvVal.getValue(1);
3213 // Load TOC of the callee into r2. We are using a target-specific load
3214 // with r2 hard coded, because the result of a target-independent load
3215 // would never go directly into r2, since r2 is a reserved register (which
3216 // prevents the register allocator from allocating it), resulting in an
3217 // additional register being allocated and an unnecessary move instruction
3219 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3220 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3222 Chain = LoadTOCPtr.getValue(0);
3223 InFlag = LoadTOCPtr.getValue(1);
3225 MTCTROps[0] = Chain;
3226 MTCTROps[1] = LoadFuncPtr;
3227 MTCTROps[2] = InFlag;
3230 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys, MTCTROps,
3231 2 + (InFlag.getNode() != 0));
3232 InFlag = Chain.getValue(1);
3235 NodeTys.push_back(MVT::Other);
3236 NodeTys.push_back(MVT::Glue);
3237 Ops.push_back(Chain);
3238 CallOpc = PPCISD::BCTRL;
3240 // Add use of X11 (holding environment pointer)
3241 if (isSVR4ABI && isPPC64)
3242 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3243 // Add CTR register as callee so a bctr can be emitted later.
3245 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3248 // If this is a direct call, pass the chain and the callee.
3249 if (Callee.getNode()) {
3250 Ops.push_back(Chain);
3251 Ops.push_back(Callee);
3253 // If this is a tail call add stack pointer delta.
3255 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3257 // Add argument registers to the end of the list so that they are known live
3259 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3260 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3261 RegsToPass[i].second.getValueType()));
3267 bool isLocalCall(const SDValue &Callee)
3269 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3270 return !G->getGlobal()->isDeclaration() &&
3271 !G->getGlobal()->isWeakForLinker();
3276 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3277 CallingConv::ID CallConv, bool isVarArg,
3278 const SmallVectorImpl<ISD::InputArg> &Ins,
3279 SDLoc dl, SelectionDAG &DAG,
3280 SmallVectorImpl<SDValue> &InVals) const {
3282 SmallVector<CCValAssign, 16> RVLocs;
3283 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3284 getTargetMachine(), RVLocs, *DAG.getContext());
3285 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3287 // Copy all of the result registers out of their specified physreg.
3288 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3289 CCValAssign &VA = RVLocs[i];
3290 assert(VA.isRegLoc() && "Can only return in registers!");
3292 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3293 VA.getLocReg(), VA.getLocVT(), InFlag);
3294 Chain = Val.getValue(1);
3295 InFlag = Val.getValue(2);
3297 switch (VA.getLocInfo()) {
3298 default: llvm_unreachable("Unknown loc info!");
3299 case CCValAssign::Full: break;
3300 case CCValAssign::AExt:
3301 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3303 case CCValAssign::ZExt:
3304 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3305 DAG.getValueType(VA.getValVT()));
3306 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3308 case CCValAssign::SExt:
3309 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3310 DAG.getValueType(VA.getValVT()));
3311 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3315 InVals.push_back(Val);
3322 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3323 bool isTailCall, bool isVarArg,
3325 SmallVector<std::pair<unsigned, SDValue>, 8>
3327 SDValue InFlag, SDValue Chain,
3329 int SPDiff, unsigned NumBytes,
3330 const SmallVectorImpl<ISD::InputArg> &Ins,
3331 SmallVectorImpl<SDValue> &InVals) const {
3332 std::vector<EVT> NodeTys;
3333 SmallVector<SDValue, 8> Ops;
3334 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3335 isTailCall, RegsToPass, Ops, NodeTys,
3338 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3339 if (isVarArg && PPCSubTarget.isSVR4ABI() && !PPCSubTarget.isPPC64())
3340 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3342 // When performing tail call optimization the callee pops its arguments off
3343 // the stack. Account for this here so these bytes can be pushed back on in
3344 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3345 int BytesCalleePops =
3346 (CallConv == CallingConv::Fast &&
3347 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3349 // Add a register mask operand representing the call-preserved registers.
3350 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3351 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3352 assert(Mask && "Missing call preserved mask for calling convention");
3353 Ops.push_back(DAG.getRegisterMask(Mask));
3355 if (InFlag.getNode())
3356 Ops.push_back(InFlag);
3360 assert(((Callee.getOpcode() == ISD::Register &&
3361 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3362 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3363 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3364 isa<ConstantSDNode>(Callee)) &&
3365 "Expecting an global address, external symbol, absolute value or register");
3367 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, &Ops[0], Ops.size());
3370 // Add a NOP immediately after the branch instruction when using the 64-bit
3371 // SVR4 ABI. At link time, if caller and callee are in a different module and
3372 // thus have a different TOC, the call will be replaced with a call to a stub
3373 // function which saves the current TOC, loads the TOC of the callee and
3374 // branches to the callee. The NOP will be replaced with a load instruction
3375 // which restores the TOC of the caller from the TOC save slot of the current
3376 // stack frame. If caller and callee belong to the same module (and have the
3377 // same TOC), the NOP will remain unchanged.
3379 bool needsTOCRestore = false;
3380 if (!isTailCall && PPCSubTarget.isSVR4ABI()&& PPCSubTarget.isPPC64()) {
3381 if (CallOpc == PPCISD::BCTRL) {
3382 // This is a call through a function pointer.
3383 // Restore the caller TOC from the save area into R2.
3384 // See PrepareCall() for more information about calls through function
3385 // pointers in the 64-bit SVR4 ABI.
3386 // We are using a target-specific load with r2 hard coded, because the
3387 // result of a target-independent load would never go directly into r2,
3388 // since r2 is a reserved register (which prevents the register allocator
3389 // from allocating it), resulting in an additional register being
3390 // allocated and an unnecessary move instruction being generated.
3391 needsTOCRestore = true;
3392 } else if ((CallOpc == PPCISD::CALL) && !isLocalCall(Callee)) {
3393 // Otherwise insert NOP for non-local calls.
3394 CallOpc = PPCISD::CALL_NOP;
3398 Chain = DAG.getNode(CallOpc, dl, NodeTys, &Ops[0], Ops.size());
3399 InFlag = Chain.getValue(1);
3401 if (needsTOCRestore) {
3402 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3403 Chain = DAG.getNode(PPCISD::TOC_RESTORE, dl, VTs, Chain, InFlag);
3404 InFlag = Chain.getValue(1);
3407 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3408 DAG.getIntPtrConstant(BytesCalleePops, true),
3411 InFlag = Chain.getValue(1);
3413 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3414 Ins, dl, DAG, InVals);
3418 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3419 SmallVectorImpl<SDValue> &InVals) const {
3420 SelectionDAG &DAG = CLI.DAG;
3422 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3423 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3424 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3425 SDValue Chain = CLI.Chain;
3426 SDValue Callee = CLI.Callee;
3427 bool &isTailCall = CLI.IsTailCall;
3428 CallingConv::ID CallConv = CLI.CallConv;
3429 bool isVarArg = CLI.IsVarArg;
3432 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3435 if (PPCSubTarget.isSVR4ABI()) {
3436 if (PPCSubTarget.isPPC64())
3437 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3438 isTailCall, Outs, OutVals, Ins,
3441 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3442 isTailCall, Outs, OutVals, Ins,
3446 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3447 isTailCall, Outs, OutVals, Ins,
3452 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3453 CallingConv::ID CallConv, bool isVarArg,
3455 const SmallVectorImpl<ISD::OutputArg> &Outs,
3456 const SmallVectorImpl<SDValue> &OutVals,
3457 const SmallVectorImpl<ISD::InputArg> &Ins,
3458 SDLoc dl, SelectionDAG &DAG,
3459 SmallVectorImpl<SDValue> &InVals) const {
3460 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
3461 // of the 32-bit SVR4 ABI stack frame layout.
3463 assert((CallConv == CallingConv::C ||
3464 CallConv == CallingConv::Fast) && "Unknown calling convention!");
3466 unsigned PtrByteSize = 4;
3468 MachineFunction &MF = DAG.getMachineFunction();
3470 // Mark this function as potentially containing a function that contains a
3471 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3472 // and restoring the callers stack pointer in this functions epilog. This is
3473 // done because by tail calling the called function might overwrite the value
3474 // in this function's (MF) stack pointer stack slot 0(SP).
3475 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3476 CallConv == CallingConv::Fast)
3477 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3479 // Count how many bytes are to be pushed on the stack, including the linkage
3480 // area, parameter list area and the part of the local variable space which
3481 // contains copies of aggregates which are passed by value.
3483 // Assign locations to all of the outgoing arguments.
3484 SmallVector<CCValAssign, 16> ArgLocs;
3485 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3486 getTargetMachine(), ArgLocs, *DAG.getContext());
3488 // Reserve space for the linkage area on the stack.
3489 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false), PtrByteSize);
3492 // Handle fixed and variable vector arguments differently.
3493 // Fixed vector arguments go into registers as long as registers are
3494 // available. Variable vector arguments always go into memory.
3495 unsigned NumArgs = Outs.size();
3497 for (unsigned i = 0; i != NumArgs; ++i) {
3498 MVT ArgVT = Outs[i].VT;
3499 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3502 if (Outs[i].IsFixed) {
3503 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
3506 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
3512 errs() << "Call operand #" << i << " has unhandled type "
3513 << EVT(ArgVT).getEVTString() << "\n";
3515 llvm_unreachable(0);
3519 // All arguments are treated the same.
3520 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
3523 // Assign locations to all of the outgoing aggregate by value arguments.
3524 SmallVector<CCValAssign, 16> ByValArgLocs;
3525 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3526 getTargetMachine(), ByValArgLocs, *DAG.getContext());
3528 // Reserve stack space for the allocations in CCInfo.
3529 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
3531 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
3533 // Size of the linkage area, parameter list area and the part of the local
3534 // space variable where copies of aggregates which are passed by value are
3536 unsigned NumBytes = CCByValInfo.getNextStackOffset();
3538 // Calculate by how many bytes the stack has to be adjusted in case of tail
3539 // call optimization.
3540 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3542 // Adjust the stack pointer for the new arguments...
3543 // These operations are automatically eliminated by the prolog/epilog pass
3544 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3546 SDValue CallSeqStart = Chain;
3548 // Load the return address and frame pointer so it can be moved somewhere else
3551 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
3554 // Set up a copy of the stack pointer for use loading and storing any
3555 // arguments that may not fit in the registers available for argument
3557 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3559 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3560 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3561 SmallVector<SDValue, 8> MemOpChains;
3563 bool seenFloatArg = false;
3564 // Walk the register/memloc assignments, inserting copies/loads.
3565 for (unsigned i = 0, j = 0, e = ArgLocs.size();
3568 CCValAssign &VA = ArgLocs[i];
3569 SDValue Arg = OutVals[i];
3570 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3572 if (Flags.isByVal()) {
3573 // Argument is an aggregate which is passed by value, thus we need to
3574 // create a copy of it in the local variable space of the current stack
3575 // frame (which is the stack frame of the caller) and pass the address of
3576 // this copy to the callee.
3577 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
3578 CCValAssign &ByValVA = ByValArgLocs[j++];
3579 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
3581 // Memory reserved in the local variable space of the callers stack frame.
3582 unsigned LocMemOffset = ByValVA.getLocMemOffset();
3584 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3585 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3587 // Create a copy of the argument in the local area of the current
3589 SDValue MemcpyCall =
3590 CreateCopyOfByValArgument(Arg, PtrOff,
3591 CallSeqStart.getNode()->getOperand(0),
3594 // This must go outside the CALLSEQ_START..END.
3595 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3596 CallSeqStart.getNode()->getOperand(1),
3598 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3599 NewCallSeqStart.getNode());
3600 Chain = CallSeqStart = NewCallSeqStart;
3602 // Pass the address of the aggregate copy on the stack either in a
3603 // physical register or in the parameter list area of the current stack
3604 // frame to the callee.
3608 if (VA.isRegLoc()) {
3609 seenFloatArg |= VA.getLocVT().isFloatingPoint();
3610 // Put argument in a physical register.
3611 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3613 // Put argument in the parameter list area of the current stack frame.
3614 assert(VA.isMemLoc());
3615 unsigned LocMemOffset = VA.getLocMemOffset();
3618 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
3619 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
3621 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3622 MachinePointerInfo(),
3625 // Calculate and remember argument location.
3626 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
3632 if (!MemOpChains.empty())
3633 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3634 &MemOpChains[0], MemOpChains.size());
3636 // Build a sequence of copy-to-reg nodes chained together with token chain
3637 // and flag operands which copy the outgoing args into the appropriate regs.
3639 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3640 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3641 RegsToPass[i].second, InFlag);
3642 InFlag = Chain.getValue(1);
3645 // Set CR bit 6 to true if this is a vararg call with floating args passed in
3648 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3649 SDValue Ops[] = { Chain, InFlag };
3651 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
3652 dl, VTs, Ops, InFlag.getNode() ? 2 : 1);
3654 InFlag = Chain.getValue(1);
3658 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
3659 false, TailCallArguments);
3661 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
3662 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
3666 // Copy an argument into memory, being careful to do this outside the
3667 // call sequence for the call to which the argument belongs.
3669 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
3670 SDValue CallSeqStart,
3671 ISD::ArgFlagsTy Flags,
3674 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
3675 CallSeqStart.getNode()->getOperand(0),
3677 // The MEMCPY must go outside the CALLSEQ_START..END.
3678 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
3679 CallSeqStart.getNode()->getOperand(1),
3681 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
3682 NewCallSeqStart.getNode());
3683 return NewCallSeqStart;
3687 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
3688 CallingConv::ID CallConv, bool isVarArg,
3690 const SmallVectorImpl<ISD::OutputArg> &Outs,
3691 const SmallVectorImpl<SDValue> &OutVals,
3692 const SmallVectorImpl<ISD::InputArg> &Ins,
3693 SDLoc dl, SelectionDAG &DAG,
3694 SmallVectorImpl<SDValue> &InVals) const {
3696 unsigned NumOps = Outs.size();
3698 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3699 unsigned PtrByteSize = 8;
3701 MachineFunction &MF = DAG.getMachineFunction();
3703 // Mark this function as potentially containing a function that contains a
3704 // tail call. As a consequence the frame pointer will be used for dynamicalloc
3705 // and restoring the callers stack pointer in this functions epilog. This is
3706 // done because by tail calling the called function might overwrite the value
3707 // in this function's (MF) stack pointer stack slot 0(SP).
3708 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
3709 CallConv == CallingConv::Fast)
3710 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
3712 unsigned nAltivecParamsAtEnd = 0;
3714 // Count how many bytes are to be pushed on the stack, including the linkage
3715 // area, and parameter passing area. We start with at least 48 bytes, which
3716 // is reserved space for [SP][CR][LR][3 x unused].
3717 // NOTE: For PPC64, nAltivecParamsAtEnd always remains zero as a result
3720 CalculateParameterAndLinkageAreaSize(DAG, true, isVarArg, CallConv,
3721 Outs, OutVals, nAltivecParamsAtEnd);
3723 // Calculate by how many bytes the stack has to be adjusted in case of tail
3724 // call optimization.
3725 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
3727 // To protect arguments on the stack from being clobbered in a tail call,
3728 // force all the loads to happen before doing any other lowering.
3730 Chain = DAG.getStackArgumentTokenFactor(Chain);
3732 // Adjust the stack pointer for the new arguments...
3733 // These operations are automatically eliminated by the prolog/epilog pass
3734 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
3736 SDValue CallSeqStart = Chain;
3738 // Load the return address and frame pointer so it can be move somewhere else
3741 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
3744 // Set up a copy of the stack pointer for use loading and storing any
3745 // arguments that may not fit in the registers available for argument
3747 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3749 // Figure out which arguments are going to go in registers, and which in
3750 // memory. Also, if this is a vararg function, floating point operations
3751 // must be stored to our stack, and loaded into integer regs as well, if
3752 // any integer regs are available for argument passing.
3753 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(true, true);
3754 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3756 static const uint16_t GPR[] = {
3757 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
3758 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
3760 static const uint16_t *FPR = GetFPR();
3762 static const uint16_t VR[] = {
3763 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
3764 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
3766 const unsigned NumGPRs = array_lengthof(GPR);
3767 const unsigned NumFPRs = 13;
3768 const unsigned NumVRs = array_lengthof(VR);
3770 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3771 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
3773 SmallVector<SDValue, 8> MemOpChains;
3774 for (unsigned i = 0; i != NumOps; ++i) {
3775 SDValue Arg = OutVals[i];
3776 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3778 // PtrOff will be used to store the current argument to the stack if a
3779 // register cannot be found for it.
3782 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
3784 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
3786 // Promote integers to 64-bit values.
3787 if (Arg.getValueType() == MVT::i32) {
3788 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
3789 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3790 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
3793 // FIXME memcpy is used way more than necessary. Correctness first.
3794 // Note: "by value" is code for passing a structure by value, not
3796 if (Flags.isByVal()) {
3797 // Note: Size includes alignment padding, so
3798 // struct x { short a; char b; }
3799 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
3800 // These are the proper values we need for right-justifying the
3801 // aggregate in a parameter register.
3802 unsigned Size = Flags.getByValSize();
3804 // An empty aggregate parameter takes up no storage and no
3809 // All aggregates smaller than 8 bytes must be passed right-justified.
3810 if (Size==1 || Size==2 || Size==4) {
3811 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
3812 if (GPR_idx != NumGPRs) {
3813 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
3814 MachinePointerInfo(), VT,
3816 MemOpChains.push_back(Load.getValue(1));
3817 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3819 ArgOffset += PtrByteSize;
3824 if (GPR_idx == NumGPRs && Size < 8) {
3825 SDValue Const = DAG.getConstant(PtrByteSize - Size,
3826 PtrOff.getValueType());
3827 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3828 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3831 ArgOffset += PtrByteSize;
3834 // Copy entire object into memory. There are cases where gcc-generated
3835 // code assumes it is there, even if it could be put entirely into
3836 // registers. (This is not what the doc says.)
3838 // FIXME: The above statement is likely due to a misunderstanding of the
3839 // documents. All arguments must be copied into the parameter area BY
3840 // THE CALLEE in the event that the callee takes the address of any
3841 // formal argument. That has not yet been implemented. However, it is
3842 // reasonable to use the stack area as a staging area for the register
3845 // Skip this for small aggregates, as we will use the same slot for a
3846 // right-justified copy, below.
3848 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
3852 // When a register is available, pass a small aggregate right-justified.
3853 if (Size < 8 && GPR_idx != NumGPRs) {
3854 // The easiest way to get this right-justified in a register
3855 // is to copy the structure into the rightmost portion of a
3856 // local variable slot, then load the whole slot into the
3858 // FIXME: The memcpy seems to produce pretty awful code for
3859 // small aggregates, particularly for packed ones.
3860 // FIXME: It would be preferable to use the slot in the
3861 // parameter save area instead of a new local variable.
3862 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
3863 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
3864 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
3868 // Load the slot into the register.
3869 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
3870 MachinePointerInfo(),
3871 false, false, false, 0);
3872 MemOpChains.push_back(Load.getValue(1));
3873 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3875 // Done with this argument.
3876 ArgOffset += PtrByteSize;
3880 // For aggregates larger than PtrByteSize, copy the pieces of the
3881 // object that fit into registers from the parameter save area.
3882 for (unsigned j=0; j<Size; j+=PtrByteSize) {
3883 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
3884 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
3885 if (GPR_idx != NumGPRs) {
3886 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
3887 MachinePointerInfo(),
3888 false, false, false, 0);
3889 MemOpChains.push_back(Load.getValue(1));
3890 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3891 ArgOffset += PtrByteSize;
3893 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
3900 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
3901 default: llvm_unreachable("Unexpected ValueType for argument!");
3904 if (GPR_idx != NumGPRs) {
3905 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
3907 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3908 true, isTailCall, false, MemOpChains,
3909 TailCallArguments, dl);
3911 ArgOffset += PtrByteSize;
3915 if (FPR_idx != NumFPRs) {
3916 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
3919 // A single float or an aggregate containing only a single float
3920 // must be passed right-justified in the stack doubleword, and
3921 // in the GPR, if one is available.
3923 if (Arg.getValueType().getSimpleVT().SimpleTy == MVT::f32) {
3924 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3925 StoreOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3929 SDValue Store = DAG.getStore(Chain, dl, Arg, StoreOff,
3930 MachinePointerInfo(), false, false, 0);
3931 MemOpChains.push_back(Store);
3933 // Float varargs are always shadowed in available integer registers
3934 if (GPR_idx != NumGPRs) {
3935 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
3936 MachinePointerInfo(), false, false,
3938 MemOpChains.push_back(Load.getValue(1));
3939 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
3941 } else if (GPR_idx != NumGPRs)
3942 // If we have any FPRs remaining, we may also have GPRs remaining.
3945 // Single-precision floating-point values are mapped to the
3946 // second (rightmost) word of the stack doubleword.
3947 if (Arg.getValueType() == MVT::f32) {
3948 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
3949 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
3952 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
3953 true, isTailCall, false, MemOpChains,
3954 TailCallArguments, dl);
3963 // These go aligned on the stack, or in the corresponding R registers
3964 // when within range. The Darwin PPC ABI doc claims they also go in
3965 // V registers; in fact gcc does this only for arguments that are
3966 // prototyped, not for those that match the ... We do it for all
3967 // arguments, seems to work.
3968 while (ArgOffset % 16 !=0) {
3969 ArgOffset += PtrByteSize;
3970 if (GPR_idx != NumGPRs)
3973 // We could elide this store in the case where the object fits
3974 // entirely in R registers. Maybe later.
3975 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3976 DAG.getConstant(ArgOffset, PtrVT));
3977 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
3978 MachinePointerInfo(), false, false, 0);
3979 MemOpChains.push_back(Store);
3980 if (VR_idx != NumVRs) {
3981 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
3982 MachinePointerInfo(),
3983 false, false, false, 0);
3984 MemOpChains.push_back(Load.getValue(1));
3985 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
3988 for (unsigned i=0; i<16; i+=PtrByteSize) {
3989 if (GPR_idx == NumGPRs)
3991 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
3992 DAG.getConstant(i, PtrVT));
3993 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
3994 false, false, false, 0);
3995 MemOpChains.push_back(Load.getValue(1));
3996 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4001 // Non-varargs Altivec params generally go in registers, but have
4002 // stack space allocated at the end.
4003 if (VR_idx != NumVRs) {
4004 // Doesn't have GPR space allocated.
4005 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4007 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4008 true, isTailCall, true, MemOpChains,
4009 TailCallArguments, dl);
4016 if (!MemOpChains.empty())
4017 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4018 &MemOpChains[0], MemOpChains.size());
4020 // Check if this is an indirect call (MTCTR/BCTRL).
4021 // See PrepareCall() for more information about calls through function
4022 // pointers in the 64-bit SVR4 ABI.
4024 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4025 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4026 !isBLACompatibleAddress(Callee, DAG)) {
4027 // Load r2 into a virtual register and store it to the TOC save area.
4028 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4029 // TOC save area offset.
4030 SDValue PtrOff = DAG.getIntPtrConstant(40);
4031 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4032 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4034 // R12 must contain the address of an indirect callee. This does not
4035 // mean the MTCTR instruction must use R12; it's easier to model this
4036 // as an extra parameter, so do that.
4037 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4040 // Build a sequence of copy-to-reg nodes chained together with token chain
4041 // and flag operands which copy the outgoing args into the appropriate regs.
4043 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4044 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4045 RegsToPass[i].second, InFlag);
4046 InFlag = Chain.getValue(1);
4050 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4051 FPOp, true, TailCallArguments);
4053 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4054 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4059 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4060 CallingConv::ID CallConv, bool isVarArg,
4062 const SmallVectorImpl<ISD::OutputArg> &Outs,
4063 const SmallVectorImpl<SDValue> &OutVals,
4064 const SmallVectorImpl<ISD::InputArg> &Ins,
4065 SDLoc dl, SelectionDAG &DAG,
4066 SmallVectorImpl<SDValue> &InVals) const {
4068 unsigned NumOps = Outs.size();
4070 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4071 bool isPPC64 = PtrVT == MVT::i64;
4072 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4074 MachineFunction &MF = DAG.getMachineFunction();
4076 // Mark this function as potentially containing a function that contains a
4077 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4078 // and restoring the callers stack pointer in this functions epilog. This is
4079 // done because by tail calling the called function might overwrite the value
4080 // in this function's (MF) stack pointer stack slot 0(SP).
4081 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4082 CallConv == CallingConv::Fast)
4083 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4085 unsigned nAltivecParamsAtEnd = 0;
4087 // Count how many bytes are to be pushed on the stack, including the linkage
4088 // area, and parameter passing area. We start with 24/48 bytes, which is
4089 // prereserved space for [SP][CR][LR][3 x unused].
4091 CalculateParameterAndLinkageAreaSize(DAG, isPPC64, isVarArg, CallConv,
4093 nAltivecParamsAtEnd);
4095 // Calculate by how many bytes the stack has to be adjusted in case of tail
4096 // call optimization.
4097 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4099 // To protect arguments on the stack from being clobbered in a tail call,
4100 // force all the loads to happen before doing any other lowering.
4102 Chain = DAG.getStackArgumentTokenFactor(Chain);
4104 // Adjust the stack pointer for the new arguments...
4105 // These operations are automatically eliminated by the prolog/epilog pass
4106 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4108 SDValue CallSeqStart = Chain;
4110 // Load the return address and frame pointer so it can be move somewhere else
4113 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4116 // Set up a copy of the stack pointer for use loading and storing any
4117 // arguments that may not fit in the registers available for argument
4121 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4123 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4125 // Figure out which arguments are going to go in registers, and which in
4126 // memory. Also, if this is a vararg function, floating point operations
4127 // must be stored to our stack, and loaded into integer regs as well, if
4128 // any integer regs are available for argument passing.
4129 unsigned ArgOffset = PPCFrameLowering::getLinkageSize(isPPC64, true);
4130 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4132 static const uint16_t GPR_32[] = { // 32-bit registers.
4133 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4134 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4136 static const uint16_t GPR_64[] = { // 64-bit registers.
4137 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4138 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4140 static const uint16_t *FPR = GetFPR();
4142 static const uint16_t VR[] = {
4143 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4144 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4146 const unsigned NumGPRs = array_lengthof(GPR_32);
4147 const unsigned NumFPRs = 13;
4148 const unsigned NumVRs = array_lengthof(VR);
4150 const uint16_t *GPR = isPPC64 ? GPR_64 : GPR_32;
4152 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4153 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4155 SmallVector<SDValue, 8> MemOpChains;
4156 for (unsigned i = 0; i != NumOps; ++i) {
4157 SDValue Arg = OutVals[i];
4158 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4160 // PtrOff will be used to store the current argument to the stack if a
4161 // register cannot be found for it.
4164 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4166 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4168 // On PPC64, promote integers to 64-bit values.
4169 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4170 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4171 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4172 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4175 // FIXME memcpy is used way more than necessary. Correctness first.
4176 // Note: "by value" is code for passing a structure by value, not
4178 if (Flags.isByVal()) {
4179 unsigned Size = Flags.getByValSize();
4180 // Very small objects are passed right-justified. Everything else is
4181 // passed left-justified.
4182 if (Size==1 || Size==2) {
4183 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4184 if (GPR_idx != NumGPRs) {
4185 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4186 MachinePointerInfo(), VT,
4188 MemOpChains.push_back(Load.getValue(1));
4189 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4191 ArgOffset += PtrByteSize;
4193 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4194 PtrOff.getValueType());
4195 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4196 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4199 ArgOffset += PtrByteSize;
4203 // Copy entire object into memory. There are cases where gcc-generated
4204 // code assumes it is there, even if it could be put entirely into
4205 // registers. (This is not what the doc says.)
4206 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4210 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4211 // copy the pieces of the object that fit into registers from the
4212 // parameter save area.
4213 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4214 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4215 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4216 if (GPR_idx != NumGPRs) {
4217 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4218 MachinePointerInfo(),
4219 false, false, false, 0);
4220 MemOpChains.push_back(Load.getValue(1));
4221 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4222 ArgOffset += PtrByteSize;
4224 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4231 switch (Arg.getValueType().getSimpleVT().SimpleTy) {
4232 default: llvm_unreachable("Unexpected ValueType for argument!");
4235 if (GPR_idx != NumGPRs) {
4236 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4238 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4239 isPPC64, isTailCall, false, MemOpChains,
4240 TailCallArguments, dl);
4242 ArgOffset += PtrByteSize;
4246 if (FPR_idx != NumFPRs) {
4247 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4250 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4251 MachinePointerInfo(), false, false, 0);
4252 MemOpChains.push_back(Store);
4254 // Float varargs are always shadowed in available integer registers
4255 if (GPR_idx != NumGPRs) {
4256 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4257 MachinePointerInfo(), false, false,
4259 MemOpChains.push_back(Load.getValue(1));
4260 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4262 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4263 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4264 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4265 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4266 MachinePointerInfo(),
4267 false, false, false, 0);
4268 MemOpChains.push_back(Load.getValue(1));
4269 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4272 // If we have any FPRs remaining, we may also have GPRs remaining.
4273 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4275 if (GPR_idx != NumGPRs)
4277 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4278 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4282 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4283 isPPC64, isTailCall, false, MemOpChains,
4284 TailCallArguments, dl);
4288 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4295 // These go aligned on the stack, or in the corresponding R registers
4296 // when within range. The Darwin PPC ABI doc claims they also go in
4297 // V registers; in fact gcc does this only for arguments that are
4298 // prototyped, not for those that match the ... We do it for all
4299 // arguments, seems to work.
4300 while (ArgOffset % 16 !=0) {
4301 ArgOffset += PtrByteSize;
4302 if (GPR_idx != NumGPRs)
4305 // We could elide this store in the case where the object fits
4306 // entirely in R registers. Maybe later.
4307 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
4308 DAG.getConstant(ArgOffset, PtrVT));
4309 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4310 MachinePointerInfo(), false, false, 0);
4311 MemOpChains.push_back(Store);
4312 if (VR_idx != NumVRs) {
4313 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4314 MachinePointerInfo(),
4315 false, false, false, 0);
4316 MemOpChains.push_back(Load.getValue(1));
4317 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
4320 for (unsigned i=0; i<16; i+=PtrByteSize) {
4321 if (GPR_idx == NumGPRs)
4323 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4324 DAG.getConstant(i, PtrVT));
4325 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4326 false, false, false, 0);
4327 MemOpChains.push_back(Load.getValue(1));
4328 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4333 // Non-varargs Altivec params generally go in registers, but have
4334 // stack space allocated at the end.
4335 if (VR_idx != NumVRs) {
4336 // Doesn't have GPR space allocated.
4337 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
4338 } else if (nAltivecParamsAtEnd==0) {
4339 // We are emitting Altivec params in order.
4340 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4341 isPPC64, isTailCall, true, MemOpChains,
4342 TailCallArguments, dl);
4348 // If all Altivec parameters fit in registers, as they usually do,
4349 // they get stack space following the non-Altivec parameters. We
4350 // don't track this here because nobody below needs it.
4351 // If there are more Altivec parameters than fit in registers emit
4353 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
4355 // Offset is aligned; skip 1st 12 params which go in V registers.
4356 ArgOffset = ((ArgOffset+15)/16)*16;
4358 for (unsigned i = 0; i != NumOps; ++i) {
4359 SDValue Arg = OutVals[i];
4360 EVT ArgType = Outs[i].VT;
4361 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
4362 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
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);
4375 if (!MemOpChains.empty())
4376 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4377 &MemOpChains[0], MemOpChains.size());
4379 // On Darwin, R12 must contain the address of an indirect callee. This does
4380 // not mean the MTCTR instruction must use R12; it's easier to model this as
4381 // an extra parameter, so do that.
4383 !dyn_cast<GlobalAddressSDNode>(Callee) &&
4384 !dyn_cast<ExternalSymbolSDNode>(Callee) &&
4385 !isBLACompatibleAddress(Callee, DAG))
4386 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
4387 PPC::R12), Callee));
4389 // Build a sequence of copy-to-reg nodes chained together with token chain
4390 // and flag operands which copy the outgoing args into the appropriate regs.
4392 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4393 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4394 RegsToPass[i].second, InFlag);
4395 InFlag = Chain.getValue(1);
4399 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
4400 FPOp, true, TailCallArguments);
4402 return FinishCall(CallConv, dl, isTailCall, isVarArg, DAG,
4403 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4408 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
4409 MachineFunction &MF, bool isVarArg,
4410 const SmallVectorImpl<ISD::OutputArg> &Outs,
4411 LLVMContext &Context) const {
4412 SmallVector<CCValAssign, 16> RVLocs;
4413 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
4415 return CCInfo.CheckReturn(Outs, RetCC_PPC);
4419 PPCTargetLowering::LowerReturn(SDValue Chain,
4420 CallingConv::ID CallConv, bool isVarArg,
4421 const SmallVectorImpl<ISD::OutputArg> &Outs,
4422 const SmallVectorImpl<SDValue> &OutVals,
4423 SDLoc dl, SelectionDAG &DAG) const {
4425 SmallVector<CCValAssign, 16> RVLocs;
4426 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4427 getTargetMachine(), RVLocs, *DAG.getContext());
4428 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
4431 SmallVector<SDValue, 4> RetOps(1, Chain);
4433 // Copy the result values into the output registers.
4434 for (unsigned i = 0; i != RVLocs.size(); ++i) {
4435 CCValAssign &VA = RVLocs[i];
4436 assert(VA.isRegLoc() && "Can only return in registers!");
4438 SDValue Arg = OutVals[i];
4440 switch (VA.getLocInfo()) {
4441 default: llvm_unreachable("Unknown loc info!");
4442 case CCValAssign::Full: break;
4443 case CCValAssign::AExt:
4444 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
4446 case CCValAssign::ZExt:
4447 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
4449 case CCValAssign::SExt:
4450 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
4454 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
4455 Flag = Chain.getValue(1);
4456 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
4459 RetOps[0] = Chain; // Update chain.
4461 // Add the flag if we have it.
4463 RetOps.push_back(Flag);
4465 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other,
4466 &RetOps[0], RetOps.size());
4469 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
4470 const PPCSubtarget &Subtarget) const {
4471 // When we pop the dynamic allocation we need to restore the SP link.
4474 // Get the corect type for pointers.
4475 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4477 // Construct the stack pointer operand.
4478 bool isPPC64 = Subtarget.isPPC64();
4479 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
4480 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
4482 // Get the operands for the STACKRESTORE.
4483 SDValue Chain = Op.getOperand(0);
4484 SDValue SaveSP = Op.getOperand(1);
4486 // Load the old link SP.
4487 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
4488 MachinePointerInfo(),
4489 false, false, false, 0);
4491 // Restore the stack pointer.
4492 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
4494 // Store the old link SP.
4495 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
4502 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
4503 MachineFunction &MF = DAG.getMachineFunction();
4504 bool isPPC64 = PPCSubTarget.isPPC64();
4505 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4506 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4508 // Get current frame pointer save index. The users of this index will be
4509 // primarily DYNALLOC instructions.
4510 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4511 int RASI = FI->getReturnAddrSaveIndex();
4513 // If the frame pointer save index hasn't been defined yet.
4515 // Find out what the fix offset of the frame pointer save area.
4516 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
4517 // Allocate the frame index for frame pointer save area.
4518 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, true);
4520 FI->setReturnAddrSaveIndex(RASI);
4522 return DAG.getFrameIndex(RASI, PtrVT);
4526 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
4527 MachineFunction &MF = DAG.getMachineFunction();
4528 bool isPPC64 = PPCSubTarget.isPPC64();
4529 bool isDarwinABI = PPCSubTarget.isDarwinABI();
4530 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4532 // Get current frame pointer save index. The users of this index will be
4533 // primarily DYNALLOC instructions.
4534 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
4535 int FPSI = FI->getFramePointerSaveIndex();
4537 // If the frame pointer save index hasn't been defined yet.
4539 // Find out what the fix offset of the frame pointer save area.
4540 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
4543 // Allocate the frame index for frame pointer save area.
4544 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
4546 FI->setFramePointerSaveIndex(FPSI);
4548 return DAG.getFrameIndex(FPSI, PtrVT);
4551 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
4553 const PPCSubtarget &Subtarget) const {
4555 SDValue Chain = Op.getOperand(0);
4556 SDValue Size = Op.getOperand(1);
4559 // Get the corect type for pointers.
4560 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4562 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
4563 DAG.getConstant(0, PtrVT), Size);
4564 // Construct a node for the frame pointer save index.
4565 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
4566 // Build a DYNALLOC node.
4567 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
4568 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
4569 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops, 3);
4572 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
4573 SelectionDAG &DAG) const {
4575 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
4576 DAG.getVTList(MVT::i32, MVT::Other),
4577 Op.getOperand(0), Op.getOperand(1));
4580 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
4581 SelectionDAG &DAG) const {
4583 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
4584 Op.getOperand(0), Op.getOperand(1));
4587 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
4589 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4590 // Not FP? Not a fsel.
4591 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
4592 !Op.getOperand(2).getValueType().isFloatingPoint())
4595 // We might be able to do better than this under some circumstances, but in
4596 // general, fsel-based lowering of select is a finite-math-only optimization.
4597 // For more information, see section F.3 of the 2.06 ISA specification.
4598 if (!DAG.getTarget().Options.NoInfsFPMath ||
4599 !DAG.getTarget().Options.NoNaNsFPMath)
4602 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4604 EVT ResVT = Op.getValueType();
4605 EVT CmpVT = Op.getOperand(0).getValueType();
4606 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
4607 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
4610 // If the RHS of the comparison is a 0.0, we don't need to do the
4611 // subtraction at all.
4613 if (isFloatingPointZero(RHS))
4615 default: break; // SETUO etc aren't handled by fsel.
4619 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4620 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4621 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4622 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4623 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4624 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4625 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
4628 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4631 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4632 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4633 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
4636 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
4639 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
4640 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
4641 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4642 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
4647 default: break; // SETUO etc aren't handled by fsel.
4651 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
4652 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
4653 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
4654 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
4655 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
4656 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
4657 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
4658 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
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,
4690 assert(Op.getOperand(0).getValueType().isFloatingPoint());
4691 SDValue Src = Op.getOperand(0);
4693 // If we have a long double here, it must be that we have an undef of
4694 // that type. In this case return an undef of the target type.
4695 if (Src.getValueType() == MVT::ppcf128) {
4696 assert(Src.getOpcode() == ISD::UNDEF && "Unhandled ppcf128!");
4697 return DAG.getNode(ISD::UNDEF, dl,
4698 Op.getValueType().getSimpleVT().SimpleTy);
4701 if (Src.getValueType() == MVT::f32)
4702 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
4705 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4706 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
4708 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
4709 (PPCSubTarget.hasFPCVT() ? PPCISD::FCTIWUZ :
4714 assert((Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT()) &&
4715 "i64 FP_TO_UINT is supported only with FPCVT");
4716 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
4722 // Convert the FP value to an int value through memory.
4723 bool i32Stack = Op.getValueType() == MVT::i32 && PPCSubTarget.hasSTFIWX() &&
4724 (Op.getOpcode() == ISD::FP_TO_SINT || PPCSubTarget.hasFPCVT());
4725 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
4726 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
4727 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
4729 // Emit a store to the stack slot.
4732 MachineFunction &MF = DAG.getMachineFunction();
4733 MachineMemOperand *MMO =
4734 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
4735 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
4736 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
4737 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
4740 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
4741 MPI, false, false, 0);
4743 // Result is a load from the stack slot. If loading 4 bytes, make sure to
4745 if (Op.getValueType() == MVT::i32 && !i32Stack) {
4746 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
4747 DAG.getConstant(4, FIPtr.getValueType()));
4748 MPI = MachinePointerInfo();
4751 return DAG.getLoad(Op.getValueType(), dl, Chain, FIPtr, MPI,
4752 false, false, false, 0);
4755 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
4756 SelectionDAG &DAG) const {
4758 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
4759 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
4762 assert((Op.getOpcode() == ISD::SINT_TO_FP || PPCSubTarget.hasFPCVT()) &&
4763 "UINT_TO_FP is supported only with FPCVT");
4765 // If we have FCFIDS, then use it when converting to single-precision.
4766 // Otherwise, convert to double-precision and then round.
4767 unsigned FCFOp = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4768 (Op.getOpcode() == ISD::UINT_TO_FP ?
4769 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
4770 (Op.getOpcode() == ISD::UINT_TO_FP ?
4771 PPCISD::FCFIDU : PPCISD::FCFID);
4772 MVT FCFTy = (PPCSubTarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
4773 MVT::f32 : MVT::f64;
4775 if (Op.getOperand(0).getValueType() == MVT::i64) {
4776 SDValue SINT = Op.getOperand(0);
4777 // When converting to single-precision, we actually need to convert
4778 // to double-precision first and then round to single-precision.
4779 // To avoid double-rounding effects during that operation, we have
4780 // to prepare the input operand. Bits that might be truncated when
4781 // converting to double-precision are replaced by a bit that won't
4782 // be lost at this stage, but is below the single-precision rounding
4785 // However, if -enable-unsafe-fp-math is in effect, accept double
4786 // rounding to avoid the extra overhead.
4787 if (Op.getValueType() == MVT::f32 &&
4788 !PPCSubTarget.hasFPCVT() &&
4789 !DAG.getTarget().Options.UnsafeFPMath) {
4791 // Twiddle input to make sure the low 11 bits are zero. (If this
4792 // is the case, we are guaranteed the value will fit into the 53 bit
4793 // mantissa of an IEEE double-precision value without rounding.)
4794 // If any of those low 11 bits were not zero originally, make sure
4795 // bit 12 (value 2048) is set instead, so that the final rounding
4796 // to single-precision gets the correct result.
4797 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4798 SINT, DAG.getConstant(2047, MVT::i64));
4799 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
4800 Round, DAG.getConstant(2047, MVT::i64));
4801 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
4802 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
4803 Round, DAG.getConstant(-2048, MVT::i64));
4805 // However, we cannot use that value unconditionally: if the magnitude
4806 // of the input value is small, the bit-twiddling we did above might
4807 // end up visibly changing the output. Fortunately, in that case, we
4808 // don't need to twiddle bits since the original input will convert
4809 // exactly to double-precision floating-point already. Therefore,
4810 // construct a conditional to use the original value if the top 11
4811 // bits are all sign-bit copies, and use the rounded value computed
4813 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
4814 SINT, DAG.getConstant(53, MVT::i32));
4815 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
4816 Cond, DAG.getConstant(1, MVT::i64));
4817 Cond = DAG.getSetCC(dl, MVT::i32,
4818 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
4820 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
4823 SDValue Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
4824 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
4826 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4827 FP = DAG.getNode(ISD::FP_ROUND, dl,
4828 MVT::f32, FP, DAG.getIntPtrConstant(0));
4832 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
4833 "Unhandled INT_TO_FP type in custom expander!");
4834 // Since we only generate this in 64-bit mode, we can take advantage of
4835 // 64-bit registers. In particular, sign extend the input value into the
4836 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
4837 // then lfd it and fcfid it.
4838 MachineFunction &MF = DAG.getMachineFunction();
4839 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
4840 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4843 if (PPCSubTarget.hasLFIWAX() || PPCSubTarget.hasFPCVT()) {
4844 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
4845 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4847 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
4848 MachinePointerInfo::getFixedStack(FrameIdx),
4851 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
4852 "Expected an i32 store");
4853 MachineMemOperand *MMO =
4854 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(FrameIdx),
4855 MachineMemOperand::MOLoad, 4, 4);
4856 SDValue Ops[] = { Store, FIdx };
4857 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
4858 PPCISD::LFIWZX : PPCISD::LFIWAX,
4859 dl, DAG.getVTList(MVT::f64, MVT::Other),
4860 Ops, 2, MVT::i32, MMO);
4862 assert(PPCSubTarget.isPPC64() &&
4863 "i32->FP without LFIWAX supported only on PPC64");
4865 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
4866 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
4868 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
4871 // STD the extended value into the stack slot.
4872 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
4873 MachinePointerInfo::getFixedStack(FrameIdx),
4876 // Load the value as a double.
4877 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
4878 MachinePointerInfo::getFixedStack(FrameIdx),
4879 false, false, false, 0);
4882 // FCFID it and return it.
4883 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
4884 if (Op.getValueType() == MVT::f32 && !PPCSubTarget.hasFPCVT())
4885 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
4889 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4890 SelectionDAG &DAG) const {
4893 The rounding mode is in bits 30:31 of FPSR, and has the following
4900 FLT_ROUNDS, on the other hand, expects the following:
4907 To perform the conversion, we do:
4908 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
4911 MachineFunction &MF = DAG.getMachineFunction();
4912 EVT VT = Op.getValueType();
4913 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4914 SDValue MFFSreg, InFlag;
4916 // Save FP Control Word to register
4918 MVT::f64, // return register
4919 MVT::Glue // unused in this context
4921 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, &InFlag, 0);
4923 // Save FP register to stack slot
4924 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
4925 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
4926 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
4927 StackSlot, MachinePointerInfo(), false, false,0);
4929 // Load FP Control Word from low 32 bits of stack slot.
4930 SDValue Four = DAG.getConstant(4, PtrVT);
4931 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
4932 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
4933 false, false, false, 0);
4935 // Transform as necessary
4937 DAG.getNode(ISD::AND, dl, MVT::i32,
4938 CWD, DAG.getConstant(3, MVT::i32));
4940 DAG.getNode(ISD::SRL, dl, MVT::i32,
4941 DAG.getNode(ISD::AND, dl, MVT::i32,
4942 DAG.getNode(ISD::XOR, dl, MVT::i32,
4943 CWD, DAG.getConstant(3, MVT::i32)),
4944 DAG.getConstant(3, MVT::i32)),
4945 DAG.getConstant(1, MVT::i32));
4948 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
4950 return DAG.getNode((VT.getSizeInBits() < 16 ?
4951 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
4954 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4955 EVT VT = Op.getValueType();
4956 unsigned BitWidth = VT.getSizeInBits();
4958 assert(Op.getNumOperands() == 3 &&
4959 VT == Op.getOperand(1).getValueType() &&
4962 // Expand into a bunch of logical ops. Note that these ops
4963 // depend on the PPC behavior for oversized shift amounts.
4964 SDValue Lo = Op.getOperand(0);
4965 SDValue Hi = Op.getOperand(1);
4966 SDValue Amt = Op.getOperand(2);
4967 EVT AmtVT = Amt.getValueType();
4969 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4970 DAG.getConstant(BitWidth, AmtVT), Amt);
4971 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
4972 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
4973 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
4974 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
4975 DAG.getConstant(-BitWidth, AmtVT));
4976 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
4977 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
4978 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
4979 SDValue OutOps[] = { OutLo, OutHi };
4980 return DAG.getMergeValues(OutOps, 2, dl);
4983 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
4984 EVT VT = Op.getValueType();
4986 unsigned BitWidth = VT.getSizeInBits();
4987 assert(Op.getNumOperands() == 3 &&
4988 VT == Op.getOperand(1).getValueType() &&
4991 // Expand into a bunch of logical ops. Note that these ops
4992 // depend on the PPC behavior for oversized shift amounts.
4993 SDValue Lo = Op.getOperand(0);
4994 SDValue Hi = Op.getOperand(1);
4995 SDValue Amt = Op.getOperand(2);
4996 EVT AmtVT = Amt.getValueType();
4998 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
4999 DAG.getConstant(BitWidth, AmtVT), Amt);
5000 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5001 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5002 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5003 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5004 DAG.getConstant(-BitWidth, AmtVT));
5005 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5006 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5007 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5008 SDValue OutOps[] = { OutLo, OutHi };
5009 return DAG.getMergeValues(OutOps, 2, dl);
5012 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5014 EVT VT = Op.getValueType();
5015 unsigned BitWidth = VT.getSizeInBits();
5016 assert(Op.getNumOperands() == 3 &&
5017 VT == Op.getOperand(1).getValueType() &&
5020 // Expand into a bunch of logical ops, followed by a select_cc.
5021 SDValue Lo = Op.getOperand(0);
5022 SDValue Hi = Op.getOperand(1);
5023 SDValue Amt = Op.getOperand(2);
5024 EVT AmtVT = Amt.getValueType();
5026 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5027 DAG.getConstant(BitWidth, AmtVT), Amt);
5028 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5029 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5030 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5031 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5032 DAG.getConstant(-BitWidth, AmtVT));
5033 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5034 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5035 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5036 Tmp4, Tmp6, ISD::SETLE);
5037 SDValue OutOps[] = { OutLo, OutHi };
5038 return DAG.getMergeValues(OutOps, 2, dl);
5041 //===----------------------------------------------------------------------===//
5042 // Vector related lowering.
5045 /// BuildSplatI - Build a canonical splati of Val with an element size of
5046 /// SplatSize. Cast the result to VT.
5047 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5048 SelectionDAG &DAG, SDLoc dl) {
5049 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5051 static const EVT VTys[] = { // canonical VT to use for each size.
5052 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5055 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5057 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5061 EVT CanonicalVT = VTys[SplatSize-1];
5063 // Build a canonical splat for this value.
5064 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5065 SmallVector<SDValue, 8> Ops;
5066 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5067 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT,
5068 &Ops[0], Ops.size());
5069 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5072 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5073 /// specified intrinsic ID.
5074 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5075 SelectionDAG &DAG, SDLoc dl,
5076 EVT DestVT = MVT::Other) {
5077 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5078 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5079 DAG.getConstant(IID, MVT::i32), Op);
5082 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5083 /// specified intrinsic ID.
5084 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5085 SelectionDAG &DAG, SDLoc dl,
5086 EVT DestVT = MVT::Other) {
5087 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5088 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5089 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5092 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5093 /// specified intrinsic ID.
5094 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5095 SDValue Op2, SelectionDAG &DAG,
5096 SDLoc dl, EVT DestVT = MVT::Other) {
5097 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5098 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5099 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5103 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5104 /// amount. The result has the specified value type.
5105 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5106 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5107 // Force LHS/RHS to be the right type.
5108 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
5109 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
5112 for (unsigned i = 0; i != 16; ++i)
5114 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
5115 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5118 // If this is a case we can't handle, return null and let the default
5119 // expansion code take care of it. If we CAN select this case, and if it
5120 // selects to a single instruction, return Op. Otherwise, if we can codegen
5121 // this case more efficiently than a constant pool load, lower it to the
5122 // sequence of ops that should be used.
5123 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
5124 SelectionDAG &DAG) const {
5126 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5127 assert(BVN != 0 && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
5129 // Check if this is a splat of a constant value.
5130 APInt APSplatBits, APSplatUndef;
5131 unsigned SplatBitSize;
5133 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
5134 HasAnyUndefs, 0, true) || SplatBitSize > 32)
5137 unsigned SplatBits = APSplatBits.getZExtValue();
5138 unsigned SplatUndef = APSplatUndef.getZExtValue();
5139 unsigned SplatSize = SplatBitSize / 8;
5141 // First, handle single instruction cases.
5144 if (SplatBits == 0) {
5145 // Canonicalize all zero vectors to be v4i32.
5146 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
5147 SDValue Z = DAG.getConstant(0, MVT::i32);
5148 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
5149 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
5154 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
5155 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
5157 if (SextVal >= -16 && SextVal <= 15)
5158 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
5161 // Two instruction sequences.
5163 // If this value is in the range [-32,30] and is even, use:
5164 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
5165 // If this value is in the range [17,31] and is odd, use:
5166 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
5167 // If this value is in the range [-31,-17] and is odd, use:
5168 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
5169 // Note the last two are three-instruction sequences.
5170 if (SextVal >= -32 && SextVal <= 31) {
5171 // To avoid having these optimizations undone by constant folding,
5172 // we convert to a pseudo that will be expanded later into one of
5174 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
5175 EVT VT = Op.getValueType();
5176 int Size = VT == MVT::v16i8 ? 1 : (VT == MVT::v8i16 ? 2 : 4);
5177 SDValue EltSize = DAG.getConstant(Size, MVT::i32);
5178 return DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
5181 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
5182 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
5184 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
5185 // Make -1 and vspltisw -1:
5186 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
5188 // Make the VSLW intrinsic, computing 0x8000_0000.
5189 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
5192 // xor by OnesV to invert it.
5193 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
5194 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5197 // Check to see if this is a wide variety of vsplti*, binop self cases.
5198 static const signed char SplatCsts[] = {
5199 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
5200 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
5203 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
5204 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
5205 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
5206 int i = SplatCsts[idx];
5208 // Figure out what shift amount will be used by altivec if shifted by i in
5210 unsigned TypeShiftAmt = i & (SplatBitSize-1);
5212 // vsplti + shl self.
5213 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
5214 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5215 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5216 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
5217 Intrinsic::ppc_altivec_vslw
5219 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5220 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5223 // vsplti + srl self.
5224 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5225 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5226 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5227 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
5228 Intrinsic::ppc_altivec_vsrw
5230 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5231 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5234 // vsplti + sra self.
5235 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
5236 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5237 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5238 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
5239 Intrinsic::ppc_altivec_vsraw
5241 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5242 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5245 // vsplti + rol self.
5246 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
5247 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
5248 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
5249 static const unsigned IIDs[] = { // Intrinsic to use for each size.
5250 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
5251 Intrinsic::ppc_altivec_vrlw
5253 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
5254 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
5257 // t = vsplti c, result = vsldoi t, t, 1
5258 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
5259 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5260 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
5262 // t = vsplti c, result = vsldoi t, t, 2
5263 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
5264 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5265 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
5267 // t = vsplti c, result = vsldoi t, t, 3
5268 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
5269 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
5270 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
5277 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5278 /// the specified operations to build the shuffle.
5279 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5280 SDValue RHS, SelectionDAG &DAG,
5282 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5283 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
5284 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
5287 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5299 if (OpNum == OP_COPY) {
5300 if (LHSID == (1*9+2)*9+3) return LHS;
5301 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
5305 SDValue OpLHS, OpRHS;
5306 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5307 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5311 default: llvm_unreachable("Unknown i32 permute!");
5313 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
5314 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
5315 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
5316 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
5319 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
5320 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
5321 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
5322 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
5325 for (unsigned i = 0; i != 16; ++i)
5326 ShufIdxs[i] = (i&3)+0;
5329 for (unsigned i = 0; i != 16; ++i)
5330 ShufIdxs[i] = (i&3)+4;
5333 for (unsigned i = 0; i != 16; ++i)
5334 ShufIdxs[i] = (i&3)+8;
5337 for (unsigned i = 0; i != 16; ++i)
5338 ShufIdxs[i] = (i&3)+12;
5341 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
5343 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
5345 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
5347 EVT VT = OpLHS.getValueType();
5348 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
5349 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
5350 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
5351 return DAG.getNode(ISD::BITCAST, dl, VT, T);
5354 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
5355 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
5356 /// return the code it can be lowered into. Worst case, it can always be
5357 /// lowered into a vperm.
5358 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5359 SelectionDAG &DAG) const {
5361 SDValue V1 = Op.getOperand(0);
5362 SDValue V2 = Op.getOperand(1);
5363 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5364 EVT VT = Op.getValueType();
5366 // Cases that are handled by instructions that take permute immediates
5367 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
5368 // selected by the instruction selector.
5369 if (V2.getOpcode() == ISD::UNDEF) {
5370 if (PPC::isSplatShuffleMask(SVOp, 1) ||
5371 PPC::isSplatShuffleMask(SVOp, 2) ||
5372 PPC::isSplatShuffleMask(SVOp, 4) ||
5373 PPC::isVPKUWUMShuffleMask(SVOp, true) ||
5374 PPC::isVPKUHUMShuffleMask(SVOp, true) ||
5375 PPC::isVSLDOIShuffleMask(SVOp, true) != -1 ||
5376 PPC::isVMRGLShuffleMask(SVOp, 1, true) ||
5377 PPC::isVMRGLShuffleMask(SVOp, 2, true) ||
5378 PPC::isVMRGLShuffleMask(SVOp, 4, true) ||
5379 PPC::isVMRGHShuffleMask(SVOp, 1, true) ||
5380 PPC::isVMRGHShuffleMask(SVOp, 2, true) ||
5381 PPC::isVMRGHShuffleMask(SVOp, 4, true)) {
5386 // Altivec has a variety of "shuffle immediates" that take two vector inputs
5387 // and produce a fixed permutation. If any of these match, do not lower to
5389 if (PPC::isVPKUWUMShuffleMask(SVOp, false) ||
5390 PPC::isVPKUHUMShuffleMask(SVOp, false) ||
5391 PPC::isVSLDOIShuffleMask(SVOp, false) != -1 ||
5392 PPC::isVMRGLShuffleMask(SVOp, 1, false) ||
5393 PPC::isVMRGLShuffleMask(SVOp, 2, false) ||
5394 PPC::isVMRGLShuffleMask(SVOp, 4, false) ||
5395 PPC::isVMRGHShuffleMask(SVOp, 1, false) ||
5396 PPC::isVMRGHShuffleMask(SVOp, 2, false) ||
5397 PPC::isVMRGHShuffleMask(SVOp, 4, false))
5400 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
5401 // perfect shuffle table to emit an optimal matching sequence.
5402 ArrayRef<int> PermMask = SVOp->getMask();
5404 unsigned PFIndexes[4];
5405 bool isFourElementShuffle = true;
5406 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
5407 unsigned EltNo = 8; // Start out undef.
5408 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
5409 if (PermMask[i*4+j] < 0)
5410 continue; // Undef, ignore it.
5412 unsigned ByteSource = PermMask[i*4+j];
5413 if ((ByteSource & 3) != j) {
5414 isFourElementShuffle = false;
5419 EltNo = ByteSource/4;
5420 } else if (EltNo != ByteSource/4) {
5421 isFourElementShuffle = false;
5425 PFIndexes[i] = EltNo;
5428 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
5429 // perfect shuffle vector to determine if it is cost effective to do this as
5430 // discrete instructions, or whether we should use a vperm.
5431 if (isFourElementShuffle) {
5432 // Compute the index in the perfect shuffle table.
5433 unsigned PFTableIndex =
5434 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
5436 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5437 unsigned Cost = (PFEntry >> 30);
5439 // Determining when to avoid vperm is tricky. Many things affect the cost
5440 // of vperm, particularly how many times the perm mask needs to be computed.
5441 // For example, if the perm mask can be hoisted out of a loop or is already
5442 // used (perhaps because there are multiple permutes with the same shuffle
5443 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
5444 // the loop requires an extra register.
5446 // As a compromise, we only emit discrete instructions if the shuffle can be
5447 // generated in 3 or fewer operations. When we have loop information
5448 // available, if this block is within a loop, we should avoid using vperm
5449 // for 3-operation perms and use a constant pool load instead.
5451 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5454 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
5455 // vector that will get spilled to the constant pool.
5456 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
5458 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
5459 // that it is in input element units, not in bytes. Convert now.
5460 EVT EltVT = V1.getValueType().getVectorElementType();
5461 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
5463 SmallVector<SDValue, 16> ResultMask;
5464 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5465 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
5467 for (unsigned j = 0; j != BytesPerElement; ++j)
5468 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
5472 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
5473 &ResultMask[0], ResultMask.size());
5474 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(), V1, V2, VPermMask);
5477 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
5478 /// altivec comparison. If it is, return true and fill in Opc/isDot with
5479 /// information about the intrinsic.
5480 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
5482 unsigned IntrinsicID =
5483 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
5486 switch (IntrinsicID) {
5487 default: return false;
5488 // Comparison predicates.
5489 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
5490 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
5491 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
5492 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
5493 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
5494 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
5495 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
5496 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
5497 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
5498 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
5499 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
5500 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
5501 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
5503 // Normal Comparisons.
5504 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
5505 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
5506 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
5507 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
5508 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
5509 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
5510 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
5511 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
5512 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
5513 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
5514 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
5515 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
5516 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
5521 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
5522 /// lower, do it, otherwise return null.
5523 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5524 SelectionDAG &DAG) const {
5525 // If this is a lowered altivec predicate compare, CompareOpc is set to the
5526 // opcode number of the comparison.
5530 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
5531 return SDValue(); // Don't custom lower most intrinsics.
5533 // If this is a non-dot comparison, make the VCMP node and we are done.
5535 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
5536 Op.getOperand(1), Op.getOperand(2),
5537 DAG.getConstant(CompareOpc, MVT::i32));
5538 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
5541 // Create the PPCISD altivec 'dot' comparison node.
5543 Op.getOperand(2), // LHS
5544 Op.getOperand(3), // RHS
5545 DAG.getConstant(CompareOpc, MVT::i32)
5547 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
5548 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
5550 // Now that we have the comparison, emit a copy from the CR to a GPR.
5551 // This is flagged to the above dot comparison.
5552 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
5553 DAG.getRegister(PPC::CR6, MVT::i32),
5554 CompNode.getValue(1));
5556 // Unpack the result based on how the target uses it.
5557 unsigned BitNo; // Bit # of CR6.
5558 bool InvertBit; // Invert result?
5559 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
5560 default: // Can't happen, don't crash on invalid number though.
5561 case 0: // Return the value of the EQ bit of CR6.
5562 BitNo = 0; InvertBit = false;
5564 case 1: // Return the inverted value of the EQ bit of CR6.
5565 BitNo = 0; InvertBit = true;
5567 case 2: // Return the value of the LT bit of CR6.
5568 BitNo = 2; InvertBit = false;
5570 case 3: // Return the inverted value of the LT bit of CR6.
5571 BitNo = 2; InvertBit = true;
5575 // Shift the bit into the low position.
5576 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
5577 DAG.getConstant(8-(3-BitNo), MVT::i32));
5579 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
5580 DAG.getConstant(1, MVT::i32));
5582 // If we are supposed to, toggle the bit.
5584 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
5585 DAG.getConstant(1, MVT::i32));
5589 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
5590 SelectionDAG &DAG) const {
5592 // Create a stack slot that is 16-byte aligned.
5593 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
5594 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
5595 EVT PtrVT = getPointerTy();
5596 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5598 // Store the input value into Value#0 of the stack slot.
5599 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
5600 Op.getOperand(0), FIdx, MachinePointerInfo(),
5603 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
5604 false, false, false, 0);
5607 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
5609 if (Op.getValueType() == MVT::v4i32) {
5610 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5612 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
5613 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
5615 SDValue RHSSwap = // = vrlw RHS, 16
5616 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
5618 // Shrinkify inputs to v8i16.
5619 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
5620 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
5621 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
5623 // Low parts multiplied together, generating 32-bit results (we ignore the
5625 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
5626 LHS, RHS, DAG, dl, MVT::v4i32);
5628 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
5629 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
5630 // Shift the high parts up 16 bits.
5631 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
5633 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
5634 } else if (Op.getValueType() == MVT::v8i16) {
5635 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5637 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
5639 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
5640 LHS, RHS, Zero, DAG, dl);
5641 } else if (Op.getValueType() == MVT::v16i8) {
5642 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5644 // Multiply the even 8-bit parts, producing 16-bit sums.
5645 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
5646 LHS, RHS, DAG, dl, MVT::v8i16);
5647 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
5649 // Multiply the odd 8-bit parts, producing 16-bit sums.
5650 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
5651 LHS, RHS, DAG, dl, MVT::v8i16);
5652 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
5654 // Merge the results together.
5656 for (unsigned i = 0; i != 8; ++i) {
5658 Ops[i*2+1] = 2*i+1+16;
5660 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
5662 llvm_unreachable("Unknown mul to lower!");
5666 /// LowerOperation - Provide custom lowering hooks for some operations.
5668 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
5669 switch (Op.getOpcode()) {
5670 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
5671 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5672 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
5673 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5674 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5675 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5676 case ISD::SETCC: return LowerSETCC(Op, DAG);
5677 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
5678 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
5680 return LowerVASTART(Op, DAG, PPCSubTarget);
5683 return LowerVAARG(Op, DAG, PPCSubTarget);
5685 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, PPCSubTarget);
5686 case ISD::DYNAMIC_STACKALLOC:
5687 return LowerDYNAMIC_STACKALLOC(Op, DAG, PPCSubTarget);
5689 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
5690 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
5692 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
5693 case ISD::FP_TO_UINT:
5694 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
5696 case ISD::UINT_TO_FP:
5697 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
5698 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5700 // Lower 64-bit shifts.
5701 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
5702 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
5703 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
5705 // Vector-related lowering.
5706 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5707 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5708 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5709 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5710 case ISD::MUL: return LowerMUL(Op, DAG);
5712 // For counter-based loop handling.
5713 case ISD::INTRINSIC_W_CHAIN: return SDValue();
5715 // Frame & Return address.
5716 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5717 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5721 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
5722 SmallVectorImpl<SDValue>&Results,
5723 SelectionDAG &DAG) const {
5724 const TargetMachine &TM = getTargetMachine();
5726 switch (N->getOpcode()) {
5728 llvm_unreachable("Do not know how to custom type legalize this operation!");
5729 case ISD::INTRINSIC_W_CHAIN: {
5730 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
5731 Intrinsic::ppc_is_decremented_ctr_nonzero)
5734 assert(N->getValueType(0) == MVT::i1 &&
5735 "Unexpected result type for CTR decrement intrinsic");
5736 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
5737 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
5738 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
5741 Results.push_back(NewInt);
5742 Results.push_back(NewInt.getValue(1));
5746 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
5747 || TM.getSubtarget<PPCSubtarget>().isPPC64())
5750 EVT VT = N->getValueType(0);
5752 if (VT == MVT::i64) {
5753 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, PPCSubTarget);
5755 Results.push_back(NewNode);
5756 Results.push_back(NewNode.getValue(1));
5760 case ISD::FP_ROUND_INREG: {
5761 assert(N->getValueType(0) == MVT::ppcf128);
5762 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
5763 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5764 MVT::f64, N->getOperand(0),
5765 DAG.getIntPtrConstant(0));
5766 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
5767 MVT::f64, N->getOperand(0),
5768 DAG.getIntPtrConstant(1));
5770 // Add the two halves of the long double in round-to-zero mode.
5771 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
5773 // We know the low half is about to be thrown away, so just use something
5775 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
5779 case ISD::FP_TO_SINT:
5780 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
5786 //===----------------------------------------------------------------------===//
5787 // Other Lowering Code
5788 //===----------------------------------------------------------------------===//
5791 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
5792 bool is64bit, unsigned BinOpcode) const {
5793 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5794 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5796 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5797 MachineFunction *F = BB->getParent();
5798 MachineFunction::iterator It = BB;
5801 unsigned dest = MI->getOperand(0).getReg();
5802 unsigned ptrA = MI->getOperand(1).getReg();
5803 unsigned ptrB = MI->getOperand(2).getReg();
5804 unsigned incr = MI->getOperand(3).getReg();
5805 DebugLoc dl = MI->getDebugLoc();
5807 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5808 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5809 F->insert(It, loopMBB);
5810 F->insert(It, exitMBB);
5811 exitMBB->splice(exitMBB->begin(), BB,
5812 llvm::next(MachineBasicBlock::iterator(MI)),
5814 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5816 MachineRegisterInfo &RegInfo = F->getRegInfo();
5817 unsigned TmpReg = (!BinOpcode) ? incr :
5818 RegInfo.createVirtualRegister(
5819 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5820 (const TargetRegisterClass *) &PPC::GPRCRegClass);
5824 // fallthrough --> loopMBB
5825 BB->addSuccessor(loopMBB);
5828 // l[wd]arx dest, ptr
5829 // add r0, dest, incr
5830 // st[wd]cx. r0, ptr
5832 // fallthrough --> exitMBB
5834 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
5835 .addReg(ptrA).addReg(ptrB);
5837 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
5838 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
5839 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
5840 BuildMI(BB, dl, TII->get(PPC::BCC))
5841 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5842 BB->addSuccessor(loopMBB);
5843 BB->addSuccessor(exitMBB);
5852 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
5853 MachineBasicBlock *BB,
5854 bool is8bit, // operation
5855 unsigned BinOpcode) const {
5856 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
5857 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5858 // In 64 bit mode we have to use 64 bits for addresses, even though the
5859 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
5860 // registers without caring whether they're 32 or 64, but here we're
5861 // doing actual arithmetic on the addresses.
5862 bool is64bit = PPCSubTarget.isPPC64();
5863 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
5865 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5866 MachineFunction *F = BB->getParent();
5867 MachineFunction::iterator It = BB;
5870 unsigned dest = MI->getOperand(0).getReg();
5871 unsigned ptrA = MI->getOperand(1).getReg();
5872 unsigned ptrB = MI->getOperand(2).getReg();
5873 unsigned incr = MI->getOperand(3).getReg();
5874 DebugLoc dl = MI->getDebugLoc();
5876 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
5877 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
5878 F->insert(It, loopMBB);
5879 F->insert(It, exitMBB);
5880 exitMBB->splice(exitMBB->begin(), BB,
5881 llvm::next(MachineBasicBlock::iterator(MI)),
5883 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
5885 MachineRegisterInfo &RegInfo = F->getRegInfo();
5886 const TargetRegisterClass *RC =
5887 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
5888 (const TargetRegisterClass *) &PPC::GPRCRegClass;
5889 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
5890 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
5891 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
5892 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
5893 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
5894 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
5895 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
5896 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
5897 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
5898 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
5899 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
5901 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
5905 // fallthrough --> loopMBB
5906 BB->addSuccessor(loopMBB);
5908 // The 4-byte load must be aligned, while a char or short may be
5909 // anywhere in the word. Hence all this nasty bookkeeping code.
5910 // add ptr1, ptrA, ptrB [copy if ptrA==0]
5911 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
5912 // xori shift, shift1, 24 [16]
5913 // rlwinm ptr, ptr1, 0, 0, 29
5914 // slw incr2, incr, shift
5915 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
5916 // slw mask, mask2, shift
5918 // lwarx tmpDest, ptr
5919 // add tmp, tmpDest, incr2
5920 // andc tmp2, tmpDest, mask
5921 // and tmp3, tmp, mask
5922 // or tmp4, tmp3, tmp2
5925 // fallthrough --> exitMBB
5926 // srw dest, tmpDest, shift
5927 if (ptrA != ZeroReg) {
5928 Ptr1Reg = RegInfo.createVirtualRegister(RC);
5929 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
5930 .addReg(ptrA).addReg(ptrB);
5934 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
5935 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
5936 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
5937 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
5939 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
5940 .addReg(Ptr1Reg).addImm(0).addImm(61);
5942 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
5943 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
5944 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
5945 .addReg(incr).addReg(ShiftReg);
5947 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
5949 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
5950 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
5952 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
5953 .addReg(Mask2Reg).addReg(ShiftReg);
5956 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
5957 .addReg(ZeroReg).addReg(PtrReg);
5959 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
5960 .addReg(Incr2Reg).addReg(TmpDestReg);
5961 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
5962 .addReg(TmpDestReg).addReg(MaskReg);
5963 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
5964 .addReg(TmpReg).addReg(MaskReg);
5965 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
5966 .addReg(Tmp3Reg).addReg(Tmp2Reg);
5967 BuildMI(BB, dl, TII->get(PPC::STWCX))
5968 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
5969 BuildMI(BB, dl, TII->get(PPC::BCC))
5970 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
5971 BB->addSuccessor(loopMBB);
5972 BB->addSuccessor(exitMBB);
5977 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
5982 llvm::MachineBasicBlock*
5983 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
5984 MachineBasicBlock *MBB) const {
5985 DebugLoc DL = MI->getDebugLoc();
5986 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5988 MachineFunction *MF = MBB->getParent();
5989 MachineRegisterInfo &MRI = MF->getRegInfo();
5991 const BasicBlock *BB = MBB->getBasicBlock();
5992 MachineFunction::iterator I = MBB;
5996 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
5997 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
5999 unsigned DstReg = MI->getOperand(0).getReg();
6000 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
6001 assert(RC->hasType(MVT::i32) && "Invalid destination!");
6002 unsigned mainDstReg = MRI.createVirtualRegister(RC);
6003 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
6005 MVT PVT = getPointerTy();
6006 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6007 "Invalid Pointer Size!");
6008 // For v = setjmp(buf), we generate
6011 // SjLjSetup mainMBB
6017 // buf[LabelOffset] = LR
6021 // v = phi(main, restore)
6024 MachineBasicBlock *thisMBB = MBB;
6025 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
6026 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
6027 MF->insert(I, mainMBB);
6028 MF->insert(I, sinkMBB);
6030 MachineInstrBuilder MIB;
6032 // Transfer the remainder of BB and its successor edges to sinkMBB.
6033 sinkMBB->splice(sinkMBB->begin(), MBB,
6034 llvm::next(MachineBasicBlock::iterator(MI)), MBB->end());
6035 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
6037 // Note that the structure of the jmp_buf used here is not compatible
6038 // with that used by libc, and is not designed to be. Specifically, it
6039 // stores only those 'reserved' registers that LLVM does not otherwise
6040 // understand how to spill. Also, by convention, by the time this
6041 // intrinsic is called, Clang has already stored the frame address in the
6042 // first slot of the buffer and stack address in the third. Following the
6043 // X86 target code, we'll store the jump address in the second slot. We also
6044 // need to save the TOC pointer (R2) to handle jumps between shared
6045 // libraries, and that will be stored in the fourth slot. The thread
6046 // identifier (R13) is not affected.
6049 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6050 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6052 // Prepare IP either in reg.
6053 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
6054 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
6055 unsigned BufReg = MI->getOperand(1).getReg();
6057 if (PPCSubTarget.isPPC64() && PPCSubTarget.isSVR4ABI()) {
6058 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
6063 MIB.setMemRefs(MMOBegin, MMOEnd);
6067 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
6068 const PPCRegisterInfo *TRI =
6069 static_cast<const PPCRegisterInfo*>(getTargetMachine().getRegisterInfo());
6070 MIB.addRegMask(TRI->getNoPreservedMask());
6072 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
6074 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
6076 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
6078 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
6079 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
6083 MIB = BuildMI(mainMBB, DL,
6084 TII->get(PPCSubTarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
6087 if (PPCSubTarget.isPPC64()) {
6088 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
6090 .addImm(LabelOffset)
6093 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
6095 .addImm(LabelOffset)
6099 MIB.setMemRefs(MMOBegin, MMOEnd);
6101 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
6102 mainMBB->addSuccessor(sinkMBB);
6105 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
6106 TII->get(PPC::PHI), DstReg)
6107 .addReg(mainDstReg).addMBB(mainMBB)
6108 .addReg(restoreDstReg).addMBB(thisMBB);
6110 MI->eraseFromParent();
6115 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
6116 MachineBasicBlock *MBB) const {
6117 DebugLoc DL = MI->getDebugLoc();
6118 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6120 MachineFunction *MF = MBB->getParent();
6121 MachineRegisterInfo &MRI = MF->getRegInfo();
6124 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
6125 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
6127 MVT PVT = getPointerTy();
6128 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
6129 "Invalid Pointer Size!");
6131 const TargetRegisterClass *RC =
6132 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
6133 unsigned Tmp = MRI.createVirtualRegister(RC);
6134 // Since FP is only updated here but NOT referenced, it's treated as GPR.
6135 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
6136 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
6138 MachineInstrBuilder MIB;
6140 const int64_t LabelOffset = 1 * PVT.getStoreSize();
6141 const int64_t SPOffset = 2 * PVT.getStoreSize();
6142 const int64_t TOCOffset = 3 * PVT.getStoreSize();
6144 unsigned BufReg = MI->getOperand(0).getReg();
6146 // Reload FP (the jumped-to function may not have had a
6147 // frame pointer, and if so, then its r31 will be restored
6149 if (PVT == MVT::i64) {
6150 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
6154 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
6158 MIB.setMemRefs(MMOBegin, MMOEnd);
6161 if (PVT == MVT::i64) {
6162 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
6163 .addImm(LabelOffset)
6166 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
6167 .addImm(LabelOffset)
6170 MIB.setMemRefs(MMOBegin, MMOEnd);
6173 if (PVT == MVT::i64) {
6174 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
6178 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
6182 MIB.setMemRefs(MMOBegin, MMOEnd);
6184 // FIXME: When we also support base pointers, that register must also be
6188 if (PVT == MVT::i64 && PPCSubTarget.isSVR4ABI()) {
6189 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
6193 MIB.setMemRefs(MMOBegin, MMOEnd);
6197 BuildMI(*MBB, MI, DL,
6198 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
6199 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
6201 MI->eraseFromParent();
6206 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6207 MachineBasicBlock *BB) const {
6208 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
6209 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
6210 return emitEHSjLjSetJmp(MI, BB);
6211 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
6212 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
6213 return emitEHSjLjLongJmp(MI, BB);
6216 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6218 // To "insert" these instructions we actually have to insert their
6219 // control-flow patterns.
6220 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6221 MachineFunction::iterator It = BB;
6224 MachineFunction *F = BB->getParent();
6226 if (PPCSubTarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6227 MI->getOpcode() == PPC::SELECT_CC_I8)) {
6228 SmallVector<MachineOperand, 2> Cond;
6229 Cond.push_back(MI->getOperand(4));
6230 Cond.push_back(MI->getOperand(1));
6232 DebugLoc dl = MI->getDebugLoc();
6233 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6234 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
6235 Cond, MI->getOperand(2).getReg(),
6236 MI->getOperand(3).getReg());
6237 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
6238 MI->getOpcode() == PPC::SELECT_CC_I8 ||
6239 MI->getOpcode() == PPC::SELECT_CC_F4 ||
6240 MI->getOpcode() == PPC::SELECT_CC_F8 ||
6241 MI->getOpcode() == PPC::SELECT_CC_VRRC) {
6244 // The incoming instruction knows the destination vreg to set, the
6245 // condition code register to branch on, the true/false values to
6246 // select between, and a branch opcode to use.
6251 // cmpTY ccX, r1, r2
6253 // fallthrough --> copy0MBB
6254 MachineBasicBlock *thisMBB = BB;
6255 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6256 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6257 unsigned SelectPred = MI->getOperand(4).getImm();
6258 DebugLoc dl = MI->getDebugLoc();
6259 F->insert(It, copy0MBB);
6260 F->insert(It, sinkMBB);
6262 // Transfer the remainder of BB and its successor edges to sinkMBB.
6263 sinkMBB->splice(sinkMBB->begin(), BB,
6264 llvm::next(MachineBasicBlock::iterator(MI)),
6266 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
6268 // Next, add the true and fallthrough blocks as its successors.
6269 BB->addSuccessor(copy0MBB);
6270 BB->addSuccessor(sinkMBB);
6272 BuildMI(BB, dl, TII->get(PPC::BCC))
6273 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
6276 // %FalseValue = ...
6277 // # fallthrough to sinkMBB
6280 // Update machine-CFG edges
6281 BB->addSuccessor(sinkMBB);
6284 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6287 BuildMI(*BB, BB->begin(), dl,
6288 TII->get(PPC::PHI), MI->getOperand(0).getReg())
6289 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
6290 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6292 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
6293 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
6294 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
6295 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
6296 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
6297 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
6298 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
6299 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
6301 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
6302 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
6303 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
6304 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
6305 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
6306 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
6307 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
6308 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
6310 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
6311 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
6312 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
6313 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
6314 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
6315 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
6316 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
6317 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
6319 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
6320 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
6321 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
6322 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
6323 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
6324 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
6325 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
6326 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
6328 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
6329 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ANDC);
6330 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
6331 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ANDC);
6332 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
6333 BB = EmitAtomicBinary(MI, BB, false, PPC::ANDC);
6334 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
6335 BB = EmitAtomicBinary(MI, BB, true, PPC::ANDC8);
6337 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
6338 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
6339 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
6340 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
6341 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
6342 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
6343 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
6344 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
6346 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
6347 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
6348 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
6349 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
6350 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
6351 BB = EmitAtomicBinary(MI, BB, false, 0);
6352 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
6353 BB = EmitAtomicBinary(MI, BB, true, 0);
6355 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
6356 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
6357 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
6359 unsigned dest = MI->getOperand(0).getReg();
6360 unsigned ptrA = MI->getOperand(1).getReg();
6361 unsigned ptrB = MI->getOperand(2).getReg();
6362 unsigned oldval = MI->getOperand(3).getReg();
6363 unsigned newval = MI->getOperand(4).getReg();
6364 DebugLoc dl = MI->getDebugLoc();
6366 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6367 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6368 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6369 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6370 F->insert(It, loop1MBB);
6371 F->insert(It, loop2MBB);
6372 F->insert(It, midMBB);
6373 F->insert(It, exitMBB);
6374 exitMBB->splice(exitMBB->begin(), BB,
6375 llvm::next(MachineBasicBlock::iterator(MI)),
6377 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6381 // fallthrough --> loopMBB
6382 BB->addSuccessor(loop1MBB);
6385 // l[wd]arx dest, ptr
6386 // cmp[wd] dest, oldval
6389 // st[wd]cx. newval, ptr
6393 // st[wd]cx. dest, ptr
6396 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6397 .addReg(ptrA).addReg(ptrB);
6398 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
6399 .addReg(oldval).addReg(dest);
6400 BuildMI(BB, dl, TII->get(PPC::BCC))
6401 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6402 BB->addSuccessor(loop2MBB);
6403 BB->addSuccessor(midMBB);
6406 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6407 .addReg(newval).addReg(ptrA).addReg(ptrB);
6408 BuildMI(BB, dl, TII->get(PPC::BCC))
6409 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6410 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6411 BB->addSuccessor(loop1MBB);
6412 BB->addSuccessor(exitMBB);
6415 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6416 .addReg(dest).addReg(ptrA).addReg(ptrB);
6417 BB->addSuccessor(exitMBB);
6422 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
6423 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
6424 // We must use 64-bit registers for addresses when targeting 64-bit,
6425 // since we're actually doing arithmetic on them. Other registers
6427 bool is64bit = PPCSubTarget.isPPC64();
6428 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
6430 unsigned dest = MI->getOperand(0).getReg();
6431 unsigned ptrA = MI->getOperand(1).getReg();
6432 unsigned ptrB = MI->getOperand(2).getReg();
6433 unsigned oldval = MI->getOperand(3).getReg();
6434 unsigned newval = MI->getOperand(4).getReg();
6435 DebugLoc dl = MI->getDebugLoc();
6437 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
6438 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
6439 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6440 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6441 F->insert(It, loop1MBB);
6442 F->insert(It, loop2MBB);
6443 F->insert(It, midMBB);
6444 F->insert(It, exitMBB);
6445 exitMBB->splice(exitMBB->begin(), BB,
6446 llvm::next(MachineBasicBlock::iterator(MI)),
6448 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6450 MachineRegisterInfo &RegInfo = F->getRegInfo();
6451 const TargetRegisterClass *RC =
6452 is64bit ? (const TargetRegisterClass *) &PPC::G8RCRegClass :
6453 (const TargetRegisterClass *) &PPC::GPRCRegClass;
6454 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6455 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6456 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6457 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
6458 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
6459 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
6460 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
6461 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6462 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6463 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6464 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6465 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6466 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6468 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
6469 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6472 // fallthrough --> loopMBB
6473 BB->addSuccessor(loop1MBB);
6475 // The 4-byte load must be aligned, while a char or short may be
6476 // anywhere in the word. Hence all this nasty bookkeeping code.
6477 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6478 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6479 // xori shift, shift1, 24 [16]
6480 // rlwinm ptr, ptr1, 0, 0, 29
6481 // slw newval2, newval, shift
6482 // slw oldval2, oldval,shift
6483 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6484 // slw mask, mask2, shift
6485 // and newval3, newval2, mask
6486 // and oldval3, oldval2, mask
6488 // lwarx tmpDest, ptr
6489 // and tmp, tmpDest, mask
6490 // cmpw tmp, oldval3
6493 // andc tmp2, tmpDest, mask
6494 // or tmp4, tmp2, newval3
6499 // stwcx. tmpDest, ptr
6501 // srw dest, tmpDest, shift
6502 if (ptrA != ZeroReg) {
6503 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6504 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6505 .addReg(ptrA).addReg(ptrB);
6509 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6510 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6511 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6512 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6514 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6515 .addReg(Ptr1Reg).addImm(0).addImm(61);
6517 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6518 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6519 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
6520 .addReg(newval).addReg(ShiftReg);
6521 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
6522 .addReg(oldval).addReg(ShiftReg);
6524 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6526 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6527 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
6528 .addReg(Mask3Reg).addImm(65535);
6530 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6531 .addReg(Mask2Reg).addReg(ShiftReg);
6532 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
6533 .addReg(NewVal2Reg).addReg(MaskReg);
6534 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
6535 .addReg(OldVal2Reg).addReg(MaskReg);
6538 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6539 .addReg(ZeroReg).addReg(PtrReg);
6540 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
6541 .addReg(TmpDestReg).addReg(MaskReg);
6542 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
6543 .addReg(TmpReg).addReg(OldVal3Reg);
6544 BuildMI(BB, dl, TII->get(PPC::BCC))
6545 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
6546 BB->addSuccessor(loop2MBB);
6547 BB->addSuccessor(midMBB);
6550 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
6551 .addReg(TmpDestReg).addReg(MaskReg);
6552 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
6553 .addReg(Tmp2Reg).addReg(NewVal3Reg);
6554 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
6555 .addReg(ZeroReg).addReg(PtrReg);
6556 BuildMI(BB, dl, TII->get(PPC::BCC))
6557 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
6558 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6559 BB->addSuccessor(loop1MBB);
6560 BB->addSuccessor(exitMBB);
6563 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
6564 .addReg(ZeroReg).addReg(PtrReg);
6565 BB->addSuccessor(exitMBB);
6570 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
6572 } else if (MI->getOpcode() == PPC::FADDrtz) {
6573 // This pseudo performs an FADD with rounding mode temporarily forced
6574 // to round-to-zero. We emit this via custom inserter since the FPSCR
6575 // is not modeled at the SelectionDAG level.
6576 unsigned Dest = MI->getOperand(0).getReg();
6577 unsigned Src1 = MI->getOperand(1).getReg();
6578 unsigned Src2 = MI->getOperand(2).getReg();
6579 DebugLoc dl = MI->getDebugLoc();
6581 MachineRegisterInfo &RegInfo = F->getRegInfo();
6582 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
6584 // Save FPSCR value.
6585 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
6587 // Set rounding mode to round-to-zero.
6588 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
6589 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
6591 // Perform addition.
6592 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
6594 // Restore FPSCR value.
6595 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
6596 } else if (MI->getOpcode() == PPC::FRINDrint ||
6597 MI->getOpcode() == PPC::FRINSrint) {
6598 bool isf32 = MI->getOpcode() == PPC::FRINSrint;
6599 unsigned Dest = MI->getOperand(0).getReg();
6600 unsigned Src = MI->getOperand(1).getReg();
6601 DebugLoc dl = MI->getDebugLoc();
6603 MachineRegisterInfo &RegInfo = F->getRegInfo();
6604 unsigned CRReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
6606 // Perform the rounding.
6607 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FRINS : PPC::FRIND), Dest)
6610 // Compare the results.
6611 BuildMI(*BB, MI, dl, TII->get(isf32 ? PPC::FCMPUS : PPC::FCMPUD), CRReg)
6612 .addReg(Dest).addReg(Src);
6614 // If the results were not equal, then set the FPSCR XX bit.
6615 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
6616 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6617 F->insert(It, midMBB);
6618 F->insert(It, exitMBB);
6619 exitMBB->splice(exitMBB->begin(), BB,
6620 llvm::next(MachineBasicBlock::iterator(MI)),
6622 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6624 BuildMI(*BB, MI, dl, TII->get(PPC::BCC))
6625 .addImm(PPC::PRED_EQ).addReg(CRReg).addMBB(exitMBB);
6627 BB->addSuccessor(midMBB);
6628 BB->addSuccessor(exitMBB);
6632 // Set the FPSCR XX bit (FE_INEXACT). Note that we cannot just set
6633 // the FI bit here because that will not automatically set XX also,
6634 // and XX is what libm interprets as the FE_INEXACT flag.
6635 BuildMI(BB, dl, TII->get(PPC::MTFSB1)).addImm(/* 38 - 32 = */ 6);
6636 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
6638 BB->addSuccessor(exitMBB);
6642 llvm_unreachable("Unexpected instr type to insert");
6645 MI->eraseFromParent(); // The pseudo instruction is gone now.
6649 //===----------------------------------------------------------------------===//
6650 // Target Optimization Hooks
6651 //===----------------------------------------------------------------------===//
6653 SDValue PPCTargetLowering::DAGCombineFastRecip(SDValue Op,
6654 DAGCombinerInfo &DCI) const {
6655 if (DCI.isAfterLegalizeVectorOps())
6658 EVT VT = Op.getValueType();
6660 if ((VT == MVT::f32 && PPCSubTarget.hasFRES()) ||
6661 (VT == MVT::f64 && PPCSubTarget.hasFRE()) ||
6662 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6664 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6665 // For the reciprocal, we need to find the zero of the function:
6666 // F(X) = A X - 1 [which has a zero at X = 1/A]
6668 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
6669 // does not require additional intermediate precision]
6671 // Convergence is quadratic, so we essentially double the number of digits
6672 // correct after every iteration. The minimum architected relative
6673 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6674 // 23 digits and double has 52 digits.
6675 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6676 if (VT.getScalarType() == MVT::f64)
6679 SelectionDAG &DAG = DCI.DAG;
6683 DAG.getConstantFP(1.0, VT.getScalarType());
6684 if (VT.isVector()) {
6685 assert(VT.getVectorNumElements() == 4 &&
6686 "Unknown vector type");
6687 FPOne = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6688 FPOne, FPOne, FPOne, FPOne);
6691 SDValue Est = DAG.getNode(PPCISD::FRE, dl, VT, Op);
6692 DCI.AddToWorklist(Est.getNode());
6694 // Newton iterations: Est = Est + Est (1 - Arg * Est)
6695 for (int i = 0; i < Iterations; ++i) {
6696 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Op, Est);
6697 DCI.AddToWorklist(NewEst.getNode());
6699 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPOne, NewEst);
6700 DCI.AddToWorklist(NewEst.getNode());
6702 NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6703 DCI.AddToWorklist(NewEst.getNode());
6705 Est = DAG.getNode(ISD::FADD, dl, VT, Est, NewEst);
6706 DCI.AddToWorklist(Est.getNode());
6715 SDValue PPCTargetLowering::DAGCombineFastRecipFSQRT(SDValue Op,
6716 DAGCombinerInfo &DCI) const {
6717 if (DCI.isAfterLegalizeVectorOps())
6720 EVT VT = Op.getValueType();
6722 if ((VT == MVT::f32 && PPCSubTarget.hasFRSQRTES()) ||
6723 (VT == MVT::f64 && PPCSubTarget.hasFRSQRTE()) ||
6724 (VT == MVT::v4f32 && PPCSubTarget.hasAltivec())) {
6726 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
6727 // For the reciprocal sqrt, we need to find the zero of the function:
6728 // F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
6730 // X_{i+1} = X_i (1.5 - A X_i^2 / 2)
6731 // As a result, we precompute A/2 prior to the iteration loop.
6733 // Convergence is quadratic, so we essentially double the number of digits
6734 // correct after every iteration. The minimum architected relative
6735 // accuracy is 2^-5. When hasRecipPrec(), this is 2^-14. IEEE float has
6736 // 23 digits and double has 52 digits.
6737 int Iterations = PPCSubTarget.hasRecipPrec() ? 1 : 3;
6738 if (VT.getScalarType() == MVT::f64)
6741 SelectionDAG &DAG = DCI.DAG;
6744 SDValue FPThreeHalves =
6745 DAG.getConstantFP(1.5, VT.getScalarType());
6746 if (VT.isVector()) {
6747 assert(VT.getVectorNumElements() == 4 &&
6748 "Unknown vector type");
6749 FPThreeHalves = DAG.getNode(ISD::BUILD_VECTOR, dl, VT,
6750 FPThreeHalves, FPThreeHalves,
6751 FPThreeHalves, FPThreeHalves);
6754 SDValue Est = DAG.getNode(PPCISD::FRSQRTE, dl, VT, Op);
6755 DCI.AddToWorklist(Est.getNode());
6757 // We now need 0.5*Arg which we can write as (1.5*Arg - Arg) so that
6758 // this entire sequence requires only one FP constant.
6759 SDValue HalfArg = DAG.getNode(ISD::FMUL, dl, VT, FPThreeHalves, Op);
6760 DCI.AddToWorklist(HalfArg.getNode());
6762 HalfArg = DAG.getNode(ISD::FSUB, dl, VT, HalfArg, Op);
6763 DCI.AddToWorklist(HalfArg.getNode());
6765 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
6766 for (int i = 0; i < Iterations; ++i) {
6767 SDValue NewEst = DAG.getNode(ISD::FMUL, dl, VT, Est, Est);
6768 DCI.AddToWorklist(NewEst.getNode());
6770 NewEst = DAG.getNode(ISD::FMUL, dl, VT, HalfArg, NewEst);
6771 DCI.AddToWorklist(NewEst.getNode());
6773 NewEst = DAG.getNode(ISD::FSUB, dl, VT, FPThreeHalves, NewEst);
6774 DCI.AddToWorklist(NewEst.getNode());
6776 Est = DAG.getNode(ISD::FMUL, dl, VT, Est, NewEst);
6777 DCI.AddToWorklist(Est.getNode());
6786 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
6787 // not enforce equality of the chain operands.
6788 static bool isConsecutiveLS(LSBaseSDNode *LS, LSBaseSDNode *Base,
6789 unsigned Bytes, int Dist,
6790 SelectionDAG &DAG) {
6791 EVT VT = LS->getMemoryVT();
6792 if (VT.getSizeInBits() / 8 != Bytes)
6795 SDValue Loc = LS->getBasePtr();
6796 SDValue BaseLoc = Base->getBasePtr();
6797 if (Loc.getOpcode() == ISD::FrameIndex) {
6798 if (BaseLoc.getOpcode() != ISD::FrameIndex)
6800 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6801 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
6802 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6803 int FS = MFI->getObjectSize(FI);
6804 int BFS = MFI->getObjectSize(BFI);
6805 if (FS != BFS || FS != (int)Bytes) return false;
6806 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6810 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
6811 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
6814 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6815 const GlobalValue *GV1 = NULL;
6816 const GlobalValue *GV2 = NULL;
6817 int64_t Offset1 = 0;
6818 int64_t Offset2 = 0;
6819 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6820 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6821 if (isGA1 && isGA2 && GV1 == GV2)
6822 return Offset1 == (Offset2 + Dist*Bytes);
6826 // Return true is there is a nearyby consecutive load to the one provided
6827 // (regardless of alignment). We search up and down the chain, looking though
6828 // token factors and other loads (but nothing else). As a result, a true
6829 // results indicates that it is safe to create a new consecutive load adjacent
6830 // to the load provided.
6831 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
6832 SDValue Chain = LD->getChain();
6833 EVT VT = LD->getMemoryVT();
6835 SmallSet<SDNode *, 16> LoadRoots;
6836 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
6837 SmallSet<SDNode *, 16> Visited;
6839 // First, search up the chain, branching to follow all token-factor operands.
6840 // If we find a consecutive load, then we're done, otherwise, record all
6841 // nodes just above the top-level loads and token factors.
6842 while (!Queue.empty()) {
6843 SDNode *ChainNext = Queue.pop_back_val();
6844 if (!Visited.insert(ChainNext))
6847 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(ChainNext)) {
6848 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
6851 if (!Visited.count(ChainLD->getChain().getNode()))
6852 Queue.push_back(ChainLD->getChain().getNode());
6853 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
6854 for (SDNode::op_iterator O = ChainNext->op_begin(),
6855 OE = ChainNext->op_end(); O != OE; ++O)
6856 if (!Visited.count(O->getNode()))
6857 Queue.push_back(O->getNode());
6859 LoadRoots.insert(ChainNext);
6862 // Second, search down the chain, starting from the top-level nodes recorded
6863 // in the first phase. These top-level nodes are the nodes just above all
6864 // loads and token factors. Starting with their uses, recursively look though
6865 // all loads (just the chain uses) and token factors to find a consecutive
6870 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
6871 IE = LoadRoots.end(); I != IE; ++I) {
6872 Queue.push_back(*I);
6874 while (!Queue.empty()) {
6875 SDNode *LoadRoot = Queue.pop_back_val();
6876 if (!Visited.insert(LoadRoot))
6879 if (LoadSDNode *ChainLD = dyn_cast<LoadSDNode>(LoadRoot))
6880 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
6883 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
6884 UE = LoadRoot->use_end(); UI != UE; ++UI)
6885 if (((isa<LoadSDNode>(*UI) &&
6886 cast<LoadSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
6887 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
6888 Queue.push_back(*UI);
6895 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
6896 DAGCombinerInfo &DCI) const {
6897 const TargetMachine &TM = getTargetMachine();
6898 SelectionDAG &DAG = DCI.DAG;
6900 switch (N->getOpcode()) {
6903 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6904 if (C->isNullValue()) // 0 << V -> 0.
6905 return N->getOperand(0);
6909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6910 if (C->isNullValue()) // 0 >>u V -> 0.
6911 return N->getOperand(0);
6915 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
6916 if (C->isNullValue() || // 0 >>s V -> 0.
6917 C->isAllOnesValue()) // -1 >>s V -> -1.
6918 return N->getOperand(0);
6922 assert(TM.Options.UnsafeFPMath &&
6923 "Reciprocal estimates require UnsafeFPMath");
6925 if (N->getOperand(1).getOpcode() == ISD::FSQRT) {
6927 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0), DCI);
6928 if (RV.getNode() != 0) {
6929 DCI.AddToWorklist(RV.getNode());
6930 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6931 N->getOperand(0), RV);
6933 } else if (N->getOperand(1).getOpcode() == ISD::FP_EXTEND &&
6934 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6936 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6938 if (RV.getNode() != 0) {
6939 DCI.AddToWorklist(RV.getNode());
6940 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N->getOperand(1)),
6941 N->getValueType(0), RV);
6942 DCI.AddToWorklist(RV.getNode());
6943 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6944 N->getOperand(0), RV);
6946 } else if (N->getOperand(1).getOpcode() == ISD::FP_ROUND &&
6947 N->getOperand(1).getOperand(0).getOpcode() == ISD::FSQRT) {
6949 DAGCombineFastRecipFSQRT(N->getOperand(1).getOperand(0).getOperand(0),
6951 if (RV.getNode() != 0) {
6952 DCI.AddToWorklist(RV.getNode());
6953 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N->getOperand(1)),
6954 N->getValueType(0), RV,
6955 N->getOperand(1).getOperand(1));
6956 DCI.AddToWorklist(RV.getNode());
6957 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6958 N->getOperand(0), RV);
6962 SDValue RV = DAGCombineFastRecip(N->getOperand(1), DCI);
6963 if (RV.getNode() != 0) {
6964 DCI.AddToWorklist(RV.getNode());
6965 return DAG.getNode(ISD::FMUL, dl, N->getValueType(0),
6966 N->getOperand(0), RV);
6972 assert(TM.Options.UnsafeFPMath &&
6973 "Reciprocal estimates require UnsafeFPMath");
6975 // Compute this as 1/(1/sqrt(X)), which is the reciprocal of the
6977 SDValue RV = DAGCombineFastRecipFSQRT(N->getOperand(0), DCI);
6978 if (RV.getNode() != 0) {
6979 DCI.AddToWorklist(RV.getNode());
6980 RV = DAGCombineFastRecip(RV, DCI);
6981 if (RV.getNode() != 0)
6987 case ISD::SINT_TO_FP:
6988 if (TM.getSubtarget<PPCSubtarget>().has64BitSupport()) {
6989 if (N->getOperand(0).getOpcode() == ISD::FP_TO_SINT) {
6990 // Turn (sint_to_fp (fp_to_sint X)) -> fctidz/fcfid without load/stores.
6991 // We allow the src/dst to be either f32/f64, but the intermediate
6992 // type must be i64.
6993 if (N->getOperand(0).getValueType() == MVT::i64 &&
6994 N->getOperand(0).getOperand(0).getValueType() != MVT::ppcf128) {
6995 SDValue Val = N->getOperand(0).getOperand(0);
6996 if (Val.getValueType() == MVT::f32) {
6997 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
6998 DCI.AddToWorklist(Val.getNode());
7001 Val = DAG.getNode(PPCISD::FCTIDZ, dl, MVT::f64, Val);
7002 DCI.AddToWorklist(Val.getNode());
7003 Val = DAG.getNode(PPCISD::FCFID, dl, MVT::f64, Val);
7004 DCI.AddToWorklist(Val.getNode());
7005 if (N->getValueType(0) == MVT::f32) {
7006 Val = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Val,
7007 DAG.getIntPtrConstant(0));
7008 DCI.AddToWorklist(Val.getNode());
7011 } else if (N->getOperand(0).getValueType() == MVT::i32) {
7012 // If the intermediate type is i32, we can avoid the load/store here
7019 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
7020 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
7021 !cast<StoreSDNode>(N)->isTruncatingStore() &&
7022 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
7023 N->getOperand(1).getValueType() == MVT::i32 &&
7024 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
7025 SDValue Val = N->getOperand(1).getOperand(0);
7026 if (Val.getValueType() == MVT::f32) {
7027 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
7028 DCI.AddToWorklist(Val.getNode());
7030 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
7031 DCI.AddToWorklist(Val.getNode());
7034 N->getOperand(0), Val, N->getOperand(2),
7035 DAG.getValueType(N->getOperand(1).getValueType())
7038 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
7039 DAG.getVTList(MVT::Other), Ops, array_lengthof(Ops),
7040 cast<StoreSDNode>(N)->getMemoryVT(),
7041 cast<StoreSDNode>(N)->getMemOperand());
7042 DCI.AddToWorklist(Val.getNode());
7046 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
7047 if (cast<StoreSDNode>(N)->isUnindexed() &&
7048 N->getOperand(1).getOpcode() == ISD::BSWAP &&
7049 N->getOperand(1).getNode()->hasOneUse() &&
7050 (N->getOperand(1).getValueType() == MVT::i32 ||
7051 N->getOperand(1).getValueType() == MVT::i16 ||
7052 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7053 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7054 N->getOperand(1).getValueType() == MVT::i64))) {
7055 SDValue BSwapOp = N->getOperand(1).getOperand(0);
7056 // Do an any-extend to 32-bits if this is a half-word input.
7057 if (BSwapOp.getValueType() == MVT::i16)
7058 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
7061 N->getOperand(0), BSwapOp, N->getOperand(2),
7062 DAG.getValueType(N->getOperand(1).getValueType())
7065 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
7066 Ops, array_lengthof(Ops),
7067 cast<StoreSDNode>(N)->getMemoryVT(),
7068 cast<StoreSDNode>(N)->getMemOperand());
7072 LoadSDNode *LD = cast<LoadSDNode>(N);
7073 EVT VT = LD->getValueType(0);
7074 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
7075 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
7076 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
7077 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
7078 DCI.getDAGCombineLevel() == AfterLegalizeTypes &&
7079 LD->getAlignment() < ABIAlignment) {
7080 // This is a type-legal unaligned Altivec load.
7081 SDValue Chain = LD->getChain();
7082 SDValue Ptr = LD->getBasePtr();
7084 // This implements the loading of unaligned vectors as described in
7085 // the venerable Apple Velocity Engine overview. Specifically:
7086 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
7087 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
7089 // The general idea is to expand a sequence of one or more unaligned
7090 // loads into a alignment-based permutation-control instruction (lvsl),
7091 // a series of regular vector loads (which always truncate their
7092 // input address to an aligned address), and a series of permutations.
7093 // The results of these permutations are the requested loaded values.
7094 // The trick is that the last "extra" load is not taken from the address
7095 // you might suspect (sizeof(vector) bytes after the last requested
7096 // load), but rather sizeof(vector) - 1 bytes after the last
7097 // requested vector. The point of this is to avoid a page fault if the
7098 // base address happend to be aligned. This works because if the base
7099 // address is aligned, then adding less than a full vector length will
7100 // cause the last vector in the sequence to be (re)loaded. Otherwise,
7101 // the next vector will be fetched as you might suspect was necessary.
7103 // We might be able to reuse the permutation generation from
7104 // a different base address offset from this one by an aligned amount.
7105 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
7106 // optimization later.
7107 SDValue PermCntl = BuildIntrinsicOp(Intrinsic::ppc_altivec_lvsl, Ptr,
7108 DAG, dl, MVT::v16i8);
7110 // Refine the alignment of the original load (a "new" load created here
7111 // which was identical to the first except for the alignment would be
7112 // merged with the existing node regardless).
7113 MachineFunction &MF = DAG.getMachineFunction();
7114 MachineMemOperand *MMO =
7115 MF.getMachineMemOperand(LD->getPointerInfo(),
7116 LD->getMemOperand()->getFlags(),
7117 LD->getMemoryVT().getStoreSize(),
7119 LD->refineAlignment(MMO);
7120 SDValue BaseLoad = SDValue(LD, 0);
7122 // Note that the value of IncOffset (which is provided to the next
7123 // load's pointer info offset value, and thus used to calculate the
7124 // alignment), and the value of IncValue (which is actually used to
7125 // increment the pointer value) are different! This is because we
7126 // require the next load to appear to be aligned, even though it
7127 // is actually offset from the base pointer by a lesser amount.
7128 int IncOffset = VT.getSizeInBits() / 8;
7129 int IncValue = IncOffset;
7131 // Walk (both up and down) the chain looking for another load at the real
7132 // (aligned) offset (the alignment of the other load does not matter in
7133 // this case). If found, then do not use the offset reduction trick, as
7134 // that will prevent the loads from being later combined (as they would
7135 // otherwise be duplicates).
7136 if (!findConsecutiveLoad(LD, DAG))
7139 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
7140 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
7143 DAG.getLoad(VT, dl, Chain, Ptr,
7144 LD->getPointerInfo().getWithOffset(IncOffset),
7145 LD->isVolatile(), LD->isNonTemporal(),
7146 LD->isInvariant(), ABIAlignment);
7148 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7149 BaseLoad.getValue(1), ExtraLoad.getValue(1));
7151 if (BaseLoad.getValueType() != MVT::v4i32)
7152 BaseLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, BaseLoad);
7154 if (ExtraLoad.getValueType() != MVT::v4i32)
7155 ExtraLoad = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, ExtraLoad);
7157 SDValue Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
7158 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
7160 if (VT != MVT::v4i32)
7161 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
7163 // Now we need to be really careful about how we update the users of the
7164 // original load. We cannot just call DCI.CombineTo (or
7165 // DAG.ReplaceAllUsesWith for that matter), because the load still has
7166 // uses created here (the permutation for example) that need to stay.
7167 SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
7169 SDUse &Use = UI.getUse();
7171 // Note: BaseLoad is checked here because it might not be N, but a
7173 if (User == Perm.getNode() || User == BaseLoad.getNode() ||
7174 User == TF.getNode() || Use.getResNo() > 1) {
7179 SDValue To = Use.getResNo() ? TF : Perm;
7182 SmallVector<SDValue, 8> Ops;
7183 for (SDNode::op_iterator O = User->op_begin(),
7184 OE = User->op_end(); O != OE; ++O) {
7191 DAG.UpdateNodeOperands(User, Ops.data(), Ops.size());
7194 return SDValue(N, 0);
7198 case ISD::INTRINSIC_WO_CHAIN:
7199 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() ==
7200 Intrinsic::ppc_altivec_lvsl &&
7201 N->getOperand(1)->getOpcode() == ISD::ADD) {
7202 SDValue Add = N->getOperand(1);
7204 if (DAG.MaskedValueIsZero(Add->getOperand(1),
7205 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
7206 Add.getValueType().getScalarType().getSizeInBits()))) {
7207 SDNode *BasePtr = Add->getOperand(0).getNode();
7208 for (SDNode::use_iterator UI = BasePtr->use_begin(),
7209 UE = BasePtr->use_end(); UI != UE; ++UI) {
7210 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7211 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
7212 Intrinsic::ppc_altivec_lvsl) {
7213 // We've found another LVSL, and this address if an aligned
7214 // multiple of that one. The results will be the same, so use the
7215 // one we've just found instead.
7217 return SDValue(*UI, 0);
7223 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
7224 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
7225 N->getOperand(0).hasOneUse() &&
7226 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
7227 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
7228 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
7229 N->getValueType(0) == MVT::i64))) {
7230 SDValue Load = N->getOperand(0);
7231 LoadSDNode *LD = cast<LoadSDNode>(Load);
7232 // Create the byte-swapping load.
7234 LD->getChain(), // Chain
7235 LD->getBasePtr(), // Ptr
7236 DAG.getValueType(N->getValueType(0)) // VT
7239 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
7240 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
7241 MVT::i64 : MVT::i32, MVT::Other),
7242 Ops, 3, LD->getMemoryVT(), LD->getMemOperand());
7244 // If this is an i16 load, insert the truncate.
7245 SDValue ResVal = BSLoad;
7246 if (N->getValueType(0) == MVT::i16)
7247 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
7249 // First, combine the bswap away. This makes the value produced by the
7251 DCI.CombineTo(N, ResVal);
7253 // Next, combine the load away, we give it a bogus result value but a real
7254 // chain result. The result value is dead because the bswap is dead.
7255 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
7257 // Return N so it doesn't get rechecked!
7258 return SDValue(N, 0);
7262 case PPCISD::VCMP: {
7263 // If a VCMPo node already exists with exactly the same operands as this
7264 // node, use its result instead of this node (VCMPo computes both a CR6 and
7265 // a normal output).
7267 if (!N->getOperand(0).hasOneUse() &&
7268 !N->getOperand(1).hasOneUse() &&
7269 !N->getOperand(2).hasOneUse()) {
7271 // Scan all of the users of the LHS, looking for VCMPo's that match.
7272 SDNode *VCMPoNode = 0;
7274 SDNode *LHSN = N->getOperand(0).getNode();
7275 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
7277 if (UI->getOpcode() == PPCISD::VCMPo &&
7278 UI->getOperand(1) == N->getOperand(1) &&
7279 UI->getOperand(2) == N->getOperand(2) &&
7280 UI->getOperand(0) == N->getOperand(0)) {
7285 // If there is no VCMPo node, or if the flag value has a single use, don't
7287 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
7290 // Look at the (necessarily single) use of the flag value. If it has a
7291 // chain, this transformation is more complex. Note that multiple things
7292 // could use the value result, which we should ignore.
7293 SDNode *FlagUser = 0;
7294 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
7295 FlagUser == 0; ++UI) {
7296 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
7298 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
7299 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
7306 // If the user is a MFOCRF instruction, we know this is safe.
7307 // Otherwise we give up for right now.
7308 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
7309 return SDValue(VCMPoNode, 0);
7314 // If this is a branch on an altivec predicate comparison, lower this so
7315 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
7316 // lowering is done pre-legalize, because the legalizer lowers the predicate
7317 // compare down to code that is difficult to reassemble.
7318 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
7319 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
7321 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
7322 // value. If so, pass-through the AND to get to the intrinsic.
7323 if (LHS.getOpcode() == ISD::AND &&
7324 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7325 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
7326 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7327 isa<ConstantSDNode>(LHS.getOperand(1)) &&
7328 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
7330 LHS = LHS.getOperand(0);
7332 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
7333 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
7334 Intrinsic::ppc_is_decremented_ctr_nonzero &&
7335 isa<ConstantSDNode>(RHS)) {
7336 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7337 "Counter decrement comparison is not EQ or NE");
7339 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7340 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
7341 (CC == ISD::SETNE && !Val);
7343 // We now need to make the intrinsic dead (it cannot be instruction
7345 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
7346 assert(LHS.getNode()->hasOneUse() &&
7347 "Counter decrement has more than one use");
7349 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
7350 N->getOperand(0), N->getOperand(4));
7356 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
7357 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
7358 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
7359 assert(isDot && "Can't compare against a vector result!");
7361 // If this is a comparison against something other than 0/1, then we know
7362 // that the condition is never/always true.
7363 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
7364 if (Val != 0 && Val != 1) {
7365 if (CC == ISD::SETEQ) // Cond never true, remove branch.
7366 return N->getOperand(0);
7367 // Always !=, turn it into an unconditional branch.
7368 return DAG.getNode(ISD::BR, dl, MVT::Other,
7369 N->getOperand(0), N->getOperand(4));
7372 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
7374 // Create the PPCISD altivec 'dot' comparison node.
7376 LHS.getOperand(2), // LHS of compare
7377 LHS.getOperand(3), // RHS of compare
7378 DAG.getConstant(CompareOpc, MVT::i32)
7380 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
7381 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops, 3);
7383 // Unpack the result based on how the target uses it.
7384 PPC::Predicate CompOpc;
7385 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
7386 default: // Can't happen, don't crash on invalid number though.
7387 case 0: // Branch on the value of the EQ bit of CR6.
7388 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
7390 case 1: // Branch on the inverted value of the EQ bit of CR6.
7391 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
7393 case 2: // Branch on the value of the LT bit of CR6.
7394 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
7396 case 3: // Branch on the inverted value of the LT bit of CR6.
7397 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
7401 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
7402 DAG.getConstant(CompOpc, MVT::i32),
7403 DAG.getRegister(PPC::CR6, MVT::i32),
7404 N->getOperand(4), CompNode.getValue(1));
7413 //===----------------------------------------------------------------------===//
7414 // Inline Assembly Support
7415 //===----------------------------------------------------------------------===//
7417 void PPCTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7420 const SelectionDAG &DAG,
7421 unsigned Depth) const {
7422 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
7423 switch (Op.getOpcode()) {
7425 case PPCISD::LBRX: {
7426 // lhbrx is known to have the top bits cleared out.
7427 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
7428 KnownZero = 0xFFFF0000;
7431 case ISD::INTRINSIC_WO_CHAIN: {
7432 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
7434 case Intrinsic::ppc_altivec_vcmpbfp_p:
7435 case Intrinsic::ppc_altivec_vcmpeqfp_p:
7436 case Intrinsic::ppc_altivec_vcmpequb_p:
7437 case Intrinsic::ppc_altivec_vcmpequh_p:
7438 case Intrinsic::ppc_altivec_vcmpequw_p:
7439 case Intrinsic::ppc_altivec_vcmpgefp_p:
7440 case Intrinsic::ppc_altivec_vcmpgtfp_p:
7441 case Intrinsic::ppc_altivec_vcmpgtsb_p:
7442 case Intrinsic::ppc_altivec_vcmpgtsh_p:
7443 case Intrinsic::ppc_altivec_vcmpgtsw_p:
7444 case Intrinsic::ppc_altivec_vcmpgtub_p:
7445 case Intrinsic::ppc_altivec_vcmpgtuh_p:
7446 case Intrinsic::ppc_altivec_vcmpgtuw_p:
7447 KnownZero = ~1U; // All bits but the low one are known to be zero.
7455 /// getConstraintType - Given a constraint, return the type of
7456 /// constraint it is for this target.
7457 PPCTargetLowering::ConstraintType
7458 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
7459 if (Constraint.size() == 1) {
7460 switch (Constraint[0]) {
7467 return C_RegisterClass;
7469 // FIXME: While Z does indicate a memory constraint, it specifically
7470 // indicates an r+r address (used in conjunction with the 'y' modifier
7471 // in the replacement string). Currently, we're forcing the base
7472 // register to be r0 in the asm printer (which is interpreted as zero)
7473 // and forming the complete address in the second register. This is
7478 return TargetLowering::getConstraintType(Constraint);
7481 /// Examine constraint type and operand type and determine a weight value.
7482 /// This object must already have been set up with the operand type
7483 /// and the current alternative constraint selected.
7484 TargetLowering::ConstraintWeight
7485 PPCTargetLowering::getSingleConstraintMatchWeight(
7486 AsmOperandInfo &info, const char *constraint) const {
7487 ConstraintWeight weight = CW_Invalid;
7488 Value *CallOperandVal = info.CallOperandVal;
7489 // If we don't have a value, we can't do a match,
7490 // but allow it at the lowest weight.
7491 if (CallOperandVal == NULL)
7493 Type *type = CallOperandVal->getType();
7494 // Look at the constraint type.
7495 switch (*constraint) {
7497 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
7500 if (type->isIntegerTy())
7501 weight = CW_Register;
7504 if (type->isFloatTy())
7505 weight = CW_Register;
7508 if (type->isDoubleTy())
7509 weight = CW_Register;
7512 if (type->isVectorTy())
7513 weight = CW_Register;
7516 weight = CW_Register;
7525 std::pair<unsigned, const TargetRegisterClass*>
7526 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7528 if (Constraint.size() == 1) {
7529 // GCC RS6000 Constraint Letters
7530 switch (Constraint[0]) {
7532 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7533 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
7534 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
7536 if (VT == MVT::i64 && PPCSubTarget.isPPC64())
7537 return std::make_pair(0U, &PPC::G8RCRegClass);
7538 return std::make_pair(0U, &PPC::GPRCRegClass);
7540 if (VT == MVT::f32 || VT == MVT::i32)
7541 return std::make_pair(0U, &PPC::F4RCRegClass);
7542 if (VT == MVT::f64 || VT == MVT::i64)
7543 return std::make_pair(0U, &PPC::F8RCRegClass);
7546 return std::make_pair(0U, &PPC::VRRCRegClass);
7548 return std::make_pair(0U, &PPC::CRRCRegClass);
7552 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7556 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7557 /// vector. If it is invalid, don't add anything to Ops.
7558 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7559 std::string &Constraint,
7560 std::vector<SDValue>&Ops,
7561 SelectionDAG &DAG) const {
7562 SDValue Result(0,0);
7564 // Only support length 1 constraints.
7565 if (Constraint.length() > 1) return;
7567 char Letter = Constraint[0];
7578 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
7579 if (!CST) return; // Must be an immediate to match.
7580 unsigned Value = CST->getZExtValue();
7582 default: llvm_unreachable("Unknown constraint letter!");
7583 case 'I': // "I" is a signed 16-bit constant.
7584 if ((short)Value == (int)Value)
7585 Result = DAG.getTargetConstant(Value, Op.getValueType());
7587 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
7588 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
7589 if ((short)Value == 0)
7590 Result = DAG.getTargetConstant(Value, Op.getValueType());
7592 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
7593 if ((Value >> 16) == 0)
7594 Result = DAG.getTargetConstant(Value, Op.getValueType());
7596 case 'M': // "M" is a constant that is greater than 31.
7598 Result = DAG.getTargetConstant(Value, Op.getValueType());
7600 case 'N': // "N" is a positive constant that is an exact power of two.
7601 if ((int)Value > 0 && isPowerOf2_32(Value))
7602 Result = DAG.getTargetConstant(Value, Op.getValueType());
7604 case 'O': // "O" is the constant zero.
7606 Result = DAG.getTargetConstant(Value, Op.getValueType());
7608 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
7609 if ((short)-Value == (int)-Value)
7610 Result = DAG.getTargetConstant(Value, Op.getValueType());
7617 if (Result.getNode()) {
7618 Ops.push_back(Result);
7622 // Handle standard constraint letters.
7623 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
7626 // isLegalAddressingMode - Return true if the addressing mode represented
7627 // by AM is legal for this target, for a load/store of the specified type.
7628 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
7630 // FIXME: PPC does not allow r+i addressing modes for vectors!
7632 // PPC allows a sign-extended 16-bit immediate field.
7633 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
7636 // No global is ever allowed as a base.
7640 // PPC only support r+r,
7642 case 0: // "r+i" or just "i", depending on HasBaseReg.
7645 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
7647 // Otherwise we have r+r or r+i.
7650 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
7652 // Allow 2*r as r+r.
7655 // No other scales are supported.
7662 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
7663 SelectionDAG &DAG) const {
7664 MachineFunction &MF = DAG.getMachineFunction();
7665 MachineFrameInfo *MFI = MF.getFrameInfo();
7666 MFI->setReturnAddressIsTaken(true);
7669 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7671 // Make sure the function does not optimize away the store of the RA to
7673 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
7674 FuncInfo->setLRStoreRequired();
7675 bool isPPC64 = PPCSubTarget.isPPC64();
7676 bool isDarwinABI = PPCSubTarget.isDarwinABI();
7679 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7682 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
7683 isPPC64? MVT::i64 : MVT::i32);
7684 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7685 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7687 MachinePointerInfo(), false, false, false, 0);
7690 // Just load the return address off the stack.
7691 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
7692 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7693 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
7696 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
7697 SelectionDAG &DAG) const {
7699 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7701 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
7702 bool isPPC64 = PtrVT == MVT::i64;
7704 MachineFunction &MF = DAG.getMachineFunction();
7705 MachineFrameInfo *MFI = MF.getFrameInfo();
7706 MFI->setFrameAddressIsTaken(true);
7708 // Naked functions never have a frame pointer, and so we use r1. For all
7709 // other functions, this decision must be delayed until during PEI.
7711 if (MF.getFunction()->getAttributes().hasAttribute(
7712 AttributeSet::FunctionIndex, Attribute::Naked))
7713 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
7715 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
7717 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
7720 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
7721 FrameAddr, MachinePointerInfo(), false, false,
7727 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
7728 // The PowerPC target isn't yet aware of offsets.
7732 /// getOptimalMemOpType - Returns the target specific optimal type for load
7733 /// and store operations as a result of memset, memcpy, and memmove
7734 /// lowering. If DstAlign is zero that means it's safe to destination
7735 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
7736 /// means there isn't a need to check it against alignment requirement,
7737 /// probably because the source does not need to be loaded. If 'IsMemset' is
7738 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
7739 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
7740 /// source is constant so it does not need to be loaded.
7741 /// It returns EVT::Other if the type should be determined using generic
7742 /// target-independent logic.
7743 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
7744 unsigned DstAlign, unsigned SrcAlign,
7745 bool IsMemset, bool ZeroMemset,
7747 MachineFunction &MF) const {
7748 if (this->PPCSubTarget.isPPC64()) {
7755 bool PPCTargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
7757 if (DisablePPCUnaligned)
7760 // PowerPC supports unaligned memory access for simple non-vector types.
7761 // Although accessing unaligned addresses is not as efficient as accessing
7762 // aligned addresses, it is generally more efficient than manual expansion,
7763 // and generally only traps for software emulation when crossing page
7769 if (VT.getSimpleVT().isVector())
7772 if (VT == MVT::ppcf128)
7781 /// isFMAFasterThanMulAndAdd - Return true if an FMA operation is faster than
7782 /// a pair of mul and add instructions. fmuladd intrinsics will be expanded to
7783 /// FMAs when this method returns true (and FMAs are legal), otherwise fmuladd
7784 /// is expanded to mul + add.
7785 bool PPCTargetLowering::isFMAFasterThanMulAndAdd(EVT VT) const {
7789 switch (VT.getSimpleVT().SimpleTy) {
7801 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
7803 return TargetLowering::getSchedulingPreference(N);