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 "PPCCallingConv.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCPerfectShuffle.h"
19 #include "PPCTargetMachine.h"
20 #include "PPCTargetObjectFile.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineLoopInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAG.h"
31 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/Constants.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetOptions.h"
44 // FIXME: Remove this once soft-float is supported.
45 static cl::opt<bool> DisablePPCFloatInVariadic("disable-ppc-float-in-variadic",
46 cl::desc("disable saving float registers for va_start on PPC"), cl::Hidden);
48 static cl::opt<bool> DisablePPCPreinc("disable-ppc-preinc",
49 cl::desc("disable preincrement load/store generation on PPC"), cl::Hidden);
51 static cl::opt<bool> DisableILPPref("disable-ppc-ilp-pref",
52 cl::desc("disable setting the node scheduling preference to ILP on PPC"), cl::Hidden);
54 static cl::opt<bool> DisablePPCUnaligned("disable-ppc-unaligned",
55 cl::desc("disable unaligned load/store generation on PPC"), cl::Hidden);
57 // FIXME: Remove this once the bug has been fixed!
58 extern cl::opt<bool> ANDIGlueBug;
60 PPCTargetLowering::PPCTargetLowering(const PPCTargetMachine &TM)
62 Subtarget(*TM.getSubtargetImpl()) {
63 // Use _setjmp/_longjmp instead of setjmp/longjmp.
64 setUseUnderscoreSetJmp(true);
65 setUseUnderscoreLongJmp(true);
67 // On PPC32/64, arguments smaller than 4/8 bytes are extended, so all
68 // arguments are at least 4/8 bytes aligned.
69 bool isPPC64 = Subtarget.isPPC64();
70 setMinStackArgumentAlignment(isPPC64 ? 8:4);
72 // Set up the register classes.
73 addRegisterClass(MVT::i32, &PPC::GPRCRegClass);
74 addRegisterClass(MVT::f32, &PPC::F4RCRegClass);
75 addRegisterClass(MVT::f64, &PPC::F8RCRegClass);
77 // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
78 for (MVT VT : MVT::integer_valuetypes()) {
79 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
80 setLoadExtAction(ISD::SEXTLOAD, VT, 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 if (Subtarget.useCRBits()) {
98 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
100 if (isPPC64 || Subtarget.hasFPCVT()) {
101 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Promote);
102 AddPromotedToType (ISD::SINT_TO_FP, MVT::i1,
103 isPPC64 ? MVT::i64 : MVT::i32);
104 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Promote);
105 AddPromotedToType (ISD::UINT_TO_FP, MVT::i1,
106 isPPC64 ? MVT::i64 : MVT::i32);
108 setOperationAction(ISD::SINT_TO_FP, MVT::i1, Custom);
109 setOperationAction(ISD::UINT_TO_FP, MVT::i1, Custom);
112 // PowerPC does not support direct load / store of condition registers
113 setOperationAction(ISD::LOAD, MVT::i1, Custom);
114 setOperationAction(ISD::STORE, MVT::i1, Custom);
116 // FIXME: Remove this once the ANDI glue bug is fixed:
118 setOperationAction(ISD::TRUNCATE, MVT::i1, Custom);
120 for (MVT VT : MVT::integer_valuetypes()) {
121 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
122 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
123 setTruncStoreAction(VT, MVT::i1, Expand);
126 addRegisterClass(MVT::i1, &PPC::CRBITRCRegClass);
129 // This is used in the ppcf128->int sequence. Note it has different semantics
130 // from FP_ROUND: that rounds to nearest, this rounds to zero.
131 setOperationAction(ISD::FP_ROUND_INREG, MVT::ppcf128, Custom);
133 // We do not currently implement these libm ops for PowerPC.
134 setOperationAction(ISD::FFLOOR, MVT::ppcf128, Expand);
135 setOperationAction(ISD::FCEIL, MVT::ppcf128, Expand);
136 setOperationAction(ISD::FTRUNC, MVT::ppcf128, Expand);
137 setOperationAction(ISD::FRINT, MVT::ppcf128, Expand);
138 setOperationAction(ISD::FNEARBYINT, MVT::ppcf128, Expand);
139 setOperationAction(ISD::FREM, MVT::ppcf128, Expand);
141 // PowerPC has no SREM/UREM instructions
142 setOperationAction(ISD::SREM, MVT::i32, Expand);
143 setOperationAction(ISD::UREM, MVT::i32, Expand);
144 setOperationAction(ISD::SREM, MVT::i64, Expand);
145 setOperationAction(ISD::UREM, MVT::i64, Expand);
147 // Don't use SMUL_LOHI/UMUL_LOHI or SDIVREM/UDIVREM to lower SREM/UREM.
148 setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
149 setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
150 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
151 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
152 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
153 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
154 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
155 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
157 // We don't support sin/cos/sqrt/fmod/pow
158 setOperationAction(ISD::FSIN , MVT::f64, Expand);
159 setOperationAction(ISD::FCOS , MVT::f64, Expand);
160 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
161 setOperationAction(ISD::FREM , MVT::f64, Expand);
162 setOperationAction(ISD::FPOW , MVT::f64, Expand);
163 setOperationAction(ISD::FMA , MVT::f64, Legal);
164 setOperationAction(ISD::FSIN , MVT::f32, Expand);
165 setOperationAction(ISD::FCOS , MVT::f32, Expand);
166 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
167 setOperationAction(ISD::FREM , MVT::f32, Expand);
168 setOperationAction(ISD::FPOW , MVT::f32, Expand);
169 setOperationAction(ISD::FMA , MVT::f32, Legal);
171 setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
173 // If we're enabling GP optimizations, use hardware square root
174 if (!Subtarget.hasFSQRT() &&
175 !(TM.Options.UnsafeFPMath &&
176 Subtarget.hasFRSQRTE() && Subtarget.hasFRE()))
177 setOperationAction(ISD::FSQRT, MVT::f64, Expand);
179 if (!Subtarget.hasFSQRT() &&
180 !(TM.Options.UnsafeFPMath &&
181 Subtarget.hasFRSQRTES() && Subtarget.hasFRES()))
182 setOperationAction(ISD::FSQRT, MVT::f32, Expand);
184 if (Subtarget.hasFCPSGN()) {
185 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Legal);
186 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Legal);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
189 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
192 if (Subtarget.hasFPRND()) {
193 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
194 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
195 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
196 setOperationAction(ISD::FROUND, MVT::f64, Legal);
198 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
199 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
200 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
201 setOperationAction(ISD::FROUND, MVT::f32, Legal);
204 // PowerPC does not have BSWAP, CTPOP or CTTZ
205 setOperationAction(ISD::BSWAP, MVT::i32 , Expand);
206 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
207 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
208 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
209 setOperationAction(ISD::BSWAP, MVT::i64 , Expand);
210 setOperationAction(ISD::CTTZ , MVT::i64 , Expand);
211 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
212 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
214 if (Subtarget.hasPOPCNTD()) {
215 setOperationAction(ISD::CTPOP, MVT::i32 , Legal);
216 setOperationAction(ISD::CTPOP, MVT::i64 , Legal);
218 setOperationAction(ISD::CTPOP, MVT::i32 , Expand);
219 setOperationAction(ISD::CTPOP, MVT::i64 , Expand);
222 // PowerPC does not have ROTR
223 setOperationAction(ISD::ROTR, MVT::i32 , Expand);
224 setOperationAction(ISD::ROTR, MVT::i64 , Expand);
226 if (!Subtarget.useCRBits()) {
227 // PowerPC does not have Select
228 setOperationAction(ISD::SELECT, MVT::i32, Expand);
229 setOperationAction(ISD::SELECT, MVT::i64, Expand);
230 setOperationAction(ISD::SELECT, MVT::f32, Expand);
231 setOperationAction(ISD::SELECT, MVT::f64, Expand);
234 // PowerPC wants to turn select_cc of FP into fsel when possible.
235 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
236 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
238 // PowerPC wants to optimize integer setcc a bit
239 if (!Subtarget.useCRBits())
240 setOperationAction(ISD::SETCC, MVT::i32, Custom);
242 // PowerPC does not have BRCOND which requires SetCC
243 if (!Subtarget.useCRBits())
244 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
246 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
248 // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
249 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 // PowerPC does not have [U|S]INT_TO_FP
252 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
253 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
255 setOperationAction(ISD::BITCAST, MVT::f32, Expand);
256 setOperationAction(ISD::BITCAST, MVT::i32, Expand);
257 setOperationAction(ISD::BITCAST, MVT::i64, Expand);
258 setOperationAction(ISD::BITCAST, MVT::f64, Expand);
260 // We cannot sextinreg(i1). Expand to shifts.
261 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
263 // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
264 // SjLj exception handling but a light-weight setjmp/longjmp replacement to
265 // support continuation, user-level threading, and etc.. As a result, no
266 // other SjLj exception interfaces are implemented and please don't build
267 // your own exception handling based on them.
268 // LLVM/Clang supports zero-cost DWARF exception handling.
269 setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
270 setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
272 // We want to legalize GlobalAddress and ConstantPool nodes into the
273 // appropriate instructions to materialize the address.
274 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
275 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
276 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
277 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
278 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
279 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
281 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
282 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
283 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
286 setOperationAction(ISD::TRAP, MVT::Other, Legal);
288 // TRAMPOLINE is custom lowered.
289 setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
290 setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
292 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
293 setOperationAction(ISD::VASTART , MVT::Other, Custom);
295 if (Subtarget.isSVR4ABI()) {
297 // VAARG always uses double-word chunks, so promote anything smaller.
298 setOperationAction(ISD::VAARG, MVT::i1, Promote);
299 AddPromotedToType (ISD::VAARG, MVT::i1, MVT::i64);
300 setOperationAction(ISD::VAARG, MVT::i8, Promote);
301 AddPromotedToType (ISD::VAARG, MVT::i8, MVT::i64);
302 setOperationAction(ISD::VAARG, MVT::i16, Promote);
303 AddPromotedToType (ISD::VAARG, MVT::i16, MVT::i64);
304 setOperationAction(ISD::VAARG, MVT::i32, Promote);
305 AddPromotedToType (ISD::VAARG, MVT::i32, MVT::i64);
306 setOperationAction(ISD::VAARG, MVT::Other, Expand);
308 // VAARG is custom lowered with the 32-bit SVR4 ABI.
309 setOperationAction(ISD::VAARG, MVT::Other, Custom);
310 setOperationAction(ISD::VAARG, MVT::i64, Custom);
313 setOperationAction(ISD::VAARG, MVT::Other, Expand);
315 if (Subtarget.isSVR4ABI() && !isPPC64)
316 // VACOPY is custom lowered with the 32-bit SVR4 ABI.
317 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
319 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
321 // Use the default implementation.
322 setOperationAction(ISD::VAEND , MVT::Other, Expand);
323 setOperationAction(ISD::STACKSAVE , MVT::Other, Expand);
324 setOperationAction(ISD::STACKRESTORE , MVT::Other, Custom);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32 , Custom);
326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64 , Custom);
328 // We want to custom lower some of our intrinsics.
329 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
331 // To handle counter-based loop conditions.
332 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i1, Custom);
334 // Comparisons that require checking two conditions.
335 setCondCodeAction(ISD::SETULT, MVT::f32, Expand);
336 setCondCodeAction(ISD::SETULT, MVT::f64, Expand);
337 setCondCodeAction(ISD::SETUGT, MVT::f32, Expand);
338 setCondCodeAction(ISD::SETUGT, MVT::f64, Expand);
339 setCondCodeAction(ISD::SETUEQ, MVT::f32, Expand);
340 setCondCodeAction(ISD::SETUEQ, MVT::f64, Expand);
341 setCondCodeAction(ISD::SETOGE, MVT::f32, Expand);
342 setCondCodeAction(ISD::SETOGE, MVT::f64, Expand);
343 setCondCodeAction(ISD::SETOLE, MVT::f32, Expand);
344 setCondCodeAction(ISD::SETOLE, MVT::f64, Expand);
345 setCondCodeAction(ISD::SETONE, MVT::f32, Expand);
346 setCondCodeAction(ISD::SETONE, MVT::f64, Expand);
348 if (Subtarget.has64BitSupport()) {
349 // They also have instructions for converting between i64 and fp.
350 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
351 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
352 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
353 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
354 // This is just the low 32 bits of a (signed) fp->i64 conversion.
355 // We cannot do this with Promote because i64 is not a legal type.
356 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
358 if (Subtarget.hasLFIWAX() || Subtarget.isPPC64())
359 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
361 // PowerPC does not have FP_TO_UINT on 32-bit implementations.
362 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
365 // With the instructions enabled under FPCVT, we can do everything.
366 if (Subtarget.hasFPCVT()) {
367 if (Subtarget.has64BitSupport()) {
368 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
369 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
370 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
371 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
374 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
375 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
376 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
377 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
380 if (Subtarget.use64BitRegs()) {
381 // 64-bit PowerPC implementations can support i64 types directly
382 addRegisterClass(MVT::i64, &PPC::G8RCRegClass);
383 // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
384 setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
385 // 64-bit PowerPC wants to expand i128 shifts itself.
386 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
387 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
388 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
390 // 32-bit PowerPC wants to expand i64 shifts itself.
391 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
392 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
393 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
396 if (Subtarget.hasAltivec()) {
397 // First set operation action for all vector types to expand. Then we
398 // will selectively turn on ones that can be effectively codegen'd.
399 for (MVT VT : MVT::vector_valuetypes()) {
400 // add/sub are legal for all supported vector VT's.
401 setOperationAction(ISD::ADD , VT, Legal);
402 setOperationAction(ISD::SUB , VT, Legal);
404 // We promote all shuffles to v16i8.
405 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Promote);
406 AddPromotedToType (ISD::VECTOR_SHUFFLE, VT, MVT::v16i8);
408 // We promote all non-typed operations to v4i32.
409 setOperationAction(ISD::AND , VT, Promote);
410 AddPromotedToType (ISD::AND , VT, MVT::v4i32);
411 setOperationAction(ISD::OR , VT, Promote);
412 AddPromotedToType (ISD::OR , VT, MVT::v4i32);
413 setOperationAction(ISD::XOR , VT, Promote);
414 AddPromotedToType (ISD::XOR , VT, MVT::v4i32);
415 setOperationAction(ISD::LOAD , VT, Promote);
416 AddPromotedToType (ISD::LOAD , VT, MVT::v4i32);
417 setOperationAction(ISD::SELECT, VT, Promote);
418 AddPromotedToType (ISD::SELECT, VT, MVT::v4i32);
419 setOperationAction(ISD::STORE, VT, Promote);
420 AddPromotedToType (ISD::STORE, VT, MVT::v4i32);
422 // No other operations are legal.
423 setOperationAction(ISD::MUL , VT, Expand);
424 setOperationAction(ISD::SDIV, VT, Expand);
425 setOperationAction(ISD::SREM, VT, Expand);
426 setOperationAction(ISD::UDIV, VT, Expand);
427 setOperationAction(ISD::UREM, VT, Expand);
428 setOperationAction(ISD::FDIV, VT, Expand);
429 setOperationAction(ISD::FREM, VT, Expand);
430 setOperationAction(ISD::FNEG, VT, Expand);
431 setOperationAction(ISD::FSQRT, VT, Expand);
432 setOperationAction(ISD::FLOG, VT, Expand);
433 setOperationAction(ISD::FLOG10, VT, Expand);
434 setOperationAction(ISD::FLOG2, VT, Expand);
435 setOperationAction(ISD::FEXP, VT, Expand);
436 setOperationAction(ISD::FEXP2, VT, Expand);
437 setOperationAction(ISD::FSIN, VT, Expand);
438 setOperationAction(ISD::FCOS, VT, Expand);
439 setOperationAction(ISD::FABS, VT, Expand);
440 setOperationAction(ISD::FPOWI, VT, Expand);
441 setOperationAction(ISD::FFLOOR, VT, Expand);
442 setOperationAction(ISD::FCEIL, VT, Expand);
443 setOperationAction(ISD::FTRUNC, VT, Expand);
444 setOperationAction(ISD::FRINT, VT, Expand);
445 setOperationAction(ISD::FNEARBYINT, VT, Expand);
446 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Expand);
447 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
448 setOperationAction(ISD::BUILD_VECTOR, VT, Expand);
449 setOperationAction(ISD::MULHU, VT, Expand);
450 setOperationAction(ISD::MULHS, VT, Expand);
451 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
452 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
453 setOperationAction(ISD::UDIVREM, VT, Expand);
454 setOperationAction(ISD::SDIVREM, VT, Expand);
455 setOperationAction(ISD::SCALAR_TO_VECTOR, VT, Expand);
456 setOperationAction(ISD::FPOW, VT, Expand);
457 setOperationAction(ISD::BSWAP, VT, Expand);
458 setOperationAction(ISD::CTPOP, VT, Expand);
459 setOperationAction(ISD::CTLZ, VT, Expand);
460 setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
461 setOperationAction(ISD::CTTZ, VT, Expand);
462 setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
463 setOperationAction(ISD::VSELECT, VT, Expand);
464 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
466 for (MVT InnerVT : MVT::vector_valuetypes()) {
467 setTruncStoreAction(VT, InnerVT, Expand);
468 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
469 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
470 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
474 // We can custom expand all VECTOR_SHUFFLEs to VPERM, others we can handle
475 // with merges, splats, etc.
476 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i8, Custom);
478 setOperationAction(ISD::AND , MVT::v4i32, Legal);
479 setOperationAction(ISD::OR , MVT::v4i32, Legal);
480 setOperationAction(ISD::XOR , MVT::v4i32, Legal);
481 setOperationAction(ISD::LOAD , MVT::v4i32, Legal);
482 setOperationAction(ISD::SELECT, MVT::v4i32,
483 Subtarget.useCRBits() ? Legal : Expand);
484 setOperationAction(ISD::STORE , MVT::v4i32, Legal);
485 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
486 setOperationAction(ISD::FP_TO_UINT, MVT::v4i32, Legal);
487 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
488 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Legal);
489 setOperationAction(ISD::FFLOOR, MVT::v4f32, Legal);
490 setOperationAction(ISD::FCEIL, MVT::v4f32, Legal);
491 setOperationAction(ISD::FTRUNC, MVT::v4f32, Legal);
492 setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Legal);
494 addRegisterClass(MVT::v4f32, &PPC::VRRCRegClass);
495 addRegisterClass(MVT::v4i32, &PPC::VRRCRegClass);
496 addRegisterClass(MVT::v8i16, &PPC::VRRCRegClass);
497 addRegisterClass(MVT::v16i8, &PPC::VRRCRegClass);
499 setOperationAction(ISD::MUL, MVT::v4f32, Legal);
500 setOperationAction(ISD::FMA, MVT::v4f32, Legal);
502 if (TM.Options.UnsafeFPMath || Subtarget.hasVSX()) {
503 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
504 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
507 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
508 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
509 setOperationAction(ISD::MUL, MVT::v16i8, Custom);
511 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4f32, Custom);
512 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i32, Custom);
514 setOperationAction(ISD::BUILD_VECTOR, MVT::v16i8, Custom);
515 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i16, Custom);
516 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i32, Custom);
517 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
519 // Altivec does not contain unordered floating-point compare instructions
520 setCondCodeAction(ISD::SETUO, MVT::v4f32, Expand);
521 setCondCodeAction(ISD::SETUEQ, MVT::v4f32, Expand);
522 setCondCodeAction(ISD::SETO, MVT::v4f32, Expand);
523 setCondCodeAction(ISD::SETONE, MVT::v4f32, Expand);
525 if (Subtarget.hasVSX()) {
526 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f64, Legal);
527 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Legal);
529 setOperationAction(ISD::FFLOOR, MVT::v2f64, Legal);
530 setOperationAction(ISD::FCEIL, MVT::v2f64, Legal);
531 setOperationAction(ISD::FTRUNC, MVT::v2f64, Legal);
532 setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Legal);
533 setOperationAction(ISD::FROUND, MVT::v2f64, Legal);
535 setOperationAction(ISD::FROUND, MVT::v4f32, Legal);
537 setOperationAction(ISD::MUL, MVT::v2f64, Legal);
538 setOperationAction(ISD::FMA, MVT::v2f64, Legal);
540 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
541 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
543 setOperationAction(ISD::VSELECT, MVT::v16i8, Legal);
544 setOperationAction(ISD::VSELECT, MVT::v8i16, Legal);
545 setOperationAction(ISD::VSELECT, MVT::v4i32, Legal);
546 setOperationAction(ISD::VSELECT, MVT::v4f32, Legal);
547 setOperationAction(ISD::VSELECT, MVT::v2f64, Legal);
549 // Share the Altivec comparison restrictions.
550 setCondCodeAction(ISD::SETUO, MVT::v2f64, Expand);
551 setCondCodeAction(ISD::SETUEQ, MVT::v2f64, Expand);
552 setCondCodeAction(ISD::SETO, MVT::v2f64, Expand);
553 setCondCodeAction(ISD::SETONE, MVT::v2f64, Expand);
555 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
556 setOperationAction(ISD::STORE, MVT::v2f64, Legal);
558 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Legal);
560 addRegisterClass(MVT::f64, &PPC::VSFRCRegClass);
562 addRegisterClass(MVT::v4f32, &PPC::VSRCRegClass);
563 addRegisterClass(MVT::v2f64, &PPC::VSRCRegClass);
565 // VSX v2i64 only supports non-arithmetic operations.
566 setOperationAction(ISD::ADD, MVT::v2i64, Expand);
567 setOperationAction(ISD::SUB, MVT::v2i64, Expand);
569 setOperationAction(ISD::SHL, MVT::v2i64, Expand);
570 setOperationAction(ISD::SRA, MVT::v2i64, Expand);
571 setOperationAction(ISD::SRL, MVT::v2i64, Expand);
573 setOperationAction(ISD::SETCC, MVT::v2i64, Custom);
575 setOperationAction(ISD::LOAD, MVT::v2i64, Promote);
576 AddPromotedToType (ISD::LOAD, MVT::v2i64, MVT::v2f64);
577 setOperationAction(ISD::STORE, MVT::v2i64, Promote);
578 AddPromotedToType (ISD::STORE, MVT::v2i64, MVT::v2f64);
580 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Legal);
582 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Legal);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Legal);
584 setOperationAction(ISD::FP_TO_SINT, MVT::v2i64, Legal);
585 setOperationAction(ISD::FP_TO_UINT, MVT::v2i64, Legal);
587 // Vector operation legalization checks the result type of
588 // SIGN_EXTEND_INREG, overall legalization checks the inner type.
589 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i64, Legal);
590 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i32, Legal);
591 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
592 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
594 addRegisterClass(MVT::v2i64, &PPC::VSRCRegClass);
598 if (Subtarget.has64BitSupport())
599 setOperationAction(ISD::PREFETCH, MVT::Other, Legal);
601 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, isPPC64 ? Legal : Custom);
604 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
605 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
608 setBooleanContents(ZeroOrOneBooleanContent);
609 // Altivec instructions set fields to all zeros or all ones.
610 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
613 // These libcalls are not available in 32-bit.
614 setLibcallName(RTLIB::SHL_I128, nullptr);
615 setLibcallName(RTLIB::SRL_I128, nullptr);
616 setLibcallName(RTLIB::SRA_I128, nullptr);
620 setStackPointerRegisterToSaveRestore(PPC::X1);
621 setExceptionPointerRegister(PPC::X3);
622 setExceptionSelectorRegister(PPC::X4);
624 setStackPointerRegisterToSaveRestore(PPC::R1);
625 setExceptionPointerRegister(PPC::R3);
626 setExceptionSelectorRegister(PPC::R4);
629 // We have target-specific dag combine patterns for the following nodes:
630 setTargetDAGCombine(ISD::SINT_TO_FP);
631 if (Subtarget.hasFPCVT())
632 setTargetDAGCombine(ISD::UINT_TO_FP);
633 setTargetDAGCombine(ISD::LOAD);
634 setTargetDAGCombine(ISD::STORE);
635 setTargetDAGCombine(ISD::BR_CC);
636 if (Subtarget.useCRBits())
637 setTargetDAGCombine(ISD::BRCOND);
638 setTargetDAGCombine(ISD::BSWAP);
639 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
640 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
641 setTargetDAGCombine(ISD::INTRINSIC_VOID);
643 setTargetDAGCombine(ISD::SIGN_EXTEND);
644 setTargetDAGCombine(ISD::ZERO_EXTEND);
645 setTargetDAGCombine(ISD::ANY_EXTEND);
647 if (Subtarget.useCRBits()) {
648 setTargetDAGCombine(ISD::TRUNCATE);
649 setTargetDAGCombine(ISD::SETCC);
650 setTargetDAGCombine(ISD::SELECT_CC);
653 // Use reciprocal estimates.
654 if (TM.Options.UnsafeFPMath) {
655 setTargetDAGCombine(ISD::FDIV);
656 setTargetDAGCombine(ISD::FSQRT);
659 // Darwin long double math library functions have $LDBL128 appended.
660 if (Subtarget.isDarwin()) {
661 setLibcallName(RTLIB::COS_PPCF128, "cosl$LDBL128");
662 setLibcallName(RTLIB::POW_PPCF128, "powl$LDBL128");
663 setLibcallName(RTLIB::REM_PPCF128, "fmodl$LDBL128");
664 setLibcallName(RTLIB::SIN_PPCF128, "sinl$LDBL128");
665 setLibcallName(RTLIB::SQRT_PPCF128, "sqrtl$LDBL128");
666 setLibcallName(RTLIB::LOG_PPCF128, "logl$LDBL128");
667 setLibcallName(RTLIB::LOG2_PPCF128, "log2l$LDBL128");
668 setLibcallName(RTLIB::LOG10_PPCF128, "log10l$LDBL128");
669 setLibcallName(RTLIB::EXP_PPCF128, "expl$LDBL128");
670 setLibcallName(RTLIB::EXP2_PPCF128, "exp2l$LDBL128");
673 // With 32 condition bits, we don't need to sink (and duplicate) compares
674 // aggressively in CodeGenPrep.
675 if (Subtarget.useCRBits())
676 setHasMultipleConditionRegisters();
678 setMinFunctionAlignment(2);
679 if (Subtarget.isDarwin())
680 setPrefFunctionAlignment(4);
682 switch (Subtarget.getDarwinDirective()) {
686 case PPC::DIR_E500mc:
695 setPrefFunctionAlignment(4);
696 setPrefLoopAlignment(4);
700 setInsertFencesForAtomic(true);
702 if (Subtarget.enableMachineScheduler())
703 setSchedulingPreference(Sched::Source);
705 setSchedulingPreference(Sched::Hybrid);
707 computeRegisterProperties();
709 // The Freescale cores do better with aggressive inlining of memcpy and
710 // friends. GCC uses same threshold of 128 bytes (= 32 word stores).
711 if (Subtarget.getDarwinDirective() == PPC::DIR_E500mc ||
712 Subtarget.getDarwinDirective() == PPC::DIR_E5500) {
713 MaxStoresPerMemset = 32;
714 MaxStoresPerMemsetOptSize = 16;
715 MaxStoresPerMemcpy = 32;
716 MaxStoresPerMemcpyOptSize = 8;
717 MaxStoresPerMemmove = 32;
718 MaxStoresPerMemmoveOptSize = 8;
722 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
723 /// the desired ByVal argument alignment.
724 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign,
725 unsigned MaxMaxAlign) {
726 if (MaxAlign == MaxMaxAlign)
728 if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
729 if (MaxMaxAlign >= 32 && VTy->getBitWidth() >= 256)
731 else if (VTy->getBitWidth() >= 128 && MaxAlign < 16)
733 } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(ATy->getElementType(), EltAlign, MaxMaxAlign);
736 if (EltAlign > MaxAlign)
738 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
739 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
740 unsigned EltAlign = 0;
741 getMaxByValAlign(STy->getElementType(i), EltAlign, MaxMaxAlign);
742 if (EltAlign > MaxAlign)
744 if (MaxAlign == MaxMaxAlign)
750 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
751 /// function arguments in the caller parameter area.
752 unsigned PPCTargetLowering::getByValTypeAlignment(Type *Ty) const {
753 // Darwin passes everything on 4 byte boundary.
754 if (Subtarget.isDarwin())
757 // 16byte and wider vectors are passed on 16byte boundary.
758 // The rest is 8 on PPC64 and 4 on PPC32 boundary.
759 unsigned Align = Subtarget.isPPC64() ? 8 : 4;
760 if (Subtarget.hasAltivec() || Subtarget.hasQPX())
761 getMaxByValAlign(Ty, Align, Subtarget.hasQPX() ? 32 : 16);
765 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
767 default: return nullptr;
768 case PPCISD::FSEL: return "PPCISD::FSEL";
769 case PPCISD::FCFID: return "PPCISD::FCFID";
770 case PPCISD::FCFIDU: return "PPCISD::FCFIDU";
771 case PPCISD::FCFIDS: return "PPCISD::FCFIDS";
772 case PPCISD::FCFIDUS: return "PPCISD::FCFIDUS";
773 case PPCISD::FCTIDZ: return "PPCISD::FCTIDZ";
774 case PPCISD::FCTIWZ: return "PPCISD::FCTIWZ";
775 case PPCISD::FCTIDUZ: return "PPCISD::FCTIDUZ";
776 case PPCISD::FCTIWUZ: return "PPCISD::FCTIWUZ";
777 case PPCISD::FRE: return "PPCISD::FRE";
778 case PPCISD::FRSQRTE: return "PPCISD::FRSQRTE";
779 case PPCISD::STFIWX: return "PPCISD::STFIWX";
780 case PPCISD::VMADDFP: return "PPCISD::VMADDFP";
781 case PPCISD::VNMSUBFP: return "PPCISD::VNMSUBFP";
782 case PPCISD::VPERM: return "PPCISD::VPERM";
783 case PPCISD::CMPB: return "PPCISD::CMPB";
784 case PPCISD::Hi: return "PPCISD::Hi";
785 case PPCISD::Lo: return "PPCISD::Lo";
786 case PPCISD::TOC_ENTRY: return "PPCISD::TOC_ENTRY";
787 case PPCISD::LOAD: return "PPCISD::LOAD";
788 case PPCISD::LOAD_TOC: return "PPCISD::LOAD_TOC";
789 case PPCISD::DYNALLOC: return "PPCISD::DYNALLOC";
790 case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
791 case PPCISD::SRL: return "PPCISD::SRL";
792 case PPCISD::SRA: return "PPCISD::SRA";
793 case PPCISD::SHL: return "PPCISD::SHL";
794 case PPCISD::CALL: return "PPCISD::CALL";
795 case PPCISD::CALL_NOP: return "PPCISD::CALL_NOP";
796 case PPCISD::CALL_TLS: return "PPCISD::CALL_TLS";
797 case PPCISD::CALL_NOP_TLS: return "PPCISD::CALL_NOP_TLS";
798 case PPCISD::MTCTR: return "PPCISD::MTCTR";
799 case PPCISD::BCTRL: return "PPCISD::BCTRL";
800 case PPCISD::BCTRL_LOAD_TOC: return "PPCISD::BCTRL_LOAD_TOC";
801 case PPCISD::RET_FLAG: return "PPCISD::RET_FLAG";
802 case PPCISD::READ_TIME_BASE: return "PPCISD::READ_TIME_BASE";
803 case PPCISD::EH_SJLJ_SETJMP: return "PPCISD::EH_SJLJ_SETJMP";
804 case PPCISD::EH_SJLJ_LONGJMP: return "PPCISD::EH_SJLJ_LONGJMP";
805 case PPCISD::MFOCRF: return "PPCISD::MFOCRF";
806 case PPCISD::VCMP: return "PPCISD::VCMP";
807 case PPCISD::VCMPo: return "PPCISD::VCMPo";
808 case PPCISD::LBRX: return "PPCISD::LBRX";
809 case PPCISD::STBRX: return "PPCISD::STBRX";
810 case PPCISD::LFIWAX: return "PPCISD::LFIWAX";
811 case PPCISD::LFIWZX: return "PPCISD::LFIWZX";
812 case PPCISD::LARX: return "PPCISD::LARX";
813 case PPCISD::STCX: return "PPCISD::STCX";
814 case PPCISD::COND_BRANCH: return "PPCISD::COND_BRANCH";
815 case PPCISD::BDNZ: return "PPCISD::BDNZ";
816 case PPCISD::BDZ: return "PPCISD::BDZ";
817 case PPCISD::MFFS: return "PPCISD::MFFS";
818 case PPCISD::FADDRTZ: return "PPCISD::FADDRTZ";
819 case PPCISD::TC_RETURN: return "PPCISD::TC_RETURN";
820 case PPCISD::CR6SET: return "PPCISD::CR6SET";
821 case PPCISD::CR6UNSET: return "PPCISD::CR6UNSET";
822 case PPCISD::ADDIS_TOC_HA: return "PPCISD::ADDIS_TOC_HA";
823 case PPCISD::LD_TOC_L: return "PPCISD::LD_TOC_L";
824 case PPCISD::ADDI_TOC_L: return "PPCISD::ADDI_TOC_L";
825 case PPCISD::PPC32_GOT: return "PPCISD::PPC32_GOT";
826 case PPCISD::ADDIS_GOT_TPREL_HA: return "PPCISD::ADDIS_GOT_TPREL_HA";
827 case PPCISD::LD_GOT_TPREL_L: return "PPCISD::LD_GOT_TPREL_L";
828 case PPCISD::ADD_TLS: return "PPCISD::ADD_TLS";
829 case PPCISD::ADDIS_TLSGD_HA: return "PPCISD::ADDIS_TLSGD_HA";
830 case PPCISD::ADDI_TLSGD_L: return "PPCISD::ADDI_TLSGD_L";
831 case PPCISD::ADDIS_TLSLD_HA: return "PPCISD::ADDIS_TLSLD_HA";
832 case PPCISD::ADDI_TLSLD_L: return "PPCISD::ADDI_TLSLD_L";
833 case PPCISD::ADDIS_DTPREL_HA: return "PPCISD::ADDIS_DTPREL_HA";
834 case PPCISD::ADDI_DTPREL_L: return "PPCISD::ADDI_DTPREL_L";
835 case PPCISD::VADD_SPLAT: return "PPCISD::VADD_SPLAT";
836 case PPCISD::SC: return "PPCISD::SC";
840 EVT PPCTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
842 return Subtarget.useCRBits() ? MVT::i1 : MVT::i32;
843 return VT.changeVectorElementTypeToInteger();
846 bool PPCTargetLowering::enableAggressiveFMAFusion(EVT VT) const {
847 assert(VT.isFloatingPoint() && "Non-floating-point FMA?");
851 //===----------------------------------------------------------------------===//
852 // Node matching predicates, for use by the tblgen matching code.
853 //===----------------------------------------------------------------------===//
855 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
856 static bool isFloatingPointZero(SDValue Op) {
857 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
858 return CFP->getValueAPF().isZero();
859 else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
860 // Maybe this has already been legalized into the constant pool?
861 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
862 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
863 return CFP->getValueAPF().isZero();
868 /// isConstantOrUndef - Op is either an undef node or a ConstantSDNode. Return
869 /// true if Op is undef or if it matches the specified value.
870 static bool isConstantOrUndef(int Op, int Val) {
871 return Op < 0 || Op == Val;
874 /// isVPKUHUMShuffleMask - Return true if this is the shuffle mask for a
875 /// VPKUHUM instruction.
876 /// The ShuffleKind distinguishes between big-endian operations with
877 /// two different inputs (0), either-endian operations with two identical
878 /// inputs (1), and little-endian operantion with two different inputs (2).
879 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
880 bool PPC::isVPKUHUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
882 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
883 if (ShuffleKind == 0) {
886 for (unsigned i = 0; i != 16; ++i)
887 if (!isConstantOrUndef(N->getMaskElt(i), i*2+1))
889 } else if (ShuffleKind == 2) {
892 for (unsigned i = 0; i != 16; ++i)
893 if (!isConstantOrUndef(N->getMaskElt(i), i*2))
895 } else if (ShuffleKind == 1) {
896 unsigned j = IsLE ? 0 : 1;
897 for (unsigned i = 0; i != 8; ++i)
898 if (!isConstantOrUndef(N->getMaskElt(i), i*2+j) ||
899 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j))
905 /// isVPKUWUMShuffleMask - Return true if this is the shuffle mask for a
906 /// VPKUWUM instruction.
907 /// The ShuffleKind distinguishes between big-endian operations with
908 /// two different inputs (0), either-endian operations with two identical
909 /// inputs (1), and little-endian operantion with two different inputs (2).
910 /// For the latter, the input operands are swapped (see PPCInstrAltivec.td).
911 bool PPC::isVPKUWUMShuffleMask(ShuffleVectorSDNode *N, unsigned ShuffleKind,
913 bool IsLE = DAG.getSubtarget().getDataLayout()->isLittleEndian();
914 if (ShuffleKind == 0) {
917 for (unsigned i = 0; i != 16; i += 2)
918 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+2) ||
919 !isConstantOrUndef(N->getMaskElt(i+1), i*2+3))
921 } else if (ShuffleKind == 2) {
924 for (unsigned i = 0; i != 16; i += 2)
925 if (!isConstantOrUndef(N->getMaskElt(i ), i*2) ||
926 !isConstantOrUndef(N->getMaskElt(i+1), i*2+1))
928 } else if (ShuffleKind == 1) {
929 unsigned j = IsLE ? 0 : 2;
930 for (unsigned i = 0; i != 8; i += 2)
931 if (!isConstantOrUndef(N->getMaskElt(i ), i*2+j) ||
932 !isConstantOrUndef(N->getMaskElt(i+1), i*2+j+1) ||
933 !isConstantOrUndef(N->getMaskElt(i+8), i*2+j) ||
934 !isConstantOrUndef(N->getMaskElt(i+9), i*2+j+1))
940 /// isVMerge - Common function, used to match vmrg* shuffles.
942 static bool isVMerge(ShuffleVectorSDNode *N, unsigned UnitSize,
943 unsigned LHSStart, unsigned RHSStart) {
944 if (N->getValueType(0) != MVT::v16i8)
946 assert((UnitSize == 1 || UnitSize == 2 || UnitSize == 4) &&
947 "Unsupported merge size!");
949 for (unsigned i = 0; i != 8/UnitSize; ++i) // Step over units
950 for (unsigned j = 0; j != UnitSize; ++j) { // Step over bytes within unit
951 if (!isConstantOrUndef(N->getMaskElt(i*UnitSize*2+j),
952 LHSStart+j+i*UnitSize) ||
953 !isConstantOrUndef(N->getMaskElt(i*UnitSize*2+UnitSize+j),
954 RHSStart+j+i*UnitSize))
960 /// isVMRGLShuffleMask - Return true if this is a shuffle mask suitable for
961 /// a VMRGL* instruction with the specified unit size (1,2 or 4 bytes).
962 /// The ShuffleKind distinguishes between big-endian merges with two
963 /// different inputs (0), either-endian merges with two identical inputs (1),
964 /// and little-endian merges with two different inputs (2). For the latter,
965 /// the input operands are swapped (see PPCInstrAltivec.td).
966 bool PPC::isVMRGLShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
967 unsigned ShuffleKind, SelectionDAG &DAG) {
968 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
969 if (ShuffleKind == 1) // unary
970 return isVMerge(N, UnitSize, 0, 0);
971 else if (ShuffleKind == 2) // swapped
972 return isVMerge(N, UnitSize, 0, 16);
976 if (ShuffleKind == 1) // unary
977 return isVMerge(N, UnitSize, 8, 8);
978 else if (ShuffleKind == 0) // normal
979 return isVMerge(N, UnitSize, 8, 24);
985 /// isVMRGHShuffleMask - Return true if this is a shuffle mask suitable for
986 /// a VMRGH* instruction with the specified unit size (1,2 or 4 bytes).
987 /// The ShuffleKind distinguishes between big-endian merges with two
988 /// different inputs (0), either-endian merges with two identical inputs (1),
989 /// and little-endian merges with two different inputs (2). For the latter,
990 /// the input operands are swapped (see PPCInstrAltivec.td).
991 bool PPC::isVMRGHShuffleMask(ShuffleVectorSDNode *N, unsigned UnitSize,
992 unsigned ShuffleKind, SelectionDAG &DAG) {
993 if (DAG.getSubtarget().getDataLayout()->isLittleEndian()) {
994 if (ShuffleKind == 1) // unary
995 return isVMerge(N, UnitSize, 8, 8);
996 else if (ShuffleKind == 2) // swapped
997 return isVMerge(N, UnitSize, 8, 24);
1001 if (ShuffleKind == 1) // unary
1002 return isVMerge(N, UnitSize, 0, 0);
1003 else if (ShuffleKind == 0) // normal
1004 return isVMerge(N, UnitSize, 0, 16);
1011 /// isVSLDOIShuffleMask - If this is a vsldoi shuffle mask, return the shift
1012 /// amount, otherwise return -1.
1013 /// The ShuffleKind distinguishes between big-endian operations with two
1014 /// different inputs (0), either-endian operations with two identical inputs
1015 /// (1), and little-endian operations with two different inputs (2). For the
1016 /// latter, the input operands are swapped (see PPCInstrAltivec.td).
1017 int PPC::isVSLDOIShuffleMask(SDNode *N, unsigned ShuffleKind,
1018 SelectionDAG &DAG) {
1019 if (N->getValueType(0) != MVT::v16i8)
1022 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1024 // Find the first non-undef value in the shuffle mask.
1026 for (i = 0; i != 16 && SVOp->getMaskElt(i) < 0; ++i)
1029 if (i == 16) return -1; // all undef.
1031 // Otherwise, check to see if the rest of the elements are consecutively
1032 // numbered from this value.
1033 unsigned ShiftAmt = SVOp->getMaskElt(i);
1034 if (ShiftAmt < i) return -1;
1037 bool isLE = DAG.getTarget().getSubtargetImpl()->getDataLayout()->
1040 if ((ShuffleKind == 0 && !isLE) || (ShuffleKind == 2 && isLE)) {
1041 // Check the rest of the elements to see if they are consecutive.
1042 for (++i; i != 16; ++i)
1043 if (!isConstantOrUndef(SVOp->getMaskElt(i), ShiftAmt+i))
1045 } else if (ShuffleKind == 1) {
1046 // Check the rest of the elements to see if they are consecutive.
1047 for (++i; i != 16; ++i)
1048 if (!isConstantOrUndef(SVOp->getMaskElt(i), (ShiftAmt+i) & 15))
1053 if (ShuffleKind == 2 && isLE)
1054 ShiftAmt = 16 - ShiftAmt;
1059 /// isSplatShuffleMask - Return true if the specified VECTOR_SHUFFLE operand
1060 /// specifies a splat of a single element that is suitable for input to
1061 /// VSPLTB/VSPLTH/VSPLTW.
1062 bool PPC::isSplatShuffleMask(ShuffleVectorSDNode *N, unsigned EltSize) {
1063 assert(N->getValueType(0) == MVT::v16i8 &&
1064 (EltSize == 1 || EltSize == 2 || EltSize == 4));
1066 // This is a splat operation if each element of the permute is the same, and
1067 // if the value doesn't reference the second vector.
1068 unsigned ElementBase = N->getMaskElt(0);
1070 // FIXME: Handle UNDEF elements too!
1071 if (ElementBase >= 16)
1074 // Check that the indices are consecutive, in the case of a multi-byte element
1075 // splatted with a v16i8 mask.
1076 for (unsigned i = 1; i != EltSize; ++i)
1077 if (N->getMaskElt(i) < 0 || N->getMaskElt(i) != (int)(i+ElementBase))
1080 for (unsigned i = EltSize, e = 16; i != e; i += EltSize) {
1081 if (N->getMaskElt(i) < 0) continue;
1082 for (unsigned j = 0; j != EltSize; ++j)
1083 if (N->getMaskElt(i+j) != N->getMaskElt(j))
1089 /// isAllNegativeZeroVector - Returns true if all elements of build_vector
1091 bool PPC::isAllNegativeZeroVector(SDNode *N) {
1092 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
1094 APInt APVal, APUndef;
1098 if (BV->isConstantSplat(APVal, APUndef, BitSize, HasAnyUndefs, 32, true))
1099 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
1100 return CFP->getValueAPF().isNegZero();
1105 /// getVSPLTImmediate - Return the appropriate VSPLT* immediate to splat the
1106 /// specified isSplatShuffleMask VECTOR_SHUFFLE mask.
1107 unsigned PPC::getVSPLTImmediate(SDNode *N, unsigned EltSize,
1108 SelectionDAG &DAG) {
1109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
1110 assert(isSplatShuffleMask(SVOp, EltSize));
1111 if (DAG.getSubtarget().getDataLayout()->isLittleEndian())
1112 return (16 / EltSize) - 1 - (SVOp->getMaskElt(0) / EltSize);
1114 return SVOp->getMaskElt(0) / EltSize;
1117 /// get_VSPLTI_elt - If this is a build_vector of constants which can be formed
1118 /// by using a vspltis[bhw] instruction of the specified element size, return
1119 /// the constant being splatted. The ByteSize field indicates the number of
1120 /// bytes of each element [124] -> [bhw].
1121 SDValue PPC::get_VSPLTI_elt(SDNode *N, unsigned ByteSize, SelectionDAG &DAG) {
1122 SDValue OpVal(nullptr, 0);
1124 // If ByteSize of the splat is bigger than the element size of the
1125 // build_vector, then we have a case where we are checking for a splat where
1126 // multiple elements of the buildvector are folded together into a single
1127 // logical element of the splat (e.g. "vsplish 1" to splat {0,1}*8).
1128 unsigned EltSize = 16/N->getNumOperands();
1129 if (EltSize < ByteSize) {
1130 unsigned Multiple = ByteSize/EltSize; // Number of BV entries per spltval.
1131 SDValue UniquedVals[4];
1132 assert(Multiple > 1 && Multiple <= 4 && "How can this happen?");
1134 // See if all of the elements in the buildvector agree across.
1135 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1136 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1137 // If the element isn't a constant, bail fully out.
1138 if (!isa<ConstantSDNode>(N->getOperand(i))) return SDValue();
1141 if (!UniquedVals[i&(Multiple-1)].getNode())
1142 UniquedVals[i&(Multiple-1)] = N->getOperand(i);
1143 else if (UniquedVals[i&(Multiple-1)] != N->getOperand(i))
1144 return SDValue(); // no match.
1147 // Okay, if we reached this point, UniquedVals[0..Multiple-1] contains
1148 // either constant or undef values that are identical for each chunk. See
1149 // if these chunks can form into a larger vspltis*.
1151 // Check to see if all of the leading entries are either 0 or -1. If
1152 // neither, then this won't fit into the immediate field.
1153 bool LeadingZero = true;
1154 bool LeadingOnes = true;
1155 for (unsigned i = 0; i != Multiple-1; ++i) {
1156 if (!UniquedVals[i].getNode()) continue; // Must have been undefs.
1158 LeadingZero &= cast<ConstantSDNode>(UniquedVals[i])->isNullValue();
1159 LeadingOnes &= cast<ConstantSDNode>(UniquedVals[i])->isAllOnesValue();
1161 // Finally, check the least significant entry.
1163 if (!UniquedVals[Multiple-1].getNode())
1164 return DAG.getTargetConstant(0, MVT::i32); // 0,0,0,undef
1165 int Val = cast<ConstantSDNode>(UniquedVals[Multiple-1])->getZExtValue();
1167 return DAG.getTargetConstant(Val, MVT::i32); // 0,0,0,4 -> vspltisw(4)
1170 if (!UniquedVals[Multiple-1].getNode())
1171 return DAG.getTargetConstant(~0U, MVT::i32); // -1,-1,-1,undef
1172 int Val =cast<ConstantSDNode>(UniquedVals[Multiple-1])->getSExtValue();
1173 if (Val >= -16) // -1,-1,-1,-2 -> vspltisw(-2)
1174 return DAG.getTargetConstant(Val, MVT::i32);
1180 // Check to see if this buildvec has a single non-undef value in its elements.
1181 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1182 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1183 if (!OpVal.getNode())
1184 OpVal = N->getOperand(i);
1185 else if (OpVal != N->getOperand(i))
1189 if (!OpVal.getNode()) return SDValue(); // All UNDEF: use implicit def.
1191 unsigned ValSizeInBytes = EltSize;
1193 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal)) {
1194 Value = CN->getZExtValue();
1195 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal)) {
1196 assert(CN->getValueType(0) == MVT::f32 && "Only one legal FP vector type!");
1197 Value = FloatToBits(CN->getValueAPF().convertToFloat());
1200 // If the splat value is larger than the element value, then we can never do
1201 // this splat. The only case that we could fit the replicated bits into our
1202 // immediate field for would be zero, and we prefer to use vxor for it.
1203 if (ValSizeInBytes < ByteSize) return SDValue();
1205 // If the element value is larger than the splat value, cut it in half and
1206 // check to see if the two halves are equal. Continue doing this until we
1207 // get to ByteSize. This allows us to handle 0x01010101 as 0x01.
1208 while (ValSizeInBytes > ByteSize) {
1209 ValSizeInBytes >>= 1;
1211 // If the top half equals the bottom half, we're still ok.
1212 if (((Value >> (ValSizeInBytes*8)) & ((1 << (8*ValSizeInBytes))-1)) !=
1213 (Value & ((1 << (8*ValSizeInBytes))-1)))
1217 // Properly sign extend the value.
1218 int MaskVal = SignExtend32(Value, ByteSize * 8);
1220 // If this is zero, don't match, zero matches ISD::isBuildVectorAllZeros.
1221 if (MaskVal == 0) return SDValue();
1223 // Finally, if this value fits in a 5 bit sext field, return it
1224 if (SignExtend32<5>(MaskVal) == MaskVal)
1225 return DAG.getTargetConstant(MaskVal, MVT::i32);
1229 //===----------------------------------------------------------------------===//
1230 // Addressing Mode Selection
1231 //===----------------------------------------------------------------------===//
1233 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
1234 /// or 64-bit immediate, and if the value can be accurately represented as a
1235 /// sign extension from a 16-bit value. If so, this returns true and the
1237 static bool isIntS16Immediate(SDNode *N, short &Imm) {
1238 if (!isa<ConstantSDNode>(N))
1241 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
1242 if (N->getValueType(0) == MVT::i32)
1243 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
1245 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
1247 static bool isIntS16Immediate(SDValue Op, short &Imm) {
1248 return isIntS16Immediate(Op.getNode(), Imm);
1252 /// SelectAddressRegReg - Given the specified addressed, check to see if it
1253 /// can be represented as an indexed [r+r] operation. Returns false if it
1254 /// can be more efficiently represented with [r+imm].
1255 bool PPCTargetLowering::SelectAddressRegReg(SDValue N, SDValue &Base,
1257 SelectionDAG &DAG) const {
1259 if (N.getOpcode() == ISD::ADD) {
1260 if (isIntS16Immediate(N.getOperand(1), imm))
1261 return false; // r+i
1262 if (N.getOperand(1).getOpcode() == PPCISD::Lo)
1263 return false; // r+i
1265 Base = N.getOperand(0);
1266 Index = N.getOperand(1);
1268 } else if (N.getOpcode() == ISD::OR) {
1269 if (isIntS16Immediate(N.getOperand(1), imm))
1270 return false; // r+i can fold it if we can.
1272 // If this is an or of disjoint bitfields, we can codegen this as an add
1273 // (for better address arithmetic) if the LHS and RHS of the OR are provably
1275 APInt LHSKnownZero, LHSKnownOne;
1276 APInt RHSKnownZero, RHSKnownOne;
1277 DAG.computeKnownBits(N.getOperand(0),
1278 LHSKnownZero, LHSKnownOne);
1280 if (LHSKnownZero.getBoolValue()) {
1281 DAG.computeKnownBits(N.getOperand(1),
1282 RHSKnownZero, RHSKnownOne);
1283 // If all of the bits are known zero on the LHS or RHS, the add won't
1285 if (~(LHSKnownZero | RHSKnownZero) == 0) {
1286 Base = N.getOperand(0);
1287 Index = N.getOperand(1);
1296 // If we happen to be doing an i64 load or store into a stack slot that has
1297 // less than a 4-byte alignment, then the frame-index elimination may need to
1298 // use an indexed load or store instruction (because the offset may not be a
1299 // multiple of 4). The extra register needed to hold the offset comes from the
1300 // register scavenger, and it is possible that the scavenger will need to use
1301 // an emergency spill slot. As a result, we need to make sure that a spill slot
1302 // is allocated when doing an i64 load/store into a less-than-4-byte-aligned
1304 static void fixupFuncForFI(SelectionDAG &DAG, int FrameIdx, EVT VT) {
1305 // FIXME: This does not handle the LWA case.
1309 // NOTE: We'll exclude negative FIs here, which come from argument
1310 // lowering, because there are no known test cases triggering this problem
1311 // using packed structures (or similar). We can remove this exclusion if
1312 // we find such a test case. The reason why this is so test-case driven is
1313 // because this entire 'fixup' is only to prevent crashes (from the
1314 // register scavenger) on not-really-valid inputs. For example, if we have:
1316 // %b = bitcast i1* %a to i64*
1317 // store i64* a, i64 b
1318 // then the store should really be marked as 'align 1', but is not. If it
1319 // were marked as 'align 1' then the indexed form would have been
1320 // instruction-selected initially, and the problem this 'fixup' is preventing
1321 // won't happen regardless.
1325 MachineFunction &MF = DAG.getMachineFunction();
1326 MachineFrameInfo *MFI = MF.getFrameInfo();
1328 unsigned Align = MFI->getObjectAlignment(FrameIdx);
1332 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
1333 FuncInfo->setHasNonRISpills();
1336 /// Returns true if the address N can be represented by a base register plus
1337 /// a signed 16-bit displacement [r+imm], and if it is not better
1338 /// represented as reg+reg. If Aligned is true, only accept displacements
1339 /// suitable for STD and friends, i.e. multiples of 4.
1340 bool PPCTargetLowering::SelectAddressRegImm(SDValue N, SDValue &Disp,
1343 bool Aligned) const {
1344 // FIXME dl should come from parent load or store, not from address
1346 // If this can be more profitably realized as r+r, fail.
1347 if (SelectAddressRegReg(N, Disp, Base, DAG))
1350 if (N.getOpcode() == ISD::ADD) {
1352 if (isIntS16Immediate(N.getOperand(1), imm) &&
1353 (!Aligned || (imm & 3) == 0)) {
1354 Disp = DAG.getTargetConstant(imm, N.getValueType());
1355 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1356 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1357 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1359 Base = N.getOperand(0);
1361 return true; // [r+i]
1362 } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
1363 // Match LOAD (ADD (X, Lo(G))).
1364 assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getZExtValue()
1365 && "Cannot handle constant offsets yet!");
1366 Disp = N.getOperand(1).getOperand(0); // The global address.
1367 assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
1368 Disp.getOpcode() == ISD::TargetGlobalTLSAddress ||
1369 Disp.getOpcode() == ISD::TargetConstantPool ||
1370 Disp.getOpcode() == ISD::TargetJumpTable);
1371 Base = N.getOperand(0);
1372 return true; // [&g+r]
1374 } else if (N.getOpcode() == ISD::OR) {
1376 if (isIntS16Immediate(N.getOperand(1), imm) &&
1377 (!Aligned || (imm & 3) == 0)) {
1378 // If this is an or of disjoint bitfields, we can codegen this as an add
1379 // (for better address arithmetic) if the LHS and RHS of the OR are
1380 // provably disjoint.
1381 APInt LHSKnownZero, LHSKnownOne;
1382 DAG.computeKnownBits(N.getOperand(0), LHSKnownZero, LHSKnownOne);
1384 if ((LHSKnownZero.getZExtValue()|~(uint64_t)imm) == ~0ULL) {
1385 // If all of the bits are known zero on the LHS or RHS, the add won't
1387 if (FrameIndexSDNode *FI =
1388 dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
1389 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1390 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1392 Base = N.getOperand(0);
1394 Disp = DAG.getTargetConstant(imm, N.getValueType());
1398 } else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
1399 // Loading from a constant address.
1401 // If this address fits entirely in a 16-bit sext immediate field, codegen
1404 if (isIntS16Immediate(CN, Imm) && (!Aligned || (Imm & 3) == 0)) {
1405 Disp = DAG.getTargetConstant(Imm, CN->getValueType(0));
1406 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1407 CN->getValueType(0));
1411 // Handle 32-bit sext immediates with LIS + addr mode.
1412 if ((CN->getValueType(0) == MVT::i32 ||
1413 (int64_t)CN->getZExtValue() == (int)CN->getZExtValue()) &&
1414 (!Aligned || (CN->getZExtValue() & 3) == 0)) {
1415 int Addr = (int)CN->getZExtValue();
1417 // Otherwise, break this down into an LIS + disp.
1418 Disp = DAG.getTargetConstant((short)Addr, MVT::i32);
1420 Base = DAG.getTargetConstant((Addr - (signed short)Addr) >> 16, MVT::i32);
1421 unsigned Opc = CN->getValueType(0) == MVT::i32 ? PPC::LIS : PPC::LIS8;
1422 Base = SDValue(DAG.getMachineNode(Opc, dl, CN->getValueType(0), Base), 0);
1427 Disp = DAG.getTargetConstant(0, getPointerTy());
1428 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N)) {
1429 Base = DAG.getTargetFrameIndex(FI->getIndex(), N.getValueType());
1430 fixupFuncForFI(DAG, FI->getIndex(), N.getValueType());
1433 return true; // [r+0]
1436 /// SelectAddressRegRegOnly - Given the specified addressed, force it to be
1437 /// represented as an indexed [r+r] operation.
1438 bool PPCTargetLowering::SelectAddressRegRegOnly(SDValue N, SDValue &Base,
1440 SelectionDAG &DAG) const {
1441 // Check to see if we can easily represent this as an [r+r] address. This
1442 // will fail if it thinks that the address is more profitably represented as
1443 // reg+imm, e.g. where imm = 0.
1444 if (SelectAddressRegReg(N, Base, Index, DAG))
1447 // If the operand is an addition, always emit this as [r+r], since this is
1448 // better (for code size, and execution, as the memop does the add for free)
1449 // than emitting an explicit add.
1450 if (N.getOpcode() == ISD::ADD) {
1451 Base = N.getOperand(0);
1452 Index = N.getOperand(1);
1456 // Otherwise, do it the hard way, using R0 as the base register.
1457 Base = DAG.getRegister(Subtarget.isPPC64() ? PPC::ZERO8 : PPC::ZERO,
1463 /// getPreIndexedAddressParts - returns true by value, base pointer and
1464 /// offset pointer and addressing mode by reference if the node's address
1465 /// can be legally represented as pre-indexed load / store address.
1466 bool PPCTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
1468 ISD::MemIndexedMode &AM,
1469 SelectionDAG &DAG) const {
1470 if (DisablePPCPreinc) return false;
1476 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1477 Ptr = LD->getBasePtr();
1478 VT = LD->getMemoryVT();
1479 Alignment = LD->getAlignment();
1480 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
1481 Ptr = ST->getBasePtr();
1482 VT = ST->getMemoryVT();
1483 Alignment = ST->getAlignment();
1488 // PowerPC doesn't have preinc load/store instructions for vectors.
1492 if (SelectAddressRegReg(Ptr, Base, Offset, DAG)) {
1494 // Common code will reject creating a pre-inc form if the base pointer
1495 // is a frame index, or if N is a store and the base pointer is either
1496 // the same as or a predecessor of the value being stored. Check for
1497 // those situations here, and try with swapped Base/Offset instead.
1500 if (isa<FrameIndexSDNode>(Base) || isa<RegisterSDNode>(Base))
1503 SDValue Val = cast<StoreSDNode>(N)->getValue();
1504 if (Val == Base || Base.getNode()->isPredecessorOf(Val.getNode()))
1509 std::swap(Base, Offset);
1515 // LDU/STU can only handle immediates that are a multiple of 4.
1516 if (VT != MVT::i64) {
1517 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, false))
1520 // LDU/STU need an address with at least 4-byte alignment.
1524 if (!SelectAddressRegImm(Ptr, Offset, Base, DAG, true))
1528 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
1529 // PPC64 doesn't have lwau, but it does have lwaux. Reject preinc load of
1530 // sext i32 to i64 when addr mode is r+i.
1531 if (LD->getValueType(0) == MVT::i64 && LD->getMemoryVT() == MVT::i32 &&
1532 LD->getExtensionType() == ISD::SEXTLOAD &&
1533 isa<ConstantSDNode>(Offset))
1541 //===----------------------------------------------------------------------===//
1542 // LowerOperation implementation
1543 //===----------------------------------------------------------------------===//
1545 /// GetLabelAccessInfo - Return true if we should reference labels using a
1546 /// PICBase, set the HiOpFlags and LoOpFlags to the target MO flags.
1547 static bool GetLabelAccessInfo(const TargetMachine &TM, unsigned &HiOpFlags,
1548 unsigned &LoOpFlags,
1549 const GlobalValue *GV = nullptr) {
1550 HiOpFlags = PPCII::MO_HA;
1551 LoOpFlags = PPCII::MO_LO;
1553 // Don't use the pic base if not in PIC relocation model.
1554 bool isPIC = TM.getRelocationModel() == Reloc::PIC_;
1557 HiOpFlags |= PPCII::MO_PIC_FLAG;
1558 LoOpFlags |= PPCII::MO_PIC_FLAG;
1561 // If this is a reference to a global value that requires a non-lazy-ptr, make
1562 // sure that instruction lowering adds it.
1563 if (GV && TM.getSubtarget<PPCSubtarget>().hasLazyResolverStub(GV, TM)) {
1564 HiOpFlags |= PPCII::MO_NLP_FLAG;
1565 LoOpFlags |= PPCII::MO_NLP_FLAG;
1567 if (GV->hasHiddenVisibility()) {
1568 HiOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1569 LoOpFlags |= PPCII::MO_NLP_HIDDEN_FLAG;
1576 static SDValue LowerLabelRef(SDValue HiPart, SDValue LoPart, bool isPIC,
1577 SelectionDAG &DAG) {
1578 EVT PtrVT = HiPart.getValueType();
1579 SDValue Zero = DAG.getConstant(0, PtrVT);
1582 SDValue Hi = DAG.getNode(PPCISD::Hi, DL, PtrVT, HiPart, Zero);
1583 SDValue Lo = DAG.getNode(PPCISD::Lo, DL, PtrVT, LoPart, Zero);
1585 // With PIC, the first instruction is actually "GR+hi(&G)".
1587 Hi = DAG.getNode(ISD::ADD, DL, PtrVT,
1588 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT), Hi);
1590 // Generate non-pic code that has direct accesses to the constant pool.
1591 // The address of the global is just (hi(&g)+lo(&g)).
1592 return DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1595 SDValue PPCTargetLowering::LowerConstantPool(SDValue Op,
1596 SelectionDAG &DAG) const {
1597 EVT PtrVT = Op.getValueType();
1598 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
1599 const Constant *C = CP->getConstVal();
1601 // 64-bit SVR4 ABI code is always position-independent.
1602 // The actual address of the GlobalValue is stored in the TOC.
1603 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1604 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0);
1605 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(CP), MVT::i64, GA,
1606 DAG.getRegister(PPC::X2, MVT::i64));
1609 unsigned MOHiFlag, MOLoFlag;
1610 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1612 if (isPIC && Subtarget.isSVR4ABI()) {
1613 SDValue GA = DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(),
1614 PPCII::MO_PIC_FLAG);
1616 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1617 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1621 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOHiFlag);
1623 DAG.getTargetConstantPool(C, PtrVT, CP->getAlignment(), 0, MOLoFlag);
1624 return LowerLabelRef(CPIHi, CPILo, isPIC, DAG);
1627 SDValue PPCTargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
1628 EVT PtrVT = Op.getValueType();
1629 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1631 // 64-bit SVR4 ABI code is always position-independent.
1632 // The actual address of the GlobalValue is stored in the TOC.
1633 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1634 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT);
1635 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), MVT::i64, GA,
1636 DAG.getRegister(PPC::X2, MVT::i64));
1639 unsigned MOHiFlag, MOLoFlag;
1640 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1642 if (isPIC && Subtarget.isSVR4ABI()) {
1643 SDValue GA = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1644 PPCII::MO_PIC_FLAG);
1646 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(JT), PtrVT, GA,
1647 DAG.getNode(PPCISD::GlobalBaseReg, DL, PtrVT));
1650 SDValue JTIHi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOHiFlag);
1651 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MOLoFlag);
1652 return LowerLabelRef(JTIHi, JTILo, isPIC, DAG);
1655 SDValue PPCTargetLowering::LowerBlockAddress(SDValue Op,
1656 SelectionDAG &DAG) const {
1657 EVT PtrVT = Op.getValueType();
1658 BlockAddressSDNode *BASDN = cast<BlockAddressSDNode>(Op);
1659 const BlockAddress *BA = BASDN->getBlockAddress();
1661 // 64-bit SVR4 ABI code is always position-independent.
1662 // The actual BlockAddress is stored in the TOC.
1663 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1664 SDValue GA = DAG.getTargetBlockAddress(BA, PtrVT, BASDN->getOffset());
1665 return DAG.getNode(PPCISD::TOC_ENTRY, SDLoc(BASDN), MVT::i64, GA,
1666 DAG.getRegister(PPC::X2, MVT::i64));
1669 unsigned MOHiFlag, MOLoFlag;
1670 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag);
1671 SDValue TgtBAHi = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOHiFlag);
1672 SDValue TgtBALo = DAG.getTargetBlockAddress(BA, PtrVT, 0, MOLoFlag);
1673 return LowerLabelRef(TgtBAHi, TgtBALo, isPIC, DAG);
1676 // Generate a call to __tls_get_addr for the given GOT entry Op.
1677 std::pair<SDValue,SDValue>
1678 PPCTargetLowering::lowerTLSCall(SDValue Op, SDLoc dl,
1679 SelectionDAG &DAG) const {
1681 Type *IntPtrTy = getDataLayout()->getIntPtrType(*DAG.getContext());
1682 TargetLowering::ArgListTy Args;
1683 TargetLowering::ArgListEntry Entry;
1685 Entry.Ty = IntPtrTy;
1686 Args.push_back(Entry);
1688 TargetLowering::CallLoweringInfo CLI(DAG);
1689 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1690 .setCallee(CallingConv::C, IntPtrTy,
1691 DAG.getTargetExternalSymbol("__tls_get_addr", getPointerTy()),
1692 std::move(Args), 0);
1694 return LowerCallTo(CLI);
1697 SDValue PPCTargetLowering::LowerGlobalTLSAddress(SDValue Op,
1698 SelectionDAG &DAG) const {
1700 // FIXME: TLS addresses currently use medium model code sequences,
1701 // which is the most useful form. Eventually support for small and
1702 // large models could be added if users need it, at the cost of
1703 // additional complexity.
1704 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1706 const GlobalValue *GV = GA->getGlobal();
1707 EVT PtrVT = getPointerTy();
1708 bool is64bit = Subtarget.isPPC64();
1709 const Module *M = DAG.getMachineFunction().getFunction()->getParent();
1710 PICLevel::Level picLevel = M->getPICLevel();
1712 TLSModel::Model Model = getTargetMachine().getTLSModel(GV);
1714 if (Model == TLSModel::LocalExec) {
1715 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1716 PPCII::MO_TPREL_HA);
1717 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1718 PPCII::MO_TPREL_LO);
1719 SDValue TLSReg = DAG.getRegister(is64bit ? PPC::X13 : PPC::R2,
1720 is64bit ? MVT::i64 : MVT::i32);
1721 SDValue Hi = DAG.getNode(PPCISD::Hi, dl, PtrVT, TGAHi, TLSReg);
1722 return DAG.getNode(PPCISD::Lo, dl, PtrVT, TGALo, Hi);
1725 if (Model == TLSModel::InitialExec) {
1726 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, 0);
1727 SDValue TGATLS = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1731 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1732 GOTPtr = DAG.getNode(PPCISD::ADDIS_GOT_TPREL_HA, dl,
1733 PtrVT, GOTReg, TGA);
1735 GOTPtr = DAG.getNode(PPCISD::PPC32_GOT, dl, PtrVT);
1736 SDValue TPOffset = DAG.getNode(PPCISD::LD_GOT_TPREL_L, dl,
1737 PtrVT, TGA, GOTPtr);
1738 return DAG.getNode(PPCISD::ADD_TLS, dl, PtrVT, TPOffset, TGATLS);
1741 if (Model == TLSModel::GeneralDynamic) {
1742 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1746 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1747 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSGD_HA, dl, PtrVT,
1750 if (picLevel == PICLevel::Small)
1751 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1753 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1755 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSGD_L, dl, PtrVT,
1757 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1758 return CallResult.first;
1761 if (Model == TLSModel::LocalDynamic) {
1762 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1766 SDValue GOTReg = DAG.getRegister(PPC::X2, MVT::i64);
1767 GOTPtr = DAG.getNode(PPCISD::ADDIS_TLSLD_HA, dl, PtrVT,
1770 if (picLevel == PICLevel::Small)
1771 GOTPtr = DAG.getNode(PPCISD::GlobalBaseReg, dl, PtrVT);
1773 GOTPtr = DAG.getNode(PPCISD::PPC32_PICGOT, dl, PtrVT);
1775 SDValue GOTEntry = DAG.getNode(PPCISD::ADDI_TLSLD_L, dl, PtrVT,
1777 std::pair<SDValue, SDValue> CallResult = lowerTLSCall(GOTEntry, dl, DAG);
1778 SDValue TLSAddr = CallResult.first;
1779 SDValue Chain = CallResult.second;
1780 SDValue DtvOffsetHi = DAG.getNode(PPCISD::ADDIS_DTPREL_HA, dl, PtrVT,
1781 Chain, TLSAddr, TGA);
1782 return DAG.getNode(PPCISD::ADDI_DTPREL_L, dl, PtrVT, DtvOffsetHi, TGA);
1785 llvm_unreachable("Unknown TLS model!");
1788 SDValue PPCTargetLowering::LowerGlobalAddress(SDValue Op,
1789 SelectionDAG &DAG) const {
1790 EVT PtrVT = Op.getValueType();
1791 GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
1793 const GlobalValue *GV = GSDN->getGlobal();
1795 // 64-bit SVR4 ABI code is always position-independent.
1796 // The actual address of the GlobalValue is stored in the TOC.
1797 if (Subtarget.isSVR4ABI() && Subtarget.isPPC64()) {
1798 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset());
1799 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i64, GA,
1800 DAG.getRegister(PPC::X2, MVT::i64));
1803 unsigned MOHiFlag, MOLoFlag;
1804 bool isPIC = GetLabelAccessInfo(DAG.getTarget(), MOHiFlag, MOLoFlag, GV);
1806 if (isPIC && Subtarget.isSVR4ABI()) {
1807 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, PtrVT,
1809 PPCII::MO_PIC_FLAG);
1810 return DAG.getNode(PPCISD::TOC_ENTRY, DL, MVT::i32, GA,
1811 DAG.getNode(PPCISD::GlobalBaseReg, DL, MVT::i32));
1815 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOHiFlag);
1817 DAG.getTargetGlobalAddress(GV, DL, PtrVT, GSDN->getOffset(), MOLoFlag);
1819 SDValue Ptr = LowerLabelRef(GAHi, GALo, isPIC, DAG);
1821 // If the global reference is actually to a non-lazy-pointer, we have to do an
1822 // extra load to get the address of the global.
1823 if (MOHiFlag & PPCII::MO_NLP_FLAG)
1824 Ptr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo(),
1825 false, false, false, 0);
1829 SDValue PPCTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1830 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1833 if (Op.getValueType() == MVT::v2i64) {
1834 // When the operands themselves are v2i64 values, we need to do something
1835 // special because VSX has no underlying comparison operations for these.
1836 if (Op.getOperand(0).getValueType() == MVT::v2i64) {
1837 // Equality can be handled by casting to the legal type for Altivec
1838 // comparisons, everything else needs to be expanded.
1839 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
1840 return DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
1841 DAG.getSetCC(dl, MVT::v4i32,
1842 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0)),
1843 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(1)),
1850 // We handle most of these in the usual way.
1854 // If we're comparing for equality to zero, expose the fact that this is
1855 // implented as a ctlz/srl pair on ppc, so that the dag combiner can
1856 // fold the new nodes.
1857 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1858 if (C->isNullValue() && CC == ISD::SETEQ) {
1859 EVT VT = Op.getOperand(0).getValueType();
1860 SDValue Zext = Op.getOperand(0);
1861 if (VT.bitsLT(MVT::i32)) {
1863 Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
1865 unsigned Log2b = Log2_32(VT.getSizeInBits());
1866 SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
1867 SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
1868 DAG.getConstant(Log2b, MVT::i32));
1869 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
1871 // Leave comparisons against 0 and -1 alone for now, since they're usually
1872 // optimized. FIXME: revisit this when we can custom lower all setcc
1874 if (C->isAllOnesValue() || C->isNullValue())
1878 // If we have an integer seteq/setne, turn it into a compare against zero
1879 // by xor'ing the rhs with the lhs, which is faster than setting a
1880 // condition register, reading it back out, and masking the correct bit. The
1881 // normal approach here uses sub to do this instead of xor. Using xor exposes
1882 // the result to other bit-twiddling opportunities.
1883 EVT LHSVT = Op.getOperand(0).getValueType();
1884 if (LHSVT.isInteger() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1885 EVT VT = Op.getValueType();
1886 SDValue Sub = DAG.getNode(ISD::XOR, dl, LHSVT, Op.getOperand(0),
1888 return DAG.getSetCC(dl, VT, Sub, DAG.getConstant(0, LHSVT), CC);
1893 SDValue PPCTargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG,
1894 const PPCSubtarget &Subtarget) const {
1895 SDNode *Node = Op.getNode();
1896 EVT VT = Node->getValueType(0);
1897 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
1898 SDValue InChain = Node->getOperand(0);
1899 SDValue VAListPtr = Node->getOperand(1);
1900 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1903 assert(!Subtarget.isPPC64() && "LowerVAARG is PPC32 only");
1906 SDValue GprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1907 VAListPtr, MachinePointerInfo(SV), MVT::i8,
1908 false, false, false, 0);
1909 InChain = GprIndex.getValue(1);
1911 if (VT == MVT::i64) {
1912 // Check if GprIndex is even
1913 SDValue GprAnd = DAG.getNode(ISD::AND, dl, MVT::i32, GprIndex,
1914 DAG.getConstant(1, MVT::i32));
1915 SDValue CC64 = DAG.getSetCC(dl, MVT::i32, GprAnd,
1916 DAG.getConstant(0, MVT::i32), ISD::SETNE);
1917 SDValue GprIndexPlusOne = DAG.getNode(ISD::ADD, dl, MVT::i32, GprIndex,
1918 DAG.getConstant(1, MVT::i32));
1919 // Align GprIndex to be even if it isn't
1920 GprIndex = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC64, GprIndexPlusOne,
1924 // fpr index is 1 byte after gpr
1925 SDValue FprPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1926 DAG.getConstant(1, MVT::i32));
1929 SDValue FprIndex = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, InChain,
1930 FprPtr, MachinePointerInfo(SV), MVT::i8,
1931 false, false, false, 0);
1932 InChain = FprIndex.getValue(1);
1934 SDValue RegSaveAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1935 DAG.getConstant(8, MVT::i32));
1937 SDValue OverflowAreaPtr = DAG.getNode(ISD::ADD, dl, PtrVT, VAListPtr,
1938 DAG.getConstant(4, MVT::i32));
1941 SDValue OverflowArea = DAG.getLoad(MVT::i32, dl, InChain, OverflowAreaPtr,
1942 MachinePointerInfo(), false, false,
1944 InChain = OverflowArea.getValue(1);
1946 SDValue RegSaveArea = DAG.getLoad(MVT::i32, dl, InChain, RegSaveAreaPtr,
1947 MachinePointerInfo(), false, false,
1949 InChain = RegSaveArea.getValue(1);
1951 // select overflow_area if index > 8
1952 SDValue CC = DAG.getSetCC(dl, MVT::i32, VT.isInteger() ? GprIndex : FprIndex,
1953 DAG.getConstant(8, MVT::i32), ISD::SETLT);
1955 // adjustment constant gpr_index * 4/8
1956 SDValue RegConstant = DAG.getNode(ISD::MUL, dl, MVT::i32,
1957 VT.isInteger() ? GprIndex : FprIndex,
1958 DAG.getConstant(VT.isInteger() ? 4 : 8,
1961 // OurReg = RegSaveArea + RegConstant
1962 SDValue OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, RegSaveArea,
1965 // Floating types are 32 bytes into RegSaveArea
1966 if (VT.isFloatingPoint())
1967 OurReg = DAG.getNode(ISD::ADD, dl, PtrVT, OurReg,
1968 DAG.getConstant(32, MVT::i32));
1970 // increase {f,g}pr_index by 1 (or 2 if VT is i64)
1971 SDValue IndexPlus1 = DAG.getNode(ISD::ADD, dl, MVT::i32,
1972 VT.isInteger() ? GprIndex : FprIndex,
1973 DAG.getConstant(VT == MVT::i64 ? 2 : 1,
1976 InChain = DAG.getTruncStore(InChain, dl, IndexPlus1,
1977 VT.isInteger() ? VAListPtr : FprPtr,
1978 MachinePointerInfo(SV),
1979 MVT::i8, false, false, 0);
1981 // determine if we should load from reg_save_area or overflow_area
1982 SDValue Result = DAG.getNode(ISD::SELECT, dl, PtrVT, CC, OurReg, OverflowArea);
1984 // increase overflow_area by 4/8 if gpr/fpr > 8
1985 SDValue OverflowAreaPlusN = DAG.getNode(ISD::ADD, dl, PtrVT, OverflowArea,
1986 DAG.getConstant(VT.isInteger() ? 4 : 8,
1989 OverflowArea = DAG.getNode(ISD::SELECT, dl, MVT::i32, CC, OverflowArea,
1992 InChain = DAG.getTruncStore(InChain, dl, OverflowArea,
1994 MachinePointerInfo(),
1995 MVT::i32, false, false, 0);
1997 return DAG.getLoad(VT, dl, InChain, Result, MachinePointerInfo(),
1998 false, false, false, 0);
2001 SDValue PPCTargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG,
2002 const PPCSubtarget &Subtarget) const {
2003 assert(!Subtarget.isPPC64() && "LowerVACOPY is PPC32 only");
2005 // We have to copy the entire va_list struct:
2006 // 2*sizeof(char) + 2 Byte alignment + 2*sizeof(char*) = 12 Byte
2007 return DAG.getMemcpy(Op.getOperand(0), Op,
2008 Op.getOperand(1), Op.getOperand(2),
2009 DAG.getConstant(12, MVT::i32), 8, false, true,
2010 MachinePointerInfo(), MachinePointerInfo());
2013 SDValue PPCTargetLowering::LowerADJUST_TRAMPOLINE(SDValue Op,
2014 SelectionDAG &DAG) const {
2015 return Op.getOperand(0);
2018 SDValue PPCTargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
2019 SelectionDAG &DAG) const {
2020 SDValue Chain = Op.getOperand(0);
2021 SDValue Trmp = Op.getOperand(1); // trampoline
2022 SDValue FPtr = Op.getOperand(2); // nested function
2023 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
2026 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2027 bool isPPC64 = (PtrVT == MVT::i64);
2029 DAG.getTargetLoweringInfo().getDataLayout()->getIntPtrType(
2032 TargetLowering::ArgListTy Args;
2033 TargetLowering::ArgListEntry Entry;
2035 Entry.Ty = IntPtrTy;
2036 Entry.Node = Trmp; Args.push_back(Entry);
2038 // TrampSize == (isPPC64 ? 48 : 40);
2039 Entry.Node = DAG.getConstant(isPPC64 ? 48 : 40,
2040 isPPC64 ? MVT::i64 : MVT::i32);
2041 Args.push_back(Entry);
2043 Entry.Node = FPtr; Args.push_back(Entry);
2044 Entry.Node = Nest; Args.push_back(Entry);
2046 // Lower to a call to __trampoline_setup(Trmp, TrampSize, FPtr, ctx_reg)
2047 TargetLowering::CallLoweringInfo CLI(DAG);
2048 CLI.setDebugLoc(dl).setChain(Chain)
2049 .setCallee(CallingConv::C, Type::getVoidTy(*DAG.getContext()),
2050 DAG.getExternalSymbol("__trampoline_setup", PtrVT),
2051 std::move(Args), 0);
2053 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2054 return CallResult.second;
2057 SDValue PPCTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG,
2058 const PPCSubtarget &Subtarget) const {
2059 MachineFunction &MF = DAG.getMachineFunction();
2060 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2064 if (Subtarget.isDarwinABI() || Subtarget.isPPC64()) {
2065 // vastart just stores the address of the VarArgsFrameIndex slot into the
2066 // memory location argument.
2067 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2068 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2069 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2070 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
2071 MachinePointerInfo(SV),
2075 // For the 32-bit SVR4 ABI we follow the layout of the va_list struct.
2076 // We suppose the given va_list is already allocated.
2079 // char gpr; /* index into the array of 8 GPRs
2080 // * stored in the register save area
2081 // * gpr=0 corresponds to r3,
2082 // * gpr=1 to r4, etc.
2084 // char fpr; /* index into the array of 8 FPRs
2085 // * stored in the register save area
2086 // * fpr=0 corresponds to f1,
2087 // * fpr=1 to f2, etc.
2089 // char *overflow_arg_area;
2090 // /* location on stack that holds
2091 // * the next overflow argument
2093 // char *reg_save_area;
2094 // /* where r3:r10 and f1:f8 (if saved)
2100 SDValue ArgGPR = DAG.getConstant(FuncInfo->getVarArgsNumGPR(), MVT::i32);
2101 SDValue ArgFPR = DAG.getConstant(FuncInfo->getVarArgsNumFPR(), MVT::i32);
2104 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2106 SDValue StackOffsetFI = DAG.getFrameIndex(FuncInfo->getVarArgsStackOffset(),
2108 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2111 uint64_t FrameOffset = PtrVT.getSizeInBits()/8;
2112 SDValue ConstFrameOffset = DAG.getConstant(FrameOffset, PtrVT);
2114 uint64_t StackOffset = PtrVT.getSizeInBits()/8 - 1;
2115 SDValue ConstStackOffset = DAG.getConstant(StackOffset, PtrVT);
2117 uint64_t FPROffset = 1;
2118 SDValue ConstFPROffset = DAG.getConstant(FPROffset, PtrVT);
2120 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2122 // Store first byte : number of int regs
2123 SDValue firstStore = DAG.getTruncStore(Op.getOperand(0), dl, ArgGPR,
2125 MachinePointerInfo(SV),
2126 MVT::i8, false, false, 0);
2127 uint64_t nextOffset = FPROffset;
2128 SDValue nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, Op.getOperand(1),
2131 // Store second byte : number of float regs
2132 SDValue secondStore =
2133 DAG.getTruncStore(firstStore, dl, ArgFPR, nextPtr,
2134 MachinePointerInfo(SV, nextOffset), MVT::i8,
2136 nextOffset += StackOffset;
2137 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstStackOffset);
2139 // Store second word : arguments given on stack
2140 SDValue thirdStore =
2141 DAG.getStore(secondStore, dl, StackOffsetFI, nextPtr,
2142 MachinePointerInfo(SV, nextOffset),
2144 nextOffset += FrameOffset;
2145 nextPtr = DAG.getNode(ISD::ADD, dl, PtrVT, nextPtr, ConstFrameOffset);
2147 // Store third word : arguments given in registers
2148 return DAG.getStore(thirdStore, dl, FR, nextPtr,
2149 MachinePointerInfo(SV, nextOffset),
2154 #include "PPCGenCallingConv.inc"
2156 // Function whose sole purpose is to kill compiler warnings
2157 // stemming from unused functions included from PPCGenCallingConv.inc.
2158 CCAssignFn *PPCTargetLowering::useFastISelCCs(unsigned Flag) const {
2159 return Flag ? CC_PPC64_ELF_FIS : RetCC_PPC64_ELF_FIS;
2162 bool llvm::CC_PPC32_SVR4_Custom_Dummy(unsigned &ValNo, MVT &ValVT, MVT &LocVT,
2163 CCValAssign::LocInfo &LocInfo,
2164 ISD::ArgFlagsTy &ArgFlags,
2169 bool llvm::CC_PPC32_SVR4_Custom_AlignArgRegs(unsigned &ValNo, MVT &ValVT,
2171 CCValAssign::LocInfo &LocInfo,
2172 ISD::ArgFlagsTy &ArgFlags,
2174 static const MCPhysReg ArgRegs[] = {
2175 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2176 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2178 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2180 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2182 // Skip one register if the first unallocated register has an even register
2183 // number and there are still argument registers available which have not been
2184 // allocated yet. RegNum is actually an index into ArgRegs, which means we
2185 // need to skip a register if RegNum is odd.
2186 if (RegNum != NumArgRegs && RegNum % 2 == 1) {
2187 State.AllocateReg(ArgRegs[RegNum]);
2190 // Always return false here, as this function only makes sure that the first
2191 // unallocated register has an odd register number and does not actually
2192 // allocate a register for the current argument.
2196 bool llvm::CC_PPC32_SVR4_Custom_AlignFPArgRegs(unsigned &ValNo, MVT &ValVT,
2198 CCValAssign::LocInfo &LocInfo,
2199 ISD::ArgFlagsTy &ArgFlags,
2201 static const MCPhysReg ArgRegs[] = {
2202 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2206 const unsigned NumArgRegs = array_lengthof(ArgRegs);
2208 unsigned RegNum = State.getFirstUnallocated(ArgRegs, NumArgRegs);
2210 // If there is only one Floating-point register left we need to put both f64
2211 // values of a split ppc_fp128 value on the stack.
2212 if (RegNum != NumArgRegs && ArgRegs[RegNum] == PPC::F8) {
2213 State.AllocateReg(ArgRegs[RegNum]);
2216 // Always return false here, as this function only makes sure that the two f64
2217 // values a ppc_fp128 value is split into are both passed in registers or both
2218 // passed on the stack and does not actually allocate a register for the
2219 // current argument.
2223 /// GetFPR - Get the set of FP registers that should be allocated for arguments,
2225 static const MCPhysReg *GetFPR() {
2226 static const MCPhysReg FPR[] = {
2227 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2228 PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
2234 /// CalculateStackSlotSize - Calculates the size reserved for this argument on
2236 static unsigned CalculateStackSlotSize(EVT ArgVT, ISD::ArgFlagsTy Flags,
2237 unsigned PtrByteSize) {
2238 unsigned ArgSize = ArgVT.getStoreSize();
2239 if (Flags.isByVal())
2240 ArgSize = Flags.getByValSize();
2242 // Round up to multiples of the pointer size, except for array members,
2243 // which are always packed.
2244 if (!Flags.isInConsecutiveRegs())
2245 ArgSize = ((ArgSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2250 /// CalculateStackSlotAlignment - Calculates the alignment of this argument
2252 static unsigned CalculateStackSlotAlignment(EVT ArgVT, EVT OrigVT,
2253 ISD::ArgFlagsTy Flags,
2254 unsigned PtrByteSize) {
2255 unsigned Align = PtrByteSize;
2257 // Altivec parameters are padded to a 16 byte boundary.
2258 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2259 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2260 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2263 // ByVal parameters are aligned as requested.
2264 if (Flags.isByVal()) {
2265 unsigned BVAlign = Flags.getByValAlign();
2266 if (BVAlign > PtrByteSize) {
2267 if (BVAlign % PtrByteSize != 0)
2269 "ByVal alignment is not a multiple of the pointer size");
2275 // Array members are always packed to their original alignment.
2276 if (Flags.isInConsecutiveRegs()) {
2277 // If the array member was split into multiple registers, the first
2278 // needs to be aligned to the size of the full type. (Except for
2279 // ppcf128, which is only aligned as its f64 components.)
2280 if (Flags.isSplit() && OrigVT != MVT::ppcf128)
2281 Align = OrigVT.getStoreSize();
2283 Align = ArgVT.getStoreSize();
2289 /// CalculateStackSlotUsed - Return whether this argument will use its
2290 /// stack slot (instead of being passed in registers). ArgOffset,
2291 /// AvailableFPRs, and AvailableVRs must hold the current argument
2292 /// position, and will be updated to account for this argument.
2293 static bool CalculateStackSlotUsed(EVT ArgVT, EVT OrigVT,
2294 ISD::ArgFlagsTy Flags,
2295 unsigned PtrByteSize,
2296 unsigned LinkageSize,
2297 unsigned ParamAreaSize,
2298 unsigned &ArgOffset,
2299 unsigned &AvailableFPRs,
2300 unsigned &AvailableVRs) {
2301 bool UseMemory = false;
2303 // Respect alignment of argument on the stack.
2305 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
2306 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2307 // If there's no space left in the argument save area, we must
2308 // use memory (this check also catches zero-sized arguments).
2309 if (ArgOffset >= LinkageSize + ParamAreaSize)
2312 // Allocate argument on the stack.
2313 ArgOffset += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
2314 if (Flags.isInConsecutiveRegsLast())
2315 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2316 // If we overran the argument save area, we must use memory
2317 // (this check catches arguments passed partially in memory)
2318 if (ArgOffset > LinkageSize + ParamAreaSize)
2321 // However, if the argument is actually passed in an FPR or a VR,
2322 // we don't use memory after all.
2323 if (!Flags.isByVal()) {
2324 if (ArgVT == MVT::f32 || ArgVT == MVT::f64)
2325 if (AvailableFPRs > 0) {
2329 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
2330 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
2331 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64)
2332 if (AvailableVRs > 0) {
2341 /// EnsureStackAlignment - Round stack frame size up from NumBytes to
2342 /// ensure minimum alignment required for target.
2343 static unsigned EnsureStackAlignment(const TargetMachine &Target,
2344 unsigned NumBytes) {
2345 unsigned TargetAlign =
2346 Target.getSubtargetImpl()->getFrameLowering()->getStackAlignment();
2347 unsigned AlignMask = TargetAlign - 1;
2348 NumBytes = (NumBytes + AlignMask) & ~AlignMask;
2353 PPCTargetLowering::LowerFormalArguments(SDValue Chain,
2354 CallingConv::ID CallConv, bool isVarArg,
2355 const SmallVectorImpl<ISD::InputArg>
2357 SDLoc dl, SelectionDAG &DAG,
2358 SmallVectorImpl<SDValue> &InVals)
2360 if (Subtarget.isSVR4ABI()) {
2361 if (Subtarget.isPPC64())
2362 return LowerFormalArguments_64SVR4(Chain, CallConv, isVarArg, Ins,
2365 return LowerFormalArguments_32SVR4(Chain, CallConv, isVarArg, Ins,
2368 return LowerFormalArguments_Darwin(Chain, CallConv, isVarArg, Ins,
2374 PPCTargetLowering::LowerFormalArguments_32SVR4(
2376 CallingConv::ID CallConv, bool isVarArg,
2377 const SmallVectorImpl<ISD::InputArg>
2379 SDLoc dl, SelectionDAG &DAG,
2380 SmallVectorImpl<SDValue> &InVals) const {
2382 // 32-bit SVR4 ABI Stack Frame Layout:
2383 // +-----------------------------------+
2384 // +--> | Back chain |
2385 // | +-----------------------------------+
2386 // | | Floating-point register save area |
2387 // | +-----------------------------------+
2388 // | | General register save area |
2389 // | +-----------------------------------+
2390 // | | CR save word |
2391 // | +-----------------------------------+
2392 // | | VRSAVE save word |
2393 // | +-----------------------------------+
2394 // | | Alignment padding |
2395 // | +-----------------------------------+
2396 // | | Vector register save area |
2397 // | +-----------------------------------+
2398 // | | Local variable space |
2399 // | +-----------------------------------+
2400 // | | Parameter list area |
2401 // | +-----------------------------------+
2402 // | | LR save word |
2403 // | +-----------------------------------+
2404 // SP--> +--- | Back chain |
2405 // +-----------------------------------+
2408 // System V Application Binary Interface PowerPC Processor Supplement
2409 // AltiVec Technology Programming Interface Manual
2411 MachineFunction &MF = DAG.getMachineFunction();
2412 MachineFrameInfo *MFI = MF.getFrameInfo();
2413 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2415 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2416 // Potential tail calls could cause overwriting of argument stack slots.
2417 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2418 (CallConv == CallingConv::Fast));
2419 unsigned PtrByteSize = 4;
2421 // Assign locations to all of the incoming arguments.
2422 SmallVector<CCValAssign, 16> ArgLocs;
2423 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2426 // Reserve space for the linkage area on the stack.
2427 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(false, false, false);
2428 CCInfo.AllocateStack(LinkageSize, PtrByteSize);
2430 CCInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4);
2432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2433 CCValAssign &VA = ArgLocs[i];
2435 // Arguments stored in registers.
2436 if (VA.isRegLoc()) {
2437 const TargetRegisterClass *RC;
2438 EVT ValVT = VA.getValVT();
2440 switch (ValVT.getSimpleVT().SimpleTy) {
2442 llvm_unreachable("ValVT not supported by formal arguments Lowering");
2445 RC = &PPC::GPRCRegClass;
2448 RC = &PPC::F4RCRegClass;
2451 if (Subtarget.hasVSX())
2452 RC = &PPC::VSFRCRegClass;
2454 RC = &PPC::F8RCRegClass;
2460 RC = &PPC::VRRCRegClass;
2464 RC = &PPC::VSHRCRegClass;
2468 // Transform the arguments stored in physical registers into virtual ones.
2469 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2470 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2471 ValVT == MVT::i1 ? MVT::i32 : ValVT);
2473 if (ValVT == MVT::i1)
2474 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgValue);
2476 InVals.push_back(ArgValue);
2478 // Argument stored in memory.
2479 assert(VA.isMemLoc());
2481 unsigned ArgSize = VA.getLocVT().getStoreSize();
2482 int FI = MFI->CreateFixedObject(ArgSize, VA.getLocMemOffset(),
2485 // Create load nodes to retrieve arguments from the stack.
2486 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2487 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2488 MachinePointerInfo(),
2489 false, false, false, 0));
2493 // Assign locations to all of the incoming aggregate by value arguments.
2494 // Aggregates passed by value are stored in the local variable space of the
2495 // caller's stack frame, right above the parameter list area.
2496 SmallVector<CCValAssign, 16> ByValArgLocs;
2497 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2498 ByValArgLocs, *DAG.getContext());
2500 // Reserve stack space for the allocations in CCInfo.
2501 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
2503 CCByValInfo.AnalyzeFormalArguments(Ins, CC_PPC32_SVR4_ByVal);
2505 // Area that is at least reserved in the caller of this function.
2506 unsigned MinReservedArea = CCByValInfo.getNextStackOffset();
2507 MinReservedArea = std::max(MinReservedArea, LinkageSize);
2509 // Set the size that is at least reserved in caller of this function. Tail
2510 // call optimized function's reserved stack space needs to be aligned so that
2511 // taking the difference between two stack areas will result in an aligned
2513 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2514 FuncInfo->setMinReservedArea(MinReservedArea);
2516 SmallVector<SDValue, 8> MemOps;
2518 // If the function takes variable number of arguments, make a frame index for
2519 // the start of the first vararg value... for expansion of llvm.va_start.
2521 static const MCPhysReg GPArgRegs[] = {
2522 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2523 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2525 const unsigned NumGPArgRegs = array_lengthof(GPArgRegs);
2527 static const MCPhysReg FPArgRegs[] = {
2528 PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
2531 unsigned NumFPArgRegs = array_lengthof(FPArgRegs);
2532 if (DisablePPCFloatInVariadic)
2535 FuncInfo->setVarArgsNumGPR(CCInfo.getFirstUnallocated(GPArgRegs,
2537 FuncInfo->setVarArgsNumFPR(CCInfo.getFirstUnallocated(FPArgRegs,
2540 // Make room for NumGPArgRegs and NumFPArgRegs.
2541 int Depth = NumGPArgRegs * PtrVT.getSizeInBits()/8 +
2542 NumFPArgRegs * MVT(MVT::f64).getSizeInBits()/8;
2544 FuncInfo->setVarArgsStackOffset(
2545 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
2546 CCInfo.getNextStackOffset(), true));
2548 FuncInfo->setVarArgsFrameIndex(MFI->CreateStackObject(Depth, 8, false));
2549 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2551 // The fixed integer arguments of a variadic function are stored to the
2552 // VarArgsFrameIndex on the stack so that they may be loaded by deferencing
2553 // the result of va_next.
2554 for (unsigned GPRIndex = 0; GPRIndex != NumGPArgRegs; ++GPRIndex) {
2555 // Get an existing live-in vreg, or add a new one.
2556 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(GPArgRegs[GPRIndex]);
2558 VReg = MF.addLiveIn(GPArgRegs[GPRIndex], &PPC::GPRCRegClass);
2560 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2561 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2562 MachinePointerInfo(), false, false, 0);
2563 MemOps.push_back(Store);
2564 // Increment the address by four for the next argument to store
2565 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
2566 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2569 // FIXME 32-bit SVR4: We only need to save FP argument registers if CR bit 6
2571 // The double arguments are stored to the VarArgsFrameIndex
2573 for (unsigned FPRIndex = 0; FPRIndex != NumFPArgRegs; ++FPRIndex) {
2574 // Get an existing live-in vreg, or add a new one.
2575 unsigned VReg = MF.getRegInfo().getLiveInVirtReg(FPArgRegs[FPRIndex]);
2577 VReg = MF.addLiveIn(FPArgRegs[FPRIndex], &PPC::F8RCRegClass);
2579 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::f64);
2580 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2581 MachinePointerInfo(), false, false, 0);
2582 MemOps.push_back(Store);
2583 // Increment the address by eight for the next argument to store
2584 SDValue PtrOff = DAG.getConstant(MVT(MVT::f64).getSizeInBits()/8,
2586 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2590 if (!MemOps.empty())
2591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2596 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2597 // value to MVT::i64 and then truncate to the correct register size.
2599 PPCTargetLowering::extendArgForPPC64(ISD::ArgFlagsTy Flags, EVT ObjectVT,
2600 SelectionDAG &DAG, SDValue ArgVal,
2603 ArgVal = DAG.getNode(ISD::AssertSext, dl, MVT::i64, ArgVal,
2604 DAG.getValueType(ObjectVT));
2605 else if (Flags.isZExt())
2606 ArgVal = DAG.getNode(ISD::AssertZext, dl, MVT::i64, ArgVal,
2607 DAG.getValueType(ObjectVT));
2609 return DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, ArgVal);
2613 PPCTargetLowering::LowerFormalArguments_64SVR4(
2615 CallingConv::ID CallConv, bool isVarArg,
2616 const SmallVectorImpl<ISD::InputArg>
2618 SDLoc dl, SelectionDAG &DAG,
2619 SmallVectorImpl<SDValue> &InVals) const {
2620 // TODO: add description of PPC stack frame format, or at least some docs.
2622 bool isELFv2ABI = Subtarget.isELFv2ABI();
2623 bool isLittleEndian = Subtarget.isLittleEndian();
2624 MachineFunction &MF = DAG.getMachineFunction();
2625 MachineFrameInfo *MFI = MF.getFrameInfo();
2626 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2628 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2629 // Potential tail calls could cause overwriting of argument stack slots.
2630 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2631 (CallConv == CallingConv::Fast));
2632 unsigned PtrByteSize = 8;
2634 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
2637 static const MCPhysReg GPR[] = {
2638 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2639 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2642 static const MCPhysReg *FPR = GetFPR();
2644 static const MCPhysReg VR[] = {
2645 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2646 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2648 static const MCPhysReg VSRH[] = {
2649 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
2650 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
2653 const unsigned Num_GPR_Regs = array_lengthof(GPR);
2654 const unsigned Num_FPR_Regs = 13;
2655 const unsigned Num_VR_Regs = array_lengthof(VR);
2657 // Do a first pass over the arguments to determine whether the ABI
2658 // guarantees that our caller has allocated the parameter save area
2659 // on its stack frame. In the ELFv1 ABI, this is always the case;
2660 // in the ELFv2 ABI, it is true if this is a vararg function or if
2661 // any parameter is located in a stack slot.
2663 bool HasParameterArea = !isELFv2ABI || isVarArg;
2664 unsigned ParamAreaSize = Num_GPR_Regs * PtrByteSize;
2665 unsigned NumBytes = LinkageSize;
2666 unsigned AvailableFPRs = Num_FPR_Regs;
2667 unsigned AvailableVRs = Num_VR_Regs;
2668 for (unsigned i = 0, e = Ins.size(); i != e; ++i)
2669 if (CalculateStackSlotUsed(Ins[i].VT, Ins[i].ArgVT, Ins[i].Flags,
2670 PtrByteSize, LinkageSize, ParamAreaSize,
2671 NumBytes, AvailableFPRs, AvailableVRs))
2672 HasParameterArea = true;
2674 // Add DAG nodes to load the arguments or copy them out of registers. On
2675 // entry to a function on PPC, the arguments start after the linkage area,
2676 // although the first ones are often in registers.
2678 unsigned ArgOffset = LinkageSize;
2679 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
2680 SmallVector<SDValue, 8> MemOps;
2681 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
2682 unsigned CurArgIdx = 0;
2683 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
2685 bool needsLoad = false;
2686 EVT ObjectVT = Ins[ArgNo].VT;
2687 EVT OrigVT = Ins[ArgNo].ArgVT;
2688 unsigned ObjSize = ObjectVT.getStoreSize();
2689 unsigned ArgSize = ObjSize;
2690 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
2691 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
2692 CurArgIdx = Ins[ArgNo].OrigArgIndex;
2694 /* Respect alignment of argument on the stack. */
2696 CalculateStackSlotAlignment(ObjectVT, OrigVT, Flags, PtrByteSize);
2697 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
2698 unsigned CurArgOffset = ArgOffset;
2700 /* Compute GPR index associated with argument offset. */
2701 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2702 GPR_idx = std::min(GPR_idx, Num_GPR_Regs);
2704 // FIXME the codegen can be much improved in some cases.
2705 // We do not have to keep everything in memory.
2706 if (Flags.isByVal()) {
2707 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
2708 ObjSize = Flags.getByValSize();
2709 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2710 // Empty aggregate parameters do not take up registers. Examples:
2714 // etc. However, we have to provide a place-holder in InVals, so
2715 // pretend we have an 8-byte item at the current address for that
2718 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
2719 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2720 InVals.push_back(FIN);
2724 // Create a stack object covering all stack doublewords occupied
2725 // by the argument. If the argument is (fully or partially) on
2726 // the stack, or if the argument is fully in registers but the
2727 // caller has allocated the parameter save anyway, we can refer
2728 // directly to the caller's stack frame. Otherwise, create a
2729 // local copy in our own frame.
2731 if (HasParameterArea ||
2732 ArgSize + ArgOffset > LinkageSize + Num_GPR_Regs * PtrByteSize)
2733 FI = MFI->CreateFixedObject(ArgSize, ArgOffset, false, true);
2735 FI = MFI->CreateStackObject(ArgSize, Align, false);
2736 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2738 // Handle aggregates smaller than 8 bytes.
2739 if (ObjSize < PtrByteSize) {
2740 // The value of the object is its address, which differs from the
2741 // address of the enclosing doubleword on big-endian systems.
2743 if (!isLittleEndian) {
2744 SDValue ArgOff = DAG.getConstant(PtrByteSize - ObjSize, PtrVT);
2745 Arg = DAG.getNode(ISD::ADD, dl, ArgOff.getValueType(), Arg, ArgOff);
2747 InVals.push_back(Arg);
2749 if (GPR_idx != Num_GPR_Regs) {
2750 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2751 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2754 if (ObjSize==1 || ObjSize==2 || ObjSize==4) {
2755 EVT ObjType = (ObjSize == 1 ? MVT::i8 :
2756 (ObjSize == 2 ? MVT::i16 : MVT::i32));
2757 Store = DAG.getTruncStore(Val.getValue(1), dl, Val, Arg,
2758 MachinePointerInfo(FuncArg),
2759 ObjType, false, false, 0);
2761 // For sizes that don't fit a truncating store (3, 5, 6, 7),
2762 // store the whole register as-is to the parameter save area
2764 Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2765 MachinePointerInfo(FuncArg),
2769 MemOps.push_back(Store);
2771 // Whether we copied from a register or not, advance the offset
2772 // into the parameter save area by a full doubleword.
2773 ArgOffset += PtrByteSize;
2777 // The value of the object is its address, which is the address of
2778 // its first stack doubleword.
2779 InVals.push_back(FIN);
2781 // Store whatever pieces of the object are in registers to memory.
2782 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
2783 if (GPR_idx == Num_GPR_Regs)
2786 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2787 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2790 SDValue Off = DAG.getConstant(j, PtrVT);
2791 Addr = DAG.getNode(ISD::ADD, dl, Off.getValueType(), Addr, Off);
2793 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, Addr,
2794 MachinePointerInfo(FuncArg, j),
2796 MemOps.push_back(Store);
2799 ArgOffset += ArgSize;
2803 switch (ObjectVT.getSimpleVT().SimpleTy) {
2804 default: llvm_unreachable("Unhandled argument type!");
2808 // These can be scalar arguments or elements of an integer array type
2809 // passed directly. Clang may use those instead of "byval" aggregate
2810 // types to avoid forcing arguments to memory unnecessarily.
2811 if (GPR_idx != Num_GPR_Regs) {
2812 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2813 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2815 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
2816 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
2817 // value to MVT::i64 and then truncate to the correct register size.
2818 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
2821 ArgSize = PtrByteSize;
2828 // These can be scalar arguments or elements of a float array type
2829 // passed directly. The latter are used to implement ELFv2 homogenous
2830 // float aggregates.
2831 if (FPR_idx != Num_FPR_Regs) {
2834 if (ObjectVT == MVT::f32)
2835 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
2837 VReg = MF.addLiveIn(FPR[FPR_idx], Subtarget.hasVSX() ?
2838 &PPC::VSFRCRegClass :
2839 &PPC::F8RCRegClass);
2841 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2843 } else if (GPR_idx != Num_GPR_Regs) {
2844 // This can only ever happen in the presence of f32 array types,
2845 // since otherwise we never run out of FPRs before running out
2847 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2848 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2850 if (ObjectVT == MVT::f32) {
2851 if ((ArgOffset % PtrByteSize) == (isLittleEndian ? 4 : 0))
2852 ArgVal = DAG.getNode(ISD::SRL, dl, MVT::i64, ArgVal,
2853 DAG.getConstant(32, MVT::i32));
2854 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, ArgVal);
2857 ArgVal = DAG.getNode(ISD::BITCAST, dl, ObjectVT, ArgVal);
2862 // When passing an array of floats, the array occupies consecutive
2863 // space in the argument area; only round up to the next doubleword
2864 // at the end of the array. Otherwise, each float takes 8 bytes.
2865 ArgSize = Flags.isInConsecutiveRegs() ? ObjSize : PtrByteSize;
2866 ArgOffset += ArgSize;
2867 if (Flags.isInConsecutiveRegsLast())
2868 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
2876 // These can be scalar arguments or elements of a vector array type
2877 // passed directly. The latter are used to implement ELFv2 homogenous
2878 // vector aggregates.
2879 if (VR_idx != Num_VR_Regs) {
2880 unsigned VReg = (ObjectVT == MVT::v2f64 || ObjectVT == MVT::v2i64) ?
2881 MF.addLiveIn(VSRH[VR_idx], &PPC::VSHRCRegClass) :
2882 MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
2883 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
2892 // We need to load the argument to a virtual register if we determined
2893 // above that we ran out of physical registers of the appropriate type.
2895 if (ObjSize < ArgSize && !isLittleEndian)
2896 CurArgOffset += ArgSize - ObjSize;
2897 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, isImmutable);
2898 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
2899 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
2900 false, false, false, 0);
2903 InVals.push_back(ArgVal);
2906 // Area that is at least reserved in the caller of this function.
2907 unsigned MinReservedArea;
2908 if (HasParameterArea)
2909 MinReservedArea = std::max(ArgOffset, LinkageSize + 8 * PtrByteSize);
2911 MinReservedArea = LinkageSize;
2913 // Set the size that is at least reserved in caller of this function. Tail
2914 // call optimized functions' reserved stack space needs to be aligned so that
2915 // taking the difference between two stack areas will result in an aligned
2917 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
2918 FuncInfo->setMinReservedArea(MinReservedArea);
2920 // If the function takes variable number of arguments, make a frame index for
2921 // the start of the first vararg value... for expansion of llvm.va_start.
2923 int Depth = ArgOffset;
2925 FuncInfo->setVarArgsFrameIndex(
2926 MFI->CreateFixedObject(PtrByteSize, Depth, true));
2927 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
2929 // If this function is vararg, store any remaining integer argument regs
2930 // to their spots on the stack so that they may be loaded by deferencing the
2931 // result of va_next.
2932 for (GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
2933 GPR_idx < Num_GPR_Regs; ++GPR_idx) {
2934 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
2935 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
2936 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
2937 MachinePointerInfo(), false, false, 0);
2938 MemOps.push_back(Store);
2939 // Increment the address by four for the next argument to store
2940 SDValue PtrOff = DAG.getConstant(PtrByteSize, PtrVT);
2941 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
2945 if (!MemOps.empty())
2946 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2952 PPCTargetLowering::LowerFormalArguments_Darwin(
2954 CallingConv::ID CallConv, bool isVarArg,
2955 const SmallVectorImpl<ISD::InputArg>
2957 SDLoc dl, SelectionDAG &DAG,
2958 SmallVectorImpl<SDValue> &InVals) const {
2959 // TODO: add description of PPC stack frame format, or at least some docs.
2961 MachineFunction &MF = DAG.getMachineFunction();
2962 MachineFrameInfo *MFI = MF.getFrameInfo();
2963 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
2965 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
2966 bool isPPC64 = PtrVT == MVT::i64;
2967 // Potential tail calls could cause overwriting of argument stack slots.
2968 bool isImmutable = !(getTargetMachine().Options.GuaranteedTailCallOpt &&
2969 (CallConv == CallingConv::Fast));
2970 unsigned PtrByteSize = isPPC64 ? 8 : 4;
2972 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
2974 unsigned ArgOffset = LinkageSize;
2975 // Area that is at least reserved in caller of this function.
2976 unsigned MinReservedArea = ArgOffset;
2978 static const MCPhysReg GPR_32[] = { // 32-bit registers.
2979 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
2980 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
2982 static const MCPhysReg GPR_64[] = { // 64-bit registers.
2983 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
2984 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
2987 static const MCPhysReg *FPR = GetFPR();
2989 static const MCPhysReg VR[] = {
2990 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
2991 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
2994 const unsigned Num_GPR_Regs = array_lengthof(GPR_32);
2995 const unsigned Num_FPR_Regs = 13;
2996 const unsigned Num_VR_Regs = array_lengthof( VR);
2998 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
3000 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
3002 // In 32-bit non-varargs functions, the stack space for vectors is after the
3003 // stack space for non-vectors. We do not use this space unless we have
3004 // too many vectors to fit in registers, something that only occurs in
3005 // constructed examples:), but we have to walk the arglist to figure
3006 // that out...for the pathological case, compute VecArgOffset as the
3007 // start of the vector parameter area. Computing VecArgOffset is the
3008 // entire point of the following loop.
3009 unsigned VecArgOffset = ArgOffset;
3010 if (!isVarArg && !isPPC64) {
3011 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e;
3013 EVT ObjectVT = Ins[ArgNo].VT;
3014 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3016 if (Flags.isByVal()) {
3017 // ObjSize is the true size, ArgSize rounded up to multiple of regs.
3018 unsigned ObjSize = Flags.getByValSize();
3020 ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3021 VecArgOffset += ArgSize;
3025 switch(ObjectVT.getSimpleVT().SimpleTy) {
3026 default: llvm_unreachable("Unhandled argument type!");
3032 case MVT::i64: // PPC64
3034 // FIXME: We are guaranteed to be !isPPC64 at this point.
3035 // Does MVT::i64 apply?
3042 // Nothing to do, we're only looking at Nonvector args here.
3047 // We've found where the vector parameter area in memory is. Skip the
3048 // first 12 parameters; these don't use that memory.
3049 VecArgOffset = ((VecArgOffset+15)/16)*16;
3050 VecArgOffset += 12*16;
3052 // Add DAG nodes to load the arguments or copy them out of registers. On
3053 // entry to a function on PPC, the arguments start after the linkage area,
3054 // although the first ones are often in registers.
3056 SmallVector<SDValue, 8> MemOps;
3057 unsigned nAltivecParamsAtEnd = 0;
3058 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
3059 unsigned CurArgIdx = 0;
3060 for (unsigned ArgNo = 0, e = Ins.size(); ArgNo != e; ++ArgNo) {
3062 bool needsLoad = false;
3063 EVT ObjectVT = Ins[ArgNo].VT;
3064 unsigned ObjSize = ObjectVT.getSizeInBits()/8;
3065 unsigned ArgSize = ObjSize;
3066 ISD::ArgFlagsTy Flags = Ins[ArgNo].Flags;
3067 std::advance(FuncArg, Ins[ArgNo].OrigArgIndex - CurArgIdx);
3068 CurArgIdx = Ins[ArgNo].OrigArgIndex;
3070 unsigned CurArgOffset = ArgOffset;
3072 // Varargs or 64 bit Altivec parameters are padded to a 16 byte boundary.
3073 if (ObjectVT==MVT::v4f32 || ObjectVT==MVT::v4i32 ||
3074 ObjectVT==MVT::v8i16 || ObjectVT==MVT::v16i8) {
3075 if (isVarArg || isPPC64) {
3076 MinReservedArea = ((MinReservedArea+15)/16)*16;
3077 MinReservedArea += CalculateStackSlotSize(ObjectVT,
3080 } else nAltivecParamsAtEnd++;
3082 // Calculate min reserved area.
3083 MinReservedArea += CalculateStackSlotSize(Ins[ArgNo].VT,
3087 // FIXME the codegen can be much improved in some cases.
3088 // We do not have to keep everything in memory.
3089 if (Flags.isByVal()) {
3090 // ObjSize is the true size, ArgSize rounded up to multiple of registers.
3091 ObjSize = Flags.getByValSize();
3092 ArgSize = ((ObjSize + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
3093 // Objects of size 1 and 2 are right justified, everything else is
3094 // left justified. This means the memory address is adjusted forwards.
3095 if (ObjSize==1 || ObjSize==2) {
3096 CurArgOffset = CurArgOffset + (4 - ObjSize);
3098 // The value of the object is its address.
3099 int FI = MFI->CreateFixedObject(ObjSize, CurArgOffset, false, true);
3100 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3101 InVals.push_back(FIN);
3102 if (ObjSize==1 || ObjSize==2) {
3103 if (GPR_idx != Num_GPR_Regs) {
3106 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3108 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3109 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3110 EVT ObjType = ObjSize == 1 ? MVT::i8 : MVT::i16;
3111 SDValue Store = DAG.getTruncStore(Val.getValue(1), dl, Val, FIN,
3112 MachinePointerInfo(FuncArg),
3113 ObjType, false, false, 0);
3114 MemOps.push_back(Store);
3118 ArgOffset += PtrByteSize;
3122 for (unsigned j = 0; j < ArgSize; j += PtrByteSize) {
3123 // Store whatever pieces of the object are in registers
3124 // to memory. ArgOffset will be the address of the beginning
3126 if (GPR_idx != Num_GPR_Regs) {
3129 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3131 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3132 int FI = MFI->CreateFixedObject(PtrByteSize, ArgOffset, true);
3133 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3134 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3135 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3136 MachinePointerInfo(FuncArg, j),
3138 MemOps.push_back(Store);
3140 ArgOffset += PtrByteSize;
3142 ArgOffset += ArgSize - (ArgOffset-CurArgOffset);
3149 switch (ObjectVT.getSimpleVT().SimpleTy) {
3150 default: llvm_unreachable("Unhandled argument type!");
3154 if (GPR_idx != Num_GPR_Regs) {
3155 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3156 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3158 if (ObjectVT == MVT::i1)
3159 ArgVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, ArgVal);
3164 ArgSize = PtrByteSize;
3166 // All int arguments reserve stack space in the Darwin ABI.
3167 ArgOffset += PtrByteSize;
3171 case MVT::i64: // PPC64
3172 if (GPR_idx != Num_GPR_Regs) {
3173 unsigned VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3174 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
3176 if (ObjectVT == MVT::i32 || ObjectVT == MVT::i1)
3177 // PPC64 passes i8, i16, and i32 values in i64 registers. Promote
3178 // value to MVT::i64 and then truncate to the correct register size.
3179 ArgVal = extendArgForPPC64(Flags, ObjectVT, DAG, ArgVal, dl);
3184 ArgSize = PtrByteSize;
3186 // All int arguments reserve stack space in the Darwin ABI.
3192 // Every 4 bytes of argument space consumes one of the GPRs available for
3193 // argument passing.
3194 if (GPR_idx != Num_GPR_Regs) {
3196 if (ObjSize == 8 && GPR_idx != Num_GPR_Regs && !isPPC64)
3199 if (FPR_idx != Num_FPR_Regs) {
3202 if (ObjectVT == MVT::f32)
3203 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F4RCRegClass);
3205 VReg = MF.addLiveIn(FPR[FPR_idx], &PPC::F8RCRegClass);
3207 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3213 // All FP arguments reserve stack space in the Darwin ABI.
3214 ArgOffset += isPPC64 ? 8 : ObjSize;
3220 // Note that vector arguments in registers don't reserve stack space,
3221 // except in varargs functions.
3222 if (VR_idx != Num_VR_Regs) {
3223 unsigned VReg = MF.addLiveIn(VR[VR_idx], &PPC::VRRCRegClass);
3224 ArgVal = DAG.getCopyFromReg(Chain, dl, VReg, ObjectVT);
3226 while ((ArgOffset % 16) != 0) {
3227 ArgOffset += PtrByteSize;
3228 if (GPR_idx != Num_GPR_Regs)
3232 GPR_idx = std::min(GPR_idx+4, Num_GPR_Regs); // FIXME correct for ppc64?
3236 if (!isVarArg && !isPPC64) {
3237 // Vectors go after all the nonvectors.
3238 CurArgOffset = VecArgOffset;
3241 // Vectors are aligned.
3242 ArgOffset = ((ArgOffset+15)/16)*16;
3243 CurArgOffset = ArgOffset;
3251 // We need to load the argument to a virtual register if we determined above
3252 // that we ran out of physical registers of the appropriate type.
3254 int FI = MFI->CreateFixedObject(ObjSize,
3255 CurArgOffset + (ArgSize - ObjSize),
3257 SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3258 ArgVal = DAG.getLoad(ObjectVT, dl, Chain, FIN, MachinePointerInfo(),
3259 false, false, false, 0);
3262 InVals.push_back(ArgVal);
3265 // Allow for Altivec parameters at the end, if needed.
3266 if (nAltivecParamsAtEnd) {
3267 MinReservedArea = ((MinReservedArea+15)/16)*16;
3268 MinReservedArea += 16*nAltivecParamsAtEnd;
3271 // Area that is at least reserved in the caller of this function.
3272 MinReservedArea = std::max(MinReservedArea, LinkageSize + 8 * PtrByteSize);
3274 // Set the size that is at least reserved in caller of this function. Tail
3275 // call optimized functions' reserved stack space needs to be aligned so that
3276 // taking the difference between two stack areas will result in an aligned
3278 MinReservedArea = EnsureStackAlignment(MF.getTarget(), MinReservedArea);
3279 FuncInfo->setMinReservedArea(MinReservedArea);
3281 // If the function takes variable number of arguments, make a frame index for
3282 // the start of the first vararg value... for expansion of llvm.va_start.
3284 int Depth = ArgOffset;
3286 FuncInfo->setVarArgsFrameIndex(
3287 MFI->CreateFixedObject(PtrVT.getSizeInBits()/8,
3289 SDValue FIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3291 // If this function is vararg, store any remaining integer argument regs
3292 // to their spots on the stack so that they may be loaded by deferencing the
3293 // result of va_next.
3294 for (; GPR_idx != Num_GPR_Regs; ++GPR_idx) {
3298 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::G8RCRegClass);
3300 VReg = MF.addLiveIn(GPR[GPR_idx], &PPC::GPRCRegClass);
3302 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, PtrVT);
3303 SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3304 MachinePointerInfo(), false, false, 0);
3305 MemOps.push_back(Store);
3306 // Increment the address by four for the next argument to store
3307 SDValue PtrOff = DAG.getConstant(PtrVT.getSizeInBits()/8, PtrVT);
3308 FIN = DAG.getNode(ISD::ADD, dl, PtrOff.getValueType(), FIN, PtrOff);
3312 if (!MemOps.empty())
3313 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3318 /// CalculateTailCallSPDiff - Get the amount the stack pointer has to be
3319 /// adjusted to accommodate the arguments for the tailcall.
3320 static int CalculateTailCallSPDiff(SelectionDAG& DAG, bool isTailCall,
3321 unsigned ParamSize) {
3323 if (!isTailCall) return 0;
3325 PPCFunctionInfo *FI = DAG.getMachineFunction().getInfo<PPCFunctionInfo>();
3326 unsigned CallerMinReservedArea = FI->getMinReservedArea();
3327 int SPDiff = (int)CallerMinReservedArea - (int)ParamSize;
3328 // Remember only if the new adjustement is bigger.
3329 if (SPDiff < FI->getTailCallSPDelta())
3330 FI->setTailCallSPDelta(SPDiff);
3335 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3336 /// for tail call optimization. Targets which want to do tail call
3337 /// optimization should implement this function.
3339 PPCTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3340 CallingConv::ID CalleeCC,
3342 const SmallVectorImpl<ISD::InputArg> &Ins,
3343 SelectionDAG& DAG) const {
3344 if (!getTargetMachine().Options.GuaranteedTailCallOpt)
3347 // Variable argument functions are not supported.
3351 MachineFunction &MF = DAG.getMachineFunction();
3352 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
3353 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
3354 // Functions containing by val parameters are not supported.
3355 for (unsigned i = 0; i != Ins.size(); i++) {
3356 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3357 if (Flags.isByVal()) return false;
3360 // Non-PIC/GOT tail calls are supported.
3361 if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
3364 // At the moment we can only do local tail calls (in same module, hidden
3365 // or protected) if we are generating PIC.
3366 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3367 return G->getGlobal()->hasHiddenVisibility()
3368 || G->getGlobal()->hasProtectedVisibility();
3374 /// isCallCompatibleAddress - Return the immediate to use if the specified
3375 /// 32-bit value is representable in the immediate field of a BxA instruction.
3376 static SDNode *isBLACompatibleAddress(SDValue Op, SelectionDAG &DAG) {
3377 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3378 if (!C) return nullptr;
3380 int Addr = C->getZExtValue();
3381 if ((Addr & 3) != 0 || // Low 2 bits are implicitly zero.
3382 SignExtend32<26>(Addr) != Addr)
3383 return nullptr; // Top 6 bits have to be sext of immediate.
3385 return DAG.getConstant((int)C->getZExtValue() >> 2,
3386 DAG.getTargetLoweringInfo().getPointerTy()).getNode();
3391 struct TailCallArgumentInfo {
3396 TailCallArgumentInfo() : FrameIdx(0) {}
3401 /// StoreTailCallArgumentsToStackSlot - Stores arguments to their stack slot.
3403 StoreTailCallArgumentsToStackSlot(SelectionDAG &DAG,
3405 const SmallVectorImpl<TailCallArgumentInfo> &TailCallArgs,
3406 SmallVectorImpl<SDValue> &MemOpChains,
3408 for (unsigned i = 0, e = TailCallArgs.size(); i != e; ++i) {
3409 SDValue Arg = TailCallArgs[i].Arg;
3410 SDValue FIN = TailCallArgs[i].FrameIdxOp;
3411 int FI = TailCallArgs[i].FrameIdx;
3412 // Store relative to framepointer.
3413 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, FIN,
3414 MachinePointerInfo::getFixedStack(FI),
3419 /// EmitTailCallStoreFPAndRetAddr - Move the frame pointer and return address to
3420 /// the appropriate stack slot for the tail call optimized function call.
3421 static SDValue EmitTailCallStoreFPAndRetAddr(SelectionDAG &DAG,
3422 MachineFunction &MF,
3431 // Calculate the new stack slot for the return address.
3432 int SlotSize = isPPC64 ? 8 : 4;
3433 int NewRetAddrLoc = SPDiff + PPCFrameLowering::getReturnSaveOffset(isPPC64,
3435 int NewRetAddr = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3436 NewRetAddrLoc, true);
3437 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3438 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewRetAddr, VT);
3439 Chain = DAG.getStore(Chain, dl, OldRetAddr, NewRetAddrFrIdx,
3440 MachinePointerInfo::getFixedStack(NewRetAddr),
3443 // When using the 32/64-bit SVR4 ABI there is no need to move the FP stack
3444 // slot as the FP is never overwritten.
3447 SPDiff + PPCFrameLowering::getFramePointerSaveOffset(isPPC64, isDarwinABI);
3448 int NewFPIdx = MF.getFrameInfo()->CreateFixedObject(SlotSize, NewFPLoc,
3450 SDValue NewFramePtrIdx = DAG.getFrameIndex(NewFPIdx, VT);
3451 Chain = DAG.getStore(Chain, dl, OldFP, NewFramePtrIdx,
3452 MachinePointerInfo::getFixedStack(NewFPIdx),
3459 /// CalculateTailCallArgDest - Remember Argument for later processing. Calculate
3460 /// the position of the argument.
3462 CalculateTailCallArgDest(SelectionDAG &DAG, MachineFunction &MF, bool isPPC64,
3463 SDValue Arg, int SPDiff, unsigned ArgOffset,
3464 SmallVectorImpl<TailCallArgumentInfo>& TailCallArguments) {
3465 int Offset = ArgOffset + SPDiff;
3466 uint32_t OpSize = (Arg.getValueType().getSizeInBits()+7)/8;
3467 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3468 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
3469 SDValue FIN = DAG.getFrameIndex(FI, VT);
3470 TailCallArgumentInfo Info;
3472 Info.FrameIdxOp = FIN;
3474 TailCallArguments.push_back(Info);
3477 /// EmitTCFPAndRetAddrLoad - Emit load from frame pointer and return address
3478 /// stack slot. Returns the chain as result and the loaded frame pointers in
3479 /// LROpOut/FPOpout. Used when tail calling.
3480 SDValue PPCTargetLowering::EmitTailCallLoadFPAndRetAddr(SelectionDAG & DAG,
3488 // Load the LR and FP stack slot for later adjusting.
3489 EVT VT = Subtarget.isPPC64() ? MVT::i64 : MVT::i32;
3490 LROpOut = getReturnAddrFrameIndex(DAG);
3491 LROpOut = DAG.getLoad(VT, dl, Chain, LROpOut, MachinePointerInfo(),
3492 false, false, false, 0);
3493 Chain = SDValue(LROpOut.getNode(), 1);
3495 // When using the 32/64-bit SVR4 ABI there is no need to load the FP stack
3496 // slot as the FP is never overwritten.
3498 FPOpOut = getFramePointerFrameIndex(DAG);
3499 FPOpOut = DAG.getLoad(VT, dl, Chain, FPOpOut, MachinePointerInfo(),
3500 false, false, false, 0);
3501 Chain = SDValue(FPOpOut.getNode(), 1);
3507 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
3508 /// by "Src" to address "Dst" of size "Size". Alignment information is
3509 /// specified by the specific parameter attribute. The copy will be passed as
3510 /// a byval function parameter.
3511 /// Sometimes what we are copying is the end of a larger object, the part that
3512 /// does not fit in registers.
3514 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
3515 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
3517 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
3518 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
3519 false, false, MachinePointerInfo(),
3520 MachinePointerInfo());
3523 /// LowerMemOpCallTo - Store the argument to the stack or remember it in case of
3526 LowerMemOpCallTo(SelectionDAG &DAG, MachineFunction &MF, SDValue Chain,
3527 SDValue Arg, SDValue PtrOff, int SPDiff,
3528 unsigned ArgOffset, bool isPPC64, bool isTailCall,
3529 bool isVector, SmallVectorImpl<SDValue> &MemOpChains,
3530 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments,
3532 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3537 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
3539 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
3540 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
3541 DAG.getConstant(ArgOffset, PtrVT));
3543 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
3544 MachinePointerInfo(), false, false, 0));
3545 // Calculate and remember argument location.
3546 } else CalculateTailCallArgDest(DAG, MF, isPPC64, Arg, SPDiff, ArgOffset,
3551 void PrepareTailCall(SelectionDAG &DAG, SDValue &InFlag, SDValue &Chain,
3552 SDLoc dl, bool isPPC64, int SPDiff, unsigned NumBytes,
3553 SDValue LROp, SDValue FPOp, bool isDarwinABI,
3554 SmallVectorImpl<TailCallArgumentInfo> &TailCallArguments) {
3555 MachineFunction &MF = DAG.getMachineFunction();
3557 // Emit a sequence of copyto/copyfrom virtual registers for arguments that
3558 // might overwrite each other in case of tail call optimization.
3559 SmallVector<SDValue, 8> MemOpChains2;
3560 // Do not flag preceding copytoreg stuff together with the following stuff.
3562 StoreTailCallArgumentsToStackSlot(DAG, Chain, TailCallArguments,
3564 if (!MemOpChains2.empty())
3565 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3567 // Store the return address to the appropriate stack slot.
3568 Chain = EmitTailCallStoreFPAndRetAddr(DAG, MF, Chain, LROp, FPOp, SPDiff,
3569 isPPC64, isDarwinABI, dl);
3571 // Emit callseq_end just before tailcall node.
3572 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3573 DAG.getIntPtrConstant(0, true), InFlag, dl);
3574 InFlag = Chain.getValue(1);
3577 // Is this global address that of a function that can be called by name? (as
3578 // opposed to something that must hold a descriptor for an indirect call).
3579 static bool isFunctionGlobalAddress(SDValue Callee) {
3580 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3581 if (Callee.getOpcode() == ISD::GlobalTLSAddress ||
3582 Callee.getOpcode() == ISD::TargetGlobalTLSAddress)
3585 return G->getGlobal()->getType()->getElementType()->isFunctionTy();
3592 unsigned PrepareCall(SelectionDAG &DAG, SDValue &Callee, SDValue &InFlag,
3593 SDValue &Chain, SDLoc dl, int SPDiff, bool isTailCall,
3595 SmallVectorImpl<std::pair<unsigned, SDValue> > &RegsToPass,
3596 SmallVectorImpl<SDValue> &Ops, std::vector<EVT> &NodeTys,
3597 const PPCSubtarget &Subtarget) {
3599 bool isPPC64 = Subtarget.isPPC64();
3600 bool isSVR4ABI = Subtarget.isSVR4ABI();
3601 bool isELFv2ABI = Subtarget.isELFv2ABI();
3603 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3604 NodeTys.push_back(MVT::Other); // Returns a chain
3605 NodeTys.push_back(MVT::Glue); // Returns a flag for retval copy to use.
3607 unsigned CallOpc = PPCISD::CALL;
3609 bool needIndirectCall = true;
3610 if (!isSVR4ABI || !isPPC64)
3611 if (SDNode *Dest = isBLACompatibleAddress(Callee, DAG)) {
3612 // If this is an absolute destination address, use the munged value.
3613 Callee = SDValue(Dest, 0);
3614 needIndirectCall = false;
3617 if (isFunctionGlobalAddress(Callee)) {
3618 GlobalAddressSDNode *G = cast<GlobalAddressSDNode>(Callee);
3619 // A call to a TLS address is actually an indirect call to a
3620 // thread-specific pointer.
3621 unsigned OpFlags = 0;
3622 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3623 (Subtarget.getTargetTriple().isMacOSX() &&
3624 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5)) &&
3625 (G->getGlobal()->isDeclaration() ||
3626 G->getGlobal()->isWeakForLinker())) ||
3627 (Subtarget.isTargetELF() && !isPPC64 &&
3628 !G->getGlobal()->hasLocalLinkage() &&
3629 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3630 // PC-relative references to external symbols should go through $stub,
3631 // unless we're building with the leopard linker or later, which
3632 // automatically synthesizes these stubs.
3633 OpFlags = PPCII::MO_PLT_OR_STUB;
3636 // If the callee is a GlobalAddress/ExternalSymbol node (quite common,
3637 // every direct call is) turn it into a TargetGlobalAddress /
3638 // TargetExternalSymbol node so that legalize doesn't hack it.
3639 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
3640 Callee.getValueType(), 0, OpFlags);
3641 needIndirectCall = false;
3644 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3645 unsigned char OpFlags = 0;
3647 if ((DAG.getTarget().getRelocationModel() != Reloc::Static &&
3648 (Subtarget.getTargetTriple().isMacOSX() &&
3649 Subtarget.getTargetTriple().isMacOSXVersionLT(10, 5))) ||
3650 (Subtarget.isTargetELF() && !isPPC64 &&
3651 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3652 // PC-relative references to external symbols should go through $stub,
3653 // unless we're building with the leopard linker or later, which
3654 // automatically synthesizes these stubs.
3655 OpFlags = PPCII::MO_PLT_OR_STUB;
3658 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), Callee.getValueType(),
3660 needIndirectCall = false;
3663 if (needIndirectCall) {
3664 // Otherwise, this is an indirect call. We have to use a MTCTR/BCTRL pair
3665 // to do the call, we can't use PPCISD::CALL.
3666 SDValue MTCTROps[] = {Chain, Callee, InFlag};
3668 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !IsPatchPoint) {
3669 // Function pointers in the 64-bit SVR4 ABI do not point to the function
3670 // entry point, but to the function descriptor (the function entry point
3671 // address is part of the function descriptor though).
3672 // The function descriptor is a three doubleword structure with the
3673 // following fields: function entry point, TOC base address and
3674 // environment pointer.
3675 // Thus for a call through a function pointer, the following actions need
3677 // 1. Save the TOC of the caller in the TOC save area of its stack
3678 // frame (this is done in LowerCall_Darwin() or LowerCall_64SVR4()).
3679 // 2. Load the address of the function entry point from the function
3681 // 3. Load the TOC of the callee from the function descriptor into r2.
3682 // 4. Load the environment pointer from the function descriptor into
3684 // 5. Branch to the function entry point address.
3685 // 6. On return of the callee, the TOC of the caller needs to be
3686 // restored (this is done in FinishCall()).
3688 // All those operations are flagged together to ensure that no other
3689 // operations can be scheduled in between. E.g. without flagging the
3690 // operations together, a TOC access in the caller could be scheduled
3691 // between the load of the callee TOC and the branch to the callee, which
3692 // results in the TOC access going through the TOC of the callee instead
3693 // of going through the TOC of the caller, which leads to incorrect code.
3695 // Load the address of the function entry point from the function
3697 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other, MVT::Glue);
3698 SDValue LoadFuncPtr = DAG.getNode(PPCISD::LOAD, dl, VTs,
3699 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3700 Chain = LoadFuncPtr.getValue(1);
3701 InFlag = LoadFuncPtr.getValue(2);
3703 // Load environment pointer into r11.
3704 // Offset of the environment pointer within the function descriptor.
3705 SDValue PtrOff = DAG.getIntPtrConstant(16);
3707 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, PtrOff);
3708 SDValue LoadEnvPtr = DAG.getNode(PPCISD::LOAD, dl, VTs, Chain, AddPtr,
3710 Chain = LoadEnvPtr.getValue(1);
3711 InFlag = LoadEnvPtr.getValue(2);
3713 SDValue EnvVal = DAG.getCopyToReg(Chain, dl, PPC::X11, LoadEnvPtr,
3715 Chain = EnvVal.getValue(0);
3716 InFlag = EnvVal.getValue(1);
3718 // Load TOC of the callee into r2. We are using a target-specific load
3719 // with r2 hard coded, because the result of a target-independent load
3720 // would never go directly into r2, since r2 is a reserved register (which
3721 // prevents the register allocator from allocating it), resulting in an
3722 // additional register being allocated and an unnecessary move instruction
3724 VTs = DAG.getVTList(MVT::Other, MVT::Glue);
3725 SDValue TOCOff = DAG.getIntPtrConstant(8);
3726 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, Callee, TOCOff);
3727 SDValue LoadTOCPtr = DAG.getNode(PPCISD::LOAD_TOC, dl, VTs, Chain,
3729 Chain = LoadTOCPtr.getValue(0);
3730 InFlag = LoadTOCPtr.getValue(1);
3732 MTCTROps[0] = Chain;
3733 MTCTROps[1] = LoadFuncPtr;
3734 MTCTROps[2] = InFlag;
3737 if (!IsPatchPoint) {
3738 Chain = DAG.getNode(PPCISD::MTCTR, dl, NodeTys,
3739 makeArrayRef(MTCTROps, InFlag.getNode() ? 3 : 2));
3740 InFlag = Chain.getValue(1);
3744 NodeTys.push_back(MVT::Other);
3745 NodeTys.push_back(MVT::Glue);
3746 Ops.push_back(Chain);
3747 CallOpc = PPCISD::BCTRL;
3748 Callee.setNode(nullptr);
3749 // Add use of X11 (holding environment pointer)
3750 if (isSVR4ABI && isPPC64 && !isELFv2ABI && !IsPatchPoint)
3751 Ops.push_back(DAG.getRegister(PPC::X11, PtrVT));
3752 // Add CTR register as callee so a bctr can be emitted later.
3754 Ops.push_back(DAG.getRegister(isPPC64 ? PPC::CTR8 : PPC::CTR, PtrVT));
3757 // If this is a direct call, pass the chain and the callee.
3758 if (Callee.getNode()) {
3759 Ops.push_back(Chain);
3760 Ops.push_back(Callee);
3762 // If this is a call to __tls_get_addr, find the symbol whose address
3763 // is to be taken and add it to the list. This will be used to
3764 // generate __tls_get_addr(<sym>@tlsgd) or __tls_get_addr(<sym>@tlsld).
3765 // We find the symbol by walking the chain to the CopyFromReg, walking
3766 // back from the CopyFromReg to the ADDI_TLSGD_L or ADDI_TLSLD_L, and
3767 // pulling the symbol from that node.
3768 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee))
3769 if (!strcmp(S->getSymbol(), "__tls_get_addr")) {
3770 assert(!needIndirectCall && "Indirect call to __tls_get_addr???");
3771 SDNode *AddI = Chain.getNode()->getOperand(2).getNode();
3772 SDValue TGTAddr = AddI->getOperand(1);
3773 assert(TGTAddr.getNode()->getOpcode() == ISD::TargetGlobalTLSAddress &&
3774 "Didn't find target global TLS address where we expected one");
3775 Ops.push_back(TGTAddr);
3776 CallOpc = PPCISD::CALL_TLS;
3779 // If this is a tail call add stack pointer delta.
3781 Ops.push_back(DAG.getConstant(SPDiff, MVT::i32));
3783 // Add argument registers to the end of the list so that they are known live
3785 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3786 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3787 RegsToPass[i].second.getValueType()));
3789 // Direct calls in the ELFv2 ABI need the TOC register live into the call.
3790 if (Callee.getNode() && isELFv2ABI && !IsPatchPoint)
3791 Ops.push_back(DAG.getRegister(PPC::X2, PtrVT));
3797 bool isLocalCall(const SDValue &Callee)
3799 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
3800 return !G->getGlobal()->isDeclaration() &&
3801 !G->getGlobal()->isWeakForLinker();
3806 PPCTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3807 CallingConv::ID CallConv, bool isVarArg,
3808 const SmallVectorImpl<ISD::InputArg> &Ins,
3809 SDLoc dl, SelectionDAG &DAG,
3810 SmallVectorImpl<SDValue> &InVals) const {
3812 SmallVector<CCValAssign, 16> RVLocs;
3813 CCState CCRetInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3815 CCRetInfo.AnalyzeCallResult(Ins, RetCC_PPC);
3817 // Copy all of the result registers out of their specified physreg.
3818 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3819 CCValAssign &VA = RVLocs[i];
3820 assert(VA.isRegLoc() && "Can only return in registers!");
3822 SDValue Val = DAG.getCopyFromReg(Chain, dl,
3823 VA.getLocReg(), VA.getLocVT(), InFlag);
3824 Chain = Val.getValue(1);
3825 InFlag = Val.getValue(2);
3827 switch (VA.getLocInfo()) {
3828 default: llvm_unreachable("Unknown loc info!");
3829 case CCValAssign::Full: break;
3830 case CCValAssign::AExt:
3831 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3833 case CCValAssign::ZExt:
3834 Val = DAG.getNode(ISD::AssertZext, dl, VA.getLocVT(), Val,
3835 DAG.getValueType(VA.getValVT()));
3836 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3838 case CCValAssign::SExt:
3839 Val = DAG.getNode(ISD::AssertSext, dl, VA.getLocVT(), Val,
3840 DAG.getValueType(VA.getValVT()));
3841 Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
3845 InVals.push_back(Val);
3852 PPCTargetLowering::FinishCall(CallingConv::ID CallConv, SDLoc dl,
3853 bool isTailCall, bool isVarArg, bool IsPatchPoint,
3855 SmallVector<std::pair<unsigned, SDValue>, 8>
3857 SDValue InFlag, SDValue Chain,
3859 int SPDiff, unsigned NumBytes,
3860 const SmallVectorImpl<ISD::InputArg> &Ins,
3861 SmallVectorImpl<SDValue> &InVals) const {
3863 bool isELFv2ABI = Subtarget.isELFv2ABI();
3864 std::vector<EVT> NodeTys;
3865 SmallVector<SDValue, 8> Ops;
3866 unsigned CallOpc = PrepareCall(DAG, Callee, InFlag, Chain, dl, SPDiff,
3867 isTailCall, IsPatchPoint, RegsToPass, Ops,
3868 NodeTys, Subtarget);
3870 // Add implicit use of CR bit 6 for 32-bit SVR4 vararg calls
3871 if (isVarArg && Subtarget.isSVR4ABI() && !Subtarget.isPPC64())
3872 Ops.push_back(DAG.getRegister(PPC::CR1EQ, MVT::i32));
3874 // When performing tail call optimization the callee pops its arguments off
3875 // the stack. Account for this here so these bytes can be pushed back on in
3876 // PPCFrameLowering::eliminateCallFramePseudoInstr.
3877 int BytesCalleePops =
3878 (CallConv == CallingConv::Fast &&
3879 getTargetMachine().Options.GuaranteedTailCallOpt) ? NumBytes : 0;
3881 // Add a register mask operand representing the call-preserved registers.
3882 const TargetRegisterInfo *TRI =
3883 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3884 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3885 assert(Mask && "Missing call preserved mask for calling convention");
3886 Ops.push_back(DAG.getRegisterMask(Mask));
3888 if (InFlag.getNode())
3889 Ops.push_back(InFlag);
3893 assert(((Callee.getOpcode() == ISD::Register &&
3894 cast<RegisterSDNode>(Callee)->getReg() == PPC::CTR) ||
3895 Callee.getOpcode() == ISD::TargetExternalSymbol ||
3896 Callee.getOpcode() == ISD::TargetGlobalAddress ||
3897 isa<ConstantSDNode>(Callee)) &&
3898 "Expecting an global address, external symbol, absolute value or register");
3900 return DAG.getNode(PPCISD::TC_RETURN, dl, MVT::Other, Ops);
3903 // Add a NOP immediately after the branch instruction when using the 64-bit
3904 // SVR4 ABI. At link time, if caller and callee are in a different module and
3905 // thus have a different TOC, the call will be replaced with a call to a stub
3906 // function which saves the current TOC, loads the TOC of the callee and
3907 // branches to the callee. The NOP will be replaced with a load instruction
3908 // which restores the TOC of the caller from the TOC save slot of the current
3909 // stack frame. If caller and callee belong to the same module (and have the
3910 // same TOC), the NOP will remain unchanged.
3912 if (!isTailCall && Subtarget.isSVR4ABI()&& Subtarget.isPPC64()) {
3913 if (CallOpc == PPCISD::BCTRL) {
3914 // This is a call through a function pointer.
3915 // Restore the caller TOC from the save area into R2.
3916 // See PrepareCall() for more information about calls through function
3917 // pointers in the 64-bit SVR4 ABI.
3918 // We are using a target-specific load with r2 hard coded, because the
3919 // result of a target-independent load would never go directly into r2,
3920 // since r2 is a reserved register (which prevents the register allocator
3921 // from allocating it), resulting in an additional register being
3922 // allocated and an unnecessary move instruction being generated.
3923 CallOpc = PPCISD::BCTRL_LOAD_TOC;
3925 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
3926 SDValue StackPtr = DAG.getRegister(PPC::X1, PtrVT);
3927 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
3928 SDValue TOCOff = DAG.getIntPtrConstant(TOCSaveOffset);
3929 SDValue AddTOC = DAG.getNode(ISD::ADD, dl, MVT::i64, StackPtr, TOCOff);
3931 // The address needs to go after the chain input but before the flag (or
3932 // any other variadic arguments).
3933 Ops.insert(std::next(Ops.begin()), AddTOC);
3934 } else if ((CallOpc == PPCISD::CALL) &&
3935 (!isLocalCall(Callee) ||
3936 DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3937 // Otherwise insert NOP for non-local calls.
3938 CallOpc = PPCISD::CALL_NOP;
3939 } else if (CallOpc == PPCISD::CALL_TLS)
3940 // For 64-bit SVR4, TLS calls are always non-local.
3941 CallOpc = PPCISD::CALL_NOP_TLS;
3944 Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
3945 InFlag = Chain.getValue(1);
3947 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
3948 DAG.getIntPtrConstant(BytesCalleePops, true),
3951 InFlag = Chain.getValue(1);
3953 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3954 Ins, dl, DAG, InVals);
3958 PPCTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3959 SmallVectorImpl<SDValue> &InVals) const {
3960 SelectionDAG &DAG = CLI.DAG;
3962 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3963 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3964 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3965 SDValue Chain = CLI.Chain;
3966 SDValue Callee = CLI.Callee;
3967 bool &isTailCall = CLI.IsTailCall;
3968 CallingConv::ID CallConv = CLI.CallConv;
3969 bool isVarArg = CLI.IsVarArg;
3970 bool IsPatchPoint = CLI.IsPatchPoint;
3973 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
3976 if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
3977 report_fatal_error("failed to perform tail call elimination on a call "
3978 "site marked musttail");
3980 if (Subtarget.isSVR4ABI()) {
3981 if (Subtarget.isPPC64())
3982 return LowerCall_64SVR4(Chain, Callee, CallConv, isVarArg,
3983 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
3986 return LowerCall_32SVR4(Chain, Callee, CallConv, isVarArg,
3987 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
3991 return LowerCall_Darwin(Chain, Callee, CallConv, isVarArg,
3992 isTailCall, IsPatchPoint, Outs, OutVals, Ins,
3997 PPCTargetLowering::LowerCall_32SVR4(SDValue Chain, SDValue Callee,
3998 CallingConv::ID CallConv, bool isVarArg,
3999 bool isTailCall, bool IsPatchPoint,
4000 const SmallVectorImpl<ISD::OutputArg> &Outs,
4001 const SmallVectorImpl<SDValue> &OutVals,
4002 const SmallVectorImpl<ISD::InputArg> &Ins,
4003 SDLoc dl, SelectionDAG &DAG,
4004 SmallVectorImpl<SDValue> &InVals) const {
4005 // See PPCTargetLowering::LowerFormalArguments_32SVR4() for a description
4006 // of the 32-bit SVR4 ABI stack frame layout.
4008 assert((CallConv == CallingConv::C ||
4009 CallConv == CallingConv::Fast) && "Unknown calling convention!");
4011 unsigned PtrByteSize = 4;
4013 MachineFunction &MF = DAG.getMachineFunction();
4015 // Mark this function as potentially containing a function that contains a
4016 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4017 // and restoring the callers stack pointer in this functions epilog. This is
4018 // done because by tail calling the called function might overwrite the value
4019 // in this function's (MF) stack pointer stack slot 0(SP).
4020 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4021 CallConv == CallingConv::Fast)
4022 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4024 // Count how many bytes are to be pushed on the stack, including the linkage
4025 // area, parameter list area and the part of the local variable space which
4026 // contains copies of aggregates which are passed by value.
4028 // Assign locations to all of the outgoing arguments.
4029 SmallVector<CCValAssign, 16> ArgLocs;
4030 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
4033 // Reserve space for the linkage area on the stack.
4034 CCInfo.AllocateStack(PPCFrameLowering::getLinkageSize(false, false, false),
4038 // Handle fixed and variable vector arguments differently.
4039 // Fixed vector arguments go into registers as long as registers are
4040 // available. Variable vector arguments always go into memory.
4041 unsigned NumArgs = Outs.size();
4043 for (unsigned i = 0; i != NumArgs; ++i) {
4044 MVT ArgVT = Outs[i].VT;
4045 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
4048 if (Outs[i].IsFixed) {
4049 Result = CC_PPC32_SVR4(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags,
4052 Result = CC_PPC32_SVR4_VarArg(i, ArgVT, ArgVT, CCValAssign::Full,
4058 errs() << "Call operand #" << i << " has unhandled type "
4059 << EVT(ArgVT).getEVTString() << "\n";
4061 llvm_unreachable(nullptr);
4065 // All arguments are treated the same.
4066 CCInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4);
4069 // Assign locations to all of the outgoing aggregate by value arguments.
4070 SmallVector<CCValAssign, 16> ByValArgLocs;
4071 CCState CCByValInfo(CallConv, isVarArg, DAG.getMachineFunction(),
4072 ByValArgLocs, *DAG.getContext());
4074 // Reserve stack space for the allocations in CCInfo.
4075 CCByValInfo.AllocateStack(CCInfo.getNextStackOffset(), PtrByteSize);
4077 CCByValInfo.AnalyzeCallOperands(Outs, CC_PPC32_SVR4_ByVal);
4079 // Size of the linkage area, parameter list area and the part of the local
4080 // space variable where copies of aggregates which are passed by value are
4082 unsigned NumBytes = CCByValInfo.getNextStackOffset();
4084 // Calculate by how many bytes the stack has to be adjusted in case of tail
4085 // call optimization.
4086 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4088 // Adjust the stack pointer for the new arguments...
4089 // These operations are automatically eliminated by the prolog/epilog pass
4090 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4092 SDValue CallSeqStart = Chain;
4094 // Load the return address and frame pointer so it can be moved somewhere else
4097 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, false,
4100 // Set up a copy of the stack pointer for use loading and storing any
4101 // arguments that may not fit in the registers available for argument
4103 SDValue StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4105 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4106 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4107 SmallVector<SDValue, 8> MemOpChains;
4109 bool seenFloatArg = false;
4110 // Walk the register/memloc assignments, inserting copies/loads.
4111 for (unsigned i = 0, j = 0, e = ArgLocs.size();
4114 CCValAssign &VA = ArgLocs[i];
4115 SDValue Arg = OutVals[i];
4116 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4118 if (Flags.isByVal()) {
4119 // Argument is an aggregate which is passed by value, thus we need to
4120 // create a copy of it in the local variable space of the current stack
4121 // frame (which is the stack frame of the caller) and pass the address of
4122 // this copy to the callee.
4123 assert((j < ByValArgLocs.size()) && "Index out of bounds!");
4124 CCValAssign &ByValVA = ByValArgLocs[j++];
4125 assert((VA.getValNo() == ByValVA.getValNo()) && "ValNo mismatch!");
4127 // Memory reserved in the local variable space of the callers stack frame.
4128 unsigned LocMemOffset = ByValVA.getLocMemOffset();
4130 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4131 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4133 // Create a copy of the argument in the local area of the current
4135 SDValue MemcpyCall =
4136 CreateCopyOfByValArgument(Arg, PtrOff,
4137 CallSeqStart.getNode()->getOperand(0),
4140 // This must go outside the CALLSEQ_START..END.
4141 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4142 CallSeqStart.getNode()->getOperand(1),
4144 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4145 NewCallSeqStart.getNode());
4146 Chain = CallSeqStart = NewCallSeqStart;
4148 // Pass the address of the aggregate copy on the stack either in a
4149 // physical register or in the parameter list area of the current stack
4150 // frame to the callee.
4154 if (VA.isRegLoc()) {
4155 if (Arg.getValueType() == MVT::i1)
4156 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Arg);
4158 seenFloatArg |= VA.getLocVT().isFloatingPoint();
4159 // Put argument in a physical register.
4160 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
4162 // Put argument in the parameter list area of the current stack frame.
4163 assert(VA.isMemLoc());
4164 unsigned LocMemOffset = VA.getLocMemOffset();
4167 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
4168 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
4170 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
4171 MachinePointerInfo(),
4174 // Calculate and remember argument location.
4175 CalculateTailCallArgDest(DAG, MF, false, Arg, SPDiff, LocMemOffset,
4181 if (!MemOpChains.empty())
4182 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4184 // Build a sequence of copy-to-reg nodes chained together with token chain
4185 // and flag operands which copy the outgoing args into the appropriate regs.
4187 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4188 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4189 RegsToPass[i].second, InFlag);
4190 InFlag = Chain.getValue(1);
4193 // Set CR bit 6 to true if this is a vararg call with floating args passed in
4196 SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
4197 SDValue Ops[] = { Chain, InFlag };
4199 Chain = DAG.getNode(seenFloatArg ? PPCISD::CR6SET : PPCISD::CR6UNSET,
4200 dl, VTs, makeArrayRef(Ops, InFlag.getNode() ? 2 : 1));
4202 InFlag = Chain.getValue(1);
4206 PrepareTailCall(DAG, InFlag, Chain, dl, false, SPDiff, NumBytes, LROp, FPOp,
4207 false, TailCallArguments);
4209 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4210 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4214 // Copy an argument into memory, being careful to do this outside the
4215 // call sequence for the call to which the argument belongs.
4217 PPCTargetLowering::createMemcpyOutsideCallSeq(SDValue Arg, SDValue PtrOff,
4218 SDValue CallSeqStart,
4219 ISD::ArgFlagsTy Flags,
4222 SDValue MemcpyCall = CreateCopyOfByValArgument(Arg, PtrOff,
4223 CallSeqStart.getNode()->getOperand(0),
4225 // The MEMCPY must go outside the CALLSEQ_START..END.
4226 SDValue NewCallSeqStart = DAG.getCALLSEQ_START(MemcpyCall,
4227 CallSeqStart.getNode()->getOperand(1),
4229 DAG.ReplaceAllUsesWith(CallSeqStart.getNode(),
4230 NewCallSeqStart.getNode());
4231 return NewCallSeqStart;
4235 PPCTargetLowering::LowerCall_64SVR4(SDValue Chain, SDValue Callee,
4236 CallingConv::ID CallConv, bool isVarArg,
4237 bool isTailCall, bool IsPatchPoint,
4238 const SmallVectorImpl<ISD::OutputArg> &Outs,
4239 const SmallVectorImpl<SDValue> &OutVals,
4240 const SmallVectorImpl<ISD::InputArg> &Ins,
4241 SDLoc dl, SelectionDAG &DAG,
4242 SmallVectorImpl<SDValue> &InVals) const {
4244 bool isELFv2ABI = Subtarget.isELFv2ABI();
4245 bool isLittleEndian = Subtarget.isLittleEndian();
4246 unsigned NumOps = Outs.size();
4248 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4249 unsigned PtrByteSize = 8;
4251 MachineFunction &MF = DAG.getMachineFunction();
4253 // Mark this function as potentially containing a function that contains a
4254 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4255 // and restoring the callers stack pointer in this functions epilog. This is
4256 // done because by tail calling the called function might overwrite the value
4257 // in this function's (MF) stack pointer stack slot 0(SP).
4258 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4259 CallConv == CallingConv::Fast)
4260 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4262 // Count how many bytes are to be pushed on the stack, including the linkage
4263 // area, and parameter passing area. On ELFv1, the linkage area is 48 bytes
4264 // reserved space for [SP][CR][LR][2 x unused][TOC]; on ELFv2, the linkage
4265 // area is 32 bytes reserved space for [SP][CR][LR][TOC].
4266 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(true, false,
4268 unsigned NumBytes = LinkageSize;
4270 // Add up all the space actually used.
4271 for (unsigned i = 0; i != NumOps; ++i) {
4272 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4273 EVT ArgVT = Outs[i].VT;
4274 EVT OrigVT = Outs[i].ArgVT;
4276 /* Respect alignment of argument on the stack. */
4278 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4279 NumBytes = ((NumBytes + Align - 1) / Align) * Align;
4281 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4282 if (Flags.isInConsecutiveRegsLast())
4283 NumBytes = ((NumBytes + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4286 unsigned NumBytesActuallyUsed = NumBytes;
4288 // The prolog code of the callee may store up to 8 GPR argument registers to
4289 // the stack, allowing va_start to index over them in memory if its varargs.
4290 // Because we cannot tell if this is needed on the caller side, we have to
4291 // conservatively assume that it is needed. As such, make sure we have at
4292 // least enough stack space for the caller to store the 8 GPRs.
4293 // FIXME: On ELFv2, it may be unnecessary to allocate the parameter area.
4294 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4296 // Tail call needs the stack to be aligned.
4297 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4298 CallConv == CallingConv::Fast)
4299 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4301 // Calculate by how many bytes the stack has to be adjusted in case of tail
4302 // call optimization.
4303 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4305 // To protect arguments on the stack from being clobbered in a tail call,
4306 // force all the loads to happen before doing any other lowering.
4308 Chain = DAG.getStackArgumentTokenFactor(Chain);
4310 // Adjust the stack pointer for the new arguments...
4311 // These operations are automatically eliminated by the prolog/epilog pass
4312 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4314 SDValue CallSeqStart = Chain;
4316 // Load the return address and frame pointer so it can be move somewhere else
4319 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4322 // Set up a copy of the stack pointer for use loading and storing any
4323 // arguments that may not fit in the registers available for argument
4325 SDValue StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4327 // Figure out which arguments are going to go in registers, and which in
4328 // memory. Also, if this is a vararg function, floating point operations
4329 // must be stored to our stack, and loaded into integer regs as well, if
4330 // any integer regs are available for argument passing.
4331 unsigned ArgOffset = LinkageSize;
4332 unsigned GPR_idx, FPR_idx = 0, VR_idx = 0;
4334 static const MCPhysReg GPR[] = {
4335 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4336 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4338 static const MCPhysReg *FPR = GetFPR();
4340 static const MCPhysReg VR[] = {
4341 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4342 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4344 static const MCPhysReg VSRH[] = {
4345 PPC::VSH2, PPC::VSH3, PPC::VSH4, PPC::VSH5, PPC::VSH6, PPC::VSH7, PPC::VSH8,
4346 PPC::VSH9, PPC::VSH10, PPC::VSH11, PPC::VSH12, PPC::VSH13
4349 const unsigned NumGPRs = array_lengthof(GPR);
4350 const unsigned NumFPRs = 13;
4351 const unsigned NumVRs = array_lengthof(VR);
4353 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4354 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4356 SmallVector<SDValue, 8> MemOpChains;
4357 for (unsigned i = 0; i != NumOps; ++i) {
4358 SDValue Arg = OutVals[i];
4359 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4360 EVT ArgVT = Outs[i].VT;
4361 EVT OrigVT = Outs[i].ArgVT;
4363 /* Respect alignment of argument on the stack. */
4365 CalculateStackSlotAlignment(ArgVT, OrigVT, Flags, PtrByteSize);
4366 ArgOffset = ((ArgOffset + Align - 1) / Align) * Align;
4368 /* Compute GPR index associated with argument offset. */
4369 GPR_idx = (ArgOffset - LinkageSize) / PtrByteSize;
4370 GPR_idx = std::min(GPR_idx, NumGPRs);
4372 // PtrOff will be used to store the current argument to the stack if a
4373 // register cannot be found for it.
4376 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4378 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4380 // Promote integers to 64-bit values.
4381 if (Arg.getValueType() == MVT::i32 || Arg.getValueType() == MVT::i1) {
4382 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4383 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4384 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4387 // FIXME memcpy is used way more than necessary. Correctness first.
4388 // Note: "by value" is code for passing a structure by value, not
4390 if (Flags.isByVal()) {
4391 // Note: Size includes alignment padding, so
4392 // struct x { short a; char b; }
4393 // will have Size = 4. With #pragma pack(1), it will have Size = 3.
4394 // These are the proper values we need for right-justifying the
4395 // aggregate in a parameter register.
4396 unsigned Size = Flags.getByValSize();
4398 // An empty aggregate parameter takes up no storage and no
4403 // All aggregates smaller than 8 bytes must be passed right-justified.
4404 if (Size==1 || Size==2 || Size==4) {
4405 EVT VT = (Size==1) ? MVT::i8 : ((Size==2) ? MVT::i16 : MVT::i32);
4406 if (GPR_idx != NumGPRs) {
4407 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4408 MachinePointerInfo(), VT,
4409 false, false, false, 0);
4410 MemOpChains.push_back(Load.getValue(1));
4411 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4413 ArgOffset += PtrByteSize;
4418 if (GPR_idx == NumGPRs && Size < 8) {
4419 SDValue AddPtr = PtrOff;
4420 if (!isLittleEndian) {
4421 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4422 PtrOff.getValueType());
4423 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4425 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4428 ArgOffset += PtrByteSize;
4431 // Copy entire object into memory. There are cases where gcc-generated
4432 // code assumes it is there, even if it could be put entirely into
4433 // registers. (This is not what the doc says.)
4435 // FIXME: The above statement is likely due to a misunderstanding of the
4436 // documents. All arguments must be copied into the parameter area BY
4437 // THE CALLEE in the event that the callee takes the address of any
4438 // formal argument. That has not yet been implemented. However, it is
4439 // reasonable to use the stack area as a staging area for the register
4442 // Skip this for small aggregates, as we will use the same slot for a
4443 // right-justified copy, below.
4445 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4449 // When a register is available, pass a small aggregate right-justified.
4450 if (Size < 8 && GPR_idx != NumGPRs) {
4451 // The easiest way to get this right-justified in a register
4452 // is to copy the structure into the rightmost portion of a
4453 // local variable slot, then load the whole slot into the
4455 // FIXME: The memcpy seems to produce pretty awful code for
4456 // small aggregates, particularly for packed ones.
4457 // FIXME: It would be preferable to use the slot in the
4458 // parameter save area instead of a new local variable.
4459 SDValue AddPtr = PtrOff;
4460 if (!isLittleEndian) {
4461 SDValue Const = DAG.getConstant(8 - Size, PtrOff.getValueType());
4462 AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4464 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4468 // Load the slot into the register.
4469 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, PtrOff,
4470 MachinePointerInfo(),
4471 false, false, false, 0);
4472 MemOpChains.push_back(Load.getValue(1));
4473 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Load));
4475 // Done with this argument.
4476 ArgOffset += PtrByteSize;
4480 // For aggregates larger than PtrByteSize, copy the pieces of the
4481 // object that fit into registers from the parameter save area.
4482 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4483 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4484 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4485 if (GPR_idx != NumGPRs) {
4486 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4487 MachinePointerInfo(),
4488 false, false, false, 0);
4489 MemOpChains.push_back(Load.getValue(1));
4490 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4491 ArgOffset += PtrByteSize;
4493 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4500 switch (Arg.getSimpleValueType().SimpleTy) {
4501 default: llvm_unreachable("Unexpected ValueType for argument!");
4505 // These can be scalar arguments or elements of an integer array type
4506 // passed directly. Clang may use those instead of "byval" aggregate
4507 // types to avoid forcing arguments to memory unnecessarily.
4508 if (GPR_idx != NumGPRs) {
4509 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], Arg));
4511 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4512 true, isTailCall, false, MemOpChains,
4513 TailCallArguments, dl);
4515 ArgOffset += PtrByteSize;
4519 // These can be scalar arguments or elements of a float array type
4520 // passed directly. The latter are used to implement ELFv2 homogenous
4521 // float aggregates.
4523 // Named arguments go into FPRs first, and once they overflow, the
4524 // remaining arguments go into GPRs and then the parameter save area.
4525 // Unnamed arguments for vararg functions always go to GPRs and
4526 // then the parameter save area. For now, put all arguments to vararg
4527 // routines always in both locations (FPR *and* GPR or stack slot).
4528 bool NeedGPROrStack = isVarArg || FPR_idx == NumFPRs;
4530 // First load the argument into the next available FPR.
4531 if (FPR_idx != NumFPRs)
4532 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4534 // Next, load the argument into GPR or stack slot if needed.
4535 if (!NeedGPROrStack)
4537 else if (GPR_idx != NumGPRs) {
4538 // In the non-vararg case, this can only ever happen in the
4539 // presence of f32 array types, since otherwise we never run
4540 // out of FPRs before running out of GPRs.
4543 // Double values are always passed in a single GPR.
4544 if (Arg.getValueType() != MVT::f32) {
4545 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
4547 // Non-array float values are extended and passed in a GPR.
4548 } else if (!Flags.isInConsecutiveRegs()) {
4549 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4550 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4552 // If we have an array of floats, we collect every odd element
4553 // together with its predecessor into one GPR.
4554 } else if (ArgOffset % PtrByteSize != 0) {
4556 Lo = DAG.getNode(ISD::BITCAST, dl, MVT::i32, OutVals[i - 1]);
4557 Hi = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4558 if (!isLittleEndian)
4560 ArgVal = DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
4562 // The final element, if even, goes into the first half of a GPR.
4563 } else if (Flags.isInConsecutiveRegsLast()) {
4564 ArgVal = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
4565 ArgVal = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i64, ArgVal);
4566 if (!isLittleEndian)
4567 ArgVal = DAG.getNode(ISD::SHL, dl, MVT::i64, ArgVal,
4568 DAG.getConstant(32, MVT::i32));
4570 // Non-final even elements are skipped; they will be handled
4571 // together the with subsequent argument on the next go-around.
4575 if (ArgVal.getNode())
4576 RegsToPass.push_back(std::make_pair(GPR[GPR_idx], ArgVal));
4578 // Single-precision floating-point values are mapped to the
4579 // second (rightmost) word of the stack doubleword.
4580 if (Arg.getValueType() == MVT::f32 &&
4581 !isLittleEndian && !Flags.isInConsecutiveRegs()) {
4582 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4583 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4586 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4587 true, isTailCall, false, MemOpChains,
4588 TailCallArguments, dl);
4590 // When passing an array of floats, the array occupies consecutive
4591 // space in the argument area; only round up to the next doubleword
4592 // at the end of the array. Otherwise, each float takes 8 bytes.
4593 ArgOffset += (Arg.getValueType() == MVT::f32 &&
4594 Flags.isInConsecutiveRegs()) ? 4 : 8;
4595 if (Flags.isInConsecutiveRegsLast())
4596 ArgOffset = ((ArgOffset + PtrByteSize - 1)/PtrByteSize) * PtrByteSize;
4605 // These can be scalar arguments or elements of a vector array type
4606 // passed directly. The latter are used to implement ELFv2 homogenous
4607 // vector aggregates.
4609 // For a varargs call, named arguments go into VRs or on the stack as
4610 // usual; unnamed arguments always go to the stack or the corresponding
4611 // GPRs when within range. For now, we always put the value in both
4612 // locations (or even all three).
4614 // We could elide this store in the case where the object fits
4615 // entirely in R registers. Maybe later.
4616 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4617 MachinePointerInfo(), false, false, 0);
4618 MemOpChains.push_back(Store);
4619 if (VR_idx != NumVRs) {
4620 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
4621 MachinePointerInfo(),
4622 false, false, false, 0);
4623 MemOpChains.push_back(Load.getValue(1));
4625 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4626 Arg.getSimpleValueType() == MVT::v2i64) ?
4627 VSRH[VR_idx] : VR[VR_idx];
4630 RegsToPass.push_back(std::make_pair(VReg, Load));
4633 for (unsigned i=0; i<16; i+=PtrByteSize) {
4634 if (GPR_idx == NumGPRs)
4636 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
4637 DAG.getConstant(i, PtrVT));
4638 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
4639 false, false, false, 0);
4640 MemOpChains.push_back(Load.getValue(1));
4641 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4646 // Non-varargs Altivec params go into VRs or on the stack.
4647 if (VR_idx != NumVRs) {
4648 unsigned VReg = (Arg.getSimpleValueType() == MVT::v2f64 ||
4649 Arg.getSimpleValueType() == MVT::v2i64) ?
4650 VSRH[VR_idx] : VR[VR_idx];
4653 RegsToPass.push_back(std::make_pair(VReg, Arg));
4655 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4656 true, isTailCall, true, MemOpChains,
4657 TailCallArguments, dl);
4664 assert(NumBytesActuallyUsed == ArgOffset);
4665 (void)NumBytesActuallyUsed;
4667 if (!MemOpChains.empty())
4668 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
4670 // Check if this is an indirect call (MTCTR/BCTRL).
4671 // See PrepareCall() for more information about calls through function
4672 // pointers in the 64-bit SVR4 ABI.
4673 if (!isTailCall && !IsPatchPoint &&
4674 !isFunctionGlobalAddress(Callee) &&
4675 !isa<ExternalSymbolSDNode>(Callee)) {
4676 // Load r2 into a virtual register and store it to the TOC save area.
4677 SDValue Val = DAG.getCopyFromReg(Chain, dl, PPC::X2, MVT::i64);
4678 // TOC save area offset.
4679 unsigned TOCSaveOffset = PPCFrameLowering::getTOCSaveOffset(isELFv2ABI);
4680 SDValue PtrOff = DAG.getIntPtrConstant(TOCSaveOffset);
4681 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4682 Chain = DAG.getStore(Val.getValue(1), dl, Val, AddPtr, MachinePointerInfo(),
4684 // In the ELFv2 ABI, R12 must contain the address of an indirect callee.
4685 // This does not mean the MTCTR instruction must use R12; it's easier
4686 // to model this as an extra parameter, so do that.
4687 if (isELFv2ABI && !IsPatchPoint)
4688 RegsToPass.push_back(std::make_pair((unsigned)PPC::X12, Callee));
4691 // Build a sequence of copy-to-reg nodes chained together with token chain
4692 // and flag operands which copy the outgoing args into the appropriate regs.
4694 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
4695 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
4696 RegsToPass[i].second, InFlag);
4697 InFlag = Chain.getValue(1);
4701 PrepareTailCall(DAG, InFlag, Chain, dl, true, SPDiff, NumBytes, LROp,
4702 FPOp, true, TailCallArguments);
4704 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
4705 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
4710 PPCTargetLowering::LowerCall_Darwin(SDValue Chain, SDValue Callee,
4711 CallingConv::ID CallConv, bool isVarArg,
4712 bool isTailCall, bool IsPatchPoint,
4713 const SmallVectorImpl<ISD::OutputArg> &Outs,
4714 const SmallVectorImpl<SDValue> &OutVals,
4715 const SmallVectorImpl<ISD::InputArg> &Ins,
4716 SDLoc dl, SelectionDAG &DAG,
4717 SmallVectorImpl<SDValue> &InVals) const {
4719 unsigned NumOps = Outs.size();
4721 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
4722 bool isPPC64 = PtrVT == MVT::i64;
4723 unsigned PtrByteSize = isPPC64 ? 8 : 4;
4725 MachineFunction &MF = DAG.getMachineFunction();
4727 // Mark this function as potentially containing a function that contains a
4728 // tail call. As a consequence the frame pointer will be used for dynamicalloc
4729 // and restoring the callers stack pointer in this functions epilog. This is
4730 // done because by tail calling the called function might overwrite the value
4731 // in this function's (MF) stack pointer stack slot 0(SP).
4732 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4733 CallConv == CallingConv::Fast)
4734 MF.getInfo<PPCFunctionInfo>()->setHasFastCall();
4736 // Count how many bytes are to be pushed on the stack, including the linkage
4737 // area, and parameter passing area. We start with 24/48 bytes, which is
4738 // prereserved space for [SP][CR][LR][3 x unused].
4739 unsigned LinkageSize = PPCFrameLowering::getLinkageSize(isPPC64, true,
4741 unsigned NumBytes = LinkageSize;
4743 // Add up all the space actually used.
4744 // In 32-bit non-varargs calls, Altivec parameters all go at the end; usually
4745 // they all go in registers, but we must reserve stack space for them for
4746 // possible use by the caller. In varargs or 64-bit calls, parameters are
4747 // assigned stack space in order, with padding so Altivec parameters are
4749 unsigned nAltivecParamsAtEnd = 0;
4750 for (unsigned i = 0; i != NumOps; ++i) {
4751 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4752 EVT ArgVT = Outs[i].VT;
4753 // Varargs Altivec parameters are padded to a 16 byte boundary.
4754 if (ArgVT == MVT::v4f32 || ArgVT == MVT::v4i32 ||
4755 ArgVT == MVT::v8i16 || ArgVT == MVT::v16i8 ||
4756 ArgVT == MVT::v2f64 || ArgVT == MVT::v2i64) {
4757 if (!isVarArg && !isPPC64) {
4758 // Non-varargs Altivec parameters go after all the non-Altivec
4759 // parameters; handle those later so we know how much padding we need.
4760 nAltivecParamsAtEnd++;
4763 // Varargs and 64-bit Altivec parameters are padded to 16 byte boundary.
4764 NumBytes = ((NumBytes+15)/16)*16;
4766 NumBytes += CalculateStackSlotSize(ArgVT, Flags, PtrByteSize);
4769 // Allow for Altivec parameters at the end, if needed.
4770 if (nAltivecParamsAtEnd) {
4771 NumBytes = ((NumBytes+15)/16)*16;
4772 NumBytes += 16*nAltivecParamsAtEnd;
4775 // The prolog code of the callee may store up to 8 GPR argument registers to
4776 // the stack, allowing va_start to index over them in memory if its varargs.
4777 // Because we cannot tell if this is needed on the caller side, we have to
4778 // conservatively assume that it is needed. As such, make sure we have at
4779 // least enough stack space for the caller to store the 8 GPRs.
4780 NumBytes = std::max(NumBytes, LinkageSize + 8 * PtrByteSize);
4782 // Tail call needs the stack to be aligned.
4783 if (getTargetMachine().Options.GuaranteedTailCallOpt &&
4784 CallConv == CallingConv::Fast)
4785 NumBytes = EnsureStackAlignment(MF.getTarget(), NumBytes);
4787 // Calculate by how many bytes the stack has to be adjusted in case of tail
4788 // call optimization.
4789 int SPDiff = CalculateTailCallSPDiff(DAG, isTailCall, NumBytes);
4791 // To protect arguments on the stack from being clobbered in a tail call,
4792 // force all the loads to happen before doing any other lowering.
4794 Chain = DAG.getStackArgumentTokenFactor(Chain);
4796 // Adjust the stack pointer for the new arguments...
4797 // These operations are automatically eliminated by the prolog/epilog pass
4798 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true),
4800 SDValue CallSeqStart = Chain;
4802 // Load the return address and frame pointer so it can be move somewhere else
4805 Chain = EmitTailCallLoadFPAndRetAddr(DAG, SPDiff, Chain, LROp, FPOp, true,
4808 // Set up a copy of the stack pointer for use loading and storing any
4809 // arguments that may not fit in the registers available for argument
4813 StackPtr = DAG.getRegister(PPC::X1, MVT::i64);
4815 StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
4817 // Figure out which arguments are going to go in registers, and which in
4818 // memory. Also, if this is a vararg function, floating point operations
4819 // must be stored to our stack, and loaded into integer regs as well, if
4820 // any integer regs are available for argument passing.
4821 unsigned ArgOffset = LinkageSize;
4822 unsigned GPR_idx = 0, FPR_idx = 0, VR_idx = 0;
4824 static const MCPhysReg GPR_32[] = { // 32-bit registers.
4825 PPC::R3, PPC::R4, PPC::R5, PPC::R6,
4826 PPC::R7, PPC::R8, PPC::R9, PPC::R10,
4828 static const MCPhysReg GPR_64[] = { // 64-bit registers.
4829 PPC::X3, PPC::X4, PPC::X5, PPC::X6,
4830 PPC::X7, PPC::X8, PPC::X9, PPC::X10,
4832 static const MCPhysReg *FPR = GetFPR();
4834 static const MCPhysReg VR[] = {
4835 PPC::V2, PPC::V3, PPC::V4, PPC::V5, PPC::V6, PPC::V7, PPC::V8,
4836 PPC::V9, PPC::V10, PPC::V11, PPC::V12, PPC::V13
4838 const unsigned NumGPRs = array_lengthof(GPR_32);
4839 const unsigned NumFPRs = 13;
4840 const unsigned NumVRs = array_lengthof(VR);
4842 const MCPhysReg *GPR = isPPC64 ? GPR_64 : GPR_32;
4844 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
4845 SmallVector<TailCallArgumentInfo, 8> TailCallArguments;
4847 SmallVector<SDValue, 8> MemOpChains;
4848 for (unsigned i = 0; i != NumOps; ++i) {
4849 SDValue Arg = OutVals[i];
4850 ISD::ArgFlagsTy Flags = Outs[i].Flags;
4852 // PtrOff will be used to store the current argument to the stack if a
4853 // register cannot be found for it.
4856 PtrOff = DAG.getConstant(ArgOffset, StackPtr.getValueType());
4858 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, PtrOff);
4860 // On PPC64, promote integers to 64-bit values.
4861 if (isPPC64 && Arg.getValueType() == MVT::i32) {
4862 // FIXME: Should this use ANY_EXTEND if neither sext nor zext?
4863 unsigned ExtOp = Flags.isSExt() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4864 Arg = DAG.getNode(ExtOp, dl, MVT::i64, Arg);
4867 // FIXME memcpy is used way more than necessary. Correctness first.
4868 // Note: "by value" is code for passing a structure by value, not
4870 if (Flags.isByVal()) {
4871 unsigned Size = Flags.getByValSize();
4872 // Very small objects are passed right-justified. Everything else is
4873 // passed left-justified.
4874 if (Size==1 || Size==2) {
4875 EVT VT = (Size==1) ? MVT::i8 : MVT::i16;
4876 if (GPR_idx != NumGPRs) {
4877 SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, PtrVT, Chain, Arg,
4878 MachinePointerInfo(), VT,
4879 false, false, false, 0);
4880 MemOpChains.push_back(Load.getValue(1));
4881 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4883 ArgOffset += PtrByteSize;
4885 SDValue Const = DAG.getConstant(PtrByteSize - Size,
4886 PtrOff.getValueType());
4887 SDValue AddPtr = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, Const);
4888 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, AddPtr,
4891 ArgOffset += PtrByteSize;
4895 // Copy entire object into memory. There are cases where gcc-generated
4896 // code assumes it is there, even if it could be put entirely into
4897 // registers. (This is not what the doc says.)
4898 Chain = CallSeqStart = createMemcpyOutsideCallSeq(Arg, PtrOff,
4902 // For small aggregates (Darwin only) and aggregates >= PtrByteSize,
4903 // copy the pieces of the object that fit into registers from the
4904 // parameter save area.
4905 for (unsigned j=0; j<Size; j+=PtrByteSize) {
4906 SDValue Const = DAG.getConstant(j, PtrOff.getValueType());
4907 SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
4908 if (GPR_idx != NumGPRs) {
4909 SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
4910 MachinePointerInfo(),
4911 false, false, false, 0);
4912 MemOpChains.push_back(Load.getValue(1));
4913 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4914 ArgOffset += PtrByteSize;
4916 ArgOffset += ((Size - j + PtrByteSize-1)/PtrByteSize)*PtrByteSize;
4923 switch (Arg.getSimpleValueType().SimpleTy) {
4924 default: llvm_unreachable("Unexpected ValueType for argument!");
4928 if (GPR_idx != NumGPRs) {
4929 if (Arg.getValueType() == MVT::i1)
4930 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, PtrVT, Arg);
4932 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Arg));
4934 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4935 isPPC64, isTailCall, false, MemOpChains,
4936 TailCallArguments, dl);
4938 ArgOffset += PtrByteSize;
4942 if (FPR_idx != NumFPRs) {
4943 RegsToPass.push_back(std::make_pair(FPR[FPR_idx++], Arg));
4946 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
4947 MachinePointerInfo(), false, false, 0);
4948 MemOpChains.push_back(Store);
4950 // Float varargs are always shadowed in available integer registers
4951 if (GPR_idx != NumGPRs) {
4952 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4953 MachinePointerInfo(), false, false,
4955 MemOpChains.push_back(Load.getValue(1));
4956 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4958 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 && !isPPC64){
4959 SDValue ConstFour = DAG.getConstant(4, PtrOff.getValueType());
4960 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff, ConstFour);
4961 SDValue Load = DAG.getLoad(PtrVT, dl, Store, PtrOff,
4962 MachinePointerInfo(),
4963 false, false, false, 0);
4964 MemOpChains.push_back(Load.getValue(1));
4965 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
4968 // If we have any FPRs remaining, we may also have GPRs remaining.
4969 // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
4971 if (GPR_idx != NumGPRs)
4973 if (GPR_idx != NumGPRs && Arg.getValueType() == MVT::f64 &&
4974 !isPPC64) // PPC64 has 64-bit GPR's obviously :)
4978 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
4979 isPPC64, isTailCall, false, MemOpChains,
4980 TailCallArguments, dl);
4984 ArgOffset += Arg.getValueType() == MVT::f32 ? 4 : 8;
4991 // These go aligned on the stack, or in the corresponding R registers
4992 // when within range. The Darwin PPC ABI doc claims they also go in
4993 // V registers; in fact gcc does this only for arguments that are
4994 // prototyped, not for those that match the ... We do it for all
4995 // arguments, seems to work.
4996 while (ArgOffset % 16 !=0) {
4997 ArgOffset += PtrByteSize;
4998 if (GPR_idx != NumGPRs)
5001 // We could elide this store in the case where the object fits
5002 // entirely in R registers. Maybe later.
5003 PtrOff = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr,
5004 DAG.getConstant(ArgOffset, PtrVT));
5005 SDValue Store = DAG.getStore(Chain, dl, Arg, PtrOff,
5006 MachinePointerInfo(), false, false, 0);
5007 MemOpChains.push_back(Store);
5008 if (VR_idx != NumVRs) {
5009 SDValue Load = DAG.getLoad(MVT::v4f32, dl, Store, PtrOff,
5010 MachinePointerInfo(),
5011 false, false, false, 0);
5012 MemOpChains.push_back(Load.getValue(1));
5013 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Load));
5016 for (unsigned i=0; i<16; i+=PtrByteSize) {
5017 if (GPR_idx == NumGPRs)
5019 SDValue Ix = DAG.getNode(ISD::ADD, dl, PtrVT, PtrOff,
5020 DAG.getConstant(i, PtrVT));
5021 SDValue Load = DAG.getLoad(PtrVT, dl, Store, Ix, MachinePointerInfo(),
5022 false, false, false, 0);
5023 MemOpChains.push_back(Load.getValue(1));
5024 RegsToPass.push_back(std::make_pair(GPR[GPR_idx++], Load));
5029 // Non-varargs Altivec params generally go in registers, but have
5030 // stack space allocated at the end.
5031 if (VR_idx != NumVRs) {
5032 // Doesn't have GPR space allocated.
5033 RegsToPass.push_back(std::make_pair(VR[VR_idx++], Arg));
5034 } else if (nAltivecParamsAtEnd==0) {
5035 // We are emitting Altivec params in order.
5036 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5037 isPPC64, isTailCall, true, MemOpChains,
5038 TailCallArguments, dl);
5044 // If all Altivec parameters fit in registers, as they usually do,
5045 // they get stack space following the non-Altivec parameters. We
5046 // don't track this here because nobody below needs it.
5047 // If there are more Altivec parameters than fit in registers emit
5049 if (!isVarArg && nAltivecParamsAtEnd > NumVRs) {
5051 // Offset is aligned; skip 1st 12 params which go in V registers.
5052 ArgOffset = ((ArgOffset+15)/16)*16;
5054 for (unsigned i = 0; i != NumOps; ++i) {
5055 SDValue Arg = OutVals[i];
5056 EVT ArgType = Outs[i].VT;
5057 if (ArgType==MVT::v4f32 || ArgType==MVT::v4i32 ||
5058 ArgType==MVT::v8i16 || ArgType==MVT::v16i8) {
5061 // We are emitting Altivec params in order.
5062 LowerMemOpCallTo(DAG, MF, Chain, Arg, PtrOff, SPDiff, ArgOffset,
5063 isPPC64, isTailCall, true, MemOpChains,
5064 TailCallArguments, dl);
5071 if (!MemOpChains.empty())
5072 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
5074 // On Darwin, R12 must contain the address of an indirect callee. This does
5075 // not mean the MTCTR instruction must use R12; it's easier to model this as
5076 // an extra parameter, so do that.
5078 !isFunctionGlobalAddress(Callee) &&
5079 !isa<ExternalSymbolSDNode>(Callee) &&
5080 !isBLACompatibleAddress(Callee, DAG))
5081 RegsToPass.push_back(std::make_pair((unsigned)(isPPC64 ? PPC::X12 :
5082 PPC::R12), Callee));
5084 // Build a sequence of copy-to-reg nodes chained together with token chain
5085 // and flag operands which copy the outgoing args into the appropriate regs.
5087 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
5088 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
5089 RegsToPass[i].second, InFlag);
5090 InFlag = Chain.getValue(1);
5094 PrepareTailCall(DAG, InFlag, Chain, dl, isPPC64, SPDiff, NumBytes, LROp,
5095 FPOp, true, TailCallArguments);
5097 return FinishCall(CallConv, dl, isTailCall, isVarArg, IsPatchPoint, DAG,
5098 RegsToPass, InFlag, Chain, Callee, SPDiff, NumBytes,
5103 PPCTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
5104 MachineFunction &MF, bool isVarArg,
5105 const SmallVectorImpl<ISD::OutputArg> &Outs,
5106 LLVMContext &Context) const {
5107 SmallVector<CCValAssign, 16> RVLocs;
5108 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
5109 return CCInfo.CheckReturn(Outs, RetCC_PPC);
5113 PPCTargetLowering::LowerReturn(SDValue Chain,
5114 CallingConv::ID CallConv, bool isVarArg,
5115 const SmallVectorImpl<ISD::OutputArg> &Outs,
5116 const SmallVectorImpl<SDValue> &OutVals,
5117 SDLoc dl, SelectionDAG &DAG) const {
5119 SmallVector<CCValAssign, 16> RVLocs;
5120 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
5122 CCInfo.AnalyzeReturn(Outs, RetCC_PPC);
5125 SmallVector<SDValue, 4> RetOps(1, Chain);
5127 // Copy the result values into the output registers.
5128 for (unsigned i = 0; i != RVLocs.size(); ++i) {
5129 CCValAssign &VA = RVLocs[i];
5130 assert(VA.isRegLoc() && "Can only return in registers!");
5132 SDValue Arg = OutVals[i];
5134 switch (VA.getLocInfo()) {
5135 default: llvm_unreachable("Unknown loc info!");
5136 case CCValAssign::Full: break;
5137 case CCValAssign::AExt:
5138 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
5140 case CCValAssign::ZExt:
5141 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
5143 case CCValAssign::SExt:
5144 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
5148 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
5149 Flag = Chain.getValue(1);
5150 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
5153 RetOps[0] = Chain; // Update chain.
5155 // Add the flag if we have it.
5157 RetOps.push_back(Flag);
5159 return DAG.getNode(PPCISD::RET_FLAG, dl, MVT::Other, RetOps);
5162 SDValue PPCTargetLowering::LowerSTACKRESTORE(SDValue Op, SelectionDAG &DAG,
5163 const PPCSubtarget &Subtarget) const {
5164 // When we pop the dynamic allocation we need to restore the SP link.
5167 // Get the corect type for pointers.
5168 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5170 // Construct the stack pointer operand.
5171 bool isPPC64 = Subtarget.isPPC64();
5172 unsigned SP = isPPC64 ? PPC::X1 : PPC::R1;
5173 SDValue StackPtr = DAG.getRegister(SP, PtrVT);
5175 // Get the operands for the STACKRESTORE.
5176 SDValue Chain = Op.getOperand(0);
5177 SDValue SaveSP = Op.getOperand(1);
5179 // Load the old link SP.
5180 SDValue LoadLinkSP = DAG.getLoad(PtrVT, dl, Chain, StackPtr,
5181 MachinePointerInfo(),
5182 false, false, false, 0);
5184 // Restore the stack pointer.
5185 Chain = DAG.getCopyToReg(LoadLinkSP.getValue(1), dl, SP, SaveSP);
5187 // Store the old link SP.
5188 return DAG.getStore(Chain, dl, LoadLinkSP, StackPtr, MachinePointerInfo(),
5195 PPCTargetLowering::getReturnAddrFrameIndex(SelectionDAG & DAG) const {
5196 MachineFunction &MF = DAG.getMachineFunction();
5197 bool isPPC64 = Subtarget.isPPC64();
5198 bool isDarwinABI = Subtarget.isDarwinABI();
5199 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5201 // Get current frame pointer save index. The users of this index will be
5202 // primarily DYNALLOC instructions.
5203 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5204 int RASI = FI->getReturnAddrSaveIndex();
5206 // If the frame pointer save index hasn't been defined yet.
5208 // Find out what the fix offset of the frame pointer save area.
5209 int LROffset = PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI);
5210 // Allocate the frame index for frame pointer save area.
5211 RASI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, LROffset, false);
5213 FI->setReturnAddrSaveIndex(RASI);
5215 return DAG.getFrameIndex(RASI, PtrVT);
5219 PPCTargetLowering::getFramePointerFrameIndex(SelectionDAG & DAG) const {
5220 MachineFunction &MF = DAG.getMachineFunction();
5221 bool isPPC64 = Subtarget.isPPC64();
5222 bool isDarwinABI = Subtarget.isDarwinABI();
5223 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5225 // Get current frame pointer save index. The users of this index will be
5226 // primarily DYNALLOC instructions.
5227 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
5228 int FPSI = FI->getFramePointerSaveIndex();
5230 // If the frame pointer save index hasn't been defined yet.
5232 // Find out what the fix offset of the frame pointer save area.
5233 int FPOffset = PPCFrameLowering::getFramePointerSaveOffset(isPPC64,
5236 // Allocate the frame index for frame pointer save area.
5237 FPSI = MF.getFrameInfo()->CreateFixedObject(isPPC64? 8 : 4, FPOffset, true);
5239 FI->setFramePointerSaveIndex(FPSI);
5241 return DAG.getFrameIndex(FPSI, PtrVT);
5244 SDValue PPCTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5246 const PPCSubtarget &Subtarget) const {
5248 SDValue Chain = Op.getOperand(0);
5249 SDValue Size = Op.getOperand(1);
5252 // Get the corect type for pointers.
5253 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5255 SDValue NegSize = DAG.getNode(ISD::SUB, dl, PtrVT,
5256 DAG.getConstant(0, PtrVT), Size);
5257 // Construct a node for the frame pointer save index.
5258 SDValue FPSIdx = getFramePointerFrameIndex(DAG);
5259 // Build a DYNALLOC node.
5260 SDValue Ops[3] = { Chain, NegSize, FPSIdx };
5261 SDVTList VTs = DAG.getVTList(PtrVT, MVT::Other);
5262 return DAG.getNode(PPCISD::DYNALLOC, dl, VTs, Ops);
5265 SDValue PPCTargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
5266 SelectionDAG &DAG) const {
5268 return DAG.getNode(PPCISD::EH_SJLJ_SETJMP, DL,
5269 DAG.getVTList(MVT::i32, MVT::Other),
5270 Op.getOperand(0), Op.getOperand(1));
5273 SDValue PPCTargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
5274 SelectionDAG &DAG) const {
5276 return DAG.getNode(PPCISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
5277 Op.getOperand(0), Op.getOperand(1));
5280 SDValue PPCTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5281 assert(Op.getValueType() == MVT::i1 &&
5282 "Custom lowering only for i1 loads");
5284 // First, load 8 bits into 32 bits, then truncate to 1 bit.
5287 LoadSDNode *LD = cast<LoadSDNode>(Op);
5289 SDValue Chain = LD->getChain();
5290 SDValue BasePtr = LD->getBasePtr();
5291 MachineMemOperand *MMO = LD->getMemOperand();
5293 SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, dl, getPointerTy(), Chain,
5294 BasePtr, MVT::i8, MMO);
5295 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewLD);
5297 SDValue Ops[] = { Result, SDValue(NewLD.getNode(), 1) };
5298 return DAG.getMergeValues(Ops, dl);
5301 SDValue PPCTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5302 assert(Op.getOperand(1).getValueType() == MVT::i1 &&
5303 "Custom lowering only for i1 stores");
5305 // First, zero extend to 32 bits, then use a truncating store to 8 bits.
5308 StoreSDNode *ST = cast<StoreSDNode>(Op);
5310 SDValue Chain = ST->getChain();
5311 SDValue BasePtr = ST->getBasePtr();
5312 SDValue Value = ST->getValue();
5313 MachineMemOperand *MMO = ST->getMemOperand();
5315 Value = DAG.getNode(ISD::ZERO_EXTEND, dl, getPointerTy(), Value);
5316 return DAG.getTruncStore(Chain, dl, Value, BasePtr, MVT::i8, MMO);
5319 // FIXME: Remove this once the ANDI glue bug is fixed:
5320 SDValue PPCTargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
5321 assert(Op.getValueType() == MVT::i1 &&
5322 "Custom lowering only for i1 results");
5325 return DAG.getNode(PPCISD::ANDIo_1_GT_BIT, DL, MVT::i1,
5329 /// LowerSELECT_CC - Lower floating point select_cc's into fsel instruction when
5331 SDValue PPCTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
5332 // Not FP? Not a fsel.
5333 if (!Op.getOperand(0).getValueType().isFloatingPoint() ||
5334 !Op.getOperand(2).getValueType().isFloatingPoint())
5337 // We might be able to do better than this under some circumstances, but in
5338 // general, fsel-based lowering of select is a finite-math-only optimization.
5339 // For more information, see section F.3 of the 2.06 ISA specification.
5340 if (!DAG.getTarget().Options.NoInfsFPMath ||
5341 !DAG.getTarget().Options.NoNaNsFPMath)
5344 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
5346 EVT ResVT = Op.getValueType();
5347 EVT CmpVT = Op.getOperand(0).getValueType();
5348 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
5349 SDValue TV = Op.getOperand(2), FV = Op.getOperand(3);
5352 // If the RHS of the comparison is a 0.0, we don't need to do the
5353 // subtraction at all.
5355 if (isFloatingPointZero(RHS))
5357 default: break; // SETUO etc aren't handled by fsel.
5361 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5362 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5363 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5364 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5365 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5366 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5367 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), Sel1, FV);
5370 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5373 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5374 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5375 return DAG.getNode(PPCISD::FSEL, dl, ResVT, LHS, TV, FV);
5378 std::swap(TV, FV); // fsel is natively setge, swap operands for setlt
5381 if (LHS.getValueType() == MVT::f32) // Comparison is always 64-bits
5382 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, LHS);
5383 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5384 DAG.getNode(ISD::FNEG, dl, MVT::f64, LHS), TV, FV);
5389 default: break; // SETUO etc aren't handled by fsel.
5393 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5394 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5395 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5396 Sel1 = DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5397 if (Sel1.getValueType() == MVT::f32) // Comparison is always 64-bits
5398 Sel1 = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Sel1);
5399 return DAG.getNode(PPCISD::FSEL, dl, ResVT,
5400 DAG.getNode(ISD::FNEG, dl, MVT::f64, Cmp), Sel1, FV);
5403 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5404 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5405 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5406 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5409 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, LHS, RHS);
5410 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5411 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5412 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5415 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5416 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5417 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5418 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, FV, TV);
5421 Cmp = DAG.getNode(ISD::FSUB, dl, CmpVT, RHS, LHS);
5422 if (Cmp.getValueType() == MVT::f32) // Comparison is always 64-bits
5423 Cmp = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Cmp);
5424 return DAG.getNode(PPCISD::FSEL, dl, ResVT, Cmp, TV, FV);
5429 void PPCTargetLowering::LowerFP_TO_INTForReuse(SDValue Op, ReuseLoadInfo &RLI,
5432 assert(Op.getOperand(0).getValueType().isFloatingPoint());
5433 SDValue Src = Op.getOperand(0);
5434 if (Src.getValueType() == MVT::f32)
5435 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
5438 switch (Op.getSimpleValueType().SimpleTy) {
5439 default: llvm_unreachable("Unhandled FP_TO_INT type in custom expander!");
5441 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIWZ :
5442 (Subtarget.hasFPCVT() ? PPCISD::FCTIWUZ :
5447 assert((Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT()) &&
5448 "i64 FP_TO_UINT is supported only with FPCVT");
5449 Tmp = DAG.getNode(Op.getOpcode()==ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
5455 // Convert the FP value to an int value through memory.
5456 bool i32Stack = Op.getValueType() == MVT::i32 && Subtarget.hasSTFIWX() &&
5457 (Op.getOpcode() == ISD::FP_TO_SINT || Subtarget.hasFPCVT());
5458 SDValue FIPtr = DAG.CreateStackTemporary(i32Stack ? MVT::i32 : MVT::f64);
5459 int FI = cast<FrameIndexSDNode>(FIPtr)->getIndex();
5460 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(FI);
5462 // Emit a store to the stack slot.
5465 MachineFunction &MF = DAG.getMachineFunction();
5466 MachineMemOperand *MMO =
5467 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, 4);
5468 SDValue Ops[] = { DAG.getEntryNode(), Tmp, FIPtr };
5469 Chain = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
5470 DAG.getVTList(MVT::Other), Ops, MVT::i32, MMO);
5472 Chain = DAG.getStore(DAG.getEntryNode(), dl, Tmp, FIPtr,
5473 MPI, false, false, 0);
5475 // Result is a load from the stack slot. If loading 4 bytes, make sure to
5477 if (Op.getValueType() == MVT::i32 && !i32Stack) {
5478 FIPtr = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr,
5479 DAG.getConstant(4, FIPtr.getValueType()));
5480 MPI = MPI.getWithOffset(4);
5488 SDValue PPCTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG,
5491 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5493 return DAG.getLoad(Op.getValueType(), dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5494 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5498 // We're trying to insert a regular store, S, and then a load, L. If the
5499 // incoming value, O, is a load, we might just be able to have our load use the
5500 // address used by O. However, we don't know if anything else will store to
5501 // that address before we can load from it. To prevent this situation, we need
5502 // to insert our load, L, into the chain as a peer of O. To do this, we give L
5503 // the same chain operand as O, we create a token factor from the chain results
5504 // of O and L, and we replace all uses of O's chain result with that token
5505 // factor (see spliceIntoChain below for this last part).
5506 bool PPCTargetLowering::canReuseLoadAddress(SDValue Op, EVT MemVT,
5509 ISD::LoadExtType ET) const {
5511 if (ET == ISD::NON_EXTLOAD &&
5512 (Op.getOpcode() == ISD::FP_TO_UINT ||
5513 Op.getOpcode() == ISD::FP_TO_SINT) &&
5514 isOperationLegalOrCustom(Op.getOpcode(),
5515 Op.getOperand(0).getValueType())) {
5517 LowerFP_TO_INTForReuse(Op, RLI, DAG, dl);
5521 LoadSDNode *LD = dyn_cast<LoadSDNode>(Op);
5522 if (!LD || LD->getExtensionType() != ET || LD->isVolatile() ||
5523 LD->isNonTemporal())
5525 if (LD->getMemoryVT() != MemVT)
5528 RLI.Ptr = LD->getBasePtr();
5529 if (LD->isIndexed() && LD->getOffset().getOpcode() != ISD::UNDEF) {
5530 assert(LD->getAddressingMode() == ISD::PRE_INC &&
5531 "Non-pre-inc AM on PPC?");
5532 RLI.Ptr = DAG.getNode(ISD::ADD, dl, RLI.Ptr.getValueType(), RLI.Ptr,
5536 RLI.Chain = LD->getChain();
5537 RLI.MPI = LD->getPointerInfo();
5538 RLI.IsInvariant = LD->isInvariant();
5539 RLI.Alignment = LD->getAlignment();
5540 RLI.AAInfo = LD->getAAInfo();
5541 RLI.Ranges = LD->getRanges();
5543 RLI.ResChain = SDValue(LD, LD->isIndexed() ? 2 : 1);
5547 // Given the head of the old chain, ResChain, insert a token factor containing
5548 // it and NewResChain, and make users of ResChain now be users of that token
5550 void PPCTargetLowering::spliceIntoChain(SDValue ResChain,
5551 SDValue NewResChain,
5552 SelectionDAG &DAG) const {
5556 SDLoc dl(NewResChain);
5558 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5559 NewResChain, DAG.getUNDEF(MVT::Other));
5560 assert(TF.getNode() != NewResChain.getNode() &&
5561 "A new TF really is required here");
5563 DAG.ReplaceAllUsesOfValueWith(ResChain, TF);
5564 DAG.UpdateNodeOperands(TF.getNode(), ResChain, NewResChain);
5567 SDValue PPCTargetLowering::LowerINT_TO_FP(SDValue Op,
5568 SelectionDAG &DAG) const {
5570 // Don't handle ppc_fp128 here; let it be lowered to a libcall.
5571 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
5574 if (Op.getOperand(0).getValueType() == MVT::i1)
5575 return DAG.getNode(ISD::SELECT, dl, Op.getValueType(), Op.getOperand(0),
5576 DAG.getConstantFP(1.0, Op.getValueType()),
5577 DAG.getConstantFP(0.0, Op.getValueType()));
5579 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
5580 "UINT_TO_FP is supported only with FPCVT");
5582 // If we have FCFIDS, then use it when converting to single-precision.
5583 // Otherwise, convert to double-precision and then round.
5584 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5585 (Op.getOpcode() == ISD::UINT_TO_FP ?
5586 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
5587 (Op.getOpcode() == ISD::UINT_TO_FP ?
5588 PPCISD::FCFIDU : PPCISD::FCFID);
5589 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
5590 MVT::f32 : MVT::f64;
5592 if (Op.getOperand(0).getValueType() == MVT::i64) {
5593 SDValue SINT = Op.getOperand(0);
5594 // When converting to single-precision, we actually need to convert
5595 // to double-precision first and then round to single-precision.
5596 // To avoid double-rounding effects during that operation, we have
5597 // to prepare the input operand. Bits that might be truncated when
5598 // converting to double-precision are replaced by a bit that won't
5599 // be lost at this stage, but is below the single-precision rounding
5602 // However, if -enable-unsafe-fp-math is in effect, accept double
5603 // rounding to avoid the extra overhead.
5604 if (Op.getValueType() == MVT::f32 &&
5605 !Subtarget.hasFPCVT() &&
5606 !DAG.getTarget().Options.UnsafeFPMath) {
5608 // Twiddle input to make sure the low 11 bits are zero. (If this
5609 // is the case, we are guaranteed the value will fit into the 53 bit
5610 // mantissa of an IEEE double-precision value without rounding.)
5611 // If any of those low 11 bits were not zero originally, make sure
5612 // bit 12 (value 2048) is set instead, so that the final rounding
5613 // to single-precision gets the correct result.
5614 SDValue Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5615 SINT, DAG.getConstant(2047, MVT::i64));
5616 Round = DAG.getNode(ISD::ADD, dl, MVT::i64,
5617 Round, DAG.getConstant(2047, MVT::i64));
5618 Round = DAG.getNode(ISD::OR, dl, MVT::i64, Round, SINT);
5619 Round = DAG.getNode(ISD::AND, dl, MVT::i64,
5620 Round, DAG.getConstant(-2048, MVT::i64));
5622 // However, we cannot use that value unconditionally: if the magnitude
5623 // of the input value is small, the bit-twiddling we did above might
5624 // end up visibly changing the output. Fortunately, in that case, we
5625 // don't need to twiddle bits since the original input will convert
5626 // exactly to double-precision floating-point already. Therefore,
5627 // construct a conditional to use the original value if the top 11
5628 // bits are all sign-bit copies, and use the rounded value computed
5630 SDValue Cond = DAG.getNode(ISD::SRA, dl, MVT::i64,
5631 SINT, DAG.getConstant(53, MVT::i32));
5632 Cond = DAG.getNode(ISD::ADD, dl, MVT::i64,
5633 Cond, DAG.getConstant(1, MVT::i64));
5634 Cond = DAG.getSetCC(dl, MVT::i32,
5635 Cond, DAG.getConstant(1, MVT::i64), ISD::SETUGT);
5637 SINT = DAG.getNode(ISD::SELECT, dl, MVT::i64, Cond, Round, SINT);
5643 MachineFunction &MF = DAG.getMachineFunction();
5644 if (canReuseLoadAddress(SINT, MVT::i64, RLI, DAG)) {
5645 Bits = DAG.getLoad(MVT::f64, dl, RLI.Chain, RLI.Ptr, RLI.MPI, false,
5646 false, RLI.IsInvariant, RLI.Alignment, RLI.AAInfo,
5648 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5649 } else if (Subtarget.hasLFIWAX() &&
5650 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::SEXTLOAD)) {
5651 MachineMemOperand *MMO =
5652 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5653 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5654 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5655 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWAX, dl,
5656 DAG.getVTList(MVT::f64, MVT::Other),
5657 Ops, MVT::i32, MMO);
5658 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5659 } else if (Subtarget.hasFPCVT() &&
5660 canReuseLoadAddress(SINT, MVT::i32, RLI, DAG, ISD::ZEXTLOAD)) {
5661 MachineMemOperand *MMO =
5662 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5663 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5664 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5665 Bits = DAG.getMemIntrinsicNode(PPCISD::LFIWZX, dl,
5666 DAG.getVTList(MVT::f64, MVT::Other),
5667 Ops, MVT::i32, MMO);
5668 spliceIntoChain(RLI.ResChain, Bits.getValue(1), DAG);
5669 } else if (((Subtarget.hasLFIWAX() &&
5670 SINT.getOpcode() == ISD::SIGN_EXTEND) ||
5671 (Subtarget.hasFPCVT() &&
5672 SINT.getOpcode() == ISD::ZERO_EXTEND)) &&
5673 SINT.getOperand(0).getValueType() == MVT::i32) {
5674 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5675 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5677 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5678 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5681 DAG.getStore(DAG.getEntryNode(), dl, SINT.getOperand(0), FIdx,
5682 MachinePointerInfo::getFixedStack(FrameIdx),
5685 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5686 "Expected an i32 store");
5690 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5693 MachineMemOperand *MMO =
5694 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5695 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5696 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5697 Bits = DAG.getMemIntrinsicNode(SINT.getOpcode() == ISD::ZERO_EXTEND ?
5698 PPCISD::LFIWZX : PPCISD::LFIWAX,
5699 dl, DAG.getVTList(MVT::f64, MVT::Other),
5700 Ops, MVT::i32, MMO);
5702 Bits = DAG.getNode(ISD::BITCAST, dl, MVT::f64, SINT);
5704 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Bits);
5706 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5707 FP = DAG.getNode(ISD::FP_ROUND, dl,
5708 MVT::f32, FP, DAG.getIntPtrConstant(0));
5712 assert(Op.getOperand(0).getValueType() == MVT::i32 &&
5713 "Unhandled INT_TO_FP type in custom expander!");
5714 // Since we only generate this in 64-bit mode, we can take advantage of
5715 // 64-bit registers. In particular, sign extend the input value into the
5716 // 64-bit register with extsw, store the WHOLE 64-bit value into the stack
5717 // then lfd it and fcfid it.
5718 MachineFunction &MF = DAG.getMachineFunction();
5719 MachineFrameInfo *FrameInfo = MF.getFrameInfo();
5720 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5723 if (Subtarget.hasLFIWAX() || Subtarget.hasFPCVT()) {
5726 if (!(ReusingLoad = canReuseLoadAddress(Op.getOperand(0), MVT::i32, RLI,
5728 int FrameIdx = FrameInfo->CreateStackObject(4, 4, false);
5729 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5731 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0), FIdx,
5732 MachinePointerInfo::getFixedStack(FrameIdx),
5735 assert(cast<StoreSDNode>(Store)->getMemoryVT() == MVT::i32 &&
5736 "Expected an i32 store");
5740 RLI.MPI = MachinePointerInfo::getFixedStack(FrameIdx);
5744 MachineMemOperand *MMO =
5745 MF.getMachineMemOperand(RLI.MPI, MachineMemOperand::MOLoad, 4,
5746 RLI.Alignment, RLI.AAInfo, RLI.Ranges);
5747 SDValue Ops[] = { RLI.Chain, RLI.Ptr };
5748 Ld = DAG.getMemIntrinsicNode(Op.getOpcode() == ISD::UINT_TO_FP ?
5749 PPCISD::LFIWZX : PPCISD::LFIWAX,
5750 dl, DAG.getVTList(MVT::f64, MVT::Other),
5751 Ops, MVT::i32, MMO);
5753 spliceIntoChain(RLI.ResChain, Ld.getValue(1), DAG);
5755 assert(Subtarget.isPPC64() &&
5756 "i32->FP without LFIWAX supported only on PPC64");
5758 int FrameIdx = FrameInfo->CreateStackObject(8, 8, false);
5759 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
5761 SDValue Ext64 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::i64,
5764 // STD the extended value into the stack slot.
5765 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Ext64, FIdx,
5766 MachinePointerInfo::getFixedStack(FrameIdx),
5769 // Load the value as a double.
5770 Ld = DAG.getLoad(MVT::f64, dl, Store, FIdx,
5771 MachinePointerInfo::getFixedStack(FrameIdx),
5772 false, false, false, 0);
5775 // FCFID it and return it.
5776 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Ld);
5777 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT())
5778 FP = DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, FP, DAG.getIntPtrConstant(0));
5782 SDValue PPCTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5783 SelectionDAG &DAG) const {
5786 The rounding mode is in bits 30:31 of FPSR, and has the following
5793 FLT_ROUNDS, on the other hand, expects the following:
5800 To perform the conversion, we do:
5801 ((FPSCR & 0x3) ^ ((~FPSCR & 0x3) >> 1))
5804 MachineFunction &MF = DAG.getMachineFunction();
5805 EVT VT = Op.getValueType();
5806 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
5808 // Save FP Control Word to register
5810 MVT::f64, // return register
5811 MVT::Glue // unused in this context
5813 SDValue Chain = DAG.getNode(PPCISD::MFFS, dl, NodeTys, None);
5815 // Save FP register to stack slot
5816 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5817 SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
5818 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Chain,
5819 StackSlot, MachinePointerInfo(), false, false,0);
5821 // Load FP Control Word from low 32 bits of stack slot.
5822 SDValue Four = DAG.getConstant(4, PtrVT);
5823 SDValue Addr = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, Four);
5824 SDValue CWD = DAG.getLoad(MVT::i32, dl, Store, Addr, MachinePointerInfo(),
5825 false, false, false, 0);
5827 // Transform as necessary
5829 DAG.getNode(ISD::AND, dl, MVT::i32,
5830 CWD, DAG.getConstant(3, MVT::i32));
5832 DAG.getNode(ISD::SRL, dl, MVT::i32,
5833 DAG.getNode(ISD::AND, dl, MVT::i32,
5834 DAG.getNode(ISD::XOR, dl, MVT::i32,
5835 CWD, DAG.getConstant(3, MVT::i32)),
5836 DAG.getConstant(3, MVT::i32)),
5837 DAG.getConstant(1, MVT::i32));
5840 DAG.getNode(ISD::XOR, dl, MVT::i32, CWD1, CWD2);
5842 return DAG.getNode((VT.getSizeInBits() < 16 ?
5843 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
5846 SDValue PPCTargetLowering::LowerSHL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5847 EVT VT = Op.getValueType();
5848 unsigned BitWidth = VT.getSizeInBits();
5850 assert(Op.getNumOperands() == 3 &&
5851 VT == Op.getOperand(1).getValueType() &&
5854 // Expand into a bunch of logical ops. Note that these ops
5855 // depend on the PPC behavior for oversized shift amounts.
5856 SDValue Lo = Op.getOperand(0);
5857 SDValue Hi = Op.getOperand(1);
5858 SDValue Amt = Op.getOperand(2);
5859 EVT AmtVT = Amt.getValueType();
5861 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5862 DAG.getConstant(BitWidth, AmtVT), Amt);
5863 SDValue Tmp2 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Amt);
5864 SDValue Tmp3 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Tmp1);
5865 SDValue Tmp4 = DAG.getNode(ISD::OR , dl, VT, Tmp2, Tmp3);
5866 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5867 DAG.getConstant(-BitWidth, AmtVT));
5868 SDValue Tmp6 = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Tmp5);
5869 SDValue OutHi = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5870 SDValue OutLo = DAG.getNode(PPCISD::SHL, dl, VT, Lo, Amt);
5871 SDValue OutOps[] = { OutLo, OutHi };
5872 return DAG.getMergeValues(OutOps, dl);
5875 SDValue PPCTargetLowering::LowerSRL_PARTS(SDValue Op, SelectionDAG &DAG) const {
5876 EVT VT = Op.getValueType();
5878 unsigned BitWidth = VT.getSizeInBits();
5879 assert(Op.getNumOperands() == 3 &&
5880 VT == Op.getOperand(1).getValueType() &&
5883 // Expand into a bunch of logical ops. Note that these ops
5884 // depend on the PPC behavior for oversized shift amounts.
5885 SDValue Lo = Op.getOperand(0);
5886 SDValue Hi = Op.getOperand(1);
5887 SDValue Amt = Op.getOperand(2);
5888 EVT AmtVT = Amt.getValueType();
5890 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5891 DAG.getConstant(BitWidth, AmtVT), Amt);
5892 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5893 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5894 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5895 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5896 DAG.getConstant(-BitWidth, AmtVT));
5897 SDValue Tmp6 = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Tmp5);
5898 SDValue OutLo = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp6);
5899 SDValue OutHi = DAG.getNode(PPCISD::SRL, dl, VT, Hi, Amt);
5900 SDValue OutOps[] = { OutLo, OutHi };
5901 return DAG.getMergeValues(OutOps, dl);
5904 SDValue PPCTargetLowering::LowerSRA_PARTS(SDValue Op, SelectionDAG &DAG) const {
5906 EVT VT = Op.getValueType();
5907 unsigned BitWidth = VT.getSizeInBits();
5908 assert(Op.getNumOperands() == 3 &&
5909 VT == Op.getOperand(1).getValueType() &&
5912 // Expand into a bunch of logical ops, followed by a select_cc.
5913 SDValue Lo = Op.getOperand(0);
5914 SDValue Hi = Op.getOperand(1);
5915 SDValue Amt = Op.getOperand(2);
5916 EVT AmtVT = Amt.getValueType();
5918 SDValue Tmp1 = DAG.getNode(ISD::SUB, dl, AmtVT,
5919 DAG.getConstant(BitWidth, AmtVT), Amt);
5920 SDValue Tmp2 = DAG.getNode(PPCISD::SRL, dl, VT, Lo, Amt);
5921 SDValue Tmp3 = DAG.getNode(PPCISD::SHL, dl, VT, Hi, Tmp1);
5922 SDValue Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
5923 SDValue Tmp5 = DAG.getNode(ISD::ADD, dl, AmtVT, Amt,
5924 DAG.getConstant(-BitWidth, AmtVT));
5925 SDValue Tmp6 = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Tmp5);
5926 SDValue OutHi = DAG.getNode(PPCISD::SRA, dl, VT, Hi, Amt);
5927 SDValue OutLo = DAG.getSelectCC(dl, Tmp5, DAG.getConstant(0, AmtVT),
5928 Tmp4, Tmp6, ISD::SETLE);
5929 SDValue OutOps[] = { OutLo, OutHi };
5930 return DAG.getMergeValues(OutOps, dl);
5933 //===----------------------------------------------------------------------===//
5934 // Vector related lowering.
5937 /// BuildSplatI - Build a canonical splati of Val with an element size of
5938 /// SplatSize. Cast the result to VT.
5939 static SDValue BuildSplatI(int Val, unsigned SplatSize, EVT VT,
5940 SelectionDAG &DAG, SDLoc dl) {
5941 assert(Val >= -16 && Val <= 15 && "vsplti is out of range!");
5943 static const EVT VTys[] = { // canonical VT to use for each size.
5944 MVT::v16i8, MVT::v8i16, MVT::Other, MVT::v4i32
5947 EVT ReqVT = VT != MVT::Other ? VT : VTys[SplatSize-1];
5949 // Force vspltis[hw] -1 to vspltisb -1 to canonicalize.
5953 EVT CanonicalVT = VTys[SplatSize-1];
5955 // Build a canonical splat for this value.
5956 SDValue Elt = DAG.getConstant(Val, MVT::i32);
5957 SmallVector<SDValue, 8> Ops;
5958 Ops.assign(CanonicalVT.getVectorNumElements(), Elt);
5959 SDValue Res = DAG.getNode(ISD::BUILD_VECTOR, dl, CanonicalVT, Ops);
5960 return DAG.getNode(ISD::BITCAST, dl, ReqVT, Res);
5963 /// BuildIntrinsicOp - Return a unary operator intrinsic node with the
5964 /// specified intrinsic ID.
5965 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op,
5966 SelectionDAG &DAG, SDLoc dl,
5967 EVT DestVT = MVT::Other) {
5968 if (DestVT == MVT::Other) DestVT = Op.getValueType();
5969 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5970 DAG.getConstant(IID, MVT::i32), Op);
5973 /// BuildIntrinsicOp - Return a binary operator intrinsic node with the
5974 /// specified intrinsic ID.
5975 static SDValue BuildIntrinsicOp(unsigned IID, SDValue LHS, SDValue RHS,
5976 SelectionDAG &DAG, SDLoc dl,
5977 EVT DestVT = MVT::Other) {
5978 if (DestVT == MVT::Other) DestVT = LHS.getValueType();
5979 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5980 DAG.getConstant(IID, MVT::i32), LHS, RHS);
5983 /// BuildIntrinsicOp - Return a ternary operator intrinsic node with the
5984 /// specified intrinsic ID.
5985 static SDValue BuildIntrinsicOp(unsigned IID, SDValue Op0, SDValue Op1,
5986 SDValue Op2, SelectionDAG &DAG,
5987 SDLoc dl, EVT DestVT = MVT::Other) {
5988 if (DestVT == MVT::Other) DestVT = Op0.getValueType();
5989 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
5990 DAG.getConstant(IID, MVT::i32), Op0, Op1, Op2);
5994 /// BuildVSLDOI - Return a VECTOR_SHUFFLE that is a vsldoi of the specified
5995 /// amount. The result has the specified value type.
5996 static SDValue BuildVSLDOI(SDValue LHS, SDValue RHS, unsigned Amt,
5997 EVT VT, SelectionDAG &DAG, SDLoc dl) {
5998 // Force LHS/RHS to be the right type.
5999 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, LHS);
6000 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, RHS);
6003 for (unsigned i = 0; i != 16; ++i)
6005 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, LHS, RHS, Ops);
6006 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6009 // If this is a case we can't handle, return null and let the default
6010 // expansion code take care of it. If we CAN select this case, and if it
6011 // selects to a single instruction, return Op. Otherwise, if we can codegen
6012 // this case more efficiently than a constant pool load, lower it to the
6013 // sequence of ops that should be used.
6014 SDValue PPCTargetLowering::LowerBUILD_VECTOR(SDValue Op,
6015 SelectionDAG &DAG) const {
6017 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6018 assert(BVN && "Expected a BuildVectorSDNode in LowerBUILD_VECTOR");
6020 // Check if this is a splat of a constant value.
6021 APInt APSplatBits, APSplatUndef;
6022 unsigned SplatBitSize;
6024 if (! BVN->isConstantSplat(APSplatBits, APSplatUndef, SplatBitSize,
6025 HasAnyUndefs, 0, true) || SplatBitSize > 32)
6028 unsigned SplatBits = APSplatBits.getZExtValue();
6029 unsigned SplatUndef = APSplatUndef.getZExtValue();
6030 unsigned SplatSize = SplatBitSize / 8;
6032 // First, handle single instruction cases.
6035 if (SplatBits == 0) {
6036 // Canonicalize all zero vectors to be v4i32.
6037 if (Op.getValueType() != MVT::v4i32 || HasAnyUndefs) {
6038 SDValue Z = DAG.getConstant(0, MVT::i32);
6039 Z = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Z, Z, Z, Z);
6040 Op = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Z);
6045 // If the sign extended value is in the range [-16,15], use VSPLTI[bhw].
6046 int32_t SextVal= (int32_t(SplatBits << (32-SplatBitSize)) >>
6048 if (SextVal >= -16 && SextVal <= 15)
6049 return BuildSplatI(SextVal, SplatSize, Op.getValueType(), DAG, dl);
6052 // Two instruction sequences.
6054 // If this value is in the range [-32,30] and is even, use:
6055 // VSPLTI[bhw](val/2) + VSPLTI[bhw](val/2)
6056 // If this value is in the range [17,31] and is odd, use:
6057 // VSPLTI[bhw](val-16) - VSPLTI[bhw](-16)
6058 // If this value is in the range [-31,-17] and is odd, use:
6059 // VSPLTI[bhw](val+16) + VSPLTI[bhw](-16)
6060 // Note the last two are three-instruction sequences.
6061 if (SextVal >= -32 && SextVal <= 31) {
6062 // To avoid having these optimizations undone by constant folding,
6063 // we convert to a pseudo that will be expanded later into one of
6065 SDValue Elt = DAG.getConstant(SextVal, MVT::i32);
6066 EVT VT = (SplatSize == 1 ? MVT::v16i8 :
6067 (SplatSize == 2 ? MVT::v8i16 : MVT::v4i32));
6068 SDValue EltSize = DAG.getConstant(SplatSize, MVT::i32);
6069 SDValue RetVal = DAG.getNode(PPCISD::VADD_SPLAT, dl, VT, Elt, EltSize);
6070 if (VT == Op.getValueType())
6073 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), RetVal);
6076 // If this is 0x8000_0000 x 4, turn into vspltisw + vslw. If it is
6077 // 0x7FFF_FFFF x 4, turn it into not(0x8000_0000). This is important
6079 if (SplatSize == 4 && SplatBits == (0x7FFFFFFF&~SplatUndef)) {
6080 // Make -1 and vspltisw -1:
6081 SDValue OnesV = BuildSplatI(-1, 4, MVT::v4i32, DAG, dl);
6083 // Make the VSLW intrinsic, computing 0x8000_0000.
6084 SDValue Res = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, OnesV,
6087 // xor by OnesV to invert it.
6088 Res = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Res, OnesV);
6089 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6092 // The remaining cases assume either big endian element order or
6093 // a splat-size that equates to the element size of the vector
6094 // to be built. An example that doesn't work for little endian is
6095 // {0, -1, 0, -1, 0, -1, 0, -1} which has a splat size of 32 bits
6096 // and a vector element size of 16 bits. The code below will
6097 // produce the vector in big endian element order, which for little
6098 // endian is {-1, 0, -1, 0, -1, 0, -1, 0}.
6100 // For now, just avoid these optimizations in that case.
6101 // FIXME: Develop correct optimizations for LE with mismatched
6102 // splat and element sizes.
6104 if (Subtarget.isLittleEndian() &&
6105 SplatSize != Op.getValueType().getVectorElementType().getSizeInBits())
6108 // Check to see if this is a wide variety of vsplti*, binop self cases.
6109 static const signed char SplatCsts[] = {
6110 -1, 1, -2, 2, -3, 3, -4, 4, -5, 5, -6, 6, -7, 7,
6111 -8, 8, -9, 9, -10, 10, -11, 11, -12, 12, -13, 13, 14, -14, 15, -15, -16
6114 for (unsigned idx = 0; idx < array_lengthof(SplatCsts); ++idx) {
6115 // Indirect through the SplatCsts array so that we favor 'vsplti -1' for
6116 // cases which are ambiguous (e.g. formation of 0x8000_0000). 'vsplti -1'
6117 int i = SplatCsts[idx];
6119 // Figure out what shift amount will be used by altivec if shifted by i in
6121 unsigned TypeShiftAmt = i & (SplatBitSize-1);
6123 // vsplti + shl self.
6124 if (SextVal == (int)((unsigned)i << TypeShiftAmt)) {
6125 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6126 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6127 Intrinsic::ppc_altivec_vslb, Intrinsic::ppc_altivec_vslh, 0,
6128 Intrinsic::ppc_altivec_vslw
6130 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6131 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6134 // vsplti + srl self.
6135 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6136 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6137 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6138 Intrinsic::ppc_altivec_vsrb, Intrinsic::ppc_altivec_vsrh, 0,
6139 Intrinsic::ppc_altivec_vsrw
6141 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6142 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6145 // vsplti + sra self.
6146 if (SextVal == (int)((unsigned)i >> TypeShiftAmt)) {
6147 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6148 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6149 Intrinsic::ppc_altivec_vsrab, Intrinsic::ppc_altivec_vsrah, 0,
6150 Intrinsic::ppc_altivec_vsraw
6152 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6153 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6156 // vsplti + rol self.
6157 if (SextVal == (int)(((unsigned)i << TypeShiftAmt) |
6158 ((unsigned)i >> (SplatBitSize-TypeShiftAmt)))) {
6159 SDValue Res = BuildSplatI(i, SplatSize, MVT::Other, DAG, dl);
6160 static const unsigned IIDs[] = { // Intrinsic to use for each size.
6161 Intrinsic::ppc_altivec_vrlb, Intrinsic::ppc_altivec_vrlh, 0,
6162 Intrinsic::ppc_altivec_vrlw
6164 Res = BuildIntrinsicOp(IIDs[SplatSize-1], Res, Res, DAG, dl);
6165 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Res);
6168 // t = vsplti c, result = vsldoi t, t, 1
6169 if (SextVal == (int)(((unsigned)i << 8) | (i < 0 ? 0xFF : 0))) {
6170 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6171 return BuildVSLDOI(T, T, 1, Op.getValueType(), DAG, dl);
6173 // t = vsplti c, result = vsldoi t, t, 2
6174 if (SextVal == (int)(((unsigned)i << 16) | (i < 0 ? 0xFFFF : 0))) {
6175 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6176 return BuildVSLDOI(T, T, 2, Op.getValueType(), DAG, dl);
6178 // t = vsplti c, result = vsldoi t, t, 3
6179 if (SextVal == (int)(((unsigned)i << 24) | (i < 0 ? 0xFFFFFF : 0))) {
6180 SDValue T = BuildSplatI(i, SplatSize, MVT::v16i8, DAG, dl);
6181 return BuildVSLDOI(T, T, 3, Op.getValueType(), DAG, dl);
6188 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6189 /// the specified operations to build the shuffle.
6190 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6191 SDValue RHS, SelectionDAG &DAG,
6193 unsigned OpNum = (PFEntry >> 26) & 0x0F;
6194 unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6195 unsigned RHSID = (PFEntry >> 0) & ((1 << 13)-1);
6198 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6210 if (OpNum == OP_COPY) {
6211 if (LHSID == (1*9+2)*9+3) return LHS;
6212 assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6216 SDValue OpLHS, OpRHS;
6217 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6218 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6222 default: llvm_unreachable("Unknown i32 permute!");
6224 ShufIdxs[ 0] = 0; ShufIdxs[ 1] = 1; ShufIdxs[ 2] = 2; ShufIdxs[ 3] = 3;
6225 ShufIdxs[ 4] = 16; ShufIdxs[ 5] = 17; ShufIdxs[ 6] = 18; ShufIdxs[ 7] = 19;
6226 ShufIdxs[ 8] = 4; ShufIdxs[ 9] = 5; ShufIdxs[10] = 6; ShufIdxs[11] = 7;
6227 ShufIdxs[12] = 20; ShufIdxs[13] = 21; ShufIdxs[14] = 22; ShufIdxs[15] = 23;
6230 ShufIdxs[ 0] = 8; ShufIdxs[ 1] = 9; ShufIdxs[ 2] = 10; ShufIdxs[ 3] = 11;
6231 ShufIdxs[ 4] = 24; ShufIdxs[ 5] = 25; ShufIdxs[ 6] = 26; ShufIdxs[ 7] = 27;
6232 ShufIdxs[ 8] = 12; ShufIdxs[ 9] = 13; ShufIdxs[10] = 14; ShufIdxs[11] = 15;
6233 ShufIdxs[12] = 28; ShufIdxs[13] = 29; ShufIdxs[14] = 30; ShufIdxs[15] = 31;
6236 for (unsigned i = 0; i != 16; ++i)
6237 ShufIdxs[i] = (i&3)+0;
6240 for (unsigned i = 0; i != 16; ++i)
6241 ShufIdxs[i] = (i&3)+4;
6244 for (unsigned i = 0; i != 16; ++i)
6245 ShufIdxs[i] = (i&3)+8;
6248 for (unsigned i = 0; i != 16; ++i)
6249 ShufIdxs[i] = (i&3)+12;
6252 return BuildVSLDOI(OpLHS, OpRHS, 4, OpLHS.getValueType(), DAG, dl);
6254 return BuildVSLDOI(OpLHS, OpRHS, 8, OpLHS.getValueType(), DAG, dl);
6256 return BuildVSLDOI(OpLHS, OpRHS, 12, OpLHS.getValueType(), DAG, dl);
6258 EVT VT = OpLHS.getValueType();
6259 OpLHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpLHS);
6260 OpRHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OpRHS);
6261 SDValue T = DAG.getVectorShuffle(MVT::v16i8, dl, OpLHS, OpRHS, ShufIdxs);
6262 return DAG.getNode(ISD::BITCAST, dl, VT, T);
6265 /// LowerVECTOR_SHUFFLE - Return the code we lower for VECTOR_SHUFFLE. If this
6266 /// is a shuffle we can handle in a single instruction, return it. Otherwise,
6267 /// return the code it can be lowered into. Worst case, it can always be
6268 /// lowered into a vperm.
6269 SDValue PPCTargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6270 SelectionDAG &DAG) const {
6272 SDValue V1 = Op.getOperand(0);
6273 SDValue V2 = Op.getOperand(1);
6274 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6275 EVT VT = Op.getValueType();
6276 bool isLittleEndian = Subtarget.isLittleEndian();
6278 // Cases that are handled by instructions that take permute immediates
6279 // (such as vsplt*) should be left as VECTOR_SHUFFLE nodes so they can be
6280 // selected by the instruction selector.
6281 if (V2.getOpcode() == ISD::UNDEF) {
6282 if (PPC::isSplatShuffleMask(SVOp, 1) ||
6283 PPC::isSplatShuffleMask(SVOp, 2) ||
6284 PPC::isSplatShuffleMask(SVOp, 4) ||
6285 PPC::isVPKUWUMShuffleMask(SVOp, 1, DAG) ||
6286 PPC::isVPKUHUMShuffleMask(SVOp, 1, DAG) ||
6287 PPC::isVSLDOIShuffleMask(SVOp, 1, DAG) != -1 ||
6288 PPC::isVMRGLShuffleMask(SVOp, 1, 1, DAG) ||
6289 PPC::isVMRGLShuffleMask(SVOp, 2, 1, DAG) ||
6290 PPC::isVMRGLShuffleMask(SVOp, 4, 1, DAG) ||
6291 PPC::isVMRGHShuffleMask(SVOp, 1, 1, DAG) ||
6292 PPC::isVMRGHShuffleMask(SVOp, 2, 1, DAG) ||
6293 PPC::isVMRGHShuffleMask(SVOp, 4, 1, DAG)) {
6298 // Altivec has a variety of "shuffle immediates" that take two vector inputs
6299 // and produce a fixed permutation. If any of these match, do not lower to
6301 unsigned int ShuffleKind = isLittleEndian ? 2 : 0;
6302 if (PPC::isVPKUWUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6303 PPC::isVPKUHUMShuffleMask(SVOp, ShuffleKind, DAG) ||
6304 PPC::isVSLDOIShuffleMask(SVOp, ShuffleKind, DAG) != -1 ||
6305 PPC::isVMRGLShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6306 PPC::isVMRGLShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6307 PPC::isVMRGLShuffleMask(SVOp, 4, ShuffleKind, DAG) ||
6308 PPC::isVMRGHShuffleMask(SVOp, 1, ShuffleKind, DAG) ||
6309 PPC::isVMRGHShuffleMask(SVOp, 2, ShuffleKind, DAG) ||
6310 PPC::isVMRGHShuffleMask(SVOp, 4, ShuffleKind, DAG))
6313 // Check to see if this is a shuffle of 4-byte values. If so, we can use our
6314 // perfect shuffle table to emit an optimal matching sequence.
6315 ArrayRef<int> PermMask = SVOp->getMask();
6317 unsigned PFIndexes[4];
6318 bool isFourElementShuffle = true;
6319 for (unsigned i = 0; i != 4 && isFourElementShuffle; ++i) { // Element number
6320 unsigned EltNo = 8; // Start out undef.
6321 for (unsigned j = 0; j != 4; ++j) { // Intra-element byte.
6322 if (PermMask[i*4+j] < 0)
6323 continue; // Undef, ignore it.
6325 unsigned ByteSource = PermMask[i*4+j];
6326 if ((ByteSource & 3) != j) {
6327 isFourElementShuffle = false;
6332 EltNo = ByteSource/4;
6333 } else if (EltNo != ByteSource/4) {
6334 isFourElementShuffle = false;
6338 PFIndexes[i] = EltNo;
6341 // If this shuffle can be expressed as a shuffle of 4-byte elements, use the
6342 // perfect shuffle vector to determine if it is cost effective to do this as
6343 // discrete instructions, or whether we should use a vperm.
6344 // For now, we skip this for little endian until such time as we have a
6345 // little-endian perfect shuffle table.
6346 if (isFourElementShuffle && !isLittleEndian) {
6347 // Compute the index in the perfect shuffle table.
6348 unsigned PFTableIndex =
6349 PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6351 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6352 unsigned Cost = (PFEntry >> 30);
6354 // Determining when to avoid vperm is tricky. Many things affect the cost
6355 // of vperm, particularly how many times the perm mask needs to be computed.
6356 // For example, if the perm mask can be hoisted out of a loop or is already
6357 // used (perhaps because there are multiple permutes with the same shuffle
6358 // mask?) the vperm has a cost of 1. OTOH, hoisting the permute mask out of
6359 // the loop requires an extra register.
6361 // As a compromise, we only emit discrete instructions if the shuffle can be
6362 // generated in 3 or fewer operations. When we have loop information
6363 // available, if this block is within a loop, we should avoid using vperm
6364 // for 3-operation perms and use a constant pool load instead.
6366 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6369 // Lower this to a VPERM(V1, V2, V3) expression, where V3 is a constant
6370 // vector that will get spilled to the constant pool.
6371 if (V2.getOpcode() == ISD::UNDEF) V2 = V1;
6373 // The SHUFFLE_VECTOR mask is almost exactly what we want for vperm, except
6374 // that it is in input element units, not in bytes. Convert now.
6376 // For little endian, the order of the input vectors is reversed, and
6377 // the permutation mask is complemented with respect to 31. This is
6378 // necessary to produce proper semantics with the big-endian-biased vperm
6380 EVT EltVT = V1.getValueType().getVectorElementType();
6381 unsigned BytesPerElement = EltVT.getSizeInBits()/8;
6383 SmallVector<SDValue, 16> ResultMask;
6384 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
6385 unsigned SrcElt = PermMask[i] < 0 ? 0 : PermMask[i];
6387 for (unsigned j = 0; j != BytesPerElement; ++j)
6389 ResultMask.push_back(DAG.getConstant(31 - (SrcElt*BytesPerElement+j),
6392 ResultMask.push_back(DAG.getConstant(SrcElt*BytesPerElement+j,
6396 SDValue VPermMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i8,
6399 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6402 return DAG.getNode(PPCISD::VPERM, dl, V1.getValueType(),
6406 /// getAltivecCompareInfo - Given an intrinsic, return false if it is not an
6407 /// altivec comparison. If it is, return true and fill in Opc/isDot with
6408 /// information about the intrinsic.
6409 static bool getAltivecCompareInfo(SDValue Intrin, int &CompareOpc,
6411 unsigned IntrinsicID =
6412 cast<ConstantSDNode>(Intrin.getOperand(0))->getZExtValue();
6415 switch (IntrinsicID) {
6416 default: return false;
6417 // Comparison predicates.
6418 case Intrinsic::ppc_altivec_vcmpbfp_p: CompareOpc = 966; isDot = 1; break;
6419 case Intrinsic::ppc_altivec_vcmpeqfp_p: CompareOpc = 198; isDot = 1; break;
6420 case Intrinsic::ppc_altivec_vcmpequb_p: CompareOpc = 6; isDot = 1; break;
6421 case Intrinsic::ppc_altivec_vcmpequh_p: CompareOpc = 70; isDot = 1; break;
6422 case Intrinsic::ppc_altivec_vcmpequw_p: CompareOpc = 134; isDot = 1; break;
6423 case Intrinsic::ppc_altivec_vcmpgefp_p: CompareOpc = 454; isDot = 1; break;
6424 case Intrinsic::ppc_altivec_vcmpgtfp_p: CompareOpc = 710; isDot = 1; break;
6425 case Intrinsic::ppc_altivec_vcmpgtsb_p: CompareOpc = 774; isDot = 1; break;
6426 case Intrinsic::ppc_altivec_vcmpgtsh_p: CompareOpc = 838; isDot = 1; break;
6427 case Intrinsic::ppc_altivec_vcmpgtsw_p: CompareOpc = 902; isDot = 1; break;
6428 case Intrinsic::ppc_altivec_vcmpgtub_p: CompareOpc = 518; isDot = 1; break;
6429 case Intrinsic::ppc_altivec_vcmpgtuh_p: CompareOpc = 582; isDot = 1; break;
6430 case Intrinsic::ppc_altivec_vcmpgtuw_p: CompareOpc = 646; isDot = 1; break;
6432 // Normal Comparisons.
6433 case Intrinsic::ppc_altivec_vcmpbfp: CompareOpc = 966; isDot = 0; break;
6434 case Intrinsic::ppc_altivec_vcmpeqfp: CompareOpc = 198; isDot = 0; break;
6435 case Intrinsic::ppc_altivec_vcmpequb: CompareOpc = 6; isDot = 0; break;
6436 case Intrinsic::ppc_altivec_vcmpequh: CompareOpc = 70; isDot = 0; break;
6437 case Intrinsic::ppc_altivec_vcmpequw: CompareOpc = 134; isDot = 0; break;
6438 case Intrinsic::ppc_altivec_vcmpgefp: CompareOpc = 454; isDot = 0; break;
6439 case Intrinsic::ppc_altivec_vcmpgtfp: CompareOpc = 710; isDot = 0; break;
6440 case Intrinsic::ppc_altivec_vcmpgtsb: CompareOpc = 774; isDot = 0; break;
6441 case Intrinsic::ppc_altivec_vcmpgtsh: CompareOpc = 838; isDot = 0; break;
6442 case Intrinsic::ppc_altivec_vcmpgtsw: CompareOpc = 902; isDot = 0; break;
6443 case Intrinsic::ppc_altivec_vcmpgtub: CompareOpc = 518; isDot = 0; break;
6444 case Intrinsic::ppc_altivec_vcmpgtuh: CompareOpc = 582; isDot = 0; break;
6445 case Intrinsic::ppc_altivec_vcmpgtuw: CompareOpc = 646; isDot = 0; break;
6450 /// LowerINTRINSIC_WO_CHAIN - If this is an intrinsic that we want to custom
6451 /// lower, do it, otherwise return null.
6452 SDValue PPCTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6453 SelectionDAG &DAG) const {
6454 // If this is a lowered altivec predicate compare, CompareOpc is set to the
6455 // opcode number of the comparison.
6459 if (!getAltivecCompareInfo(Op, CompareOpc, isDot))
6460 return SDValue(); // Don't custom lower most intrinsics.
6462 // If this is a non-dot comparison, make the VCMP node and we are done.
6464 SDValue Tmp = DAG.getNode(PPCISD::VCMP, dl, Op.getOperand(2).getValueType(),
6465 Op.getOperand(1), Op.getOperand(2),
6466 DAG.getConstant(CompareOpc, MVT::i32));
6467 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Tmp);
6470 // Create the PPCISD altivec 'dot' comparison node.
6472 Op.getOperand(2), // LHS
6473 Op.getOperand(3), // RHS
6474 DAG.getConstant(CompareOpc, MVT::i32)
6476 EVT VTs[] = { Op.getOperand(2).getValueType(), MVT::Glue };
6477 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
6479 // Now that we have the comparison, emit a copy from the CR to a GPR.
6480 // This is flagged to the above dot comparison.
6481 SDValue Flags = DAG.getNode(PPCISD::MFOCRF, dl, MVT::i32,
6482 DAG.getRegister(PPC::CR6, MVT::i32),
6483 CompNode.getValue(1));
6485 // Unpack the result based on how the target uses it.
6486 unsigned BitNo; // Bit # of CR6.
6487 bool InvertBit; // Invert result?
6488 switch (cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue()) {
6489 default: // Can't happen, don't crash on invalid number though.
6490 case 0: // Return the value of the EQ bit of CR6.
6491 BitNo = 0; InvertBit = false;
6493 case 1: // Return the inverted value of the EQ bit of CR6.
6494 BitNo = 0; InvertBit = true;
6496 case 2: // Return the value of the LT bit of CR6.
6497 BitNo = 2; InvertBit = false;
6499 case 3: // Return the inverted value of the LT bit of CR6.
6500 BitNo = 2; InvertBit = true;
6504 // Shift the bit into the low position.
6505 Flags = DAG.getNode(ISD::SRL, dl, MVT::i32, Flags,
6506 DAG.getConstant(8-(3-BitNo), MVT::i32));
6508 Flags = DAG.getNode(ISD::AND, dl, MVT::i32, Flags,
6509 DAG.getConstant(1, MVT::i32));
6511 // If we are supposed to, toggle the bit.
6513 Flags = DAG.getNode(ISD::XOR, dl, MVT::i32, Flags,
6514 DAG.getConstant(1, MVT::i32));
6518 SDValue PPCTargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
6519 SelectionDAG &DAG) const {
6521 // For v2i64 (VSX), we can pattern patch the v2i32 case (using fp <-> int
6522 // instructions), but for smaller types, we need to first extend up to v2i32
6523 // before doing going farther.
6524 if (Op.getValueType() == MVT::v2i64) {
6525 EVT ExtVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
6526 if (ExtVT != MVT::v2i32) {
6527 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op.getOperand(0));
6528 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32, Op,
6529 DAG.getValueType(EVT::getVectorVT(*DAG.getContext(),
6530 ExtVT.getVectorElementType(), 4)));
6531 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Op);
6532 Op = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v2i64, Op,
6533 DAG.getValueType(MVT::v2i32));
6542 SDValue PPCTargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op,
6543 SelectionDAG &DAG) const {
6545 // Create a stack slot that is 16-byte aligned.
6546 MachineFrameInfo *FrameInfo = DAG.getMachineFunction().getFrameInfo();
6547 int FrameIdx = FrameInfo->CreateStackObject(16, 16, false);
6548 EVT PtrVT = getPointerTy();
6549 SDValue FIdx = DAG.getFrameIndex(FrameIdx, PtrVT);
6551 // Store the input value into Value#0 of the stack slot.
6552 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
6553 Op.getOperand(0), FIdx, MachinePointerInfo(),
6556 return DAG.getLoad(Op.getValueType(), dl, Store, FIdx, MachinePointerInfo(),
6557 false, false, false, 0);
6560 SDValue PPCTargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
6562 if (Op.getValueType() == MVT::v4i32) {
6563 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6565 SDValue Zero = BuildSplatI( 0, 1, MVT::v4i32, DAG, dl);
6566 SDValue Neg16 = BuildSplatI(-16, 4, MVT::v4i32, DAG, dl);//+16 as shift amt.
6568 SDValue RHSSwap = // = vrlw RHS, 16
6569 BuildIntrinsicOp(Intrinsic::ppc_altivec_vrlw, RHS, Neg16, DAG, dl);
6571 // Shrinkify inputs to v8i16.
6572 LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, LHS);
6573 RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHS);
6574 RHSSwap = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, RHSSwap);
6576 // Low parts multiplied together, generating 32-bit results (we ignore the
6578 SDValue LoProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmulouh,
6579 LHS, RHS, DAG, dl, MVT::v4i32);
6581 SDValue HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmsumuhm,
6582 LHS, RHSSwap, Zero, DAG, dl, MVT::v4i32);
6583 // Shift the high parts up 16 bits.
6584 HiProd = BuildIntrinsicOp(Intrinsic::ppc_altivec_vslw, HiProd,
6586 return DAG.getNode(ISD::ADD, dl, MVT::v4i32, LoProd, HiProd);
6587 } else if (Op.getValueType() == MVT::v8i16) {
6588 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6590 SDValue Zero = BuildSplatI(0, 1, MVT::v8i16, DAG, dl);
6592 return BuildIntrinsicOp(Intrinsic::ppc_altivec_vmladduhm,
6593 LHS, RHS, Zero, DAG, dl);
6594 } else if (Op.getValueType() == MVT::v16i8) {
6595 SDValue LHS = Op.getOperand(0), RHS = Op.getOperand(1);
6596 bool isLittleEndian = Subtarget.isLittleEndian();
6598 // Multiply the even 8-bit parts, producing 16-bit sums.
6599 SDValue EvenParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuleub,
6600 LHS, RHS, DAG, dl, MVT::v8i16);
6601 EvenParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, EvenParts);
6603 // Multiply the odd 8-bit parts, producing 16-bit sums.
6604 SDValue OddParts = BuildIntrinsicOp(Intrinsic::ppc_altivec_vmuloub,
6605 LHS, RHS, DAG, dl, MVT::v8i16);
6606 OddParts = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, OddParts);
6608 // Merge the results together. Because vmuleub and vmuloub are
6609 // instructions with a big-endian bias, we must reverse the
6610 // element numbering and reverse the meaning of "odd" and "even"
6611 // when generating little endian code.
6613 for (unsigned i = 0; i != 8; ++i) {
6614 if (isLittleEndian) {
6616 Ops[i*2+1] = 2*i+16;
6619 Ops[i*2+1] = 2*i+1+16;
6623 return DAG.getVectorShuffle(MVT::v16i8, dl, OddParts, EvenParts, Ops);
6625 return DAG.getVectorShuffle(MVT::v16i8, dl, EvenParts, OddParts, Ops);
6627 llvm_unreachable("Unknown mul to lower!");
6631 /// LowerOperation - Provide custom lowering hooks for some operations.
6633 SDValue PPCTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6634 switch (Op.getOpcode()) {
6635 default: llvm_unreachable("Wasn't expecting to be able to lower this!");
6636 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6637 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
6638 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6639 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6640 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6641 case ISD::SETCC: return LowerSETCC(Op, DAG);
6642 case ISD::INIT_TRAMPOLINE: return LowerINIT_TRAMPOLINE(Op, DAG);
6643 case ISD::ADJUST_TRAMPOLINE: return LowerADJUST_TRAMPOLINE(Op, DAG);
6645 return LowerVASTART(Op, DAG, Subtarget);
6648 return LowerVAARG(Op, DAG, Subtarget);
6651 return LowerVACOPY(Op, DAG, Subtarget);
6653 case ISD::STACKRESTORE: return LowerSTACKRESTORE(Op, DAG, Subtarget);
6654 case ISD::DYNAMIC_STACKALLOC:
6655 return LowerDYNAMIC_STACKALLOC(Op, DAG, Subtarget);
6657 case ISD::EH_SJLJ_SETJMP: return lowerEH_SJLJ_SETJMP(Op, DAG);
6658 case ISD::EH_SJLJ_LONGJMP: return lowerEH_SJLJ_LONGJMP(Op, DAG);
6660 case ISD::LOAD: return LowerLOAD(Op, DAG);
6661 case ISD::STORE: return LowerSTORE(Op, DAG);
6662 case ISD::TRUNCATE: return LowerTRUNCATE(Op, DAG);
6663 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
6664 case ISD::FP_TO_UINT:
6665 case ISD::FP_TO_SINT: return LowerFP_TO_INT(Op, DAG,
6667 case ISD::UINT_TO_FP:
6668 case ISD::SINT_TO_FP: return LowerINT_TO_FP(Op, DAG);
6669 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6671 // Lower 64-bit shifts.
6672 case ISD::SHL_PARTS: return LowerSHL_PARTS(Op, DAG);
6673 case ISD::SRL_PARTS: return LowerSRL_PARTS(Op, DAG);
6674 case ISD::SRA_PARTS: return LowerSRA_PARTS(Op, DAG);
6676 // Vector-related lowering.
6677 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6678 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6679 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6680 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6681 case ISD::SIGN_EXTEND_INREG: return LowerSIGN_EXTEND_INREG(Op, DAG);
6682 case ISD::MUL: return LowerMUL(Op, DAG);
6684 // For counter-based loop handling.
6685 case ISD::INTRINSIC_W_CHAIN: return SDValue();
6687 // Frame & Return address.
6688 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6689 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6693 void PPCTargetLowering::ReplaceNodeResults(SDNode *N,
6694 SmallVectorImpl<SDValue>&Results,
6695 SelectionDAG &DAG) const {
6696 const TargetMachine &TM = getTargetMachine();
6698 switch (N->getOpcode()) {
6700 llvm_unreachable("Do not know how to custom type legalize this operation!");
6701 case ISD::READCYCLECOUNTER: {
6702 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6703 SDValue RTB = DAG.getNode(PPCISD::READ_TIME_BASE, dl, VTs, N->getOperand(0));
6705 Results.push_back(RTB);
6706 Results.push_back(RTB.getValue(1));
6707 Results.push_back(RTB.getValue(2));
6710 case ISD::INTRINSIC_W_CHAIN: {
6711 if (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue() !=
6712 Intrinsic::ppc_is_decremented_ctr_nonzero)
6715 assert(N->getValueType(0) == MVT::i1 &&
6716 "Unexpected result type for CTR decrement intrinsic");
6717 EVT SVT = getSetCCResultType(*DAG.getContext(), N->getValueType(0));
6718 SDVTList VTs = DAG.getVTList(SVT, MVT::Other);
6719 SDValue NewInt = DAG.getNode(N->getOpcode(), dl, VTs, N->getOperand(0),
6722 Results.push_back(NewInt);
6723 Results.push_back(NewInt.getValue(1));
6727 if (!TM.getSubtarget<PPCSubtarget>().isSVR4ABI()
6728 || TM.getSubtarget<PPCSubtarget>().isPPC64())
6731 EVT VT = N->getValueType(0);
6733 if (VT == MVT::i64) {
6734 SDValue NewNode = LowerVAARG(SDValue(N, 1), DAG, Subtarget);
6736 Results.push_back(NewNode);
6737 Results.push_back(NewNode.getValue(1));
6741 case ISD::FP_ROUND_INREG: {
6742 assert(N->getValueType(0) == MVT::ppcf128);
6743 assert(N->getOperand(0).getValueType() == MVT::ppcf128);
6744 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6745 MVT::f64, N->getOperand(0),
6746 DAG.getIntPtrConstant(0));
6747 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
6748 MVT::f64, N->getOperand(0),
6749 DAG.getIntPtrConstant(1));
6751 // Add the two halves of the long double in round-to-zero mode.
6752 SDValue FPreg = DAG.getNode(PPCISD::FADDRTZ, dl, MVT::f64, Lo, Hi);
6754 // We know the low half is about to be thrown away, so just use something
6756 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::ppcf128,
6760 case ISD::FP_TO_SINT:
6761 // LowerFP_TO_INT() can only handle f32 and f64.
6762 if (N->getOperand(0).getValueType() == MVT::ppcf128)
6764 Results.push_back(LowerFP_TO_INT(SDValue(N, 0), DAG, dl));
6770 //===----------------------------------------------------------------------===//
6771 // Other Lowering Code
6772 //===----------------------------------------------------------------------===//
6774 static Instruction* callIntrinsic(IRBuilder<> &Builder, Intrinsic::ID Id) {
6775 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
6776 Function *Func = Intrinsic::getDeclaration(M, Id);
6777 return Builder.CreateCall(Func);
6780 // The mappings for emitLeading/TrailingFence is taken from
6781 // http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
6782 Instruction* PPCTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
6783 AtomicOrdering Ord, bool IsStore,
6784 bool IsLoad) const {
6785 if (Ord == SequentiallyConsistent)
6786 return callIntrinsic(Builder, Intrinsic::ppc_sync);
6787 else if (isAtLeastRelease(Ord))
6788 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6793 Instruction* PPCTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
6794 AtomicOrdering Ord, bool IsStore,
6795 bool IsLoad) const {
6796 if (IsLoad && isAtLeastAcquire(Ord))
6797 return callIntrinsic(Builder, Intrinsic::ppc_lwsync);
6798 // FIXME: this is too conservative, a dependent branch + isync is enough.
6799 // See http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html and
6800 // http://www.rdrop.com/users/paulmck/scalability/paper/N2745r.2011.03.04a.html
6801 // and http://www.cl.cam.ac.uk/~pes20/cppppc/ for justification.
6807 PPCTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
6808 bool is64bit, unsigned BinOpcode) const {
6809 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6810 const TargetInstrInfo *TII =
6811 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6813 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6814 MachineFunction *F = BB->getParent();
6815 MachineFunction::iterator It = BB;
6818 unsigned dest = MI->getOperand(0).getReg();
6819 unsigned ptrA = MI->getOperand(1).getReg();
6820 unsigned ptrB = MI->getOperand(2).getReg();
6821 unsigned incr = MI->getOperand(3).getReg();
6822 DebugLoc dl = MI->getDebugLoc();
6824 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6825 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6826 F->insert(It, loopMBB);
6827 F->insert(It, exitMBB);
6828 exitMBB->splice(exitMBB->begin(), BB,
6829 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6830 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6832 MachineRegisterInfo &RegInfo = F->getRegInfo();
6833 unsigned TmpReg = (!BinOpcode) ? incr :
6834 RegInfo.createVirtualRegister( is64bit ? &PPC::G8RCRegClass
6835 : &PPC::GPRCRegClass);
6839 // fallthrough --> loopMBB
6840 BB->addSuccessor(loopMBB);
6843 // l[wd]arx dest, ptr
6844 // add r0, dest, incr
6845 // st[wd]cx. r0, ptr
6847 // fallthrough --> exitMBB
6849 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
6850 .addReg(ptrA).addReg(ptrB);
6852 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg).addReg(incr).addReg(dest);
6853 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
6854 .addReg(TmpReg).addReg(ptrA).addReg(ptrB);
6855 BuildMI(BB, dl, TII->get(PPC::BCC))
6856 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6857 BB->addSuccessor(loopMBB);
6858 BB->addSuccessor(exitMBB);
6867 PPCTargetLowering::EmitPartwordAtomicBinary(MachineInstr *MI,
6868 MachineBasicBlock *BB,
6869 bool is8bit, // operation
6870 unsigned BinOpcode) const {
6871 // This also handles ATOMIC_SWAP, indicated by BinOpcode==0.
6872 const TargetInstrInfo *TII =
6873 getTargetMachine().getSubtargetImpl()->getInstrInfo();
6874 // In 64 bit mode we have to use 64 bits for addresses, even though the
6875 // lwarx/stwcx are 32 bits. With the 32-bit atomics we can use address
6876 // registers without caring whether they're 32 or 64, but here we're
6877 // doing actual arithmetic on the addresses.
6878 bool is64bit = Subtarget.isPPC64();
6879 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
6881 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6882 MachineFunction *F = BB->getParent();
6883 MachineFunction::iterator It = BB;
6886 unsigned dest = MI->getOperand(0).getReg();
6887 unsigned ptrA = MI->getOperand(1).getReg();
6888 unsigned ptrB = MI->getOperand(2).getReg();
6889 unsigned incr = MI->getOperand(3).getReg();
6890 DebugLoc dl = MI->getDebugLoc();
6892 MachineBasicBlock *loopMBB = F->CreateMachineBasicBlock(LLVM_BB);
6893 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
6894 F->insert(It, loopMBB);
6895 F->insert(It, exitMBB);
6896 exitMBB->splice(exitMBB->begin(), BB,
6897 std::next(MachineBasicBlock::iterator(MI)), BB->end());
6898 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
6900 MachineRegisterInfo &RegInfo = F->getRegInfo();
6901 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
6902 : &PPC::GPRCRegClass;
6903 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
6904 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
6905 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
6906 unsigned Incr2Reg = RegInfo.createVirtualRegister(RC);
6907 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
6908 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
6909 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
6910 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
6911 unsigned Tmp3Reg = RegInfo.createVirtualRegister(RC);
6912 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
6913 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
6915 unsigned TmpReg = (!BinOpcode) ? Incr2Reg : RegInfo.createVirtualRegister(RC);
6919 // fallthrough --> loopMBB
6920 BB->addSuccessor(loopMBB);
6922 // The 4-byte load must be aligned, while a char or short may be
6923 // anywhere in the word. Hence all this nasty bookkeeping code.
6924 // add ptr1, ptrA, ptrB [copy if ptrA==0]
6925 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
6926 // xori shift, shift1, 24 [16]
6927 // rlwinm ptr, ptr1, 0, 0, 29
6928 // slw incr2, incr, shift
6929 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
6930 // slw mask, mask2, shift
6932 // lwarx tmpDest, ptr
6933 // add tmp, tmpDest, incr2
6934 // andc tmp2, tmpDest, mask
6935 // and tmp3, tmp, mask
6936 // or tmp4, tmp3, tmp2
6939 // fallthrough --> exitMBB
6940 // srw dest, tmpDest, shift
6941 if (ptrA != ZeroReg) {
6942 Ptr1Reg = RegInfo.createVirtualRegister(RC);
6943 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
6944 .addReg(ptrA).addReg(ptrB);
6948 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
6949 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
6950 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
6951 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
6953 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
6954 .addReg(Ptr1Reg).addImm(0).addImm(61);
6956 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
6957 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
6958 BuildMI(BB, dl, TII->get(PPC::SLW), Incr2Reg)
6959 .addReg(incr).addReg(ShiftReg);
6961 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
6963 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
6964 BuildMI(BB, dl, TII->get(PPC::ORI),Mask2Reg).addReg(Mask3Reg).addImm(65535);
6966 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
6967 .addReg(Mask2Reg).addReg(ShiftReg);
6970 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
6971 .addReg(ZeroReg).addReg(PtrReg);
6973 BuildMI(BB, dl, TII->get(BinOpcode), TmpReg)
6974 .addReg(Incr2Reg).addReg(TmpDestReg);
6975 BuildMI(BB, dl, TII->get(is64bit ? PPC::ANDC8 : PPC::ANDC), Tmp2Reg)
6976 .addReg(TmpDestReg).addReg(MaskReg);
6977 BuildMI(BB, dl, TII->get(is64bit ? PPC::AND8 : PPC::AND), Tmp3Reg)
6978 .addReg(TmpReg).addReg(MaskReg);
6979 BuildMI(BB, dl, TII->get(is64bit ? PPC::OR8 : PPC::OR), Tmp4Reg)
6980 .addReg(Tmp3Reg).addReg(Tmp2Reg);
6981 BuildMI(BB, dl, TII->get(PPC::STWCX))
6982 .addReg(Tmp4Reg).addReg(ZeroReg).addReg(PtrReg);
6983 BuildMI(BB, dl, TII->get(PPC::BCC))
6984 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loopMBB);
6985 BB->addSuccessor(loopMBB);
6986 BB->addSuccessor(exitMBB);
6991 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW), dest).addReg(TmpDestReg)
6996 llvm::MachineBasicBlock*
6997 PPCTargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
6998 MachineBasicBlock *MBB) const {
6999 DebugLoc DL = MI->getDebugLoc();
7000 const TargetInstrInfo *TII =
7001 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7003 MachineFunction *MF = MBB->getParent();
7004 MachineRegisterInfo &MRI = MF->getRegInfo();
7006 const BasicBlock *BB = MBB->getBasicBlock();
7007 MachineFunction::iterator I = MBB;
7011 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7012 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7014 unsigned DstReg = MI->getOperand(0).getReg();
7015 const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
7016 assert(RC->hasType(MVT::i32) && "Invalid destination!");
7017 unsigned mainDstReg = MRI.createVirtualRegister(RC);
7018 unsigned restoreDstReg = MRI.createVirtualRegister(RC);
7020 MVT PVT = getPointerTy();
7021 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7022 "Invalid Pointer Size!");
7023 // For v = setjmp(buf), we generate
7026 // SjLjSetup mainMBB
7032 // buf[LabelOffset] = LR
7036 // v = phi(main, restore)
7039 MachineBasicBlock *thisMBB = MBB;
7040 MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
7041 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
7042 MF->insert(I, mainMBB);
7043 MF->insert(I, sinkMBB);
7045 MachineInstrBuilder MIB;
7047 // Transfer the remainder of BB and its successor edges to sinkMBB.
7048 sinkMBB->splice(sinkMBB->begin(), MBB,
7049 std::next(MachineBasicBlock::iterator(MI)), MBB->end());
7050 sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
7052 // Note that the structure of the jmp_buf used here is not compatible
7053 // with that used by libc, and is not designed to be. Specifically, it
7054 // stores only those 'reserved' registers that LLVM does not otherwise
7055 // understand how to spill. Also, by convention, by the time this
7056 // intrinsic is called, Clang has already stored the frame address in the
7057 // first slot of the buffer and stack address in the third. Following the
7058 // X86 target code, we'll store the jump address in the second slot. We also
7059 // need to save the TOC pointer (R2) to handle jumps between shared
7060 // libraries, and that will be stored in the fourth slot. The thread
7061 // identifier (R13) is not affected.
7064 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7065 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7066 const int64_t BPOffset = 4 * PVT.getStoreSize();
7068 // Prepare IP either in reg.
7069 const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
7070 unsigned LabelReg = MRI.createVirtualRegister(PtrRC);
7071 unsigned BufReg = MI->getOperand(1).getReg();
7073 if (Subtarget.isPPC64() && Subtarget.isSVR4ABI()) {
7074 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::STD))
7078 MIB.setMemRefs(MMOBegin, MMOEnd);
7081 // Naked functions never have a base pointer, and so we use r1. For all
7082 // other functions, this decision must be delayed until during PEI.
7084 if (MF->getFunction()->getAttributes().hasAttribute(
7085 AttributeSet::FunctionIndex, Attribute::Naked))
7086 BaseReg = Subtarget.isPPC64() ? PPC::X1 : PPC::R1;
7088 BaseReg = Subtarget.isPPC64() ? PPC::BP8 : PPC::BP;
7090 MIB = BuildMI(*thisMBB, MI, DL,
7091 TII->get(Subtarget.isPPC64() ? PPC::STD : PPC::STW))
7095 MIB.setMemRefs(MMOBegin, MMOEnd);
7098 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::BCLalways)).addMBB(mainMBB);
7099 const PPCRegisterInfo *TRI =
7100 getTargetMachine().getSubtarget<PPCSubtarget>().getRegisterInfo();
7101 MIB.addRegMask(TRI->getNoPreservedMask());
7103 BuildMI(*thisMBB, MI, DL, TII->get(PPC::LI), restoreDstReg).addImm(1);
7105 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::EH_SjLj_Setup))
7107 MIB = BuildMI(*thisMBB, MI, DL, TII->get(PPC::B)).addMBB(sinkMBB);
7109 thisMBB->addSuccessor(mainMBB, /* weight */ 0);
7110 thisMBB->addSuccessor(sinkMBB, /* weight */ 1);
7114 MIB = BuildMI(mainMBB, DL,
7115 TII->get(Subtarget.isPPC64() ? PPC::MFLR8 : PPC::MFLR), LabelReg);
7118 if (Subtarget.isPPC64()) {
7119 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STD))
7121 .addImm(LabelOffset)
7124 MIB = BuildMI(mainMBB, DL, TII->get(PPC::STW))
7126 .addImm(LabelOffset)
7130 MIB.setMemRefs(MMOBegin, MMOEnd);
7132 BuildMI(mainMBB, DL, TII->get(PPC::LI), mainDstReg).addImm(0);
7133 mainMBB->addSuccessor(sinkMBB);
7136 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
7137 TII->get(PPC::PHI), DstReg)
7138 .addReg(mainDstReg).addMBB(mainMBB)
7139 .addReg(restoreDstReg).addMBB(thisMBB);
7141 MI->eraseFromParent();
7146 PPCTargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
7147 MachineBasicBlock *MBB) const {
7148 DebugLoc DL = MI->getDebugLoc();
7149 const TargetInstrInfo *TII =
7150 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7152 MachineFunction *MF = MBB->getParent();
7153 MachineRegisterInfo &MRI = MF->getRegInfo();
7156 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
7157 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
7159 MVT PVT = getPointerTy();
7160 assert((PVT == MVT::i64 || PVT == MVT::i32) &&
7161 "Invalid Pointer Size!");
7163 const TargetRegisterClass *RC =
7164 (PVT == MVT::i64) ? &PPC::G8RCRegClass : &PPC::GPRCRegClass;
7165 unsigned Tmp = MRI.createVirtualRegister(RC);
7166 // Since FP is only updated here but NOT referenced, it's treated as GPR.
7167 unsigned FP = (PVT == MVT::i64) ? PPC::X31 : PPC::R31;
7168 unsigned SP = (PVT == MVT::i64) ? PPC::X1 : PPC::R1;
7169 unsigned BP = (PVT == MVT::i64) ? PPC::X30 :
7170 (Subtarget.isSVR4ABI() &&
7171 MF->getTarget().getRelocationModel() == Reloc::PIC_ ?
7172 PPC::R29 : PPC::R30);
7174 MachineInstrBuilder MIB;
7176 const int64_t LabelOffset = 1 * PVT.getStoreSize();
7177 const int64_t SPOffset = 2 * PVT.getStoreSize();
7178 const int64_t TOCOffset = 3 * PVT.getStoreSize();
7179 const int64_t BPOffset = 4 * PVT.getStoreSize();
7181 unsigned BufReg = MI->getOperand(0).getReg();
7183 // Reload FP (the jumped-to function may not have had a
7184 // frame pointer, and if so, then its r31 will be restored
7186 if (PVT == MVT::i64) {
7187 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), FP)
7191 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), FP)
7195 MIB.setMemRefs(MMOBegin, MMOEnd);
7198 if (PVT == MVT::i64) {
7199 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), Tmp)
7200 .addImm(LabelOffset)
7203 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), Tmp)
7204 .addImm(LabelOffset)
7207 MIB.setMemRefs(MMOBegin, MMOEnd);
7210 if (PVT == MVT::i64) {
7211 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), SP)
7215 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), SP)
7219 MIB.setMemRefs(MMOBegin, MMOEnd);
7222 if (PVT == MVT::i64) {
7223 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), BP)
7227 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LWZ), BP)
7231 MIB.setMemRefs(MMOBegin, MMOEnd);
7234 if (PVT == MVT::i64 && Subtarget.isSVR4ABI()) {
7235 MIB = BuildMI(*MBB, MI, DL, TII->get(PPC::LD), PPC::X2)
7239 MIB.setMemRefs(MMOBegin, MMOEnd);
7243 BuildMI(*MBB, MI, DL,
7244 TII->get(PVT == MVT::i64 ? PPC::MTCTR8 : PPC::MTCTR)).addReg(Tmp);
7245 BuildMI(*MBB, MI, DL, TII->get(PVT == MVT::i64 ? PPC::BCTR8 : PPC::BCTR));
7247 MI->eraseFromParent();
7252 PPCTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7253 MachineBasicBlock *BB) const {
7254 if (MI->getOpcode() == TargetOpcode::STACKMAP ||
7255 MI->getOpcode() == TargetOpcode::PATCHPOINT)
7256 return emitPatchPoint(MI, BB);
7258 if (MI->getOpcode() == PPC::EH_SjLj_SetJmp32 ||
7259 MI->getOpcode() == PPC::EH_SjLj_SetJmp64) {
7260 return emitEHSjLjSetJmp(MI, BB);
7261 } else if (MI->getOpcode() == PPC::EH_SjLj_LongJmp32 ||
7262 MI->getOpcode() == PPC::EH_SjLj_LongJmp64) {
7263 return emitEHSjLjLongJmp(MI, BB);
7266 const TargetInstrInfo *TII =
7267 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7269 // To "insert" these instructions we actually have to insert their
7270 // control-flow patterns.
7271 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7272 MachineFunction::iterator It = BB;
7275 MachineFunction *F = BB->getParent();
7277 if (Subtarget.hasISEL() && (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7278 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7279 MI->getOpcode() == PPC::SELECT_I4 ||
7280 MI->getOpcode() == PPC::SELECT_I8)) {
7281 SmallVector<MachineOperand, 2> Cond;
7282 if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7283 MI->getOpcode() == PPC::SELECT_CC_I8)
7284 Cond.push_back(MI->getOperand(4));
7286 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET));
7287 Cond.push_back(MI->getOperand(1));
7289 DebugLoc dl = MI->getDebugLoc();
7290 const TargetInstrInfo *TII =
7291 getTargetMachine().getSubtargetImpl()->getInstrInfo();
7292 TII->insertSelect(*BB, MI, dl, MI->getOperand(0).getReg(),
7293 Cond, MI->getOperand(2).getReg(),
7294 MI->getOperand(3).getReg());
7295 } else if (MI->getOpcode() == PPC::SELECT_CC_I4 ||
7296 MI->getOpcode() == PPC::SELECT_CC_I8 ||
7297 MI->getOpcode() == PPC::SELECT_CC_F4 ||
7298 MI->getOpcode() == PPC::SELECT_CC_F8 ||
7299 MI->getOpcode() == PPC::SELECT_CC_VRRC ||
7300 MI->getOpcode() == PPC::SELECT_CC_VSFRC ||
7301 MI->getOpcode() == PPC::SELECT_CC_VSRC ||
7302 MI->getOpcode() == PPC::SELECT_I4 ||
7303 MI->getOpcode() == PPC::SELECT_I8 ||
7304 MI->getOpcode() == PPC::SELECT_F4 ||
7305 MI->getOpcode() == PPC::SELECT_F8 ||
7306 MI->getOpcode() == PPC::SELECT_VRRC ||
7307 MI->getOpcode() == PPC::SELECT_VSFRC ||
7308 MI->getOpcode() == PPC::SELECT_VSRC) {
7309 // The incoming instruction knows the destination vreg to set, the
7310 // condition code register to branch on, the true/false values to
7311 // select between, and a branch opcode to use.
7316 // cmpTY ccX, r1, r2
7318 // fallthrough --> copy0MBB
7319 MachineBasicBlock *thisMBB = BB;
7320 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7321 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7322 DebugLoc dl = MI->getDebugLoc();
7323 F->insert(It, copy0MBB);
7324 F->insert(It, sinkMBB);
7326 // Transfer the remainder of BB and its successor edges to sinkMBB.
7327 sinkMBB->splice(sinkMBB->begin(), BB,
7328 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7329 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7331 // Next, add the true and fallthrough blocks as its successors.
7332 BB->addSuccessor(copy0MBB);
7333 BB->addSuccessor(sinkMBB);
7335 if (MI->getOpcode() == PPC::SELECT_I4 ||
7336 MI->getOpcode() == PPC::SELECT_I8 ||
7337 MI->getOpcode() == PPC::SELECT_F4 ||
7338 MI->getOpcode() == PPC::SELECT_F8 ||
7339 MI->getOpcode() == PPC::SELECT_VRRC ||
7340 MI->getOpcode() == PPC::SELECT_VSFRC ||
7341 MI->getOpcode() == PPC::SELECT_VSRC) {
7342 BuildMI(BB, dl, TII->get(PPC::BC))
7343 .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7345 unsigned SelectPred = MI->getOperand(4).getImm();
7346 BuildMI(BB, dl, TII->get(PPC::BCC))
7347 .addImm(SelectPred).addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
7351 // %FalseValue = ...
7352 // # fallthrough to sinkMBB
7355 // Update machine-CFG edges
7356 BB->addSuccessor(sinkMBB);
7359 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7362 BuildMI(*BB, BB->begin(), dl,
7363 TII->get(PPC::PHI), MI->getOperand(0).getReg())
7364 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
7365 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7366 } else if (MI->getOpcode() == PPC::ReadTB) {
7367 // To read the 64-bit time-base register on a 32-bit target, we read the
7368 // two halves. Should the counter have wrapped while it was being read, we
7369 // need to try again.
7372 // mfspr Rx,TBU # load from TBU
7373 // mfspr Ry,TB # load from TB
7374 // mfspr Rz,TBU # load from TBU
7375 // cmpw crX,Rx,Rz # check if ‘old’=’new’
7376 // bne readLoop # branch if they're not equal
7379 MachineBasicBlock *readMBB = F->CreateMachineBasicBlock(LLVM_BB);
7380 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7381 DebugLoc dl = MI->getDebugLoc();
7382 F->insert(It, readMBB);
7383 F->insert(It, sinkMBB);
7385 // Transfer the remainder of BB and its successor edges to sinkMBB.
7386 sinkMBB->splice(sinkMBB->begin(), BB,
7387 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7388 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
7390 BB->addSuccessor(readMBB);
7393 MachineRegisterInfo &RegInfo = F->getRegInfo();
7394 unsigned ReadAgainReg = RegInfo.createVirtualRegister(&PPC::GPRCRegClass);
7395 unsigned LoReg = MI->getOperand(0).getReg();
7396 unsigned HiReg = MI->getOperand(1).getReg();
7398 BuildMI(BB, dl, TII->get(PPC::MFSPR), HiReg).addImm(269);
7399 BuildMI(BB, dl, TII->get(PPC::MFSPR), LoReg).addImm(268);
7400 BuildMI(BB, dl, TII->get(PPC::MFSPR), ReadAgainReg).addImm(269);
7402 unsigned CmpReg = RegInfo.createVirtualRegister(&PPC::CRRCRegClass);
7404 BuildMI(BB, dl, TII->get(PPC::CMPW), CmpReg)
7405 .addReg(HiReg).addReg(ReadAgainReg);
7406 BuildMI(BB, dl, TII->get(PPC::BCC))
7407 .addImm(PPC::PRED_NE).addReg(CmpReg).addMBB(readMBB);
7409 BB->addSuccessor(readMBB);
7410 BB->addSuccessor(sinkMBB);
7412 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I8)
7413 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::ADD4);
7414 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I16)
7415 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::ADD4);
7416 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I32)
7417 BB = EmitAtomicBinary(MI, BB, false, PPC::ADD4);
7418 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_ADD_I64)
7419 BB = EmitAtomicBinary(MI, BB, true, PPC::ADD8);
7421 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I8)
7422 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::AND);
7423 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I16)
7424 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::AND);
7425 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I32)
7426 BB = EmitAtomicBinary(MI, BB, false, PPC::AND);
7427 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_AND_I64)
7428 BB = EmitAtomicBinary(MI, BB, true, PPC::AND8);
7430 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I8)
7431 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::OR);
7432 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I16)
7433 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::OR);
7434 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I32)
7435 BB = EmitAtomicBinary(MI, BB, false, PPC::OR);
7436 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_OR_I64)
7437 BB = EmitAtomicBinary(MI, BB, true, PPC::OR8);
7439 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I8)
7440 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::XOR);
7441 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I16)
7442 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::XOR);
7443 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I32)
7444 BB = EmitAtomicBinary(MI, BB, false, PPC::XOR);
7445 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_XOR_I64)
7446 BB = EmitAtomicBinary(MI, BB, true, PPC::XOR8);
7448 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I8)
7449 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::NAND);
7450 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I16)
7451 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::NAND);
7452 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I32)
7453 BB = EmitAtomicBinary(MI, BB, false, PPC::NAND);
7454 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_NAND_I64)
7455 BB = EmitAtomicBinary(MI, BB, true, PPC::NAND8);
7457 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I8)
7458 BB = EmitPartwordAtomicBinary(MI, BB, true, PPC::SUBF);
7459 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I16)
7460 BB = EmitPartwordAtomicBinary(MI, BB, false, PPC::SUBF);
7461 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I32)
7462 BB = EmitAtomicBinary(MI, BB, false, PPC::SUBF);
7463 else if (MI->getOpcode() == PPC::ATOMIC_LOAD_SUB_I64)
7464 BB = EmitAtomicBinary(MI, BB, true, PPC::SUBF8);
7466 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I8)
7467 BB = EmitPartwordAtomicBinary(MI, BB, true, 0);
7468 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I16)
7469 BB = EmitPartwordAtomicBinary(MI, BB, false, 0);
7470 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I32)
7471 BB = EmitAtomicBinary(MI, BB, false, 0);
7472 else if (MI->getOpcode() == PPC::ATOMIC_SWAP_I64)
7473 BB = EmitAtomicBinary(MI, BB, true, 0);
7475 else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I32 ||
7476 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64) {
7477 bool is64bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I64;
7479 unsigned dest = MI->getOperand(0).getReg();
7480 unsigned ptrA = MI->getOperand(1).getReg();
7481 unsigned ptrB = MI->getOperand(2).getReg();
7482 unsigned oldval = MI->getOperand(3).getReg();
7483 unsigned newval = MI->getOperand(4).getReg();
7484 DebugLoc dl = MI->getDebugLoc();
7486 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7487 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7488 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7489 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7490 F->insert(It, loop1MBB);
7491 F->insert(It, loop2MBB);
7492 F->insert(It, midMBB);
7493 F->insert(It, exitMBB);
7494 exitMBB->splice(exitMBB->begin(), BB,
7495 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7496 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7500 // fallthrough --> loopMBB
7501 BB->addSuccessor(loop1MBB);
7504 // l[wd]arx dest, ptr
7505 // cmp[wd] dest, oldval
7508 // st[wd]cx. newval, ptr
7512 // st[wd]cx. dest, ptr
7515 BuildMI(BB, dl, TII->get(is64bit ? PPC::LDARX : PPC::LWARX), dest)
7516 .addReg(ptrA).addReg(ptrB);
7517 BuildMI(BB, dl, TII->get(is64bit ? PPC::CMPD : PPC::CMPW), PPC::CR0)
7518 .addReg(oldval).addReg(dest);
7519 BuildMI(BB, dl, TII->get(PPC::BCC))
7520 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7521 BB->addSuccessor(loop2MBB);
7522 BB->addSuccessor(midMBB);
7525 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7526 .addReg(newval).addReg(ptrA).addReg(ptrB);
7527 BuildMI(BB, dl, TII->get(PPC::BCC))
7528 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7529 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7530 BB->addSuccessor(loop1MBB);
7531 BB->addSuccessor(exitMBB);
7534 BuildMI(BB, dl, TII->get(is64bit ? PPC::STDCX : PPC::STWCX))
7535 .addReg(dest).addReg(ptrA).addReg(ptrB);
7536 BB->addSuccessor(exitMBB);
7541 } else if (MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8 ||
7542 MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I16) {
7543 // We must use 64-bit registers for addresses when targeting 64-bit,
7544 // since we're actually doing arithmetic on them. Other registers
7546 bool is64bit = Subtarget.isPPC64();
7547 bool is8bit = MI->getOpcode() == PPC::ATOMIC_CMP_SWAP_I8;
7549 unsigned dest = MI->getOperand(0).getReg();
7550 unsigned ptrA = MI->getOperand(1).getReg();
7551 unsigned ptrB = MI->getOperand(2).getReg();
7552 unsigned oldval = MI->getOperand(3).getReg();
7553 unsigned newval = MI->getOperand(4).getReg();
7554 DebugLoc dl = MI->getDebugLoc();
7556 MachineBasicBlock *loop1MBB = F->CreateMachineBasicBlock(LLVM_BB);
7557 MachineBasicBlock *loop2MBB = F->CreateMachineBasicBlock(LLVM_BB);
7558 MachineBasicBlock *midMBB = F->CreateMachineBasicBlock(LLVM_BB);
7559 MachineBasicBlock *exitMBB = F->CreateMachineBasicBlock(LLVM_BB);
7560 F->insert(It, loop1MBB);
7561 F->insert(It, loop2MBB);
7562 F->insert(It, midMBB);
7563 F->insert(It, exitMBB);
7564 exitMBB->splice(exitMBB->begin(), BB,
7565 std::next(MachineBasicBlock::iterator(MI)), BB->end());
7566 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
7568 MachineRegisterInfo &RegInfo = F->getRegInfo();
7569 const TargetRegisterClass *RC = is64bit ? &PPC::G8RCRegClass
7570 : &PPC::GPRCRegClass;
7571 unsigned PtrReg = RegInfo.createVirtualRegister(RC);
7572 unsigned Shift1Reg = RegInfo.createVirtualRegister(RC);
7573 unsigned ShiftReg = RegInfo.createVirtualRegister(RC);
7574 unsigned NewVal2Reg = RegInfo.createVirtualRegister(RC);
7575 unsigned NewVal3Reg = RegInfo.createVirtualRegister(RC);
7576 unsigned OldVal2Reg = RegInfo.createVirtualRegister(RC);
7577 unsigned OldVal3Reg = RegInfo.createVirtualRegister(RC);
7578 unsigned MaskReg = RegInfo.createVirtualRegister(RC);
7579 unsigned Mask2Reg = RegInfo.createVirtualRegister(RC);
7580 unsigned Mask3Reg = RegInfo.createVirtualRegister(RC);
7581 unsigned Tmp2Reg = RegInfo.createVirtualRegister(RC);
7582 unsigned Tmp4Reg = RegInfo.createVirtualRegister(RC);
7583 unsigned TmpDestReg = RegInfo.createVirtualRegister(RC);
7585 unsigned TmpReg = RegInfo.createVirtualRegister(RC);
7586 unsigned ZeroReg = is64bit ? PPC::ZERO8 : PPC::ZERO;
7589 // fallthrough --> loopMBB
7590 BB->addSuccessor(loop1MBB);
7592 // The 4-byte load must be aligned, while a char or short may be
7593 // anywhere in the word. Hence all this nasty bookkeeping code.
7594 // add ptr1, ptrA, ptrB [copy if ptrA==0]
7595 // rlwinm shift1, ptr1, 3, 27, 28 [3, 27, 27]
7596 // xori shift, shift1, 24 [16]
7597 // rlwinm ptr, ptr1, 0, 0, 29
7598 // slw newval2, newval, shift
7599 // slw oldval2, oldval,shift
7600 // li mask2, 255 [li mask3, 0; ori mask2, mask3, 65535]
7601 // slw mask, mask2, shift
7602 // and newval3, newval2, mask
7603 // and oldval3, oldval2, mask
7605 // lwarx tmpDest, ptr
7606 // and tmp, tmpDest, mask
7607 // cmpw tmp, oldval3
7610 // andc tmp2, tmpDest, mask
7611 // or tmp4, tmp2, newval3
7616 // stwcx. tmpDest, ptr
7618 // srw dest, tmpDest, shift
7619 if (ptrA != ZeroReg) {
7620 Ptr1Reg = RegInfo.createVirtualRegister(RC);
7621 BuildMI(BB, dl, TII->get(is64bit ? PPC::ADD8 : PPC::ADD4), Ptr1Reg)
7622 .addReg(ptrA).addReg(ptrB);
7626 BuildMI(BB, dl, TII->get(PPC::RLWINM), Shift1Reg).addReg(Ptr1Reg)
7627 .addImm(3).addImm(27).addImm(is8bit ? 28 : 27);
7628 BuildMI(BB, dl, TII->get(is64bit ? PPC::XORI8 : PPC::XORI), ShiftReg)
7629 .addReg(Shift1Reg).addImm(is8bit ? 24 : 16);
7631 BuildMI(BB, dl, TII->get(PPC::RLDICR), PtrReg)
7632 .addReg(Ptr1Reg).addImm(0).addImm(61);
7634 BuildMI(BB, dl, TII->get(PPC::RLWINM), PtrReg)
7635 .addReg(Ptr1Reg).addImm(0).addImm(0).addImm(29);
7636 BuildMI(BB, dl, TII->get(PPC::SLW), NewVal2Reg)
7637 .addReg(newval).addReg(ShiftReg);
7638 BuildMI(BB, dl, TII->get(PPC::SLW), OldVal2Reg)
7639 .addReg(oldval).addReg(ShiftReg);
7641 BuildMI(BB, dl, TII->get(PPC::LI), Mask2Reg).addImm(255);
7643 BuildMI(BB, dl, TII->get(PPC::LI), Mask3Reg).addImm(0);
7644 BuildMI(BB, dl, TII->get(PPC::ORI), Mask2Reg)
7645 .addReg(Mask3Reg).addImm(65535);
7647 BuildMI(BB, dl, TII->get(PPC::SLW), MaskReg)
7648 .addReg(Mask2Reg).addReg(ShiftReg);
7649 BuildMI(BB, dl, TII->get(PPC::AND), NewVal3Reg)
7650 .addReg(NewVal2Reg).addReg(MaskReg);
7651 BuildMI(BB, dl, TII->get(PPC::AND), OldVal3Reg)
7652 .addReg(OldVal2Reg).addReg(MaskReg);
7655 BuildMI(BB, dl, TII->get(PPC::LWARX), TmpDestReg)
7656 .addReg(ZeroReg).addReg(PtrReg);
7657 BuildMI(BB, dl, TII->get(PPC::AND),TmpReg)
7658 .addReg(TmpDestReg).addReg(MaskReg);
7659 BuildMI(BB, dl, TII->get(PPC::CMPW), PPC::CR0)
7660 .addReg(TmpReg).addReg(OldVal3Reg);
7661 BuildMI(BB, dl, TII->get(PPC::BCC))
7662 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(midMBB);
7663 BB->addSuccessor(loop2MBB);
7664 BB->addSuccessor(midMBB);
7667 BuildMI(BB, dl, TII->get(PPC::ANDC),Tmp2Reg)
7668 .addReg(TmpDestReg).addReg(MaskReg);
7669 BuildMI(BB, dl, TII->get(PPC::OR),Tmp4Reg)
7670 .addReg(Tmp2Reg).addReg(NewVal3Reg);
7671 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(Tmp4Reg)
7672 .addReg(ZeroReg).addReg(PtrReg);
7673 BuildMI(BB, dl, TII->get(PPC::BCC))
7674 .addImm(PPC::PRED_NE).addReg(PPC::CR0).addMBB(loop1MBB);
7675 BuildMI(BB, dl, TII->get(PPC::B)).addMBB(exitMBB);
7676 BB->addSuccessor(loop1MBB);
7677 BB->addSuccessor(exitMBB);
7680 BuildMI(BB, dl, TII->get(PPC::STWCX)).addReg(TmpDestReg)
7681 .addReg(ZeroReg).addReg(PtrReg);
7682 BB->addSuccessor(exitMBB);
7687 BuildMI(*BB, BB->begin(), dl, TII->get(PPC::SRW),dest).addReg(TmpReg)
7689 } else if (MI->getOpcode() == PPC::FADDrtz) {
7690 // This pseudo performs an FADD with rounding mode temporarily forced
7691 // to round-to-zero. We emit this via custom inserter since the FPSCR
7692 // is not modeled at the SelectionDAG level.
7693 unsigned Dest = MI->getOperand(0).getReg();
7694 unsigned Src1 = MI->getOperand(1).getReg();
7695 unsigned Src2 = MI->getOperand(2).getReg();
7696 DebugLoc dl = MI->getDebugLoc();
7698 MachineRegisterInfo &RegInfo = F->getRegInfo();
7699 unsigned MFFSReg = RegInfo.createVirtualRegister(&PPC::F8RCRegClass);
7701 // Save FPSCR value.
7702 BuildMI(*BB, MI, dl, TII->get(PPC::MFFS), MFFSReg);
7704 // Set rounding mode to round-to-zero.
7705 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB1)).addImm(31);
7706 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSB0)).addImm(30);
7708 // Perform addition.
7709 BuildMI(*BB, MI, dl, TII->get(PPC::FADD), Dest).addReg(Src1).addReg(Src2);
7711 // Restore FPSCR value.
7712 BuildMI(*BB, MI, dl, TII->get(PPC::MTFSF)).addImm(1).addReg(MFFSReg);
7713 } else if (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7714 MI->getOpcode() == PPC::ANDIo_1_GT_BIT ||
7715 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7716 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) {
7717 unsigned Opcode = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8 ||
7718 MI->getOpcode() == PPC::ANDIo_1_GT_BIT8) ?
7719 PPC::ANDIo8 : PPC::ANDIo;
7720 bool isEQ = (MI->getOpcode() == PPC::ANDIo_1_EQ_BIT ||
7721 MI->getOpcode() == PPC::ANDIo_1_EQ_BIT8);
7723 MachineRegisterInfo &RegInfo = F->getRegInfo();
7724 unsigned Dest = RegInfo.createVirtualRegister(Opcode == PPC::ANDIo ?
7725 &PPC::GPRCRegClass :
7726 &PPC::G8RCRegClass);
7728 DebugLoc dl = MI->getDebugLoc();
7729 BuildMI(*BB, MI, dl, TII->get(Opcode), Dest)
7730 .addReg(MI->getOperand(1).getReg()).addImm(1);
7731 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY),
7732 MI->getOperand(0).getReg())
7733 .addReg(isEQ ? PPC::CR0EQ : PPC::CR0GT);
7735 llvm_unreachable("Unexpected instr type to insert");
7738 MI->eraseFromParent(); // The pseudo instruction is gone now.
7742 //===----------------------------------------------------------------------===//
7743 // Target Optimization Hooks
7744 //===----------------------------------------------------------------------===//
7746 SDValue PPCTargetLowering::getRsqrtEstimate(SDValue Operand,
7747 DAGCombinerInfo &DCI,
7748 unsigned &RefinementSteps,
7749 bool &UseOneConstNR) const {
7750 EVT VT = Operand.getValueType();
7751 if ((VT == MVT::f32 && Subtarget.hasFRSQRTES()) ||
7752 (VT == MVT::f64 && Subtarget.hasFRSQRTE()) ||
7753 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7754 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7755 // Convergence is quadratic, so we essentially double the number of digits
7756 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7757 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7758 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7759 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7760 if (VT.getScalarType() == MVT::f64)
7762 UseOneConstNR = true;
7763 return DCI.DAG.getNode(PPCISD::FRSQRTE, SDLoc(Operand), VT, Operand);
7768 SDValue PPCTargetLowering::getRecipEstimate(SDValue Operand,
7769 DAGCombinerInfo &DCI,
7770 unsigned &RefinementSteps) const {
7771 EVT VT = Operand.getValueType();
7772 if ((VT == MVT::f32 && Subtarget.hasFRES()) ||
7773 (VT == MVT::f64 && Subtarget.hasFRE()) ||
7774 (VT == MVT::v4f32 && Subtarget.hasAltivec()) ||
7775 (VT == MVT::v2f64 && Subtarget.hasVSX())) {
7776 // Convergence is quadratic, so we essentially double the number of digits
7777 // correct after every iteration. For both FRE and FRSQRTE, the minimum
7778 // architected relative accuracy is 2^-5. When hasRecipPrec(), this is
7779 // 2^-14. IEEE float has 23 digits and double has 52 digits.
7780 RefinementSteps = Subtarget.hasRecipPrec() ? 1 : 3;
7781 if (VT.getScalarType() == MVT::f64)
7783 return DCI.DAG.getNode(PPCISD::FRE, SDLoc(Operand), VT, Operand);
7788 bool PPCTargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
7789 // Note: This functionality is used only when unsafe-fp-math is enabled, and
7790 // on cores with reciprocal estimates (which are used when unsafe-fp-math is
7791 // enabled for division), this functionality is redundant with the default
7792 // combiner logic (once the division -> reciprocal/multiply transformation
7793 // has taken place). As a result, this matters more for older cores than for
7796 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7797 // reciprocal if there are two or more FDIVs (for embedded cores with only
7798 // one FP pipeline) for three or more FDIVs (for generic OOO cores).
7799 switch (Subtarget.getDarwinDirective()) {
7801 return NumUsers > 2;
7804 case PPC::DIR_E500mc:
7805 case PPC::DIR_E5500:
7806 return NumUsers > 1;
7810 static bool isConsecutiveLSLoc(SDValue Loc, EVT VT, LSBaseSDNode *Base,
7811 unsigned Bytes, int Dist,
7812 SelectionDAG &DAG) {
7813 if (VT.getSizeInBits() / 8 != Bytes)
7816 SDValue BaseLoc = Base->getBasePtr();
7817 if (Loc.getOpcode() == ISD::FrameIndex) {
7818 if (BaseLoc.getOpcode() != ISD::FrameIndex)
7820 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7821 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
7822 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
7823 int FS = MFI->getObjectSize(FI);
7824 int BFS = MFI->getObjectSize(BFI);
7825 if (FS != BFS || FS != (int)Bytes) return false;
7826 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
7830 if (DAG.isBaseWithConstantOffset(Loc) && Loc.getOperand(0) == BaseLoc &&
7831 cast<ConstantSDNode>(Loc.getOperand(1))->getSExtValue() == Dist*Bytes)
7834 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7835 const GlobalValue *GV1 = nullptr;
7836 const GlobalValue *GV2 = nullptr;
7837 int64_t Offset1 = 0;
7838 int64_t Offset2 = 0;
7839 bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
7840 bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
7841 if (isGA1 && isGA2 && GV1 == GV2)
7842 return Offset1 == (Offset2 + Dist*Bytes);
7846 // Like SelectionDAG::isConsecutiveLoad, but also works for stores, and does
7847 // not enforce equality of the chain operands.
7848 static bool isConsecutiveLS(SDNode *N, LSBaseSDNode *Base,
7849 unsigned Bytes, int Dist,
7850 SelectionDAG &DAG) {
7851 if (LSBaseSDNode *LS = dyn_cast<LSBaseSDNode>(N)) {
7852 EVT VT = LS->getMemoryVT();
7853 SDValue Loc = LS->getBasePtr();
7854 return isConsecutiveLSLoc(Loc, VT, Base, Bytes, Dist, DAG);
7857 if (N->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
7859 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7860 default: return false;
7861 case Intrinsic::ppc_altivec_lvx:
7862 case Intrinsic::ppc_altivec_lvxl:
7863 case Intrinsic::ppc_vsx_lxvw4x:
7866 case Intrinsic::ppc_vsx_lxvd2x:
7869 case Intrinsic::ppc_altivec_lvebx:
7872 case Intrinsic::ppc_altivec_lvehx:
7875 case Intrinsic::ppc_altivec_lvewx:
7880 return isConsecutiveLSLoc(N->getOperand(2), VT, Base, Bytes, Dist, DAG);
7883 if (N->getOpcode() == ISD::INTRINSIC_VOID) {
7885 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
7886 default: return false;
7887 case Intrinsic::ppc_altivec_stvx:
7888 case Intrinsic::ppc_altivec_stvxl:
7889 case Intrinsic::ppc_vsx_stxvw4x:
7892 case Intrinsic::ppc_vsx_stxvd2x:
7895 case Intrinsic::ppc_altivec_stvebx:
7898 case Intrinsic::ppc_altivec_stvehx:
7901 case Intrinsic::ppc_altivec_stvewx:
7906 return isConsecutiveLSLoc(N->getOperand(3), VT, Base, Bytes, Dist, DAG);
7912 // Return true is there is a nearyby consecutive load to the one provided
7913 // (regardless of alignment). We search up and down the chain, looking though
7914 // token factors and other loads (but nothing else). As a result, a true result
7915 // indicates that it is safe to create a new consecutive load adjacent to the
7917 static bool findConsecutiveLoad(LoadSDNode *LD, SelectionDAG &DAG) {
7918 SDValue Chain = LD->getChain();
7919 EVT VT = LD->getMemoryVT();
7921 SmallSet<SDNode *, 16> LoadRoots;
7922 SmallVector<SDNode *, 8> Queue(1, Chain.getNode());
7923 SmallSet<SDNode *, 16> Visited;
7925 // First, search up the chain, branching to follow all token-factor operands.
7926 // If we find a consecutive load, then we're done, otherwise, record all
7927 // nodes just above the top-level loads and token factors.
7928 while (!Queue.empty()) {
7929 SDNode *ChainNext = Queue.pop_back_val();
7930 if (!Visited.insert(ChainNext).second)
7933 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(ChainNext)) {
7934 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7937 if (!Visited.count(ChainLD->getChain().getNode()))
7938 Queue.push_back(ChainLD->getChain().getNode());
7939 } else if (ChainNext->getOpcode() == ISD::TokenFactor) {
7940 for (const SDUse &O : ChainNext->ops())
7941 if (!Visited.count(O.getNode()))
7942 Queue.push_back(O.getNode());
7944 LoadRoots.insert(ChainNext);
7947 // Second, search down the chain, starting from the top-level nodes recorded
7948 // in the first phase. These top-level nodes are the nodes just above all
7949 // loads and token factors. Starting with their uses, recursively look though
7950 // all loads (just the chain uses) and token factors to find a consecutive
7955 for (SmallSet<SDNode *, 16>::iterator I = LoadRoots.begin(),
7956 IE = LoadRoots.end(); I != IE; ++I) {
7957 Queue.push_back(*I);
7959 while (!Queue.empty()) {
7960 SDNode *LoadRoot = Queue.pop_back_val();
7961 if (!Visited.insert(LoadRoot).second)
7964 if (MemSDNode *ChainLD = dyn_cast<MemSDNode>(LoadRoot))
7965 if (isConsecutiveLS(ChainLD, LD, VT.getStoreSize(), 1, DAG))
7968 for (SDNode::use_iterator UI = LoadRoot->use_begin(),
7969 UE = LoadRoot->use_end(); UI != UE; ++UI)
7970 if (((isa<MemSDNode>(*UI) &&
7971 cast<MemSDNode>(*UI)->getChain().getNode() == LoadRoot) ||
7972 UI->getOpcode() == ISD::TokenFactor) && !Visited.count(*UI))
7973 Queue.push_back(*UI);
7980 SDValue PPCTargetLowering::DAGCombineTruncBoolExt(SDNode *N,
7981 DAGCombinerInfo &DCI) const {
7982 SelectionDAG &DAG = DCI.DAG;
7985 assert(Subtarget.useCRBits() &&
7986 "Expecting to be tracking CR bits");
7987 // If we're tracking CR bits, we need to be careful that we don't have:
7988 // trunc(binary-ops(zext(x), zext(y)))
7990 // trunc(binary-ops(binary-ops(zext(x), zext(y)), ...)
7991 // such that we're unnecessarily moving things into GPRs when it would be
7992 // better to keep them in CR bits.
7994 // Note that trunc here can be an actual i1 trunc, or can be the effective
7995 // truncation that comes from a setcc or select_cc.
7996 if (N->getOpcode() == ISD::TRUNCATE &&
7997 N->getValueType(0) != MVT::i1)
8000 if (N->getOperand(0).getValueType() != MVT::i32 &&
8001 N->getOperand(0).getValueType() != MVT::i64)
8004 if (N->getOpcode() == ISD::SETCC ||
8005 N->getOpcode() == ISD::SELECT_CC) {
8006 // If we're looking at a comparison, then we need to make sure that the
8007 // high bits (all except for the first) don't matter the result.
8009 cast<CondCodeSDNode>(N->getOperand(
8010 N->getOpcode() == ISD::SETCC ? 2 : 4))->get();
8011 unsigned OpBits = N->getOperand(0).getValueSizeInBits();
8013 if (ISD::isSignedIntSetCC(CC)) {
8014 if (DAG.ComputeNumSignBits(N->getOperand(0)) != OpBits ||
8015 DAG.ComputeNumSignBits(N->getOperand(1)) != OpBits)
8017 } else if (ISD::isUnsignedIntSetCC(CC)) {
8018 if (!DAG.MaskedValueIsZero(N->getOperand(0),
8019 APInt::getHighBitsSet(OpBits, OpBits-1)) ||
8020 !DAG.MaskedValueIsZero(N->getOperand(1),
8021 APInt::getHighBitsSet(OpBits, OpBits-1)))
8024 // This is neither a signed nor an unsigned comparison, just make sure
8025 // that the high bits are equal.
8026 APInt Op1Zero, Op1One;
8027 APInt Op2Zero, Op2One;
8028 DAG.computeKnownBits(N->getOperand(0), Op1Zero, Op1One);
8029 DAG.computeKnownBits(N->getOperand(1), Op2Zero, Op2One);
8031 // We don't really care about what is known about the first bit (if
8032 // anything), so clear it in all masks prior to comparing them.
8033 Op1Zero.clearBit(0); Op1One.clearBit(0);
8034 Op2Zero.clearBit(0); Op2One.clearBit(0);
8036 if (Op1Zero != Op2Zero || Op1One != Op2One)
8041 // We now know that the higher-order bits are irrelevant, we just need to
8042 // make sure that all of the intermediate operations are bit operations, and
8043 // all inputs are extensions.
8044 if (N->getOperand(0).getOpcode() != ISD::AND &&
8045 N->getOperand(0).getOpcode() != ISD::OR &&
8046 N->getOperand(0).getOpcode() != ISD::XOR &&
8047 N->getOperand(0).getOpcode() != ISD::SELECT &&
8048 N->getOperand(0).getOpcode() != ISD::SELECT_CC &&
8049 N->getOperand(0).getOpcode() != ISD::TRUNCATE &&
8050 N->getOperand(0).getOpcode() != ISD::SIGN_EXTEND &&
8051 N->getOperand(0).getOpcode() != ISD::ZERO_EXTEND &&
8052 N->getOperand(0).getOpcode() != ISD::ANY_EXTEND)
8055 if ((N->getOpcode() == ISD::SETCC || N->getOpcode() == ISD::SELECT_CC) &&
8056 N->getOperand(1).getOpcode() != ISD::AND &&
8057 N->getOperand(1).getOpcode() != ISD::OR &&
8058 N->getOperand(1).getOpcode() != ISD::XOR &&
8059 N->getOperand(1).getOpcode() != ISD::SELECT &&
8060 N->getOperand(1).getOpcode() != ISD::SELECT_CC &&
8061 N->getOperand(1).getOpcode() != ISD::TRUNCATE &&
8062 N->getOperand(1).getOpcode() != ISD::SIGN_EXTEND &&
8063 N->getOperand(1).getOpcode() != ISD::ZERO_EXTEND &&
8064 N->getOperand(1).getOpcode() != ISD::ANY_EXTEND)
8067 SmallVector<SDValue, 4> Inputs;
8068 SmallVector<SDValue, 8> BinOps, PromOps;
8069 SmallPtrSet<SDNode *, 16> Visited;
8071 for (unsigned i = 0; i < 2; ++i) {
8072 if (((N->getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8073 N->getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8074 N->getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8075 N->getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8076 isa<ConstantSDNode>(N->getOperand(i)))
8077 Inputs.push_back(N->getOperand(i));
8079 BinOps.push_back(N->getOperand(i));
8081 if (N->getOpcode() == ISD::TRUNCATE)
8085 // Visit all inputs, collect all binary operations (and, or, xor and
8086 // select) that are all fed by extensions.
8087 while (!BinOps.empty()) {
8088 SDValue BinOp = BinOps.back();
8091 if (!Visited.insert(BinOp.getNode()).second)
8094 PromOps.push_back(BinOp);
8096 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8097 // The condition of the select is not promoted.
8098 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8100 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8103 if (((BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8104 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8105 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) &&
8106 BinOp.getOperand(i).getOperand(0).getValueType() == MVT::i1) ||
8107 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8108 Inputs.push_back(BinOp.getOperand(i));
8109 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8110 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8111 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8112 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8113 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC ||
8114 BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8115 BinOp.getOperand(i).getOpcode() == ISD::SIGN_EXTEND ||
8116 BinOp.getOperand(i).getOpcode() == ISD::ZERO_EXTEND ||
8117 BinOp.getOperand(i).getOpcode() == ISD::ANY_EXTEND) {
8118 BinOps.push_back(BinOp.getOperand(i));
8120 // We have an input that is not an extension or another binary
8121 // operation; we'll abort this transformation.
8127 // Make sure that this is a self-contained cluster of operations (which
8128 // is not quite the same thing as saying that everything has only one
8130 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8131 if (isa<ConstantSDNode>(Inputs[i]))
8134 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8135 UE = Inputs[i].getNode()->use_end();
8138 if (User != N && !Visited.count(User))
8141 // Make sure that we're not going to promote the non-output-value
8142 // operand(s) or SELECT or SELECT_CC.
8143 // FIXME: Although we could sometimes handle this, and it does occur in
8144 // practice that one of the condition inputs to the select is also one of
8145 // the outputs, we currently can't deal with this.
8146 if (User->getOpcode() == ISD::SELECT) {
8147 if (User->getOperand(0) == Inputs[i])
8149 } else if (User->getOpcode() == ISD::SELECT_CC) {
8150 if (User->getOperand(0) == Inputs[i] ||
8151 User->getOperand(1) == Inputs[i])
8157 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8158 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8159 UE = PromOps[i].getNode()->use_end();
8162 if (User != N && !Visited.count(User))
8165 // Make sure that we're not going to promote the non-output-value
8166 // operand(s) or SELECT or SELECT_CC.
8167 // FIXME: Although we could sometimes handle this, and it does occur in
8168 // practice that one of the condition inputs to the select is also one of
8169 // the outputs, we currently can't deal with this.
8170 if (User->getOpcode() == ISD::SELECT) {
8171 if (User->getOperand(0) == PromOps[i])
8173 } else if (User->getOpcode() == ISD::SELECT_CC) {
8174 if (User->getOperand(0) == PromOps[i] ||
8175 User->getOperand(1) == PromOps[i])
8181 // Replace all inputs with the extension operand.
8182 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8183 // Constants may have users outside the cluster of to-be-promoted nodes,
8184 // and so we need to replace those as we do the promotions.
8185 if (isa<ConstantSDNode>(Inputs[i]))
8188 DAG.ReplaceAllUsesOfValueWith(Inputs[i], Inputs[i].getOperand(0));
8191 // Replace all operations (these are all the same, but have a different
8192 // (i1) return type). DAG.getNode will validate that the types of
8193 // a binary operator match, so go through the list in reverse so that
8194 // we've likely promoted both operands first. Any intermediate truncations or
8195 // extensions disappear.
8196 while (!PromOps.empty()) {
8197 SDValue PromOp = PromOps.back();
8200 if (PromOp.getOpcode() == ISD::TRUNCATE ||
8201 PromOp.getOpcode() == ISD::SIGN_EXTEND ||
8202 PromOp.getOpcode() == ISD::ZERO_EXTEND ||
8203 PromOp.getOpcode() == ISD::ANY_EXTEND) {
8204 if (!isa<ConstantSDNode>(PromOp.getOperand(0)) &&
8205 PromOp.getOperand(0).getValueType() != MVT::i1) {
8206 // The operand is not yet ready (see comment below).
8207 PromOps.insert(PromOps.begin(), PromOp);
8211 SDValue RepValue = PromOp.getOperand(0);
8212 if (isa<ConstantSDNode>(RepValue))
8213 RepValue = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, RepValue);
8215 DAG.ReplaceAllUsesOfValueWith(PromOp, RepValue);
8220 switch (PromOp.getOpcode()) {
8221 default: C = 0; break;
8222 case ISD::SELECT: C = 1; break;
8223 case ISD::SELECT_CC: C = 2; break;
8226 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8227 PromOp.getOperand(C).getValueType() != MVT::i1) ||
8228 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8229 PromOp.getOperand(C+1).getValueType() != MVT::i1)) {
8230 // The to-be-promoted operands of this node have not yet been
8231 // promoted (this should be rare because we're going through the
8232 // list backward, but if one of the operands has several users in
8233 // this cluster of to-be-promoted nodes, it is possible).
8234 PromOps.insert(PromOps.begin(), PromOp);
8238 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8239 PromOp.getNode()->op_end());
8241 // If there are any constant inputs, make sure they're replaced now.
8242 for (unsigned i = 0; i < 2; ++i)
8243 if (isa<ConstantSDNode>(Ops[C+i]))
8244 Ops[C+i] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Ops[C+i]);
8246 DAG.ReplaceAllUsesOfValueWith(PromOp,
8247 DAG.getNode(PromOp.getOpcode(), dl, MVT::i1, Ops));
8250 // Now we're left with the initial truncation itself.
8251 if (N->getOpcode() == ISD::TRUNCATE)
8252 return N->getOperand(0);
8254 // Otherwise, this is a comparison. The operands to be compared have just
8255 // changed type (to i1), but everything else is the same.
8256 return SDValue(N, 0);
8259 SDValue PPCTargetLowering::DAGCombineExtBoolTrunc(SDNode *N,
8260 DAGCombinerInfo &DCI) const {
8261 SelectionDAG &DAG = DCI.DAG;
8264 // If we're tracking CR bits, we need to be careful that we don't have:
8265 // zext(binary-ops(trunc(x), trunc(y)))
8267 // zext(binary-ops(binary-ops(trunc(x), trunc(y)), ...)
8268 // such that we're unnecessarily moving things into CR bits that can more
8269 // efficiently stay in GPRs. Note that if we're not certain that the high
8270 // bits are set as required by the final extension, we still may need to do
8271 // some masking to get the proper behavior.
8273 // This same functionality is important on PPC64 when dealing with
8274 // 32-to-64-bit extensions; these occur often when 32-bit values are used as
8275 // the return values of functions. Because it is so similar, it is handled
8278 if (N->getValueType(0) != MVT::i32 &&
8279 N->getValueType(0) != MVT::i64)
8282 if (!((N->getOperand(0).getValueType() == MVT::i1 &&
8283 Subtarget.useCRBits()) ||
8284 (N->getOperand(0).getValueType() == MVT::i32 &&
8285 Subtarget.isPPC64())))
8288 if (N->getOperand(0).getOpcode() != ISD::AND &&
8289 N->getOperand(0).getOpcode() != ISD::OR &&
8290 N->getOperand(0).getOpcode() != ISD::XOR &&
8291 N->getOperand(0).getOpcode() != ISD::SELECT &&
8292 N->getOperand(0).getOpcode() != ISD::SELECT_CC)
8295 SmallVector<SDValue, 4> Inputs;
8296 SmallVector<SDValue, 8> BinOps(1, N->getOperand(0)), PromOps;
8297 SmallPtrSet<SDNode *, 16> Visited;
8299 // Visit all inputs, collect all binary operations (and, or, xor and
8300 // select) that are all fed by truncations.
8301 while (!BinOps.empty()) {
8302 SDValue BinOp = BinOps.back();
8305 if (!Visited.insert(BinOp.getNode()).second)
8308 PromOps.push_back(BinOp);
8310 for (unsigned i = 0, ie = BinOp.getNumOperands(); i != ie; ++i) {
8311 // The condition of the select is not promoted.
8312 if (BinOp.getOpcode() == ISD::SELECT && i == 0)
8314 if (BinOp.getOpcode() == ISD::SELECT_CC && i != 2 && i != 3)
8317 if (BinOp.getOperand(i).getOpcode() == ISD::TRUNCATE ||
8318 isa<ConstantSDNode>(BinOp.getOperand(i))) {
8319 Inputs.push_back(BinOp.getOperand(i));
8320 } else if (BinOp.getOperand(i).getOpcode() == ISD::AND ||
8321 BinOp.getOperand(i).getOpcode() == ISD::OR ||
8322 BinOp.getOperand(i).getOpcode() == ISD::XOR ||
8323 BinOp.getOperand(i).getOpcode() == ISD::SELECT ||
8324 BinOp.getOperand(i).getOpcode() == ISD::SELECT_CC) {
8325 BinOps.push_back(BinOp.getOperand(i));
8327 // We have an input that is not a truncation or another binary
8328 // operation; we'll abort this transformation.
8334 // The operands of a select that must be truncated when the select is
8335 // promoted because the operand is actually part of the to-be-promoted set.
8336 DenseMap<SDNode *, EVT> SelectTruncOp[2];
8338 // Make sure that this is a self-contained cluster of operations (which
8339 // is not quite the same thing as saying that everything has only one
8341 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8342 if (isa<ConstantSDNode>(Inputs[i]))
8345 for (SDNode::use_iterator UI = Inputs[i].getNode()->use_begin(),
8346 UE = Inputs[i].getNode()->use_end();
8349 if (User != N && !Visited.count(User))
8352 // If we're going to promote the non-output-value operand(s) or SELECT or
8353 // SELECT_CC, record them for truncation.
8354 if (User->getOpcode() == ISD::SELECT) {
8355 if (User->getOperand(0) == Inputs[i])
8356 SelectTruncOp[0].insert(std::make_pair(User,
8357 User->getOperand(0).getValueType()));
8358 } else if (User->getOpcode() == ISD::SELECT_CC) {
8359 if (User->getOperand(0) == Inputs[i])
8360 SelectTruncOp[0].insert(std::make_pair(User,
8361 User->getOperand(0).getValueType()));
8362 if (User->getOperand(1) == Inputs[i])
8363 SelectTruncOp[1].insert(std::make_pair(User,
8364 User->getOperand(1).getValueType()));
8369 for (unsigned i = 0, ie = PromOps.size(); i != ie; ++i) {
8370 for (SDNode::use_iterator UI = PromOps[i].getNode()->use_begin(),
8371 UE = PromOps[i].getNode()->use_end();
8374 if (User != N && !Visited.count(User))
8377 // If we're going to promote the non-output-value operand(s) or SELECT or
8378 // SELECT_CC, record them for truncation.
8379 if (User->getOpcode() == ISD::SELECT) {
8380 if (User->getOperand(0) == PromOps[i])
8381 SelectTruncOp[0].insert(std::make_pair(User,
8382 User->getOperand(0).getValueType()));
8383 } else if (User->getOpcode() == ISD::SELECT_CC) {
8384 if (User->getOperand(0) == PromOps[i])
8385 SelectTruncOp[0].insert(std::make_pair(User,
8386 User->getOperand(0).getValueType()));
8387 if (User->getOperand(1) == PromOps[i])
8388 SelectTruncOp[1].insert(std::make_pair(User,
8389 User->getOperand(1).getValueType()));
8394 unsigned PromBits = N->getOperand(0).getValueSizeInBits();
8395 bool ReallyNeedsExt = false;
8396 if (N->getOpcode() != ISD::ANY_EXTEND) {
8397 // If all of the inputs are not already sign/zero extended, then
8398 // we'll still need to do that at the end.
8399 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8400 if (isa<ConstantSDNode>(Inputs[i]))
8404 Inputs[i].getOperand(0).getValueSizeInBits();
8405 assert(PromBits < OpBits && "Truncation not to a smaller bit count?");
8407 if ((N->getOpcode() == ISD::ZERO_EXTEND &&
8408 !DAG.MaskedValueIsZero(Inputs[i].getOperand(0),
8409 APInt::getHighBitsSet(OpBits,
8410 OpBits-PromBits))) ||
8411 (N->getOpcode() == ISD::SIGN_EXTEND &&
8412 DAG.ComputeNumSignBits(Inputs[i].getOperand(0)) <
8413 (OpBits-(PromBits-1)))) {
8414 ReallyNeedsExt = true;
8420 // Replace all inputs, either with the truncation operand, or a
8421 // truncation or extension to the final output type.
8422 for (unsigned i = 0, ie = Inputs.size(); i != ie; ++i) {
8423 // Constant inputs need to be replaced with the to-be-promoted nodes that
8424 // use them because they might have users outside of the cluster of
8426 if (isa<ConstantSDNode>(Inputs[i]))
8429 SDValue InSrc = Inputs[i].getOperand(0);
8430 if (Inputs[i].getValueType() == N->getValueType(0))
8431 DAG.ReplaceAllUsesOfValueWith(Inputs[i], InSrc);
8432 else if (N->getOpcode() == ISD::SIGN_EXTEND)
8433 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8434 DAG.getSExtOrTrunc(InSrc, dl, N->getValueType(0)));
8435 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8436 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8437 DAG.getZExtOrTrunc(InSrc, dl, N->getValueType(0)));
8439 DAG.ReplaceAllUsesOfValueWith(Inputs[i],
8440 DAG.getAnyExtOrTrunc(InSrc, dl, N->getValueType(0)));
8443 // Replace all operations (these are all the same, but have a different
8444 // (promoted) return type). DAG.getNode will validate that the types of
8445 // a binary operator match, so go through the list in reverse so that
8446 // we've likely promoted both operands first.
8447 while (!PromOps.empty()) {
8448 SDValue PromOp = PromOps.back();
8452 switch (PromOp.getOpcode()) {
8453 default: C = 0; break;
8454 case ISD::SELECT: C = 1; break;
8455 case ISD::SELECT_CC: C = 2; break;
8458 if ((!isa<ConstantSDNode>(PromOp.getOperand(C)) &&
8459 PromOp.getOperand(C).getValueType() != N->getValueType(0)) ||
8460 (!isa<ConstantSDNode>(PromOp.getOperand(C+1)) &&
8461 PromOp.getOperand(C+1).getValueType() != N->getValueType(0))) {
8462 // The to-be-promoted operands of this node have not yet been
8463 // promoted (this should be rare because we're going through the
8464 // list backward, but if one of the operands has several users in
8465 // this cluster of to-be-promoted nodes, it is possible).
8466 PromOps.insert(PromOps.begin(), PromOp);
8470 // For SELECT and SELECT_CC nodes, we do a similar check for any
8471 // to-be-promoted comparison inputs.
8472 if (PromOp.getOpcode() == ISD::SELECT ||
8473 PromOp.getOpcode() == ISD::SELECT_CC) {
8474 if ((SelectTruncOp[0].count(PromOp.getNode()) &&
8475 PromOp.getOperand(0).getValueType() != N->getValueType(0)) ||
8476 (SelectTruncOp[1].count(PromOp.getNode()) &&
8477 PromOp.getOperand(1).getValueType() != N->getValueType(0))) {
8478 PromOps.insert(PromOps.begin(), PromOp);
8483 SmallVector<SDValue, 3> Ops(PromOp.getNode()->op_begin(),
8484 PromOp.getNode()->op_end());
8486 // If this node has constant inputs, then they'll need to be promoted here.
8487 for (unsigned i = 0; i < 2; ++i) {
8488 if (!isa<ConstantSDNode>(Ops[C+i]))
8490 if (Ops[C+i].getValueType() == N->getValueType(0))
8493 if (N->getOpcode() == ISD::SIGN_EXTEND)
8494 Ops[C+i] = DAG.getSExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8495 else if (N->getOpcode() == ISD::ZERO_EXTEND)
8496 Ops[C+i] = DAG.getZExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8498 Ops[C+i] = DAG.getAnyExtOrTrunc(Ops[C+i], dl, N->getValueType(0));
8501 // If we've promoted the comparison inputs of a SELECT or SELECT_CC,
8502 // truncate them again to the original value type.
8503 if (PromOp.getOpcode() == ISD::SELECT ||
8504 PromOp.getOpcode() == ISD::SELECT_CC) {
8505 auto SI0 = SelectTruncOp[0].find(PromOp.getNode());
8506 if (SI0 != SelectTruncOp[0].end())
8507 Ops[0] = DAG.getNode(ISD::TRUNCATE, dl, SI0->second, Ops[0]);
8508 auto SI1 = SelectTruncOp[1].find(PromOp.getNode());
8509 if (SI1 != SelectTruncOp[1].end())
8510 Ops[1] = DAG.getNode(ISD::TRUNCATE, dl, SI1->second, Ops[1]);
8513 DAG.ReplaceAllUsesOfValueWith(PromOp,
8514 DAG.getNode(PromOp.getOpcode(), dl, N->getValueType(0), Ops));
8517 // Now we're left with the initial extension itself.
8518 if (!ReallyNeedsExt)
8519 return N->getOperand(0);
8521 // To zero extend, just mask off everything except for the first bit (in the
8523 if (N->getOpcode() == ISD::ZERO_EXTEND)
8524 return DAG.getNode(ISD::AND, dl, N->getValueType(0), N->getOperand(0),
8525 DAG.getConstant(APInt::getLowBitsSet(
8526 N->getValueSizeInBits(0), PromBits),
8527 N->getValueType(0)));
8529 assert(N->getOpcode() == ISD::SIGN_EXTEND &&
8530 "Invalid extension type");
8531 EVT ShiftAmountTy = getShiftAmountTy(N->getValueType(0));
8533 DAG.getConstant(N->getValueSizeInBits(0)-PromBits, ShiftAmountTy);
8534 return DAG.getNode(ISD::SRA, dl, N->getValueType(0),
8535 DAG.getNode(ISD::SHL, dl, N->getValueType(0),
8536 N->getOperand(0), ShiftCst), ShiftCst);
8539 SDValue PPCTargetLowering::combineFPToIntToFP(SDNode *N,
8540 DAGCombinerInfo &DCI) const {
8541 assert((N->getOpcode() == ISD::SINT_TO_FP ||
8542 N->getOpcode() == ISD::UINT_TO_FP) &&
8543 "Need an int -> FP conversion node here");
8545 if (!Subtarget.has64BitSupport())
8548 SelectionDAG &DAG = DCI.DAG;
8552 // Don't handle ppc_fp128 here or i1 conversions.
8553 if (Op.getValueType() != MVT::f32 && Op.getValueType() != MVT::f64)
8555 if (Op.getOperand(0).getValueType() == MVT::i1)
8558 // For i32 intermediate values, unfortunately, the conversion functions
8559 // leave the upper 32 bits of the value are undefined. Within the set of
8560 // scalar instructions, we have no method for zero- or sign-extending the
8561 // value. Thus, we cannot handle i32 intermediate values here.
8562 if (Op.getOperand(0).getValueType() == MVT::i32)
8565 assert((Op.getOpcode() == ISD::SINT_TO_FP || Subtarget.hasFPCVT()) &&
8566 "UINT_TO_FP is supported only with FPCVT");
8568 // If we have FCFIDS, then use it when converting to single-precision.
8569 // Otherwise, convert to double-precision and then round.
8570 unsigned FCFOp = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8571 (Op.getOpcode() == ISD::UINT_TO_FP ?
8572 PPCISD::FCFIDUS : PPCISD::FCFIDS) :
8573 (Op.getOpcode() == ISD::UINT_TO_FP ?
8574 PPCISD::FCFIDU : PPCISD::FCFID);
8575 MVT FCFTy = (Subtarget.hasFPCVT() && Op.getValueType() == MVT::f32) ?
8576 MVT::f32 : MVT::f64;
8578 // If we're converting from a float, to an int, and back to a float again,
8579 // then we don't need the store/load pair at all.
8580 if ((Op.getOperand(0).getOpcode() == ISD::FP_TO_UINT &&
8581 Subtarget.hasFPCVT()) ||
8582 (Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT)) {
8583 SDValue Src = Op.getOperand(0).getOperand(0);
8584 if (Src.getValueType() == MVT::f32) {
8585 Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Src);
8586 DCI.AddToWorklist(Src.getNode());
8590 Op.getOperand(0).getOpcode() == ISD::FP_TO_SINT ? PPCISD::FCTIDZ :
8593 SDValue Tmp = DAG.getNode(FCTOp, dl, MVT::f64, Src);
8594 SDValue FP = DAG.getNode(FCFOp, dl, FCFTy, Tmp);
8596 if (Op.getValueType() == MVT::f32 && !Subtarget.hasFPCVT()) {
8597 FP = DAG.getNode(ISD::FP_ROUND, dl,
8598 MVT::f32, FP, DAG.getIntPtrConstant(0));
8599 DCI.AddToWorklist(FP.getNode());
8608 // expandVSXLoadForLE - Convert VSX loads (which may be intrinsics for
8609 // builtins) into loads with swaps.
8610 SDValue PPCTargetLowering::expandVSXLoadForLE(SDNode *N,
8611 DAGCombinerInfo &DCI) const {
8612 SelectionDAG &DAG = DCI.DAG;
8616 MachineMemOperand *MMO;
8618 switch (N->getOpcode()) {
8620 llvm_unreachable("Unexpected opcode for little endian VSX load");
8622 LoadSDNode *LD = cast<LoadSDNode>(N);
8623 Chain = LD->getChain();
8624 Base = LD->getBasePtr();
8625 MMO = LD->getMemOperand();
8626 // If the MMO suggests this isn't a load of a full vector, leave
8627 // things alone. For a built-in, we have to make the change for
8628 // correctness, so if there is a size problem that will be a bug.
8629 if (MMO->getSize() < 16)
8633 case ISD::INTRINSIC_W_CHAIN: {
8634 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8635 Chain = Intrin->getChain();
8636 Base = Intrin->getBasePtr();
8637 MMO = Intrin->getMemOperand();
8642 MVT VecTy = N->getValueType(0).getSimpleVT();
8643 SDValue LoadOps[] = { Chain, Base };
8644 SDValue Load = DAG.getMemIntrinsicNode(PPCISD::LXVD2X, dl,
8645 DAG.getVTList(VecTy, MVT::Other),
8646 LoadOps, VecTy, MMO);
8647 DCI.AddToWorklist(Load.getNode());
8648 Chain = Load.getValue(1);
8649 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8650 DAG.getVTList(VecTy, MVT::Other), Chain, Load);
8651 DCI.AddToWorklist(Swap.getNode());
8655 // expandVSXStoreForLE - Convert VSX stores (which may be intrinsics for
8656 // builtins) into stores with swaps.
8657 SDValue PPCTargetLowering::expandVSXStoreForLE(SDNode *N,
8658 DAGCombinerInfo &DCI) const {
8659 SelectionDAG &DAG = DCI.DAG;
8664 MachineMemOperand *MMO;
8666 switch (N->getOpcode()) {
8668 llvm_unreachable("Unexpected opcode for little endian VSX store");
8670 StoreSDNode *ST = cast<StoreSDNode>(N);
8671 Chain = ST->getChain();
8672 Base = ST->getBasePtr();
8673 MMO = ST->getMemOperand();
8675 // If the MMO suggests this isn't a store of a full vector, leave
8676 // things alone. For a built-in, we have to make the change for
8677 // correctness, so if there is a size problem that will be a bug.
8678 if (MMO->getSize() < 16)
8682 case ISD::INTRINSIC_VOID: {
8683 MemIntrinsicSDNode *Intrin = cast<MemIntrinsicSDNode>(N);
8684 Chain = Intrin->getChain();
8685 // Intrin->getBasePtr() oddly does not get what we want.
8686 Base = Intrin->getOperand(3);
8687 MMO = Intrin->getMemOperand();
8693 SDValue Src = N->getOperand(SrcOpnd);
8694 MVT VecTy = Src.getValueType().getSimpleVT();
8695 SDValue Swap = DAG.getNode(PPCISD::XXSWAPD, dl,
8696 DAG.getVTList(VecTy, MVT::Other), Chain, Src);
8697 DCI.AddToWorklist(Swap.getNode());
8698 Chain = Swap.getValue(1);
8699 SDValue StoreOps[] = { Chain, Swap, Base };
8700 SDValue Store = DAG.getMemIntrinsicNode(PPCISD::STXVD2X, dl,
8701 DAG.getVTList(MVT::Other),
8702 StoreOps, VecTy, MMO);
8703 DCI.AddToWorklist(Store.getNode());
8707 SDValue PPCTargetLowering::PerformDAGCombine(SDNode *N,
8708 DAGCombinerInfo &DCI) const {
8709 const TargetMachine &TM = getTargetMachine();
8710 SelectionDAG &DAG = DCI.DAG;
8712 switch (N->getOpcode()) {
8715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8716 if (C->isNullValue()) // 0 << V -> 0.
8717 return N->getOperand(0);
8721 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8722 if (C->isNullValue()) // 0 >>u V -> 0.
8723 return N->getOperand(0);
8727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8728 if (C->isNullValue() || // 0 >>s V -> 0.
8729 C->isAllOnesValue()) // -1 >>s V -> -1.
8730 return N->getOperand(0);
8733 case ISD::SIGN_EXTEND:
8734 case ISD::ZERO_EXTEND:
8735 case ISD::ANY_EXTEND:
8736 return DAGCombineExtBoolTrunc(N, DCI);
8739 case ISD::SELECT_CC:
8740 return DAGCombineTruncBoolExt(N, DCI);
8741 case ISD::SINT_TO_FP:
8742 case ISD::UINT_TO_FP:
8743 return combineFPToIntToFP(N, DCI);
8745 // Turn STORE (FP_TO_SINT F) -> STFIWX(FCTIWZ(F)).
8746 if (TM.getSubtarget<PPCSubtarget>().hasSTFIWX() &&
8747 !cast<StoreSDNode>(N)->isTruncatingStore() &&
8748 N->getOperand(1).getOpcode() == ISD::FP_TO_SINT &&
8749 N->getOperand(1).getValueType() == MVT::i32 &&
8750 N->getOperand(1).getOperand(0).getValueType() != MVT::ppcf128) {
8751 SDValue Val = N->getOperand(1).getOperand(0);
8752 if (Val.getValueType() == MVT::f32) {
8753 Val = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f64, Val);
8754 DCI.AddToWorklist(Val.getNode());
8756 Val = DAG.getNode(PPCISD::FCTIWZ, dl, MVT::f64, Val);
8757 DCI.AddToWorklist(Val.getNode());
8760 N->getOperand(0), Val, N->getOperand(2),
8761 DAG.getValueType(N->getOperand(1).getValueType())
8764 Val = DAG.getMemIntrinsicNode(PPCISD::STFIWX, dl,
8765 DAG.getVTList(MVT::Other), Ops,
8766 cast<StoreSDNode>(N)->getMemoryVT(),
8767 cast<StoreSDNode>(N)->getMemOperand());
8768 DCI.AddToWorklist(Val.getNode());
8772 // Turn STORE (BSWAP) -> sthbrx/stwbrx.
8773 if (cast<StoreSDNode>(N)->isUnindexed() &&
8774 N->getOperand(1).getOpcode() == ISD::BSWAP &&
8775 N->getOperand(1).getNode()->hasOneUse() &&
8776 (N->getOperand(1).getValueType() == MVT::i32 ||
8777 N->getOperand(1).getValueType() == MVT::i16 ||
8778 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
8779 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
8780 N->getOperand(1).getValueType() == MVT::i64))) {
8781 SDValue BSwapOp = N->getOperand(1).getOperand(0);
8782 // Do an any-extend to 32-bits if this is a half-word input.
8783 if (BSwapOp.getValueType() == MVT::i16)
8784 BSwapOp = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BSwapOp);
8787 N->getOperand(0), BSwapOp, N->getOperand(2),
8788 DAG.getValueType(N->getOperand(1).getValueType())
8791 DAG.getMemIntrinsicNode(PPCISD::STBRX, dl, DAG.getVTList(MVT::Other),
8792 Ops, cast<StoreSDNode>(N)->getMemoryVT(),
8793 cast<StoreSDNode>(N)->getMemOperand());
8796 // For little endian, VSX stores require generating xxswapd/lxvd2x.
8797 EVT VT = N->getOperand(1).getValueType();
8798 if (VT.isSimple()) {
8799 MVT StoreVT = VT.getSimpleVT();
8800 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8801 TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8802 (StoreVT == MVT::v2f64 || StoreVT == MVT::v2i64 ||
8803 StoreVT == MVT::v4f32 || StoreVT == MVT::v4i32))
8804 return expandVSXStoreForLE(N, DCI);
8809 LoadSDNode *LD = cast<LoadSDNode>(N);
8810 EVT VT = LD->getValueType(0);
8812 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8813 if (VT.isSimple()) {
8814 MVT LoadVT = VT.getSimpleVT();
8815 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8816 TM.getSubtarget<PPCSubtarget>().isLittleEndian() &&
8817 (LoadVT == MVT::v2f64 || LoadVT == MVT::v2i64 ||
8818 LoadVT == MVT::v4f32 || LoadVT == MVT::v4i32))
8819 return expandVSXLoadForLE(N, DCI);
8822 Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
8823 unsigned ABIAlignment = getDataLayout()->getABITypeAlignment(Ty);
8824 if (ISD::isNON_EXTLoad(N) && VT.isVector() &&
8825 TM.getSubtarget<PPCSubtarget>().hasAltivec() &&
8826 // P8 and later hardware should just use LOAD.
8827 !TM.getSubtarget<PPCSubtarget>().hasP8Vector() &&
8828 (VT == MVT::v16i8 || VT == MVT::v8i16 ||
8829 VT == MVT::v4i32 || VT == MVT::v4f32) &&
8830 LD->getAlignment() < ABIAlignment) {
8831 // This is a type-legal unaligned Altivec load.
8832 SDValue Chain = LD->getChain();
8833 SDValue Ptr = LD->getBasePtr();
8834 bool isLittleEndian = Subtarget.isLittleEndian();
8836 // This implements the loading of unaligned vectors as described in
8837 // the venerable Apple Velocity Engine overview. Specifically:
8838 // https://developer.apple.com/hardwaredrivers/ve/alignment.html
8839 // https://developer.apple.com/hardwaredrivers/ve/code_optimization.html
8841 // The general idea is to expand a sequence of one or more unaligned
8842 // loads into an alignment-based permutation-control instruction (lvsl
8843 // or lvsr), a series of regular vector loads (which always truncate
8844 // their input address to an aligned address), and a series of
8845 // permutations. The results of these permutations are the requested
8846 // loaded values. The trick is that the last "extra" load is not taken
8847 // from the address you might suspect (sizeof(vector) bytes after the
8848 // last requested load), but rather sizeof(vector) - 1 bytes after the
8849 // last requested vector. The point of this is to avoid a page fault if
8850 // the base address happened to be aligned. This works because if the
8851 // base address is aligned, then adding less than a full vector length
8852 // will cause the last vector in the sequence to be (re)loaded.
8853 // Otherwise, the next vector will be fetched as you might suspect was
8856 // We might be able to reuse the permutation generation from
8857 // a different base address offset from this one by an aligned amount.
8858 // The INTRINSIC_WO_CHAIN DAG combine will attempt to perform this
8859 // optimization later.
8860 Intrinsic::ID Intr = (isLittleEndian ?
8861 Intrinsic::ppc_altivec_lvsr :
8862 Intrinsic::ppc_altivec_lvsl);
8863 SDValue PermCntl = BuildIntrinsicOp(Intr, Ptr, DAG, dl, MVT::v16i8);
8865 // Create the new MMO for the new base load. It is like the original MMO,
8866 // but represents an area in memory almost twice the vector size centered
8867 // on the original address. If the address is unaligned, we might start
8868 // reading up to (sizeof(vector)-1) bytes below the address of the
8869 // original unaligned load.
8870 MachineFunction &MF = DAG.getMachineFunction();
8871 MachineMemOperand *BaseMMO =
8872 MF.getMachineMemOperand(LD->getMemOperand(),
8873 -LD->getMemoryVT().getStoreSize()+1,
8874 2*LD->getMemoryVT().getStoreSize()-1);
8876 // Create the new base load.
8877 SDValue LDXIntID = DAG.getTargetConstant(Intrinsic::ppc_altivec_lvx,
8879 SDValue BaseLoadOps[] = { Chain, LDXIntID, Ptr };
8881 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8882 DAG.getVTList(MVT::v4i32, MVT::Other),
8883 BaseLoadOps, MVT::v4i32, BaseMMO);
8885 // Note that the value of IncOffset (which is provided to the next
8886 // load's pointer info offset value, and thus used to calculate the
8887 // alignment), and the value of IncValue (which is actually used to
8888 // increment the pointer value) are different! This is because we
8889 // require the next load to appear to be aligned, even though it
8890 // is actually offset from the base pointer by a lesser amount.
8891 int IncOffset = VT.getSizeInBits() / 8;
8892 int IncValue = IncOffset;
8894 // Walk (both up and down) the chain looking for another load at the real
8895 // (aligned) offset (the alignment of the other load does not matter in
8896 // this case). If found, then do not use the offset reduction trick, as
8897 // that will prevent the loads from being later combined (as they would
8898 // otherwise be duplicates).
8899 if (!findConsecutiveLoad(LD, DAG))
8902 SDValue Increment = DAG.getConstant(IncValue, getPointerTy());
8903 Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
8905 MachineMemOperand *ExtraMMO =
8906 MF.getMachineMemOperand(LD->getMemOperand(),
8907 1, 2*LD->getMemoryVT().getStoreSize()-1);
8908 SDValue ExtraLoadOps[] = { Chain, LDXIntID, Ptr };
8910 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, dl,
8911 DAG.getVTList(MVT::v4i32, MVT::Other),
8912 ExtraLoadOps, MVT::v4i32, ExtraMMO);
8914 SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
8915 BaseLoad.getValue(1), ExtraLoad.getValue(1));
8917 // Because vperm has a big-endian bias, we must reverse the order
8918 // of the input vectors and complement the permute control vector
8919 // when generating little endian code. We have already handled the
8920 // latter by using lvsr instead of lvsl, so just reverse BaseLoad
8921 // and ExtraLoad here.
8924 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8925 ExtraLoad, BaseLoad, PermCntl, DAG, dl);
8927 Perm = BuildIntrinsicOp(Intrinsic::ppc_altivec_vperm,
8928 BaseLoad, ExtraLoad, PermCntl, DAG, dl);
8930 if (VT != MVT::v4i32)
8931 Perm = DAG.getNode(ISD::BITCAST, dl, VT, Perm);
8933 // The output of the permutation is our loaded result, the TokenFactor is
8935 DCI.CombineTo(N, Perm, TF);
8936 return SDValue(N, 0);
8940 case ISD::INTRINSIC_WO_CHAIN: {
8941 bool isLittleEndian = Subtarget.isLittleEndian();
8942 Intrinsic::ID Intr = (isLittleEndian ?
8943 Intrinsic::ppc_altivec_lvsr :
8944 Intrinsic::ppc_altivec_lvsl);
8945 if (cast<ConstantSDNode>(N->getOperand(0))->getZExtValue() == Intr &&
8946 N->getOperand(1)->getOpcode() == ISD::ADD) {
8947 SDValue Add = N->getOperand(1);
8949 if (DAG.MaskedValueIsZero(Add->getOperand(1),
8950 APInt::getAllOnesValue(4 /* 16 byte alignment */).zext(
8951 Add.getValueType().getScalarType().getSizeInBits()))) {
8952 SDNode *BasePtr = Add->getOperand(0).getNode();
8953 for (SDNode::use_iterator UI = BasePtr->use_begin(),
8954 UE = BasePtr->use_end(); UI != UE; ++UI) {
8955 if (UI->getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
8956 cast<ConstantSDNode>(UI->getOperand(0))->getZExtValue() ==
8958 // We've found another LVSL/LVSR, and this address is an aligned
8959 // multiple of that one. The results will be the same, so use the
8960 // one we've just found instead.
8962 return SDValue(*UI, 0);
8970 case ISD::INTRINSIC_W_CHAIN: {
8971 // For little endian, VSX loads require generating lxvd2x/xxswapd.
8972 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8973 TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8974 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8977 case Intrinsic::ppc_vsx_lxvw4x:
8978 case Intrinsic::ppc_vsx_lxvd2x:
8979 return expandVSXLoadForLE(N, DCI);
8984 case ISD::INTRINSIC_VOID: {
8985 // For little endian, VSX stores require generating xxswapd/stxvd2x.
8986 if (TM.getSubtarget<PPCSubtarget>().hasVSX() &&
8987 TM.getSubtarget<PPCSubtarget>().isLittleEndian()) {
8988 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8991 case Intrinsic::ppc_vsx_stxvw4x:
8992 case Intrinsic::ppc_vsx_stxvd2x:
8993 return expandVSXStoreForLE(N, DCI);
8999 // Turn BSWAP (LOAD) -> lhbrx/lwbrx.
9000 if (ISD::isNON_EXTLoad(N->getOperand(0).getNode()) &&
9001 N->getOperand(0).hasOneUse() &&
9002 (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i16 ||
9003 (TM.getSubtarget<PPCSubtarget>().hasLDBRX() &&
9004 TM.getSubtarget<PPCSubtarget>().isPPC64() &&
9005 N->getValueType(0) == MVT::i64))) {
9006 SDValue Load = N->getOperand(0);
9007 LoadSDNode *LD = cast<LoadSDNode>(Load);
9008 // Create the byte-swapping load.
9010 LD->getChain(), // Chain
9011 LD->getBasePtr(), // Ptr
9012 DAG.getValueType(N->getValueType(0)) // VT
9015 DAG.getMemIntrinsicNode(PPCISD::LBRX, dl,
9016 DAG.getVTList(N->getValueType(0) == MVT::i64 ?
9017 MVT::i64 : MVT::i32, MVT::Other),
9018 Ops, LD->getMemoryVT(), LD->getMemOperand());
9020 // If this is an i16 load, insert the truncate.
9021 SDValue ResVal = BSLoad;
9022 if (N->getValueType(0) == MVT::i16)
9023 ResVal = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, BSLoad);
9025 // First, combine the bswap away. This makes the value produced by the
9027 DCI.CombineTo(N, ResVal);
9029 // Next, combine the load away, we give it a bogus result value but a real
9030 // chain result. The result value is dead because the bswap is dead.
9031 DCI.CombineTo(Load.getNode(), ResVal, BSLoad.getValue(1));
9033 // Return N so it doesn't get rechecked!
9034 return SDValue(N, 0);
9038 case PPCISD::VCMP: {
9039 // If a VCMPo node already exists with exactly the same operands as this
9040 // node, use its result instead of this node (VCMPo computes both a CR6 and
9041 // a normal output).
9043 if (!N->getOperand(0).hasOneUse() &&
9044 !N->getOperand(1).hasOneUse() &&
9045 !N->getOperand(2).hasOneUse()) {
9047 // Scan all of the users of the LHS, looking for VCMPo's that match.
9048 SDNode *VCMPoNode = nullptr;
9050 SDNode *LHSN = N->getOperand(0).getNode();
9051 for (SDNode::use_iterator UI = LHSN->use_begin(), E = LHSN->use_end();
9053 if (UI->getOpcode() == PPCISD::VCMPo &&
9054 UI->getOperand(1) == N->getOperand(1) &&
9055 UI->getOperand(2) == N->getOperand(2) &&
9056 UI->getOperand(0) == N->getOperand(0)) {
9061 // If there is no VCMPo node, or if the flag value has a single use, don't
9063 if (!VCMPoNode || VCMPoNode->hasNUsesOfValue(0, 1))
9066 // Look at the (necessarily single) use of the flag value. If it has a
9067 // chain, this transformation is more complex. Note that multiple things
9068 // could use the value result, which we should ignore.
9069 SDNode *FlagUser = nullptr;
9070 for (SDNode::use_iterator UI = VCMPoNode->use_begin();
9071 FlagUser == nullptr; ++UI) {
9072 assert(UI != VCMPoNode->use_end() && "Didn't find user!");
9074 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
9075 if (User->getOperand(i) == SDValue(VCMPoNode, 1)) {
9082 // If the user is a MFOCRF instruction, we know this is safe.
9083 // Otherwise we give up for right now.
9084 if (FlagUser->getOpcode() == PPCISD::MFOCRF)
9085 return SDValue(VCMPoNode, 0);
9090 SDValue Cond = N->getOperand(1);
9091 SDValue Target = N->getOperand(2);
9093 if (Cond.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9094 cast<ConstantSDNode>(Cond.getOperand(1))->getZExtValue() ==
9095 Intrinsic::ppc_is_decremented_ctr_nonzero) {
9097 // We now need to make the intrinsic dead (it cannot be instruction
9099 DAG.ReplaceAllUsesOfValueWith(Cond.getValue(1), Cond.getOperand(0));
9100 assert(Cond.getNode()->hasOneUse() &&
9101 "Counter decrement has more than one use");
9103 return DAG.getNode(PPCISD::BDNZ, dl, MVT::Other,
9104 N->getOperand(0), Target);
9109 // If this is a branch on an altivec predicate comparison, lower this so
9110 // that we don't have to do a MFOCRF: instead, branch directly on CR6. This
9111 // lowering is done pre-legalize, because the legalizer lowers the predicate
9112 // compare down to code that is difficult to reassemble.
9113 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
9114 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
9116 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
9117 // value. If so, pass-through the AND to get to the intrinsic.
9118 if (LHS.getOpcode() == ISD::AND &&
9119 LHS.getOperand(0).getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9120 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() ==
9121 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9122 isa<ConstantSDNode>(LHS.getOperand(1)) &&
9123 !cast<ConstantSDNode>(LHS.getOperand(1))->getConstantIntValue()->
9125 LHS = LHS.getOperand(0);
9127 if (LHS.getOpcode() == ISD::INTRINSIC_W_CHAIN &&
9128 cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue() ==
9129 Intrinsic::ppc_is_decremented_ctr_nonzero &&
9130 isa<ConstantSDNode>(RHS)) {
9131 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9132 "Counter decrement comparison is not EQ or NE");
9134 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9135 bool isBDNZ = (CC == ISD::SETEQ && Val) ||
9136 (CC == ISD::SETNE && !Val);
9138 // We now need to make the intrinsic dead (it cannot be instruction
9140 DAG.ReplaceAllUsesOfValueWith(LHS.getValue(1), LHS.getOperand(0));
9141 assert(LHS.getNode()->hasOneUse() &&
9142 "Counter decrement has more than one use");
9144 return DAG.getNode(isBDNZ ? PPCISD::BDNZ : PPCISD::BDZ, dl, MVT::Other,
9145 N->getOperand(0), N->getOperand(4));
9151 if (LHS.getOpcode() == ISD::INTRINSIC_WO_CHAIN &&
9152 isa<ConstantSDNode>(RHS) && (CC == ISD::SETEQ || CC == ISD::SETNE) &&
9153 getAltivecCompareInfo(LHS, CompareOpc, isDot)) {
9154 assert(isDot && "Can't compare against a vector result!");
9156 // If this is a comparison against something other than 0/1, then we know
9157 // that the condition is never/always true.
9158 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
9159 if (Val != 0 && Val != 1) {
9160 if (CC == ISD::SETEQ) // Cond never true, remove branch.
9161 return N->getOperand(0);
9162 // Always !=, turn it into an unconditional branch.
9163 return DAG.getNode(ISD::BR, dl, MVT::Other,
9164 N->getOperand(0), N->getOperand(4));
9167 bool BranchOnWhenPredTrue = (CC == ISD::SETEQ) ^ (Val == 0);
9169 // Create the PPCISD altivec 'dot' comparison node.
9171 LHS.getOperand(2), // LHS of compare
9172 LHS.getOperand(3), // RHS of compare
9173 DAG.getConstant(CompareOpc, MVT::i32)
9175 EVT VTs[] = { LHS.getOperand(2).getValueType(), MVT::Glue };
9176 SDValue CompNode = DAG.getNode(PPCISD::VCMPo, dl, VTs, Ops);
9178 // Unpack the result based on how the target uses it.
9179 PPC::Predicate CompOpc;
9180 switch (cast<ConstantSDNode>(LHS.getOperand(1))->getZExtValue()) {
9181 default: // Can't happen, don't crash on invalid number though.
9182 case 0: // Branch on the value of the EQ bit of CR6.
9183 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_EQ : PPC::PRED_NE;
9185 case 1: // Branch on the inverted value of the EQ bit of CR6.
9186 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_NE : PPC::PRED_EQ;
9188 case 2: // Branch on the value of the LT bit of CR6.
9189 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_LT : PPC::PRED_GE;
9191 case 3: // Branch on the inverted value of the LT bit of CR6.
9192 CompOpc = BranchOnWhenPredTrue ? PPC::PRED_GE : PPC::PRED_LT;
9196 return DAG.getNode(PPCISD::COND_BRANCH, dl, MVT::Other, N->getOperand(0),
9197 DAG.getConstant(CompOpc, MVT::i32),
9198 DAG.getRegister(PPC::CR6, MVT::i32),
9199 N->getOperand(4), CompNode.getValue(1));
9209 PPCTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
9211 std::vector<SDNode *> *Created) const {
9212 // fold (sdiv X, pow2)
9213 EVT VT = N->getValueType(0);
9214 if (VT == MVT::i64 && !Subtarget.isPPC64())
9216 if ((VT != MVT::i32 && VT != MVT::i64) ||
9217 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
9221 SDValue N0 = N->getOperand(0);
9223 bool IsNegPow2 = (-Divisor).isPowerOf2();
9224 unsigned Lg2 = (IsNegPow2 ? -Divisor : Divisor).countTrailingZeros();
9225 SDValue ShiftAmt = DAG.getConstant(Lg2, VT);
9227 SDValue Op = DAG.getNode(PPCISD::SRA_ADDZE, DL, VT, N0, ShiftAmt);
9229 Created->push_back(Op.getNode());
9232 Op = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), Op);
9234 Created->push_back(Op.getNode());
9240 //===----------------------------------------------------------------------===//
9241 // Inline Assembly Support
9242 //===----------------------------------------------------------------------===//
9244 void PPCTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
9247 const SelectionDAG &DAG,
9248 unsigned Depth) const {
9249 KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
9250 switch (Op.getOpcode()) {
9252 case PPCISD::LBRX: {
9253 // lhbrx is known to have the top bits cleared out.
9254 if (cast<VTSDNode>(Op.getOperand(2))->getVT() == MVT::i16)
9255 KnownZero = 0xFFFF0000;
9258 case ISD::INTRINSIC_WO_CHAIN: {
9259 switch (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue()) {
9261 case Intrinsic::ppc_altivec_vcmpbfp_p:
9262 case Intrinsic::ppc_altivec_vcmpeqfp_p:
9263 case Intrinsic::ppc_altivec_vcmpequb_p:
9264 case Intrinsic::ppc_altivec_vcmpequh_p:
9265 case Intrinsic::ppc_altivec_vcmpequw_p:
9266 case Intrinsic::ppc_altivec_vcmpgefp_p:
9267 case Intrinsic::ppc_altivec_vcmpgtfp_p:
9268 case Intrinsic::ppc_altivec_vcmpgtsb_p:
9269 case Intrinsic::ppc_altivec_vcmpgtsh_p:
9270 case Intrinsic::ppc_altivec_vcmpgtsw_p:
9271 case Intrinsic::ppc_altivec_vcmpgtub_p:
9272 case Intrinsic::ppc_altivec_vcmpgtuh_p:
9273 case Intrinsic::ppc_altivec_vcmpgtuw_p:
9274 KnownZero = ~1U; // All bits but the low one are known to be zero.
9281 unsigned PPCTargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
9282 switch (Subtarget.getDarwinDirective()) {
9287 case PPC::DIR_PWR5X:
9289 case PPC::DIR_PWR6X:
9291 case PPC::DIR_PWR8: {
9295 const PPCInstrInfo *TII =
9296 static_cast<const PPCInstrInfo *>(getTargetMachine().getSubtargetImpl()->
9299 // For small loops (between 5 and 8 instructions), align to a 32-byte
9300 // boundary so that the entire loop fits in one instruction-cache line.
9301 uint64_t LoopSize = 0;
9302 for (auto I = ML->block_begin(), IE = ML->block_end(); I != IE; ++I)
9303 for (auto J = (*I)->begin(), JE = (*I)->end(); J != JE; ++J)
9304 LoopSize += TII->GetInstSizeInBytes(J);
9306 if (LoopSize > 16 && LoopSize <= 32)
9313 return TargetLowering::getPrefLoopAlignment(ML);
9316 /// getConstraintType - Given a constraint, return the type of
9317 /// constraint it is for this target.
9318 PPCTargetLowering::ConstraintType
9319 PPCTargetLowering::getConstraintType(const std::string &Constraint) const {
9320 if (Constraint.size() == 1) {
9321 switch (Constraint[0]) {
9328 return C_RegisterClass;
9330 // FIXME: While Z does indicate a memory constraint, it specifically
9331 // indicates an r+r address (used in conjunction with the 'y' modifier
9332 // in the replacement string). Currently, we're forcing the base
9333 // register to be r0 in the asm printer (which is interpreted as zero)
9334 // and forming the complete address in the second register. This is
9338 } else if (Constraint == "wc") { // individual CR bits.
9339 return C_RegisterClass;
9340 } else if (Constraint == "wa" || Constraint == "wd" ||
9341 Constraint == "wf" || Constraint == "ws") {
9342 return C_RegisterClass; // VSX registers.
9344 return TargetLowering::getConstraintType(Constraint);
9347 /// Examine constraint type and operand type and determine a weight value.
9348 /// This object must already have been set up with the operand type
9349 /// and the current alternative constraint selected.
9350 TargetLowering::ConstraintWeight
9351 PPCTargetLowering::getSingleConstraintMatchWeight(
9352 AsmOperandInfo &info, const char *constraint) const {
9353 ConstraintWeight weight = CW_Invalid;
9354 Value *CallOperandVal = info.CallOperandVal;
9355 // If we don't have a value, we can't do a match,
9356 // but allow it at the lowest weight.
9357 if (!CallOperandVal)
9359 Type *type = CallOperandVal->getType();
9361 // Look at the constraint type.
9362 if (StringRef(constraint) == "wc" && type->isIntegerTy(1))
9363 return CW_Register; // an individual CR bit.
9364 else if ((StringRef(constraint) == "wa" ||
9365 StringRef(constraint) == "wd" ||
9366 StringRef(constraint) == "wf") &&
9369 else if (StringRef(constraint) == "ws" && type->isDoubleTy())
9372 switch (*constraint) {
9374 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
9377 if (type->isIntegerTy())
9378 weight = CW_Register;
9381 if (type->isFloatTy())
9382 weight = CW_Register;
9385 if (type->isDoubleTy())
9386 weight = CW_Register;
9389 if (type->isVectorTy())
9390 weight = CW_Register;
9393 weight = CW_Register;
9402 std::pair<unsigned, const TargetRegisterClass*>
9403 PPCTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9405 if (Constraint.size() == 1) {
9406 // GCC RS6000 Constraint Letters
9407 switch (Constraint[0]) {
9409 if (VT == MVT::i64 && Subtarget.isPPC64())
9410 return std::make_pair(0U, &PPC::G8RC_NOX0RegClass);
9411 return std::make_pair(0U, &PPC::GPRC_NOR0RegClass);
9413 if (VT == MVT::i64 && Subtarget.isPPC64())
9414 return std::make_pair(0U, &PPC::G8RCRegClass);
9415 return std::make_pair(0U, &PPC::GPRCRegClass);
9417 if (VT == MVT::f32 || VT == MVT::i32)
9418 return std::make_pair(0U, &PPC::F4RCRegClass);
9419 if (VT == MVT::f64 || VT == MVT::i64)
9420 return std::make_pair(0U, &PPC::F8RCRegClass);
9423 return std::make_pair(0U, &PPC::VRRCRegClass);
9425 return std::make_pair(0U, &PPC::CRRCRegClass);
9427 } else if (Constraint == "wc") { // an individual CR bit.
9428 return std::make_pair(0U, &PPC::CRBITRCRegClass);
9429 } else if (Constraint == "wa" || Constraint == "wd" ||
9430 Constraint == "wf") {
9431 return std::make_pair(0U, &PPC::VSRCRegClass);
9432 } else if (Constraint == "ws") {
9433 return std::make_pair(0U, &PPC::VSFRCRegClass);
9436 std::pair<unsigned, const TargetRegisterClass*> R =
9437 TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9439 // r[0-9]+ are used, on PPC64, to refer to the corresponding 64-bit registers
9440 // (which we call X[0-9]+). If a 64-bit value has been requested, and a
9441 // 32-bit GPR has been selected, then 'upgrade' it to the 64-bit parent
9443 // FIXME: If TargetLowering::getRegForInlineAsmConstraint could somehow use
9444 // the AsmName field from *RegisterInfo.td, then this would not be necessary.
9445 if (R.first && VT == MVT::i64 && Subtarget.isPPC64() &&
9446 PPC::GPRCRegClass.contains(R.first)) {
9447 const TargetRegisterInfo *TRI =
9448 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
9449 return std::make_pair(TRI->getMatchingSuperReg(R.first,
9450 PPC::sub_32, &PPC::G8RCRegClass),
9451 &PPC::G8RCRegClass);
9454 // GCC accepts 'cc' as an alias for 'cr0', and we need to do the same.
9455 if (!R.second && StringRef("{cc}").equals_lower(Constraint)) {
9457 R.second = &PPC::CRRCRegClass;
9464 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9465 /// vector. If it is invalid, don't add anything to Ops.
9466 void PPCTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9467 std::string &Constraint,
9468 std::vector<SDValue>&Ops,
9469 SelectionDAG &DAG) const {
9472 // Only support length 1 constraints.
9473 if (Constraint.length() > 1) return;
9475 char Letter = Constraint[0];
9486 ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op);
9487 if (!CST) return; // Must be an immediate to match.
9488 int64_t Value = CST->getSExtValue();
9489 EVT TCVT = MVT::i64; // All constants taken to be 64 bits so that negative
9490 // numbers are printed as such.
9492 default: llvm_unreachable("Unknown constraint letter!");
9493 case 'I': // "I" is a signed 16-bit constant.
9494 if (isInt<16>(Value))
9495 Result = DAG.getTargetConstant(Value, TCVT);
9497 case 'J': // "J" is a constant with only the high-order 16 bits nonzero.
9498 if (isShiftedUInt<16, 16>(Value))
9499 Result = DAG.getTargetConstant(Value, TCVT);
9501 case 'L': // "L" is a signed 16-bit constant shifted left 16 bits.
9502 if (isShiftedInt<16, 16>(Value))
9503 Result = DAG.getTargetConstant(Value, TCVT);
9505 case 'K': // "K" is a constant with only the low-order 16 bits nonzero.
9506 if (isUInt<16>(Value))
9507 Result = DAG.getTargetConstant(Value, TCVT);
9509 case 'M': // "M" is a constant that is greater than 31.
9511 Result = DAG.getTargetConstant(Value, TCVT);
9513 case 'N': // "N" is a positive constant that is an exact power of two.
9514 if (Value > 0 && isPowerOf2_64(Value))
9515 Result = DAG.getTargetConstant(Value, TCVT);
9517 case 'O': // "O" is the constant zero.
9519 Result = DAG.getTargetConstant(Value, TCVT);
9521 case 'P': // "P" is a constant whose negation is a signed 16-bit constant.
9522 if (isInt<16>(-Value))
9523 Result = DAG.getTargetConstant(Value, TCVT);
9530 if (Result.getNode()) {
9531 Ops.push_back(Result);
9535 // Handle standard constraint letters.
9536 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
9539 // isLegalAddressingMode - Return true if the addressing mode represented
9540 // by AM is legal for this target, for a load/store of the specified type.
9541 bool PPCTargetLowering::isLegalAddressingMode(const AddrMode &AM,
9543 // FIXME: PPC does not allow r+i addressing modes for vectors!
9545 // PPC allows a sign-extended 16-bit immediate field.
9546 if (AM.BaseOffs <= -(1LL << 16) || AM.BaseOffs >= (1LL << 16)-1)
9549 // No global is ever allowed as a base.
9553 // PPC only support r+r,
9555 case 0: // "r+i" or just "i", depending on HasBaseReg.
9558 if (AM.HasBaseReg && AM.BaseOffs) // "r+r+i" is not allowed.
9560 // Otherwise we have r+r or r+i.
9563 if (AM.HasBaseReg || AM.BaseOffs) // 2*r+r or 2*r+i is not allowed.
9565 // Allow 2*r as r+r.
9568 // No other scales are supported.
9575 SDValue PPCTargetLowering::LowerRETURNADDR(SDValue Op,
9576 SelectionDAG &DAG) const {
9577 MachineFunction &MF = DAG.getMachineFunction();
9578 MachineFrameInfo *MFI = MF.getFrameInfo();
9579 MFI->setReturnAddressIsTaken(true);
9581 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
9585 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9587 // Make sure the function does not optimize away the store of the RA to
9589 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>();
9590 FuncInfo->setLRStoreRequired();
9591 bool isPPC64 = Subtarget.isPPC64();
9592 bool isDarwinABI = Subtarget.isDarwinABI();
9595 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
9598 DAG.getConstant(PPCFrameLowering::getReturnSaveOffset(isPPC64, isDarwinABI),
9599 isPPC64? MVT::i64 : MVT::i32);
9600 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9601 DAG.getNode(ISD::ADD, dl, getPointerTy(),
9603 MachinePointerInfo(), false, false, false, 0);
9606 // Just load the return address off the stack.
9607 SDValue RetAddrFI = getReturnAddrFrameIndex(DAG);
9608 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
9609 RetAddrFI, MachinePointerInfo(), false, false, false, 0);
9612 SDValue PPCTargetLowering::LowerFRAMEADDR(SDValue Op,
9613 SelectionDAG &DAG) const {
9615 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9617 EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy();
9618 bool isPPC64 = PtrVT == MVT::i64;
9620 MachineFunction &MF = DAG.getMachineFunction();
9621 MachineFrameInfo *MFI = MF.getFrameInfo();
9622 MFI->setFrameAddressIsTaken(true);
9624 // Naked functions never have a frame pointer, and so we use r1. For all
9625 // other functions, this decision must be delayed until during PEI.
9627 if (MF.getFunction()->getAttributes().hasAttribute(
9628 AttributeSet::FunctionIndex, Attribute::Naked))
9629 FrameReg = isPPC64 ? PPC::X1 : PPC::R1;
9631 FrameReg = isPPC64 ? PPC::FP8 : PPC::FP;
9633 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg,
9636 FrameAddr = DAG.getLoad(Op.getValueType(), dl, DAG.getEntryNode(),
9637 FrameAddr, MachinePointerInfo(), false, false,
9642 // FIXME? Maybe this could be a TableGen attribute on some registers and
9643 // this table could be generated automatically from RegInfo.
9644 unsigned PPCTargetLowering::getRegisterByName(const char* RegName,
9646 bool isPPC64 = Subtarget.isPPC64();
9647 bool isDarwinABI = Subtarget.isDarwinABI();
9649 if ((isPPC64 && VT != MVT::i64 && VT != MVT::i32) ||
9650 (!isPPC64 && VT != MVT::i32))
9651 report_fatal_error("Invalid register global variable type");
9653 bool is64Bit = isPPC64 && VT == MVT::i64;
9654 unsigned Reg = StringSwitch<unsigned>(RegName)
9655 .Case("r1", is64Bit ? PPC::X1 : PPC::R1)
9656 .Case("r2", isDarwinABI ? 0 : (is64Bit ? PPC::X2 : PPC::R2))
9657 .Case("r13", (!isPPC64 && isDarwinABI) ? 0 :
9658 (is64Bit ? PPC::X13 : PPC::R13))
9663 report_fatal_error("Invalid register name global variable");
9667 PPCTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
9668 // The PowerPC target isn't yet aware of offsets.
9672 bool PPCTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
9674 unsigned Intrinsic) const {
9676 switch (Intrinsic) {
9677 case Intrinsic::ppc_altivec_lvx:
9678 case Intrinsic::ppc_altivec_lvxl:
9679 case Intrinsic::ppc_altivec_lvebx:
9680 case Intrinsic::ppc_altivec_lvehx:
9681 case Intrinsic::ppc_altivec_lvewx:
9682 case Intrinsic::ppc_vsx_lxvd2x:
9683 case Intrinsic::ppc_vsx_lxvw4x: {
9685 switch (Intrinsic) {
9686 case Intrinsic::ppc_altivec_lvebx:
9689 case Intrinsic::ppc_altivec_lvehx:
9692 case Intrinsic::ppc_altivec_lvewx:
9695 case Intrinsic::ppc_vsx_lxvd2x:
9703 Info.opc = ISD::INTRINSIC_W_CHAIN;
9705 Info.ptrVal = I.getArgOperand(0);
9706 Info.offset = -VT.getStoreSize()+1;
9707 Info.size = 2*VT.getStoreSize()-1;
9710 Info.readMem = true;
9711 Info.writeMem = false;
9714 case Intrinsic::ppc_altivec_stvx:
9715 case Intrinsic::ppc_altivec_stvxl:
9716 case Intrinsic::ppc_altivec_stvebx:
9717 case Intrinsic::ppc_altivec_stvehx:
9718 case Intrinsic::ppc_altivec_stvewx:
9719 case Intrinsic::ppc_vsx_stxvd2x:
9720 case Intrinsic::ppc_vsx_stxvw4x: {
9722 switch (Intrinsic) {
9723 case Intrinsic::ppc_altivec_stvebx:
9726 case Intrinsic::ppc_altivec_stvehx:
9729 case Intrinsic::ppc_altivec_stvewx:
9732 case Intrinsic::ppc_vsx_stxvd2x:
9740 Info.opc = ISD::INTRINSIC_VOID;
9742 Info.ptrVal = I.getArgOperand(1);
9743 Info.offset = -VT.getStoreSize()+1;
9744 Info.size = 2*VT.getStoreSize()-1;
9747 Info.readMem = false;
9748 Info.writeMem = true;
9758 /// getOptimalMemOpType - Returns the target specific optimal type for load
9759 /// and store operations as a result of memset, memcpy, and memmove
9760 /// lowering. If DstAlign is zero that means it's safe to destination
9761 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
9762 /// means there isn't a need to check it against alignment requirement,
9763 /// probably because the source does not need to be loaded. If 'IsMemset' is
9764 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
9765 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
9766 /// source is constant so it does not need to be loaded.
9767 /// It returns EVT::Other if the type should be determined using generic
9768 /// target-independent logic.
9769 EVT PPCTargetLowering::getOptimalMemOpType(uint64_t Size,
9770 unsigned DstAlign, unsigned SrcAlign,
9771 bool IsMemset, bool ZeroMemset,
9773 MachineFunction &MF) const {
9774 if (Subtarget.isPPC64()) {
9781 /// \brief Returns true if it is beneficial to convert a load of a constant
9782 /// to just the constant itself.
9783 bool PPCTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
9785 assert(Ty->isIntegerTy());
9787 unsigned BitSize = Ty->getPrimitiveSizeInBits();
9788 if (BitSize == 0 || BitSize > 64)
9793 bool PPCTargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
9794 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9796 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9797 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9798 return NumBits1 == 64 && NumBits2 == 32;
9801 bool PPCTargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9802 if (!VT1.isInteger() || !VT2.isInteger())
9804 unsigned NumBits1 = VT1.getSizeInBits();
9805 unsigned NumBits2 = VT2.getSizeInBits();
9806 return NumBits1 == 64 && NumBits2 == 32;
9809 bool PPCTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
9810 // Generally speaking, zexts are not free, but they are free when they can be
9811 // folded with other operations.
9812 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Val)) {
9813 EVT MemVT = LD->getMemoryVT();
9814 if ((MemVT == MVT::i1 || MemVT == MVT::i8 || MemVT == MVT::i16 ||
9815 (Subtarget.isPPC64() && MemVT == MVT::i32)) &&
9816 (LD->getExtensionType() == ISD::NON_EXTLOAD ||
9817 LD->getExtensionType() == ISD::ZEXTLOAD))
9821 // FIXME: Add other cases...
9822 // - 32-bit shifts with a zext to i64
9823 // - zext after ctlz, bswap, etc.
9824 // - zext after and by a constant mask
9826 return TargetLowering::isZExtFree(Val, VT2);
9829 bool PPCTargetLowering::isFPExtFree(EVT VT) const {
9830 assert(VT.isFloatingPoint());
9834 bool PPCTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
9835 return isInt<16>(Imm) || isUInt<16>(Imm);
9838 bool PPCTargetLowering::isLegalAddImmediate(int64_t Imm) const {
9839 return isInt<16>(Imm) || isUInt<16>(Imm);
9842 bool PPCTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
9846 if (DisablePPCUnaligned)
9849 // PowerPC supports unaligned memory access for simple non-vector types.
9850 // Although accessing unaligned addresses is not as efficient as accessing
9851 // aligned addresses, it is generally more efficient than manual expansion,
9852 // and generally only traps for software emulation when crossing page
9858 if (VT.getSimpleVT().isVector()) {
9859 if (Subtarget.hasVSX()) {
9860 if (VT != MVT::v2f64 && VT != MVT::v2i64 &&
9861 VT != MVT::v4f32 && VT != MVT::v4i32)
9868 if (VT == MVT::ppcf128)
9877 bool PPCTargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
9878 VT = VT.getScalarType();
9883 switch (VT.getSimpleVT().SimpleTy) {
9895 PPCTargetLowering::getScratchRegisters(CallingConv::ID) const {
9896 // LR is a callee-save register, but we must treat it as clobbered by any call
9897 // site. Hence we include LR in the scratch registers, which are in turn added
9898 // as implicit-defs for stackmaps and patchpoints. The same reasoning applies
9899 // to CTR, which is used by any indirect call.
9900 static const MCPhysReg ScratchRegs[] = {
9901 PPC::X11, PPC::X12, PPC::LR8, PPC::CTR8, 0
9908 PPCTargetLowering::shouldExpandBuildVectorWithShuffles(
9909 EVT VT , unsigned DefinedValues) const {
9910 if (VT == MVT::v2i64)
9913 return TargetLowering::shouldExpandBuildVectorWithShuffles(VT, DefinedValues);
9916 Sched::Preference PPCTargetLowering::getSchedulingPreference(SDNode *N) const {
9917 if (DisableILPPref || Subtarget.enableMachineScheduler())
9918 return TargetLowering::getSchedulingPreference(N);
9923 // Create a fast isel object.
9925 PPCTargetLowering::createFastISel(FunctionLoweringInfo &FuncInfo,
9926 const TargetLibraryInfo *LibInfo) const {
9927 return PPC::createFastISel(FuncInfo, LibInfo);